Or, using your EOF markers, you need to quote the initial marker so expansion won't be done:
#-----v---v------
cat <<'EOF' >> brightup.sh
#!/bin/bash
curr=`cat /sys/class/backlight/intel_backlight/actual_brightness`
if [ $curr -lt 4477 ]; then
curr=$((curr+406));
echo $curr > /sys/class/backlight/intel_backlight/brightness;
fi
EOF
IHTH
Use Class instead of Interface that is what I discovered after all my research.
Why? A class alone is less code than a class-plus-interface. (anyway you may require a Class for data model)
Why? A class can act as an interface (use implements instead of extends).
Why? An interface-class can be a provider lookup token in Angular dependency injection.
Basically a Class can do all, what an Interface will do. So may never need to use an Interface.
jQuery:
$("body").css("cursor", "progress");
back again
$("body").css("cursor", "default");
Pure:
document.body.style.cursor = 'progress';
back again
document.body.style.cursor = 'default';
Try this:
SELECT Count(*)
FROM <DATABASE_NAME>.INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
I found this link very helpful:
https://azure.microsoft.com/en-gb/documentation/articles/sql-database-manage-logins/
It details things like:
- Azure SQL Database subscriber account
- Using Azure Active Directory users to access the database
- Server-level principal accounts (unrestricted access)
- Adding users to the dbmanager
database role
I used this and Stuart's answer to do the following:
On the master
database (see link as to who has permissions on this):
CREATE LOGIN [MyAdmin] with password='ReallySecurePassword'
And then on the database in question:
CREATE USER [MyAdmin] FROM LOGIN [MyAdmin]
ALTER ROLE db_owner ADD MEMBER [MyAdmin]
You can also create users like this, according to the link:
CREATE USER [[email protected]] FROM EXTERNAL PROVIDER;
If you have in your java source
package mypackage;
and your class is hello.java with
public class hello {
and in that hello.java you have
public static void main(String[] args) {
Then (after compilation) changeDir (cd) to the directory where your hello.class is. Then
java -cp . mypackage.hello
Mind the current directory and the package name before the class name. It works for my on linux mint and i hope on the other os's also
Thanks Stack overflow for a wealth of info.
I had this problem and
dumpbin /exports mydll.dll
and
depends mydll.dll
showed 'DllRegisterServer'.
The problem was that there was another DLL in the system that had the same name. After renaming mydll the registration succeeded.
moment.utc(date).format(...);
is the way to go, since
moment().utc(date).format(...);
does behave weird...
If any background task runs more than 10 minutes,then the task will be suspended and code block specified with beginBackgroundTaskWithExpirationHandler is called to clean up the task. background remaining time can be checked with [[UIApplication sharedApplication] backgroundTimeRemaining]. Initially when the App is in foreground backgroundTimeRemaining is set to bigger value. When the app goes to background, you can see backgroundTimeRemaining value decreases from 599.XXX ( 1o minutes). once the backgroundTimeRemaining becomes ZERO, the background task will be suspended.
//1)Creating iOS Background Task
__block UIBackgroundTaskIdentifier background_task;
background_task = [application beginBackgroundTaskWithExpirationHandler:^ {
//This code block is execute when the application’s
//remaining background time reaches ZERO.
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//### background task starts
//#### background task ends
});
//2)Making background task Asynchronous
if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)])
{
NSLog(@"Multitasking Supported");
__block UIBackgroundTaskIdentifier background_task;
background_task = [application beginBackgroundTaskWithExpirationHandler:^ {
//Clean up code. Tell the system that we are done.
[application endBackgroundTask: background_task];
background_task = UIBackgroundTaskInvalid;
}];
**//Putting All together**
//To make the code block asynchronous
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//### background task starts
NSLog(@"Running in the background\n");
while(TRUE)
{
NSLog(@"Background time Remaining: %f",[[UIApplication sharedApplication] backgroundTimeRemaining]);
[NSThread sleepForTimeInterval:1]; //wait for 1 sec
}
//#### background task ends
//Clean up code. Tell the system that we are done.
[application endBackgroundTask: background_task];
background_task = UIBackgroundTaskInvalid;
});
}
else
{
NSLog(@"Multitasking Not Supported");
}
This code compiles and works for me. It converts a double to a string using the calls you tried.
public class TestDouble {
public static void main(String[] args) {
double total = 44;
String total2 = Double.toString(total);
System.out.println("Double is " + total2);
}
}
I am puzzled by your seeing the NumberFormatException. Look at the stack trace. I'm guessing you have other code that you are not showing in your example that is causing that exception to be thrown.
You would use aggregate function MAX and GROUP BY
SELECT username, MAX(date), value FROM tablename GROUP BY username, value
You can use $query->getSingleResult()
, which will throw an exception if more than one result are found, or if no result is found. (see the related phpdoc here https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php#L791)
There's also the less famous $query->getOneOrNullResult()
which will throw an exception if more than one result are found, and return null if no result is found. (see the related phpdoc here https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php#L752)
OK, after 2 years it's finally time to correct the syntax:
SELECT t1.value, t2.value
FROM MyTable t1
JOIN MyTable t2
ON t1.id = t2.id
WHERE t1.id = @id
AND t1.status = @status1
AND t2.status = @status2
I think Todd is correct, but I think there's one other thing you should consider. You can reliably get the home directory from the JVM at runtime, and then you can create files objects relative to that location. It's not that much more trouble, and it's something you'll appreciate if you ever move to another computer or operating system.
File homedir = new File(System.getProperty("user.home"));
File fileToRead = new File(homedir, "java/ex.txt");
This happens when a keyword argument is specified that overwrites a positional argument. For example, let's imagine a function that draws a colored box. The function selects the color to be used and delegates the drawing of the box to another function, relaying all extra arguments.
def color_box(color, *args, **kwargs):
painter.select_color(color)
painter.draw_box(*args, **kwargs)
Then the call
color_box("blellow", color="green", height=20, width=30)
will fail because two values are assigned to color
: "blellow"
as positional and "green"
as keyword. (painter.draw_box
is supposed to accept the height
and width
arguments).
This is easy to see in the example, but of course if one mixes up the arguments at call, it may not be easy to debug:
# misplaced height and width
color_box(20, 30, color="green")
Here, color
is assigned 20
, then args=[30]
and color
is again assigned "green"
.
Cmd can handle running a quoted exe, but Powershell can't. I'm just going to deal with running the exe itself, since I don't have it. If you literally need to send doublequotes to an argument of an external command, that's another issue that's been covered elsewhere.
1) add the exe folder to your path, maybe in your $profile
$env:path += ';C:\Program Files\IIS\Microsoft Web Deploy\'
msdeploy
2) backquote the spaces:
C:\Program` Files\IIS\Microsoft` Web` Deploy\msdeploy.exe
Not pretty good solution, but you can try the hjson tool. It allows you to write text multi-lined in editor and then converts it to the proper valid JSON format.
Note: it adds '\n' characters for the new lines, but you can simply delete them in any text editor with the "Replace all.." function.
The .NET implementation of UrlEncode
does not comply with RFC 3986.
Some characters are not encoded but should be. The !()*
characters are listed in the RFC's section 2.2 as a reserved characters that must be encoded yet .NET fails to encode these characters.
Some characters are encoded but should not be. The .-_
characters are not listed in the RFC's section 2.2 as a reserved character that should not be encoded yet .NET erroneously encodes these characters.
The RFC specifies that to be consistent, implementations should use upper-case HEXDIG, where .NET produces lower-case HEXDIG.
Using:
SELECT t.ctn_no
FROM YOUR_TABLE t
GROUP BY t.ctn_no
HAVING COUNT(t.ctn_no) > 1
...will show you the ctn_no
value(s) that have duplicates in your table. Adding criteria to the WHERE will allow you to further tune what duplicates there are:
SELECT t.ctn_no
FROM YOUR_TABLE t
WHERE t.s_ind = 'Y'
GROUP BY t.ctn_no
HAVING COUNT(t.ctn_no) > 1
If you want to see the other column values associated with the duplicate, you'll want to use a self join:
SELECT x.*
FROM YOUR_TABLE x
JOIN (SELECT t.ctn_no
FROM YOUR_TABLE t
GROUP BY t.ctn_no
HAVING COUNT(t.ctn_no) > 1) y ON y.ctn_no = x.ctn_no
Following works in Java 8..
List<String[]> addresses = new ArrayList<>();
I would recommend installing everything via homebrew if you have the option. I went in circles for a while, but installing php 5.x via brew and then the neccessary modules worked a treat. I was working with php 5.4 and used this to get going initially:
https://github.com/josegonzalez/homebrew-php
and then installed the additional modules with:
brew install php54-redis
brew install php54-xdebug
brew install php54-mcrypt
...
I have rewritten your code in vanilla-js, using DOM methods to prevent html injection.
var _table_ = document.createElement('table'),_x000D_
_tr_ = document.createElement('tr'),_x000D_
_th_ = document.createElement('th'),_x000D_
_td_ = document.createElement('td');_x000D_
_x000D_
// Builds the HTML Table out of myList json data from Ivy restful service._x000D_
function buildHtmlTable(arr) {_x000D_
var table = _table_.cloneNode(false),_x000D_
columns = addAllColumnHeaders(arr, table);_x000D_
for (var i = 0, maxi = arr.length; i < maxi; ++i) {_x000D_
var tr = _tr_.cloneNode(false);_x000D_
for (var j = 0, maxj = columns.length; j < maxj; ++j) {_x000D_
var td = _td_.cloneNode(false);_x000D_
cellValue = arr[i][columns[j]];_x000D_
td.appendChild(document.createTextNode(arr[i][columns[j]] || ''));_x000D_
tr.appendChild(td);_x000D_
}_x000D_
table.appendChild(tr);_x000D_
}_x000D_
return table;_x000D_
}_x000D_
_x000D_
// Adds a header row to the table and returns the set of columns._x000D_
// Need to do union of keys from all records as some records may not contain_x000D_
// all records_x000D_
function addAllColumnHeaders(arr, table) {_x000D_
var columnSet = [],_x000D_
tr = _tr_.cloneNode(false);_x000D_
for (var i = 0, l = arr.length; i < l; i++) {_x000D_
for (var key in arr[i]) {_x000D_
if (arr[i].hasOwnProperty(key) && columnSet.indexOf(key) === -1) {_x000D_
columnSet.push(key);_x000D_
var th = _th_.cloneNode(false);_x000D_
th.appendChild(document.createTextNode(key));_x000D_
tr.appendChild(th);_x000D_
}_x000D_
}_x000D_
}_x000D_
table.appendChild(tr);_x000D_
return columnSet;_x000D_
}_x000D_
_x000D_
document.body.appendChild(buildHtmlTable([{_x000D_
"name": "abc",_x000D_
"age": 50_x000D_
},_x000D_
{_x000D_
"age": "25",_x000D_
"hobby": "swimming"_x000D_
},_x000D_
{_x000D_
"name": "xyz",_x000D_
"hobby": "programming"_x000D_
}_x000D_
]));
_x000D_
<?php
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";
?>
this is the path to the web root directory c:\wamp\www
you can create different projects by adding different folders to this directory and call them like:
localhost/project1 from browser
this will run the index.html or index.php, lying inside project1
For React.js, you can do this with more readable code. Hope it helps.
handleCheckboxChange(e) {
console.log('value of checkbox : ', e.target.checked);
}
render() {
return <input type="checkbox" onChange={this.handleCheckboxChange.bind(this)} />
}
All you need is to Stop the ASP.NET Development Server and run the project again
Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.
server {
listen 80;
server_name localhost;
access_log logs/localhost.access.log main;
location / {
root /var/www/board/public;
index index.html index.htm index.php;
}
}
If you are trying to join Series of equal length but their indexes don't match (which is a common scenario), then concatenating them will generate NAs wherever they don't match.
x = pd.Series({'a':1,'b':2,})
y = pd.Series({'d':4,'e':5})
pd.concat([x,y],axis=1)
#Output (I've added column names for clarity)
Index x y
a 1.0 NaN
b 2.0 NaN
d NaN 4.0
e NaN 5.0
Assuming that you don't care if the indexes match, the solution is to reindex both Series before concatenating them. If drop=False
, which is the default, then Pandas will save the old index in a column of the new dataframe (the indexes are dropped here for simplicity).
pd.concat([x.reset_index(drop=True),y.reset_index(drop=True)],axis=1)
#Output (column names added):
Index x y
0 1 4
1 2 5
You must put the updatepanel id in the first argument if the control causing the script is inside the updatepanel else use the keyword 'this' instead of update panel here is the code
ScriptManager.RegisterStartupScript(UpdatePanel3, this.GetType(), UpdatePanel3.UniqueID, "showError();", true);
I'm guessing - are you trying to create Dialog using.
getApplicationContext()
mContext which is passed by activity.
if You displaying dialog non activity class then you have to pass activity as a parameter.
Activity activity=YourActivity.this;
Now it will be work great.
If you find any trouble then let me know.
Someone posted this link to the MDN in a comment, and I think it was very helpful. It describes things like ErrorTypes very thoroughly.
EvalError --- Creates an instance representing an error that occurs regarding the global function eval().
InternalError --- Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. "too much recursion".
RangeError --- Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range.
ReferenceError --- Creates an instance representing an error that occurs when de-referencing an invalid reference.
SyntaxError --- Creates an instance representing a syntax error that occurs while parsing code in eval().
TypeError --- Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.
URIError --- Creates an instance representing an error that occurs when encodeURI() or decodeURI() are passed invalid parameters.
I met some problems in Clion and finally, I solved them. Here is some experience.
Try adding scrolling="no"
attribute like below:
<iframe frameborder="0" scrolling="no" style="height:380px;width:6000px;border:none;" src='https://yoururl'></iframe>
_x000D_
Try this:
<tr ng-repeat="player in players | filter:{id: player_id, name:player_name} | filter:ageFilter">
$scope.ageFilter = function (player) {
return (player.age > $scope.min_age && player.age < $scope.max_age);
}
Use either
&dquo; <div>&dquo;"+ title +@"&dquo;</div>
or escape the double quote:
\" <div>\""+ title +@"\"</div>
From the MySQL 5.7 documentation:
- If Key is PRI, the column is a PRIMARY KEY or is one of the columns in a multiple-column PRIMARY KEY.
- If Key is UNI, the column is the first column of a UNIQUE index. (A UNIQUE index permits multiple NULL values, but you can tell whether the column permits NULL by checking the Null field.)
- If Key is MUL, the column is the first column of a nonunique index in which multiple occurrences of a given value are permitted within the column.
Control group, this example has neither PRI, MUL, nor UNI:
mysql> create table penguins (foo INT);
Query OK, 0 rows affected (0.01 sec)
mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| foo | int(11) | YES | | NULL | |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)
A table with one column and an index on the one column has a MUL:
mysql> create table penguins (foo INT, index(foo));
Query OK, 0 rows affected (0.01 sec)
mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| foo | int(11) | YES | MUL | NULL | |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)
A table with a column that is a primary key has PRI
mysql> create table penguins (foo INT primary key);
Query OK, 0 rows affected (0.02 sec)
mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| foo | int(11) | NO | PRI | NULL | |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)
A table with a column that is a unique key has UNI:
mysql> create table penguins (foo INT unique);
Query OK, 0 rows affected (0.01 sec)
mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| foo | int(11) | YES | UNI | NULL | |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)
A table with an index covering foo and bar has MUL only on foo:
mysql> create table penguins (foo INT, bar INT, index(foo, bar));
Query OK, 0 rows affected (0.01 sec)
mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| foo | int(11) | YES | MUL | NULL | |
| bar | int(11) | YES | | NULL | |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)
A table with two separate indexes on two columns has MUL for each one
mysql> create table penguins (foo INT, bar int, index(foo), index(bar));
Query OK, 0 rows affected (0.01 sec)
mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| foo | int(11) | YES | MUL | NULL | |
| bar | int(11) | YES | MUL | NULL | |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)
A table with an Index spanning three columns has MUL on the first:
mysql> create table penguins (foo INT,
bar INT,
baz INT,
INDEX name (foo, bar, baz));
Query OK, 0 rows affected (0.01 sec)
mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| foo | int(11) | YES | MUL | NULL | |
| bar | int(11) | YES | | NULL | |
| baz | int(11) | YES | | NULL | |
+-------+---------+------+-----+---------+-------+
3 rows in set (0.00 sec)
A table with a foreign key that references another table's primary key is MUL
mysql> create table penguins(id int primary key);
Query OK, 0 rows affected (0.01 sec)
mysql> create table skipper(id int, foreign key(id) references penguins(id));
Query OK, 0 rows affected (0.01 sec)
mysql> desc skipper;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id | int(11) | YES | MUL | NULL | |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)
mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)
Stick that in your neocortex and set the dial to "frappe".
ES6 now supports the startsWith()
and endsWith()
method for checking beginning and ending of string
s. If you want to support pre-es6 engines, you might want to consider adding one of the suggested methods to the String
prototype.
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function (str) {
return this.match(new RegExp("^" + str));
};
}
if (typeof String.prototype.endsWith != 'function') {
String.prototype.endsWith = function (str) {
return this.match(new RegExp(str + "$"));
};
}
var str = "foobar is not barfoo";
console.log(str.startsWith("foob"); // true
console.log(str.endsWith("rfoo"); // true
I'm would recommend it:
<style>
.clearfix {
*zoom: 1;
}
.clearfix:before,
.clearfix:after {
content: " ";
display: table;
}
.clearfix:after {
clear: both;
}
ul.list {
list-style: none;
}
ul.list li {
display: inline-block;
}
</style>
<ul class="list clearfix">
<li>li-one</li>
<li>li-two</li>
<li>li-three</li>
<li>li-four</li>
</ul>
This way works:
class A
{
struct Wrap
{
A& a;
Wrap(A& aa) aa(a) {}
operator int() { return a.value; }
operator std::string() { stringstream ss; ss << a.value; return ss.str(); }
}
Wrap operator*() { return Wrap(*this); }
};
It is because Bootstrap's DEFAULT CSS for <hr />
is ::
hr {
margin-top: 20px;
margin-bottom: 20px;
border: 0;
border-top: 1px solid #eeeeee;
}
it creates 40px gap between those two lines
so if you want to change any particular <hr />
margin style in your page you may try something like this ::
<hr style="margin-bottom:5px !important; margin-top:5px !important; " />
if you want to change appearance/other styles of any particular <hr />
in your page like color and border type or thickness the you may try something like :
<hr style="border-top: 1px dotted #000000 !important; " />
for all <hr />
in your page
<style>
hr {
border-top: 1px dotted #000000 !important;
margin-bottom:5px !important;
margin-top:5px !important;
}
</style>
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define MOD 1000000007
#define fo(i,k,n) for(int i=k;i<=n;++i)
#define endl '\n'
ll etf[1000001];
ll spf[1000001];
void sieve(){
ll i,j;
for(i=0;i<=1000000;i++) {etf[i]=i;spf[i]=i;}
for(i=2;i<=1000000;i++){
if(etf[i]==i){
for(j=i;j<=1000000;j+=i){
etf[j]/=i;
etf[j]*=(i-1);
if(spf[j]==j)spf[j]=i;
}
}
}
}
void primefacto(ll n,vector<pair<ll,ll>>& vec){
ll lastprime = 1,k=0;
while(n>1){
if(lastprime!=spf[n])vec.push_back(make_pair(spf[n],0));
vec[vec.size()-1].second++;
lastprime=spf[n];
n/=spf[n];
}
}
void divisors(vector<pair<ll,ll>>& vec,ll idx,vector<ll>& divs,ll num){
if(idx==vec.size()){
divs.push_back(num);
return;
}
for(ll i=0;i<=vec[idx].second;i++){
divisors(vec,idx+1,divs,num*pow(vec[idx].first,i));
}
}
void solve(){
ll n;
cin>>n;
vector<pair<ll,ll>> vec;
primefacto(n,vec);
vector<ll> divs;
divisors(vec,0,divs,1);
for(auto it=divs.begin();it!=divs.end();it++){
cout<<*it<<endl;
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
sieve();
ll t;cin>>t;
while(t--) solve();
return 0;
}
Please try the below query. Use sys.columns to get the details :-
SELECT c.name AS ColName, t.name AS TableName
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE '%MyCol%';
This query generates a list of dates 4000 days in the future and 5000 in the past as of today (inspired on http://blogs.x2line.com/al/articles/207.aspx):
SELECT * FROM (SELECT
(CONVERT(SMALLDATETIME, CONVERT(CHAR,GETDATE() ,103)) + 4000 -
n4.num * 1000 -
n3.num * 100 -
n2.num * 10 -
n1.num) AS Date,
year(CONVERT(SMALLDATETIME, CONVERT(CHAR,GETDATE() ,103)) + 4000 -
n4.num * 1000 -
n3.num * 100 -
n2.num * 10 -
n1.num) as Year,
month(CONVERT(SMALLDATETIME, CONVERT(CHAR,GETDATE() ,103)) + 4000 -
n4.num * 1000 -
n3.num * 100 -
n2.num * 10 -
n1.num) as Month,
day(CONVERT(SMALLDATETIME, CONVERT(CHAR,GETDATE() ,103)) + 4000 -
n4.num * 1000 -
n3.num * 100 -
n2.num * 10 -
n1.num) as Day
FROM (SELECT 0 AS num union ALL
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5 UNION ALL
SELECT 6 UNION ALL
SELECT 7 UNION ALL
SELECT 8 UNION ALL
SELECT 9) n1
,(SELECT 0 AS num UNION ALL
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5 UNION ALL
SELECT 6 UNION ALL
SELECT 7 UNION ALL
SELECT 8 UNION ALL
SELECT 9) n2
,(SELECT 0 AS num union ALL
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5 UNION ALL
SELECT 6 UNION ALL
SELECT 7 UNION ALL
SELECT 8 UNION ALL
SELECT 9) n3
,(SELECT 0 AS num UNION ALL
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5 UNION ALL
SELECT 6 UNION ALL
SELECT 7 UNION ALL
SELECT 8) n4
) GenCalendar ORDER BY 1
Always returning POSITION_NONE
is simple but a little inefficient way because that evoke instantiation of all page that have already instantiated.
I've created a library ArrayPagerAdapter to change items in PagerAdapters dynamically.
Internally, this library's adapters return POSITION_NONE
on getItemPosiition()
only when necessary.
You can change items dynamically like following by using this library.
@Override
protected void onCreate(Bundle savedInstanceState) {
/** ... **/
adapter = new MyStatePagerAdapter(getSupportFragmentManager()
, new String[]{"1", "2", "3"});
((ViewPager)findViewById(R.id.view_pager)).setAdapter(adapter);
adapter.add("4");
adapter.remove(0);
}
class MyPagerAdapter extends ArrayViewPagerAdapter<String> {
public MyPagerAdapter(String[] data) {
super(data);
}
@Override
public View getView(LayoutInflater inflater, ViewGroup container, String item, int position) {
View v = inflater.inflate(R.layout.item_page, container, false);
((TextView) v.findViewById(R.id.item_txt)).setText(item);
return v;
}
}
Thils library also support pages created by Fragments.
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
This will get you to a previous activity keeping its stack and clearing all activities after it from the stack.
For example, if stack was A->B->C->D and you start B with this flag, stack will be A->B
When I
git init
a folder it doesn't create a master branch
This is true, and expected behaviour. Git will not create a master
branch until you commit something.
When I do
git --bare init
it creates the files.
A non-bare git init
will also create the same files, in a hidden .git
directory in the root of your project.
When I type
git branch master
it says "fatal: Not a valid object name: 'master'"
That is again correct behaviour. Until you commit, there is no master branch.
You haven't asked a question, but I'll answer the question I assumed you mean to ask. Add one or more files to your directory, and git add
them to prepare a commit. Then git commit
to create your initial commit and master
branch.
What's happening when a members inside a class
is declared as static
..? That members can be accessed without instantiating the class
. Therefore making outer class(top level class) static
has no meaning. Therefore it is not allowed.
But you can set inner classes as static (As it is a member of the top level class). Then that class can be accessed without instantiating the top level class. Consider the following example.
public class A {
public static class B {
}
}
Now, inside a different class C
, class B
can be accessed without making an instance of class A
.
public class C {
A.B ab = new A.B();
}
static
classes can have non-static
members too. Only the class gets static.
But if the static
keyword is removed from class B
, it cannot be accessed directly without making an instance of A
.
public class C {
A a = new A();
A.B ab = a. new B();
}
But we cannot have static
members inside a non-static
inner class.
I find this at google: https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html
It mentiones that we need to
gradle-wrapper.properties
by distributionUrl=\https\://services.gradle.org/distributions/gradle-4.1-all.zip
repositories { google() }
and dependencies { classpath 'com.android.tools.build:gradle:3.0.0-beta7' }
You may require to have Android Studio 3
Finally I can fix the issue now.
At first, we need to identify or understand the problem which mostly people not really findout, my VM is came with guest OS of Ubuntu 64-bits but after import, we check on that VM it shows only 32-bits OS.
When we start the VM, we got error as:
Failed to open a session for the virtual machine ERPNext-Develop-20180331192506.
Raw-mode is unavailable courtesy of Hyper-V. (VERR_SUPDRV_NO_RAW_MODE_HYPER_V_ROOT).
Result Code: E_FAIL (0x80004005)
Component: ConsoleWrap
Interface: IConsole {872da645-4a9b-1727-bee2-5585105b9eed}
I did try above solutions, somehow not really work or I might miss something.
Then I notice the point above (32-bits OS) so I think the problem might be with this one.
With some posts around the Internet, it could explain that Windows 10 also comes with the Hyper-V which is conflict with Oracle VM VirtualBox.
So solution I did...
1. Disable Virtualization Based Security in group policy
Disable Microsoft Hyper-V
Then we can use the VM, it's started. Among the two steps above, I believe that step 2 is really solved.
Anyway, please try it and let's know if it helps.
Java 7 and up supports the Path
class (in java.nio package).
You can use this class to convert a string-path to one that works for your current OS.
Using:
Paths.get("\\folder\\subfolder").toString()
on a Unix machine, will give you /folder/subfolder
. Also works the other way around.
https://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
This is pure speculation, and not an answer.
However, I have been having this problem for a while.
I came after a time to suspect an interaction between VS and my AV precautions.
After some playing, it seems that it may have gone away when I modified my antivirus so that everything under the
C:\Users[username]\AppData\Local\Microsoft\VisualStudio\10.0\ProjectAssemblies
folder was not included in the real-time protection.
It looks as if the build actually writes the DLL here first, then copies it to the final build location.
To manipulate the stream to print in hexadecimal use the hex
manipulator:
cout << hex << a;
By default the hexadecimal characters are output in lowercase. To change it to uppercase use the uppercase
manipulator:
cout << hex << uppercase << a;
To later change the output back to lowercase, use the nouppercase
manipulator:
cout << nouppercase << b;
UTF-8 is prepared for world domination, Latin1 isn't.
If you're trying to store non-Latin characters like Chinese, Japanese, Hebrew, Russian, etc using Latin1 encoding, then they will end up as mojibake. You may find the introductory text of this article useful (and even more if you know a bit Java).
Note that full 4-byte UTF-8 support was only introduced in MySQL 5.5. Before that version, it only goes up to 3 bytes per character, not 4 bytes per character. So, it supported only the BMP plane and not e.g. the Emoji plane. If you want full 4-byte UTF-8 support, upgrade MySQL to at least 5.5 or go for another RDBMS like PostgreSQL. In MySQL 5.5+ it's called utf8mb4
.
Well then: welcome to the R world ;-)
Here you go
urls <- c(
"http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html",
"http://en.wikipedia.org/wiki/Xz",
"xxxxx"
)
readUrl <- function(url) {
out <- tryCatch(
{
# Just to highlight: if you want to use more than one
# R expression in the "try" part then you'll have to
# use curly brackets.
# 'tryCatch()' will return the last evaluated expression
# in case the "try" part was completed successfully
message("This is the 'try' part")
readLines(con=url, warn=FALSE)
# The return value of `readLines()` is the actual value
# that will be returned in case there is no condition
# (e.g. warning or error).
# You don't need to state the return value via `return()` as code
# in the "try" part is not wrapped inside a function (unlike that
# for the condition handlers for warnings and error below)
},
error=function(cond) {
message(paste("URL does not seem to exist:", url))
message("Here's the original error message:")
message(cond)
# Choose a return value in case of error
return(NA)
},
warning=function(cond) {
message(paste("URL caused a warning:", url))
message("Here's the original warning message:")
message(cond)
# Choose a return value in case of warning
return(NULL)
},
finally={
# NOTE:
# Here goes everything that should be executed at the end,
# regardless of success or error.
# If you want more than one expression to be executed, then you
# need to wrap them in curly brackets ({...}); otherwise you could
# just have written 'finally=<expression>'
message(paste("Processed URL:", url))
message("Some other message at the end")
}
)
return(out)
}
> y <- lapply(urls, readUrl)
Processed URL: http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html
Some other message at the end
Processed URL: http://en.wikipedia.org/wiki/Xz
Some other message at the end
URL does not seem to exist: xxxxx
Here's the original error message:
cannot open the connection
Processed URL: xxxxx
Some other message at the end
Warning message:
In file(con, "r") : cannot open file 'xxxxx': No such file or directory
> head(y[[1]])
[1] "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"
[2] "<html><head><title>R: Functions to Manipulate Connections</title>"
[3] "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"
[4] "<link rel=\"stylesheet\" type=\"text/css\" href=\"R.css\">"
[5] "</head><body>"
[6] ""
> length(y)
[1] 3
> y[[3]]
[1] NA
tryCatch
tryCatch
returns the value associated to executing expr
unless there's an error or a warning. In this case, specific return values (see return(NA)
above) can be specified by supplying a respective handler function (see arguments error
and warning
in ?tryCatch
). These can be functions that already exist, but you can also define them within tryCatch()
(as I did above).
The implications of choosing specific return values of the handler functions
As we've specified that NA
should be returned in case of error, the third element in y
is NA
. If we'd have chosen NULL
to be the return value, the length of y
would just have been 2
instead of 3
as lapply()
will simply "ignore" return values that are NULL
. Also note that if you don't specify an explicit return value via return()
, the handler functions will return NULL
(i.e. in case of an error or a warning condition).
"Undesired" warning message
As warn=FALSE
doesn't seem to have any effect, an alternative way to suppress the warning (which in this case isn't really of interest) is to use
suppressWarnings(readLines(con=url))
instead of
readLines(con=url, warn=FALSE)
Multiple expressions
Note that you can also place multiple expressions in the "actual expressions part" (argument expr
of tryCatch()
) if you wrap them in curly brackets (just like I illustrated in the finally
part).
Just run nodejs with proxy wrapper like tsocks tsocks node myscript.js
Original solution: Doing http requests through a SOCKS5 proxy in NodeJS
More info: https://www.binarytides.com/proxify-applications-with-tsocks-and-proxychains-on-ubuntu/
For windows: https://superuser.com/questions/319516/how-to-force-any-program-to-use-socks
$observe() is a method on the Attributes object, and as such, it can only be used to observe/watch the value change of a DOM attribute. It is only used/called inside directives. Use $observe when you need to observe/watch a DOM attribute that contains interpolation (i.e., {{}}'s).
E.g., attr1="Name: {{name}}"
, then in a directive: attrs.$observe('attr1', ...)
.
(If you try scope.$watch(attrs.attr1, ...)
it won't work because of the {{}}s -- you'll get undefined
.) Use $watch for everything else.
$watch() is more complicated. It can observe/watch an "expression", where the expression can be either a function or a string. If the expression is a string, it is $parse'd (i.e., evaluated as an Angular expression) into a function. (It is this function that is called every digest cycle.) The string expression can not contain {{}}'s. $watch is a method on the Scope object, so it can be used/called wherever you have access to a scope object, hence in
Because strings are evaluated as Angular expressions, $watch is often used when you want to observe/watch a model/scope property. E.g., attr1="myModel.some_prop"
, then in a controller or link function: scope.$watch('myModel.some_prop', ...)
or scope.$watch(attrs.attr1, ...)
(or scope.$watch(attrs['attr1'], ...)
).
(If you try attrs.$observe('attr1')
you'll get the string myModel.some_prop
, which is probably not what you want.)
As discussed in comments on @PrimosK's answer, all $observes and $watches are checked every digest cycle.
Directives with isolate scopes are more complicated. If the '@' syntax is used, you can $observe or $watch a DOM attribute that contains interpolation (i.e., {{}}'s). (The reason it works with $watch is because the '@' syntax does the interpolation for us, hence $watch sees a string without {{}}'s.) To make it easier to remember which to use when, I suggest using $observe for this case also.
To help test all of this, I wrote a Plunker that defines two directives. One (d1
) does not create a new scope, the other (d2
) creates an isolate scope. Each directive has the same six attributes. Each attribute is both $observe'd and $watch'ed.
<div d1 attr1="{{prop1}}-test" attr2="prop2" attr3="33" attr4="'a_string'"
attr5="a_string" attr6="{{1+aNumber}}"></div>
Look at the console log to see the differences between $observe and $watch in the linking function. Then click the link and see which $observes and $watches are triggered by the property changes made by the click handler.
Notice that when the link function runs, any attributes that contain {{}}'s are not evaluated yet (so if you try to examine the attributes, you'll get undefined
). The only way to see the interpolated values is to use $observe (or $watch if using an isolate scope with '@'). Therefore, getting the values of these attributes is an asynchronous operation. (And this is why we need the $observe and $watch functions.)
Sometimes you don't need $observe or $watch. E.g., if your attribute contains a number or a boolean (not a string), just evaluate it once: attr1="22"
, then in, say, your linking function: var count = scope.$eval(attrs.attr1)
. If it is just a constant string – attr1="my string"
– then just use attrs.attr1
in your directive (no need for $eval()).
See also Vojta's google group post about $watch expressions.
Did you import the packages for the file reading stuff.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
also here
cfiltering(numberOfUsers, numberOfMovies);
Are you trying to create an object or calling a method?
also another thing:
user_movie_matrix[userNo][movieNo]=rating;
you are assigning a value to a member of an instance as if it was a static variable
also remove the Th
in
private int user_movie_matrix[][];Th
Hope this helps.
Okay you must try this guys it works for me:
Try below code.. Put This Code in On Create..
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Url="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTIur0ueOsmVmFVmAA-SxcCT7bTodZb3eCNbiShIiP9qWCWk3mDfw";
// Picasso.with(getContext()).load(Url).into(img_profile);
// Picasso.with(getContext()).load(Url).into(img_c_profile);
bitmap=getBitmapFromURL(Url);
Bitmap blurred = blurRenderScript(bitmap, 12);//second parametre is radius
img_profile.setImageBitmap(blurred);
Create Below Methods.. Just Copy Past..
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
// Log exception
return null;
}
}
@SuppressLint("NewApi")
private Bitmap blurRenderScript(Bitmap smallBitmap, int radius) {
try {
smallBitmap = RGB565toARGB888(smallBitmap);
} catch (Exception e) {
e.printStackTrace();
}
Bitmap bitmap = Bitmap.createBitmap(
smallBitmap.getWidth(), smallBitmap.getHeight(),
Bitmap.Config.ARGB_8888);
RenderScript renderScript = RenderScript.create(getActivity());
Allocation blurInput = Allocation.createFromBitmap(renderScript, smallBitmap);
Allocation blurOutput = Allocation.createFromBitmap(renderScript, bitmap);
ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(renderScript,
Element.U8_4(renderScript));
blur.setInput(blurInput);
blur.setRadius(radius); // radius must be 0 < r <= 25
blur.forEach(blurOutput);
blurOutput.copyTo(bitmap);
renderScript.destroy();
return bitmap;
}
private Bitmap RGB565toARGB888(Bitmap img) throws Exception {
int numPixels = img.getWidth() * img.getHeight();
int[] pixels = new int[numPixels];
//Get JPEG pixels. Each int is the color values for one pixel.
img.getPixels(pixels, 0, img.getWidth(), 0, 0, img.getWidth(), img.getHeight());
//Create a Bitmap of the appropriate format.
Bitmap result = Bitmap.createBitmap(img.getWidth(), img.getHeight(), Bitmap.Config.ARGB_8888);
//Set RGB pixels.
result.setPixels(pixels, 0, result.getWidth(), 0, 0, result.getWidth(), result.getHeight());
return result;
}
it would be something like this
sqlplus -s /nolog <<-!
connect ${ORACLE_UID}/${ORACLE_PWD}@${ORACLE_DB};
whenever sqlerror exit sql.sqlcode;
set pagesize 0;
set linesize 150;
spool <query_output.dat> APPEND
@$<input_query.dat>
spool off;
exit;
!
here
ORACLE_UID=<user name>
ORACLE_PWD=<password>
ORACLE_DB=//<host>:<port>/<DB name>
Properties in your object are value types and you can use the shallow copy in such situation like that:
obj myobj2 = (obj)myobj.MemberwiseClone();
But in other situations, like if any members are reference types, then you need Deep Copy. You can get a deep copy of an object using Serialization
and Deserialization
techniques with the help of BinaryFormatter
class:
public static T DeepCopy<T>(T other)
{
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Context = new StreamingContext(StreamingContextStates.Clone);
formatter.Serialize(ms, other);
ms.Position = 0;
return (T)formatter.Deserialize(ms);
}
}
The purpose of setting StreamingContext
:
We can introduce special serialization and deserialization logic to our code with the help of either implementing ISerializable
interface or using built-in attributes like OnDeserialized
, OnDeserializing
, OnSerializing
, OnSerialized
. In all cases StreamingContext
will be passed as an argument to the methods(and to the special constructor in case of ISerializable
interface). With setting ContextState
to Clone
, we are just giving hint to that method about the purpose of the serialization.
Additional Info: (you can also read this article from MSDN)
Shallow copying is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed; for a reference type, the reference is copied but the referred object is not; therefore the original object and its clone refer to the same object.
Deep copy is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, a new copy of the referred object is performed.
After trying most of the solutions here, the easiest thing I found was the obvious - using a temp file. I'm not sure what you want to do with your multiple line output, but you can then deal with it line by line using read. About the only thing you can't really do is easily stick it all in the same variable, but for most practical purposes this is way easier to deal with.
./myscript.sh > /tmp/foo
while read line ; do
echo 'whatever you want to do with $line'
done < /tmp/foo
Quick hack to make it do the requested action:
result=""
./myscript.sh > /tmp/foo
while read line ; do
result="$result$line\n"
done < /tmp/foo
echo -e $result
Note this adds an extra line. If you work on it you can code around it, I'm just too lazy.
EDIT: While this case works perfectly well, people reading this should be aware that you can easily squash your stdin inside the while loop, thus giving you a script that will run one line, clear stdin, and exit. Like ssh will do that I think? I just saw it recently, other code examples here: https://unix.stackexchange.com/questions/24260/reading-lines-from-a-file-with-bash-for-vs-while
One more time! This time with a different filehandle (stdin, stdout, stderr are 0-2, so we can use &3 or higher in bash).
result=""
./test>/tmp/foo
while read line <&3; do
result="$result$line\n"
done 3</tmp/foo
echo -e $result
you can also use mktemp, but this is just a quick code example. Usage for mktemp looks like:
filenamevar=`mktemp /tmp/tempXXXXXX`
./test > $filenamevar
Then use $filenamevar like you would the actual name of a file. Probably doesn't need to be explained here but someone complained in the comments.
If you are using Oracle 12c, use:
FETCH NEXT N ROWS ONLY
SELECT DISTINCT
APP_ID,
NAME,
STORAGE_GB,
HISTORY_CREATED,
TO_CHAR(HISTORY_DATE, 'DD.MM.YYYY') AS HISTORY_DATE
FROM HISTORY WHERE
STORAGE_GB IS NOT NULL AND
APP_ID NOT IN (SELECT APP_ID FROM HISTORY WHERE TO_CHAR(HISTORY_DATE, 'DD.MM.YYYY') ='06.02.2009')
ORDER BY STORAGE_GB DESC
FETCH NEXT 10 ROWS ONLY
More info: http://docs.oracle.com/javadb/10.5.3.0/ref/rrefsqljoffsetfetch.html
#Single line
'''
multi-line
comment
'''
"""
also,
multi-line comment
"""
Solid Code Optimizing the Software Development Life Cycle
Although the book is only 300 pages and favors Microsoft technologies it still offers some good language agnostic tidbits.
What you need to do is set a token to your area name:
for instance:
context.MapRoute(
"SomeArea_default",
"SomeArea/{controller}/{action}/{id}",
new { controller = "SomeController", action = "Index", id = UrlParameter.Optional }
).DataTokens.Add("area", "YOURAREANAME");
java.nio.BufferOverflowException during from dex error This means you don't have the supporting API for that level hence the build fails, there are a number of ways you can fix this.
Check your manifest file uses-sdk android:minSdkVersion="4" and android:targetSdkVersion="14"
Any of the below will fix the problem:-
As of June 2016 (using jquery 2.1.4) none of the other suggested solutions work. Checking attr('checked')
always returns undefined
and is('checked)
always returns false
.
Just use the prop method:
$("#checkbox").change(function(e) {
if ($(this).prop('checked')){
console.log('checked');
}
});
One possible solution to this issue is ng-model
attribute is required to use that directive.
Hence adding in the 'ng-model' attribute can resolve the issue.
<input submit-required="true" ng-model="user.Name"></input>
This should work with this :
var cnt = $("#div1 p").length;
switch (true) {
case (cnt >= 10 && cnt <= 20):
alert('10');
break;
case (cnt >= 21 && cnt <= 30):
alert('21');
break;
case (cnt >= 31 && cnt <= 40):
break;
default:
alert('>41');
}
Open the Terminal
->
copy
below command
sudo gem install cocoapods
It will install the latest stable version of cocoapods
.
after that, you need to update pod using below command
pod setup
You can check pod version using below command
pod --version
To Sidebar ceased to be white:
if you installed the theme setUI, setUI file.sublime-the theme is looking for the line with comment:
"// sidebar || BG of selected files"
and under it a string
"layer0. opacity: { "target": 0.0, "speed": 50.0, "interpolation": "smoothstep" }
replaceable target": 0.0 --> target": 1.0
This is how I do it in TypeScript:
const index = this.array.indexOf(this.objectToReplace);
this.array[index] = newObject;
bash has a builtin
pushd SOME_PATH
run_stuff
...
...
popd
Iterate on array1 and find the indexof element present in array2.
var array1 = ["cat", "sum","fun", "run"];
var array2 = ["bat", "cat","sun", "hut", "gut"];
var str='';
for(var i=0;i<array1.length;i++){
if(array2.indexOf(array1[i]) != -1){
str+=array1[i]+' ';
};
}
console.log(str)
such as this kind of dataframe, there are two levels of thecolumn name:
shop_id item_id date_block_num item_cnt_day
target
0 0 30 1 31
we can use this code:
df.columns = [col[0] if col[-1]=='' else col[-1] for col in df.columns.values]
result is:
shop_id item_id date_block_num target
0 0 30 1 31
Install from package manager:
sudo apt-get install phantomjs
this shoude work
<?php
require_once('connection.php');
//fetch table rows from mysql db
$sql = "select id,fname,lname,sms,phone from data";
$result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));
//create an array
$emparray = array();
for ($i = 0; $i < 1; $i++) {
$row =mysqli_fetch_assoc($result);
} $emparray[] = $row;
echo $emparray ;
mysqli_close($connection);
?>
Use
item.Attributes["Name"].Value;
to get the value.
The player_api will be deprecated on Jun 25, 2015. For play youtube videos there is a new api IFRAME_API
It looks like the following code:
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
If you need the subdirectories too you need a "dir" command and a "For" command
dir /b /s DIRECTORY\*.* > list1.txt
for /f "tokens=*" %%A in (list1.txt) do echo %%~nxA >> list.txt
del list1.txt
put your root directory in dir command. It will create a list1.txt with full path names and then a list.txt with only the file names.
Ref: Apache redirect www to non-www and HTTP to HTTPS
to
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]
If instead of example.com you want the default URL to be www.example.com, then simply change the third and the fifth lines:
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [L,NE,R=301]
I don't see it mentioned here, but splatting your arguments is a useful alternative and becomes especially useful if you are building out the arguments to a command dynamically (as opposed to using Invoke-Expression
). You can splat with arrays for positional arguments and hashtables for named arguments. Here are some examples:
Test-Connection www.google.com localhost
$argumentArray = 'www.google.com', 'localhost'
Test-Connection @argumentArray
Note that when splatting, we reference the splatted variable with an
@
instead of a$
. It is the same when using a Hashtable to splat as well.
Test-Connection -ComputerName www.google.com -Source localhost
$argumentHash = @{
ComputerName = 'www.google.com'
Source = 'localhost'
}
Test-Connection @argumentHash
Test-Connection www.google.com localhost -Count 1
$argumentHash = @{
Count = 1
}
$argumentArray = 'www.google.com', 'localhost'
Test-Connection @argumentHash @argumentArray
Incredibly old question, but bearing in mind that the OP said he does not want to use Do While
and that none of the other solutions really work... Here's something that does exactly the same as a Exit Loop
:
This never runs anything if the status is already at "Fail"...
While (i < 20 And Not bShouldStop)
If (Status = "Fail") Then
bShouldStop = True
Else
i = i + 1
'
' Do Something
'
End If
Wend
Whereas this one always processes something first (and increment the loop variable) before deciding whether it should loop once more or not.
While (i < 20 And Not bShouldStop)
i = i + 1
'
' Do Something
'
If (Status = "Fail") Then
bShouldStop = True
End If
Wend
Ultimately, if the variable Status
is being modified inside the While
(and assuming you don't need i
outside the while, it makes no difference really, but just wanted to present multiple options...
You can use Jinja's default
:
- name: Create user
user:
name: "{{ my_variable | default('default_value') }}"
Should be xpath with not contains() method, //production[not(contains(category,'business'))]
do not forget add "use Illuminate\Http\Request;" on your controller
List<SubProduct> subProducts= (List<SubProduct>)Model.subproduct;
The implicit conversion failes because List<>
implements IList
, not viceversa. So you can say IList<T> foo = new List<T>()
, but not List<T> foo = (some IList-returning method or property)
.
All the benchmarks presented here have some flaws, thus results are not reliable.
I was surprised that nobody used JMH for benchmarking, so I did.
Results:
Benchmark Mode Cnt Score Error Units
MyBenchmark.testOld thrpt 20 9645.834 ± 238.165 ops/s // using +
MyBenchmark.testNew thrpt 20 429.898 ± 10.551 ops/s // using String.format
Units are operations per second, the more the better. Benchmark source code. OpenJDK IcedTea 2.5.4 Java Virtual Machine was used.
So, old style (using +) is much faster.
Ok for the adapter FragmentStatePagerAdapter
I fund a solution :
in your FragmentActivity :
ActionBar mActionBar = getSupportActionBar();
mActionBar.addTab(mActionBar.newTab().setText("TAB1").setTabListener(this).setTag(Fragment.instantiate(this, MyFragment1.class.getName())));
mActionBar.addTab(mActionBar.newTab().setText("TAB2").setTabListener(this).setTag(Fragment.instantiate(this, MyFragment2.class.getName())));
mActionBar.addTab(mActionBar.newTab().setText("TAB3").setTabListener(this).setTag(Fragment.instantiate(this, MyFragment3.class.getName())));
viewPager = (STViewPager) super.findViewById(R.id.viewpager);
mPagerAdapter = new MyPagerAdapter(getSupportFragmentManager(), mActionBar);
viewPager.setAdapter(this.mPagerAdapter);
and create a methode in your class FragmentActivity - So that method give you access to your Fragment, you just need to give it the position of the fragment you want:
public Fragment getActiveFragment(int position) {
String name = MyPagerAdapter.makeFragmentName(position);
return getSupportFragmentManager().findFragmentByTag(name);
}
in your Adapter :
public class MyPagerAdapter extends FragmentStatePagerAdapter {
private final ActionBar actionBar;
private final FragmentManager fragmentManager;
public MyPagerAdapter(FragmentManager fragmentManager, com.actionbarsherlock.app.ActionBarActionBar mActionBar) {super(fragmentManager);
this.actionBar = mActionBar;
this.fragmentManager = fragmentManager;
}
@Override
public Fragment getItem(int position) {
getSupportFragmentManager().beginTransaction().add(mTchatDetailsFragment, makeFragmentName(position)).commit();
return (Fragment)this.actionBar.getTabAt(position);
}
@Override
public int getCount() {
return this.actionBar.getTabCount();
}
@Override
public CharSequence getPageTitle(int position) {
return this.actionBar.getTabAt(position).getText();
}
private static String makeFragmentName(int viewId, int index) {
return "android:fragment:" + index;
}
}
I got this to work by Populating a SelectListItem, converting to an List, and adding a value at index 0.
List<SelectListItem> items = new SelectList(CurrentViewSetups, "SetupId", "SetupName", setupid).ToList();
items.Insert(0, (new SelectListItem { Text = "[None]", Value = "0" }));
ViewData["SetupsSelectList"] = items;
Old question but I think it lacked an answer. I would use an adjacent siblings selector. This way we only write "one" line of CSS and take into consideration the space at the end or beginning, which most of the answers lacks.
li + li {
margin-top: 10px;
}
As some of the other answers have stated, you probably use an alias somewhere which maps cp
to cp -i
or something similar. You can run a command without any aliases by preceding it with a backslash. In your case, try
\cp -r /zzz/zzz/* /xxx/xxx
The backslash will temporarily disable any aliases you have called cp
.
You can use AngularJs for this, Its two -way data binding feature will get solution with minimum effort and less code.
<div>
<input type="text" name="" ng-model="fbid"><br/>
<img src="https://graph.facebook.com/{{fbid}}/picture?type=normal">
</div>
I hope this answers your query.Note: You can use other library as well.
Is there any other way to convert that array into string ?
You don't want to convert the array to a string, you want to get the value of the array's sole element, if I read it correctly.
<?php
$foo = array( 18 => 'Something' );
$value = array_shift( $foo );
echo $value; // 'Something'.
?>
Using array_shift you don't have to worry about the index.
EDIT: Mind you, array_shift is not the only function that will return a single value. array_pop( ), current( ), end( ), reset( ), they will all return that one single element. All of the posted solutions work. Using array shift though, you can be sure that you'll only ever get the first value of the array, even when there are multiple.
You can use a Deferred objects for ASYNC loading.
function load_img_async(source) {
return $.Deferred (function (task) {
var image = new Image();
image.onload = function () {task.resolve(image);}
image.onerror = function () {task.reject();}
image.src=source;
}).promise();
}
$.when(load_img_async(IMAGE_URL)).done(function (image) {
$(#id).empty().append(image);
});
Please pay attention: image.onload must be before image.src to prevent problems with cache.
The alternative for explode in php is split.
The first parameter is the delimiter, the second parameter the maximum number splits. The parts are returned without the delimiter present (except possibly the last part). When the delimiter is None, all whitespace is matched. This is the default.
>>> "Rajasekar SP".split()
['Rajasekar', 'SP']
>>> "Rajasekar SP".split('a',2)
['R','j','sekar SP']
Given the fact that you can switch to origin/master
(though in detached state) while having your network cable unplugged, it must be a local representation of the master
branch at origin
.
In addition to the previous answers, you can also do Ctrl + A, and then enter colon (:), and you will notice a little input box at the bottom left. Type 'quit' and Enter to leave the current screen session. Note that this will remove your screen session.
Ctrl + A and then K will only kill the current window in the current session, not the whole session. A screen session consists of windows, which can be created using subsequent Ctrl + A followed by C. These windows can be viewed in a list using Ctrl + A + ".
here's a pure Javascript alternative:
var mydiv = document.getElementById("myDiv");
var aTag = document.createElement('a');
aTag.setAttribute('href',"yourlink.htm");
aTag.innerText = "link text";
mydiv.appendChild(aTag);
Utilities.sleep(milliseconds) creates a 'pause' in program execution, meaning it does nothing during the number of milliseconds you ask. It surely slows down your whole process and you shouldn't use it between function calls. There are a few exceptions though, at least that one that I know : in SpreadsheetApp when you want to remove a number of sheets you can add a few hundreds of millisecs between each deletion to allow for normal script execution (but this is a workaround for a known issue with this specific method). I did have to use it also when creating many sheets in a spreadsheet to avoid the Browser needing to be 'refreshed' after execution.
Here is an example :
function delsheets(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var numbofsheet=ss.getNumSheets();// check how many sheets in the spreadsheet
for (pa=numbofsheet-1;pa>0;--pa){
ss.setActiveSheet(ss.getSheets()[pa]);
var newSheet = ss.deleteActiveSheet(); // delete sheets begining with the last one
Utilities.sleep(200);// pause in the loop for 200 milliseconds
}
ss.setActiveSheet(ss.getSheets()[0]);// return to first sheet as active sheet (useful in 'list' function)
}
Just create a small delete function which can help you to achieve this task, I have tested this code and it runs perfectly well.
This function deletes files older than 90 days as well as a file with extension .zip to be deleted from a folder.
Private Sub DeleteZip()
Dim eachFileInMydirectory As New DirectoryInfo("D:\Test\")
Dim fileName As IO.FileInfo
Try
For Each fileName In eachFileInMydirectory.GetFiles
If fileName.Extension.Equals("*.zip") AndAlso (Now - fileName.CreationTime).Days > 90 Then
fileName.Delete()
End If
Next
Catch ex As Exception
WriteToLogFile("No Files older than 90 days exists be deleted " & ex.Message)
End Try
End Sub
The most likely reason would be that something else is using port 80. (Often this can be Skype, IIS, etc.)
This tutorials shows How to Change the Apache Port in XAMPP
I have been trying to attach an audio which should autoplay and will be hidden. It's very simple. Just a few lines of HTML and CSS. Check this out!! Here is the piece of code I used within the body.
<div id="player">
<audio controls autoplay hidden>
<source src="file.mp3" type="audio/mpeg">
unsupported !!
</audio>
</div>
In case if you want to implement your own Array.Copy method.
Static method which is of generic type.
static void MyCopy<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long destinationIndex, long copyNoOfElements)
{
long totaltraversal = sourceIndex + copyNoOfElements;
long sourceArrayLength = sourceArray.Length;
//to check all array's length and its indices properties before copying
CheckBoundaries(sourceArray, sourceIndex, destinationArray, copyNoOfElements, sourceArrayLength);
for (long i = sourceIndex; i < totaltraversal; i++)
{
destinationArray[destinationIndex++] = sourceArray[i];
}
}
Boundary method implementation.
private static void CheckBoundaries<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long copyNoOfElements, long sourceArrayLength)
{
if (sourceIndex >= sourceArray.Length)
{
throw new IndexOutOfRangeException();
}
if (copyNoOfElements > sourceArrayLength)
{
throw new IndexOutOfRangeException();
}
if (destinationArray.Length < copyNoOfElements)
{
throw new IndexOutOfRangeException();
}
}
This is built on some of the previous answers and comments. The following covers all the edge cases and fairly concise as well:
const isNumRegEx = /^-?(\d*\.)?\d+$/;
function isNumeric(n, allowScientificNotation = false) {
return allowScientificNotation ?
!Number.isNaN(parseFloat(n)) && Number.isFinite(n) :
isNumRegEx.test(n);
}
Another way to solve this using xpath
WebDriver driver = new FirefoxDriver();
driver.get("https://www.facebook.com/");
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.xpath(//*[@id='email'])).sendKeys("[email protected]");
Hope that will help. :)
if you using localhost just change it :
from :http://localhost:3030
to :http://10.0.2.2:3030
You can also make use of FilesystemIterator
. It requires even less code then DirectoryIterator
, and automatically removes .
and ..
.
// Let's traverse the images directory
$fileSystemIterator = new FilesystemIterator('images');
$entries = array();
foreach ($fileSystemIterator as $fileInfo){
$entries[] = $fileInfo->getFilename();
}
var_dump($entries);
//OUTPUT
object(FilesystemIterator)[1]
array (size=14)
0 => string 'aa[1].jpg' (length=9)
1 => string 'Chrysanthemum.jpg' (length=17)
2 => string 'Desert.jpg' (length=10)
3 => string 'giphy_billclinton_sad.gif' (length=25)
4 => string 'giphy_shut_your.gif' (length=19)
5 => string 'Hydrangeas.jpg' (length=14)
6 => string 'Jellyfish.jpg' (length=13)
7 => string 'Koala.jpg' (length=9)
8 => string 'Lighthouse.jpg' (length=14)
9 => string 'Penguins.jpg' (length=12)
10 => string 'pnggrad16rgb.png' (length=16)
11 => string 'pnggrad16rgba.png' (length=17)
12 => string 'pnggradHDrgba.png' (length=17)
13 => string 'Tulips.jpg' (length=10)
Adding points to the accepted answer:
See the usage of IntentService within Android API. eg:
public class SimpleWakefulService extends IntentService {
public SimpleWakefulService() {
super("SimpleWakefulService");
}
@Override
protected void onHandleIntent(Intent intent) { ...}
To create an IntentService component for your app, define a class that extends IntentService, and within it, define a method that overrides onHandleIntent().
Also, see the source code of the IntentService, it's constructor and life cycle methods like onStartCommand...
@Override
public int More ...onStartCommand(Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
Service together an AsyncTask is one of best approaches for many use cases where the payload is not huge. or just create a class extending IntentSerivce. From Android version 4.0 all network operations should be in background process otherwise the application compile/build fails. separate thread from the UI. The AsyncTask class provides one of the simplest ways to fire off a new task from the UI thread. For more discussion of this topic, see the blog post
from Android developers guide:
IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent, in turn, using a worker thread, and stops itself when it runs out of work.
Design pattern used in IntentService
: This "work queue processor" pattern is commonly used to offload tasks from an application's main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.
All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.
The IntentService class provides a straightforward structure for running an operation on a single background thread. This allows it to handle long-running operations without affecting your user interface's responsiveness. Also, an IntentService isn't affected by most user interface lifecycle events, so it continues to run in circumstances that would shut down an AsyncTask.
An IntentService has a few limitations:
It can't interact directly with your user interface. To put its results in the UI, you have to send them to an Activity. Work requests run sequentially. If an operation is running in an IntentService, and you send it another request, the request waits until the first operation is finished. An operation running on an IntentService can't be interrupted. However, in most cases
IntentService is the preferred way to simple background operations
**
Volley Library
There is the library called volley-library for developing android networking applications The source code is available for the public in GitHub.
The android official documentation for Best practices for Background jobs: helps better understand on intent service, thread, handler, service. and also Performing Network Operations
mkdirs()
also creates parent directories in the path this File
represents.
javadocs for mkdirs()
:
Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.
javadocs for mkdir()
:
Creates the directory named by this abstract pathname.
Example:
File f = new File("non_existing_dir/someDir");
System.out.println(f.mkdir());
System.out.println(f.mkdirs());
will yield false
for the first [and no dir will be created], and true
for the second, and you will have created non_existing_dir/someDir
A one-liner for creating string of HTML attributes (with quotes) from a simple array:
$attrString = str_replace("+", " ", str_replace("&", "\" ", str_replace("=", "=\"", http_build_query($attrArray)))) . "\"";
$attrArray = array("id" => "email",
"name" => "email",
"type" => "email",
"class" => "active large");
echo str_replace("+", " ", str_replace("&", "\" ", str_replace("=", "=\"", http_build_query($attrArray)))) . "\"";
// Output:
// id="email" name="email" type="email" class="active large"
use mysql_real_escape_string
So what does mysql_real_escape_string do?
This PHP library function prepends backslashes to the following characters: \n, \r, \, \x00, \x1a, ‘ and “. The important part is that the single and double quotes are escaped, because these are the characters most likely to open up vulnerabilities.
Please inform yourself about sql_injection. You can use this link as a start
In my case I needed the base URL similar to the RewriteBase
contained in the .htaccess
file.
Unfortunately simply retrieving the RewriteBase
from the .htaccess
file is impossible with PHP. But it is possible to set an environment variable in the .htaccess file and then retrieve that variable in PHP. Just check these bits of code out:
.htaccess
SetEnv BASE_PATH /
index.php
Now I use this in the base tag of the template (in the head section of the page):
<base href="<?php echo ! empty( getenv( 'BASE_PATH' ) ) ? getenv( 'BASE_PATH' ) : '/'; ?>"/>
So if the variable was not empty, we use it. Otherwise fallback to /
as default base path.
Based on the environment the base url will always be correct. I use /
as the base url on local and production websites. But /foldername/
for on the staging environment.
They all had their own .htaccess
in the first place because the RewriteBase was different. So this solution works for me.
Use the PlaceHolder control as a container to store server controls that are dynamically added to the Web page. The PlaceHolder control does not produce any visible output and is used only as a container for other controls on the Web page. You can use the Control.Controls
collection to add, insert, or remove a control in the PlaceHolder control.
The Panel control is a container for other controls. It is especially useful when you want to generate controls programmatically, hide/show a group of controls, or localize a group of controls.
The Direction
property is useful for localizing a Panel control's content to display text for languages that are written from right to left, such as Arabic or Hebrew.
The Panel control provides several properties that allow you to customize the behavior and display of its contents. Use the BackImageUr
l property to display a custom image for the Panel control. Use the ScrollBars
property to specify scroll bars for the control.
Small differences when rendering HTML: a PlaceHolder control will render nothing, but Panel control will render as a <div>
.
More information at ASP.NET Forums
You need to extract the number from the string, and pass it into the Date constructor
:
var x = [{
"id": 1,
"start": "\/Date(1238540400000)\/"
}, {
"id": 2,
"start": "\/Date(1238626800000)\/"
}];
var myDate = new Date(x[0].start.match(/\d+/)[0] * 1);
The parts are:
x[0].start - get the string from the JSON
x[0].start.match(/\d+/)[0] - extract the numeric part
x[0].start.match(/\d+/)[0] * 1 - convert it to a numeric type
new Date(x[0].start.match(/\d+/)[0] * 1)) - Create a date object
The logic is wrong. Consider this:
x = ["a","b","c"]
x[0] // "a"
x["0"] // "a"
0 in x // true
"0" in x // true
x.hasOwnProperty(0) // true
x.hasOwnProperty("0") // true
There is no reason to loop to check for key (or indices for arrays) existence. Now, values are a different story...
Happy coding
this code will return duplicate value in same array
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
foreach($arr as $key=>$item){
if(array_count_values($arr)[$item] > 1){
echo "Found Matched value : ".$item." <br />";
}
}
Below is a minimal code to achieve the effect.
This also works responsively since the border-radius
is in percentage.
.semi-circle{_x000D_
width: 200px;_x000D_
height: 100px;_x000D_
border-radius: 50% 50% 0 0 / 100% 100% 0 0;_x000D_
border: 10px solid #000;_x000D_
border-bottom: 0;_x000D_
}
_x000D_
<div class="semi-circle"></div>
_x000D_
Adding solution for CentOs 7 (python 3.6.x)
yum install python36-tkinter
I had tried about every version possible, hopefully this helps out others.
Here is how to do dump the database (with just the schema):
mysqldump -u root -p"passwd" --no-data --add-drop-database --databases my_db_name | sed 's#/[*]!40000 DROP DATABASE IF EXISTS my_db_name;#' >my_db_name.sql
If you also want the data, remove the --no-data
option.
Swift 4.1 and 5. We use queues in many places in our code. So, I created Threads class with all queues. If you don't want to use Threads class you can copy the desired queue code from class methods.
class Threads {
static let concurrentQueue = DispatchQueue(label: "AppNameConcurrentQueue", attributes: .concurrent)
static let serialQueue = DispatchQueue(label: "AppNameSerialQueue")
// Main Queue
class func performTaskInMainQueue(task: @escaping ()->()) {
DispatchQueue.main.async {
task()
}
}
// Background Queue
class func performTaskInBackground(task:@escaping () throws -> ()) {
DispatchQueue.global(qos: .background).async {
do {
try task()
} catch let error as NSError {
print("error in background thread:\(error.localizedDescription)")
}
}
}
// Concurrent Queue
class func perfromTaskInConcurrentQueue(task:@escaping () throws -> ()) {
concurrentQueue.async {
do {
try task()
} catch let error as NSError {
print("error in Concurrent Queue:\(error.localizedDescription)")
}
}
}
// Serial Queue
class func perfromTaskInSerialQueue(task:@escaping () throws -> ()) {
serialQueue.async {
do {
try task()
} catch let error as NSError {
print("error in Serial Queue:\(error.localizedDescription)")
}
}
}
// Perform task afterDelay
class func performTaskAfterDealy(_ timeInteval: TimeInterval, _ task:@escaping () -> ()) {
DispatchQueue.main.asyncAfter(deadline: (.now() + timeInteval)) {
task()
}
}
}
Example showing the use of main queue.
override func viewDidLoad() {
super.viewDidLoad()
Threads.performTaskInMainQueue {
//Update UI
}
}
Now (2021) the preferred way to use istanbul is via its "state of the art command line interface" nyc.
First, install it in your project with
npm i nyc --save-dev
Then, if you have a npm based project, just change the test script inside the scripts
object of your package.json file to execute code coverage of your mocha tests:
{
"scripts": {
"test": "nyc --reporter=text mocha"
}
}
Now run your tests
npm test
and you will see a table like this in your console, just after your tests output:
Just use
nyc --reporter=html
instead of text
. Now it will produce a report inside ./coverage/index.html
.
Istanbul supports a wide range of report formats. Just look at its reports library to find the most useful for you.
Just add a --reporter=REPORTER_NAME
option for each format you want.
For example, with
nyc --reporter=html --reporter=text
you will have both the console and the html report.
Just add another script in your package.json
and leave the test
script with only your test runner (e.g. mocha):
{
"scripts": {
"test": "mocha",
"test-with-coverage": "nyc --reporter=text mocha"
}
}
Now run this custom script
npm run test-with-coverage
to run tests with code coverage.
Fail if the total code coverage is below 90%:
nyc --check-coverage --lines 90
Fail if the code coverage of at least one file is below 90%:
nyc --check-coverage --lines 90 --per-file
SELECT
Q.DateInQuarter,
D.[Year],
Quarter = D.Year + '-Q'
+ Convert(varchar(1), ((Q.DateInQuarter % 10000 - 100) / 300 + 1))
FROM
dbo.QuarterDates Q
CROSS APPLY (
VALUES (Convert(varchar(4), Q.DateInQuarter / 10000))
) D ([Year])
;
I have a GIST for this and the usage is pretty simple
watchfiles <cmd> <paths...>
To illustrate, the following command will echo Hello World
every time that file1
OR file2
change; and the default interval check is 1 second
watchfiles 'echo Hello World' /path/to/file1 /path/to/file2
If I want to check every 5 seconds I can use the -t
flag
watchfiles -t 'echo Hello World' /path/to/file1 /path/to/file2
-v
enables the verbose
mode which shows debug information-q
makes watchfiles
execute quietly (#
will be shown so the user can see the program is executing)-qq
makes watchfiles
execute completely quietly-h
shows the help and usagehttps://gist.github.com/thiagoh/5d8f53bfb64985b94e5bc8b3844dba55
It may not be quite what you want, since it's not a standard command on anyone's systems, but since my program should work fine on POSIX systems (if compiled), I'll mention it anyway. If you have the ability to compile or add programs on the machine in question, it should work.
I've used it without issue for about a year now, but it could be that it won't handle some edge cases. Most specifically, I have no idea what it would do with newlines in strings; a case for \\n
might need to be added. This list of characters is not authoritative, but I believe it covers everything else.
I wrote this specifically as a 'helper' program so I could make a wrapper for things like scp
commands.
It can likely be implemented as a shell function as well
I therefore present escapify.c
. I use it like so:
scp user@host:"$(escapify "/this/path/needs to be escaped/file.c")" destination_file.c
PLEASE NOTE: I made this program for my own personal use. It also will (probably wrongly) assume that if it is given more than one argument that it should just print an unescaped space and continue on. This means that it can be used to pass multiple escaped arguments correctly, but could be seen as unwanted behavior by some.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
char c='\0';
int i=0;
int j=1;
/* do not care if no args passed; escaped nothing is still nothing. */
if(argc < 2)
{
return 0;
}
while(j<argc)
{
while(i<strlen(argv[j]))
{
c=argv[j][i];
/* this switch has no breaks on purpose. */
switch(c)
{
case ';':
case '\'':
case ' ':
case '!':
case '"':
case '#':
case '$':
case '&':
case '(':
case ')':
case '|':
case '*':
case ',':
case '<':
case '>':
case '[':
case ']':
case '\\':
case '^':
case '`':
case '{':
case '}':
putchar('\\');
default:
putchar(c);
}
i++;
}
j++;
if(j<argc) {
putchar(' ');
}
i=0;
}
/* newline at end */
putchar ('\n');
return 0;
}
You can use the standard HTML title attribute of image for this:
<img src="source of image" alt="alternative text" title="this will be displayed as a tooltip"/>
I tried experimenting with the answers given. My personal finding came out to be:
git rm -r --cached .
And then
git add .
This seemed to make my working directory nice and clean. You can put your fileName in place of the dot.
Final conclusion: arithmetic on a void*
is illegal in both C and C++.
GCC allows it as an extension, see Arithmetic on void
- and Function-Pointers (note that this section is part of the "C Extensions" chapter of the manual). Clang and ICC likely allow void*
arithmetic for the purposes of compatibility with GCC. Other compilers (such as MSVC) disallow arithmetic on void*
, and GCC disallows it if the -pedantic-errors
flag is specified, or if the -Werror-pointer-arith
flag is specified (this flag is useful if your code base must also compile with MSVC).
Quotes are taken from the n1256 draft.
The standard's description of the addition operation states:
6.5.6-2: For addition, either both operands shall have arithmetic type, or one operand shall be a pointer to an object type and the other shall have integer type.
So, the question here is whether void*
is a pointer to an "object type", or equivalently, whether void
is an "object type". The definition for "object type" is:
6.2.5.1: Types are partitioned into object types (types that fully describe objects) , function types (types that describe functions), and incomplete types (types that describe objects but lack information needed to determine their sizes).
And the standard defines void
as:
6.2.5-19: The
void
type comprises an empty set of values; it is an incomplete type that cannot be completed.
Since void
is an incomplete type, it is not an object type. Therefore it is not a valid operand to an addition operation.
Therefore you cannot perform pointer arithmetic on a void
pointer.
Originally, it was thought that void*
arithmetic was permitted, because of these sections of the C standard:
6.2.5-27: A pointer to void shall have the same representation and alignment requirements as a pointer to a character type.
However,
The same representation and alignment requirements are meant to imply interchangeability as arguments to functions, return values from functions, and members of unions.
So this means that printf("%s", x)
has the same meaning whether x
has type char*
or void*
, but it does not mean that you can do arithmetic on a void*
.
Editor's note: This answer has been edited to reflect the final conclusion.
Field[] fields = YourClassName.class.getFields();
returns an array of all public variables of the class.
getFields()
return the fields in the whole class-heirarcy. If you want to have the fields defined only in the class in question, and not its superclasses, use getDeclaredFields()
, and filter the public
ones with the following Modifier
approach:
Modifier.isPublic(field.getModifiers());
The YourClassName.class
literal actually represents an object of type java.lang.Class
. Check its docs for more interesting reflection methods.
The Field
class above is java.lang.reflect.Field
. You may take a look at the whole java.lang.reflect
package.
In the case of a past rebase that you did not properly aborted, you now (Git 2.12, Q1 2017) have git rebase --quit
See commit 9512177 (12 Nov 2016) by Nguy?n Thái Ng?c Duy (pclouds
).
(Merged by Junio C Hamano -- gitster
-- in commit 06cd5a1, 19 Dec 2016)
rebase
: add--quit
to cleanup rebase, leave everything else untouchedThere are occasions when you decide to abort an in-progress rebase and move on to do something else but you forget to do "
git rebase --abort
" first. Or the rebase has been in progress for so long you forgot about it. By the time you realize that (e.g. by starting another rebase) it's already too late to retrace your steps. The solution is normallyrm -r .git/<some rebase dir>
and continue with your life.
But there could be two different directories for<some rebase dir>
(and it obviously requires some knowledge of how rebase works), and the ".git
" part could be much longer if you are not at top-dir, or in a linked worktree. And "rm -r
" is very dangerous to do in.git
, a mistake in there could destroy object database or other important data.Provide "
git rebase --quit
" for this use case, mimicking a precedent that is "git cherry-pick --quit
".
Before Git 2.27 (Q2 2020), The stash entry created by "git merge --autostash
" to keep the initial dirty state were discarded by mistake upon "git rebase --quit
", which has been corrected.
See commit 9b2df3e (28 Apr 2020) by Denton Liu (Denton-L
).
(Merged by Junio C Hamano -- gitster
-- in commit 3afdeef, 29 Apr 2020)
rebase
: save autostash entry intostash reflog
on--quit
Signed-off-by: Denton Liu
In a03b55530a ("
merge
: teach --autostash option", 2020-04-07, Git v2.27.0 -- merge listed in batch #5), the--autostash
option was introduced forgit merge
.
(See "Can “git pull
” automatically stash and pop pending changes?")
Notably, when
git merge --quit
is run with an autostash entry present, it is saved into the stash reflog.This is contrasted with the current behaviour of
git rebase --quit
where the autostash entry is simply just dropped out of existence.Adopt the behaviour of
git merge --quit
ingit rebase --quit
and save the autostash entry into the stash reflog instead of just deleting it.
I ran into a couple of problems when I tried converting Kevin Fairchild's suggestion to work with strings containing spaces and special XML characters (&
, <
, >
) which were encoded.
The final version of my code (which doesn't answer the original question but may be useful to someone) looks like this:
CREATE TABLE #YourTable ([ID] INT, [Name] VARCHAR(MAX), [Value] INT)
INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'Oranges & Lemons',4)
INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'1 < 2',8)
INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (2,'C',9)
SELECT [ID],
STUFF((
SELECT ', ' + CAST([Name] AS VARCHAR(MAX))
FROM #YourTable WHERE (ID = Results.ID)
FOR XML PATH(''),TYPE
/* Use .value to uncomment XML entities e.g. > < etc*/
).value('.','VARCHAR(MAX)')
,1,2,'') as NameValues
FROM #YourTable Results
GROUP BY ID
DROP TABLE #YourTable
Rather than using a space as a delimiter and replacing all the spaces with commas, it just pre-pends a comma and space to each value then uses STUFF
to remove the first two characters.
The XML encoding is taken care of automatically by using the TYPE directive.
Optional<User>.ifPresent()
takes a Consumer<? super User>
as argument. You're passing it an expression whose type is void. So that doesn't compile.
A Consumer is intended to be implemented as a lambda expression:
Optional<User> user = ...
user.ifPresent(theUser -> doSomethingWithUser(theUser));
Or even simpler, using a method reference:
Optional<User> user = ...
user.ifPresent(this::doSomethingWithUser);
This is basically the same thing as
Optional<User> user = ...
user.ifPresent(new Consumer<User>() {
@Override
public void accept(User theUser) {
doSomethingWithUser(theUser);
}
});
The idea is that the doSomethingWithUser()
method call will only be executed if the user is present. Your code executes the method call directly, and tries to pass its void result to ifPresent()
.
// Sorted
let Sorted = Object.entries({ "a":4, "b":0.5 , "c":0.35, "d":5 }).sort((prev, next) => prev[1] - next[1])
>> [ [ 'c', 0.35 ], [ 'b', 0.5 ], [ 'a', 4 ], [ 'd', 5 ] ]
//Min:
Sorted.shift()
>> [ 'c', 0.35 ]
// Max:
Sorted.pop()
>> [ 'd', 5 ]
Well one of the option is to goto your workspace, your project folder, then bin copy and paste the log4j properites file. it would be better to paste the file also in source folder.
Now you may want to know from where to get this file, download smslib, then extract it, then smslib->misc->log4j sample configuration -> log4j here you go.
This what helped,me so just wanted to know.
The C# language doesn't have a power operator. However, the .NET Framework offers the Math.Pow
method:
Returns a specified number raised to the specified power.
So your example would look like this:
float Result, Number1, Number2;
Number1 = 2;
Number2 = 2;
Result = Math.Pow(Number1, Number2);
When you called notify on the notification manager you gave it an id - that is the unique id you can use to access it later (this is from the notification manager:
notify(int id, Notification notification)
To cancel, you would call:
cancel(int id)
with the same id. So, basically, you need to keep track of the id or possibly put the id into a Bundle you add to the Intent inside the PendingIntent?
A little late, but here's a regex I found that returns 0 matches for empty or white spaces:
/^(?!\s*$).+/
You can test this out at regex101
Using JODA:
PeriodFormatter periodFormat = new PeriodFormatterBuilder()
.minimumParsedDigits(2)
.appendHour() // 2 digits minimum
.appendSeparator(":")
.minimumParsedDigits(2)
.appendMinute() // 2 digits minimum
.appendSeparator(":")
.minimumParsedDigits(2)
.appendSecond()
.appendSeparator(".")
.appendMillis3Digit()
.toFormatter();
Period result = Period.parse(string, periodFormat);
return result.toStandardDuration().getMillis();
During development, I recommend using nodemon. It will restart your server whenever a file changes. As others have pointed out, Forever is an option but in production, it all depends on the platform you are using. You will typically want to use the operating system's recommended way of keeping services up (e.g. http://www.freedesktop.org/wiki/Software/systemd/).
Don't declare the variable in the userform. Declare it as Public
in the module.
Public pass As String
In the Userform
Private Sub CommandButton1_Click()
pass = UserForm1.TextBox1
Unload UserForm1
End Sub
In the Module
Public pass As String
Public Sub Login()
'
'~~> Rest of the code
'
UserForm1.Show
driver.findElementByName("PASSWORD").SendKeys pass
'
'~~> Rest of the code
'
End Sub
You might want to also add an additional check just before calling the driver.find...
line?
If Len(Trim(pass)) <> 0 Then
This will ensure that a blank string is not passed.
As far as I know, you will not be allowed to assign string values to enum. What you can do is create a class with string constants in it.
public static class SeparatorChars
{
public static String Comma { get { return ",";} }
public static String Tab { get { return "\t,";} }
public static String Space { get { return " ";} }
}
Gensim implements a model called Doc2Vec for paragraph embedding.
There are different tutorials presented as IPython notebooks:
Another method would rely on Word2Vec and Word Mover's Distance (WMD), as shown in this tutorial:
An alternative solution would be to rely on average vectors:
from gensim.models import KeyedVectors
from gensim.utils import simple_preprocess
def tidy_sentence(sentence, vocabulary):
return [word for word in simple_preprocess(sentence) if word in vocabulary]
def compute_sentence_similarity(sentence_1, sentence_2, model_wv):
vocabulary = set(model_wv.index2word)
tokens_1 = tidy_sentence(sentence_1, vocabulary)
tokens_2 = tidy_sentence(sentence_2, vocabulary)
return model_wv.n_similarity(tokens_1, tokens_2)
wv = KeyedVectors.load('model.wv', mmap='r')
sim = compute_sentence_similarity('this is a sentence', 'this is also a sentence', wv)
print(sim)
Finally, if you can run Tensorflow, you may try: https://tfhub.dev/google/universal-sentence-encoder/2
You should give the content to InfoWindow from jQuery object.
var $infoWindowContent = $("<div class='infowin-content'>Content goes here</div>");
var infoWindow = new google.maps.InfoWindow();
infowindow.setContent($infoWindowContent[0]);
shape()
consists of array having two arguments rows and columns.
if you search shape[0]
then it will gave you the number of rows.
shape[1]
will gave you number of columns.
The think best way to to it is using
Intent i = new Intent(this.myActivity, SecondActivity.class);
startActivityForResult(i, 1);
Or can also insert the statement inside bracket.
SELECT * FROM tablename WHERE NOT (columnA = 'x')
An advance approach is using Kotlin Extension function
fun Context.getRawInput(@RawRes resourceId: Int): InputStream {
return resources.openRawResource(resourceId)
}
One more interesting thing is extension function use that is defined in Closeable scope
For example you can work with input stream in elegant way without handling Exceptions and memory managing
fun Context.readRaw(@RawRes resourceId: Int): String {
return resources.openRawResource(resourceId).bufferedReader(Charsets.UTF_8).use { it.readText() }
}
I'd prefer to only add the Servlet API as dependency,
To be honest, I'm not sure to understand why but never mind...
Brabster separate dependencies have been replaced by Java EE 6 Profiles. Is there a source that confirms this assumption?
The maven repository from Java.net indeed offers the following artifact for the WebProfile:
<repositories>
<repository>
<id>java.net2</id>
<name>Repository hosting the jee6 artifacts</name>
<url>http://download.java.net/maven/2</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
This jar includes Servlet 3.0, EJB Lite 3.1, JPA 2.0, JSP 2.2, EL 1.2, JSTL 1.2, JSF 2.0, JTA 1.1, JSR-45, JSR-250.
But to my knowledge, nothing allows to say that these APIs won't be distributed separately (in java.net repository or somewhere else). For example (ok, it may a particular case), the JSF 2.0 API is available separately (in the java.net repository):
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.0.0-b10</version>
<scope>provided</scope>
</dependency>
And actually, you could get javax.servlet-3.0.jar
from there and install it in your own repository.
The registry is the official way to detect if a specific version of the Framework is installed.
Which registry keys are needed change depending on the Framework version you are looking for:
Framework Version Registry Key ------------------------------------------------------------------------------------------ 1.0 HKLM\Software\Microsoft\.NETFramework\Policy\v1.0\3705 1.1 HKLM\Software\Microsoft\NET Framework Setup\NDP\v1.1.4322\Install 2.0 HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\Install 3.0 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.0\Setup\InstallSuccess 3.5 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\Install 4.0 Client Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Client\Install 4.0 Full Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Full\Install
Generally you are looking for:
"Install"=dword:00000001
except for .NET 1.0, where the value is a string (REG_SZ
) rather than a number (REG_DWORD
).
Determining the service pack level follows a similar pattern:
Framework Version Registry Key ------------------------------------------------------------------------------------------ 1.0 HKLM\Software\Microsoft\Active Setup\Installed Components\{78705f0d-e8db-4b2d-8193-982bdda15ecd}\Version 1.0[1] HKLM\Software\Microsoft\Active Setup\Installed Components\{FDC11A6F-17D1-48f9-9EA3-9051954BAA24}\Version 1.1 HKLM\Software\Microsoft\NET Framework Setup\NDP\v1.1.4322\SP 2.0 HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\SP 3.0 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.0\SP 3.5 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\SP 4.0 Client Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Client\Servicing 4.0 Full Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Full\Servicing [1] Windows Media Center or Windows XP Tablet Edition
As you can see, determining the SP level for .NET 1.0 changes if you are running on Windows Media Center or Windows XP Tablet Edition. Again, .NET 1.0 uses a string value while all of the others use a DWORD.
For .NET 1.0 the string value at either of these keys has a format of #,#,####,#. The last # is the Service Pack level.
While I didn't explicitly ask for this, if you want to know the exact version number of the Framework you would use these registry keys:
Framework Version Registry Key ------------------------------------------------------------------------------------------ 1.0 HKLM\Software\Microsoft\Active Setup\Installed Components\{78705f0d-e8db-4b2d-8193-982bdda15ecd}\Version 1.0[1] HKLM\Software\Microsoft\Active Setup\Installed Components\{FDC11A6F-17D1-48f9-9EA3-9051954BAA24}\Version 1.1 HKLM\Software\Microsoft\NET Framework Setup\NDP\v1.1.4322 2.0[2] HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\Version 2.0[3] HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\Increment 3.0 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.0\Version 3.5 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\Version 4.0 Client Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Version 4.0 Full Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Version [1] Windows Media Center or Windows XP Tablet Edition [2] .NET 2.0 SP1 [3] .NET 2.0 Original Release (RTM)
Again, .NET 1.0 uses a string value while all of the others use a DWORD.
for .NET 1.0 the string value at either of these keys has a format of #,#,####,#
. The #,#,####
portion of the string is the Framework version.
for .NET 1.1, we use the name of the registry key itself, which represents the version number.
Finally, if you look at dependencies, .NET 3.0 adds additional functionality to .NET 2.0 so both .NET 2.0 and .NET 3.0 must both evaulate as being installed to correctly say that .NET 3.0 is installed. Likewise, .NET 3.5 adds additional functionality to .NET 2.0 and .NET 3.0, so .NET 2.0, .NET 3.0, and .NET 3. should all evaluate to being installed to correctly say that .NET 3.5 is installed.
.NET 4.0 installs a new version of the CLR (CLR version 4.0) which can run side-by-side with CLR 2.0.
There won't be a v4.5
key in the registry if .NET 4.5 is installed. Instead you have to check if the HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Full
key contains a value called Release
. If this value is present, .NET 4.5 is installed, otherwise it is not. More details can be found here and here.
Easy way out is to use a condition like this ( use desired date > GETDATE()-1)
your sql statement "date specific" > GETDATE()-1
Most possible cause of such issues can be some invisible view is on the top of view being clicked, which prevents the click event to trigger. So recheck your xml layout properly before searching anything vigorously online.
PS :- In my case, a recyclerView was totally covering the layout and hence clicking on imageView was restricted.
According to one of the first Google search hits: http://www.csharp-examples.net/string-format-datetime/
// Where 'dt' is the DateTime object...
String.Format("{0:dd-MM-yyyy}", dt);
Yes, it is. Just create files in the windows explorer and git automatically detects these files as currently untracked. Then add it with the command you already mentioned.
git add
does not create any files. See also http://gitref.org/basic/#add
Github probably creates the file with touch
and adds the file for tracking automatically. You can do this on the bash
as well.
In my case, adding a dtype attribute changed dtype of the array to a smaller type(from float64 to uint8), decreasing array size enough to not throw MemoryError in Windows(64 bit).
from
mask = np.zeros(edges.shape)
to
mask = np.zeros(edges.shape,dtype='uint8')
In some cases it might make more sense to process each selected item one at a time.
In other words, make a separate server call for each selected item passing the value of the selected item. In some cases the list will need to be processed as a whole, but in some not.
I needed to process a list of selected people and then have the results of the query show up on an existing page beneath the existing data for that person. I initially though of passing the whole list to the server, parsing the list, then passing back the data for all of the patients. I would have then needed to parse the returning data and insert it into the page in each of the appropriate places. Sending the request for the data one person at a time turned out to be much easier. Javascript for getting the selected items is described here: check if checkbox is checked javascript and jQuery for the same is described here: How to check whether a checkbox is checked in jQuery?.
You have a problem one way or the other with your datetime.datetime.fromtimestamp(time.mktime(time.gmtime()))
expression.
(1) If all you need is the difference between two instants in seconds, the very simple time.time()
does the job.
(2) If you are using those timestamps for other purposes, you need to consider what you are doing, because the result has a big smell all over it:
gmtime()
returns a time tuple in UTC but mktime()
expects a time tuple in local time.
I'm in Melbourne, Australia where the standard TZ is UTC+10, but daylight saving is still in force until tomorrow morning so it's UTC+11. When I executed the following, it was 2011-04-02T20:31 local time here ... UTC was 2011-04-02T09:31
>>> import time, datetime
>>> t1 = time.gmtime()
>>> t2 = time.mktime(t1)
>>> t3 = datetime.datetime.fromtimestamp(t2)
>>> print t0
1301735358.78
>>> print t1
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=9, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=0) ### this is UTC
>>> print t2
1301700663.0
>>> print t3
2011-04-02 10:31:03 ### this is UTC+1
>>> tt = time.time(); print tt
1301736663.88
>>> print datetime.datetime.now()
2011-04-02 20:31:03.882000 ### UTC+11, my local time
>>> print datetime.datetime(1970,1,1) + datetime.timedelta(seconds=tt)
2011-04-02 09:31:03.880000 ### UTC
>>> print time.localtime()
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=20, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=1) ### UTC+11, my local time
You'll notice that t3, the result of your expression is UTC+1, which appears to be UTC + (my local DST difference) ... not very meaningful. You should consider using datetime.datetime.utcnow()
which won't jump by an hour when DST goes on/off and may give you more precision than time.time()
We can add drawable .xml like below
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:width="1dp"
android:color="@color/color_C4CDD5"/>
<corners android:radius="8dp"/>
<solid
android:color="@color/color_white"/>
</shape>
You can add a RedirectViewController like:
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addRedirectViewController("/", "/index.html");
}
}
This is very inadvisable. But if you're not a programmer, or really prefer terrible code, you could use a substitute preg_replace
function to keep your /e
flag working temporarily.
/**
* Can be used as a stopgap shim for preg_replace() calls with /e flag.
* Is likely to fail for more complex string munging expressions. And
* very obviously won't help with local-scope variable expressions.
*
* @license: CC-BY-*.*-comment-must-be-retained
* @security: Provides `eval` support for replacement patterns. Which
* poses troubles for user-supplied input when paired with overly
* generic placeholders. This variant is only slightly stricter than
* the C implementation, but still susceptible to varexpression, quote
* breakouts and mundane exploits from unquoted capture placeholders.
* @url: https://stackoverflow.com/q/15454220
*/
function preg_replace_eval($pattern, $replacement, $subject, $limit=-1) {
# strip /e flag
$pattern = preg_replace('/(\W[a-df-z]*)e([a-df-z]*)$/i', '$1$2', $pattern);
# warn about most blatant misuses at least
if (preg_match('/\(\.[+*]/', $pattern)) {
trigger_error("preg_replace_eval(): regex contains (.*) or (.+) placeholders, which easily causes security issues for unconstrained/user input in the replacement expression. Transform your code to use preg_replace_callback() with a sane replacement callback!");
}
# run preg_replace with eval-callback
return preg_replace_callback(
$pattern,
function ($matches) use ($replacement) {
# substitute $1/$2/… with literals from $matches[]
$repl = preg_replace_callback(
'/(?<!\\\\)(?:[$]|\\\\)(\d+)/',
function ($m) use ($matches) {
if (!isset($matches[$m[1]])) { trigger_error("No capture group for '$m[0]' eval placeholder"); }
return addcslashes($matches[$m[1]], '\"\'\`\$\\\0'); # additionally escapes '$' and backticks
},
$replacement
);
# run the replacement expression
return eval("return $repl;");
},
$subject,
$limit
);
}
In essence, you just include that function in your codebase, and edit preg_replace
to preg_replace_eval
wherever the /e
flag was used.
Pros and cons:
preg_replace_callback
.Now this is somewhat redundant. But might help those users who are still overwhelmed
with manually restructuring their code to preg_replace_callback
. While this is effectively more time consuming, a code generator has less trouble to expand the /e
replacement string into an expression. It's a very unremarkable conversion, but likely suffices for the most prevalent examples.
To use this function, edit any broken preg_replace
call into preg_replace_eval_replacement
and run it once. This will print out the according preg_replace_callback
block to be used in its place.
/**
* Use once to generate a crude preg_replace_callback() substitution. Might often
* require additional changes in the `return …;` expression. You'll also have to
* refit the variable names for input/output obviously.
*
* >>> preg_replace_eval_replacement("/\w+/", 'strtopupper("$1")', $ignored);
*/
function preg_replace_eval_replacement($pattern, $replacement, $subjectvar="IGNORED") {
$pattern = preg_replace('/(\W[a-df-z]*)e([a-df-z]*)$/i', '$1$2', $pattern);
$replacement = preg_replace_callback('/[\'\"]?(?<!\\\\)(?:[$]|\\\\)(\d+)[\'\"]?/', function ($m) { return "\$m[{$m[1]}]"; }, $replacement);
$ve = "var_export";
$bt = debug_backtrace(0, 1)[0];
print "<pre><code>
#----------------------------------------------------
# replace preg_*() call in '$bt[file]' line $bt[line] with:
#----------------------------------------------------
\$OUTPUT_VAR = preg_replace_callback(
{$ve($pattern, TRUE)},
function (\$m) {
return {$replacement};
},
\$YOUR_INPUT_VARIABLE_GOES_HERE
)
#----------------------------------------------------
</code></pre>\n";
}
Take in mind that mere copy&pasting is not programming. You'll have to adapt the generated code back to your actual input/output variable names, or usage context.
$OUTPUT =
assignment would have to go if the previous preg_replace
call was used in an if
.And the replacement expression may demand more readability improvements or rework.
stripslashes()
often becomes redundant in literal expressions.use
or global
reference for/within the callback."-$1-$2"
capture references will end up syntactically broken by the plain transformation into "-$m[1]-$m[2]
.The code output is merely a starting point. And yes, this would have been more useful as an online tool. This code rewriting approach (edit, run, edit, edit) is somewhat impractical. Yet could be more approachable to those who are accustomed to task-centric coding (more steps, more uncoveries). So this alternative might curb a few more duplicate questions.
Other possibility to keep Button theme.
<Button
android:id="@+id/pf_bt_edit"
android:layout_height="@dimen/standard_height"
android:layout_width="match_parent"
/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_alignBottom="@id/pf_bt_edit"
android:layout_alignLeft="@id/pf_bt_edit"
android:layout_alignRight="@id/pf_bt_edit"
android:layout_alignTop="@id/pf_bt_edit"
android:layout_margin="@dimen/margin_10"
android:clickable="false"
android:elevation="20dp"
android:gravity="center"
android:orientation="horizontal"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:clickable="false"
android:src="@drawable/ic_edit_white_48dp"/>
<TextView
android:id="@+id/pf_tv_edit"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="@dimen/margin_5"
android:clickable="false"
android:gravity="center"
android:text="@string/pf_bt_edit"/>
</LinearLayout>
With this solution if your add @color/your_color @color/your_highlight_color in your activity theme, you can have Matherial theme on Lollipop whith shadow and ripple, and for previous version flat button with your color and highlight coor when you press it.
Moreover, with this solution autoresize of picture
Result : First on Lollipop device Second : On pre lollipop device 3th : Pre lollipop device press button
A couple of notes first: when you use Data/data1.txt
as an argument, should it really be /Data/data1.txt
(with a leading slash)? Also, should the outer loop scan only for .txt files, or all files in /Data? Here's an answer, assuming /Data/data1.txt
and .txt files only:
#!/bin/bash
for filename in /Data/*.txt; do
for ((i=0; i<=3; i++)); do
./MyProgram.exe "$filename" "Logs/$(basename "$filename" .txt)_Log$i.txt"
done
done
Notes:
/Data/*.txt
expands to the paths of the text files in /Data (including the /Data/ part)$( ... )
runs a shell command and inserts its output at that point in the command linebasename somepath .txt
outputs the base part of somepath, with .txt removed from the end (e.g. /Data/file.txt
-> file
)If you needed to run MyProgram with Data/file.txt
instead of /Data/file.txt
, use "${filename#/}"
to remove the leading slash. On the other hand, if it's really Data
not /Data
you want to scan, just use for filename in Data/*.txt
.
If you're geting [object object]
then use JSON.stringify
fs.writeFile('./data.json', JSON.stringify(obj) , 'utf-8');
It worked for me.
The statement about CMake being a "build generator" is a common misconception.
It's not technically wrong; it just describes HOW it works, but not WHAT it does.
In the context of the question, they do the same thing: take a bunch of C/C++ files and turn them into a binary.
So, what is the real difference?
CMake is much more high-level. It's tailored to compile C++, for which you write much less build code, but can be also used for general purpose build. make
has some built-in C/C++ rules as well, but they are useless at best.
CMake
does a two-step build: it generates a low-level build script in ninja
or make
or many other generators, and then you run it. All the shell script pieces that are normally piled into Makefile
are only executed at the generation stage. Thus, CMake
build can be orders of magnitude faster.
The grammar of CMake
is much easier to support for external tools than make's.
Once make
builds an artifact, it forgets how it was built. What sources it was built from, what compiler flags? CMake
tracks it, make
leaves it up to you. If one of library sources was removed since the previous version of Makefile
, make
won't rebuild it.
Modern CMake
(starting with version 3.something) works in terms of dependencies between "targets". A target is still a single output file, but it can have transitive ("public"/"interface" in CMake terms) dependencies.
These transitive dependencies can be exposed to or hidden from the dependent packages. CMake
will manage directories for you. With make
, you're stuck on a file-by-file and manage-directories-by-hand level.
You could code up something in make
using intermediate files to cover the last two gaps, but you're on your own. make
does contain a Turing complete language (even two, sometimes three counting Guile); the first two are horrible and the Guile is practically never used.
To be honest, this is what CMake
and make
have in common -- their languages are pretty horrible. Here's what comes to mind:
CMake
has three data types: string, list, and a target with properties. make
has one: string;set_property(TARGET helloworld APPEND PROPERTY INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}")
;:last
is not part of the css spec, this is jQuery specific.
you should be looking for last-child
var first = div.querySelector('[move_id]:first-child');
var last = div.querySelector('[move_id]:last-child');
Create an image to use as background with Photoshop or gimp and name it myimage. Then, add this method to your tableViewController class:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
UIImage *cellImage = [UIImage imageNamed:@"myimage.png"];//myimage is a 20x50 px with gradient color created with gimp
UIImageView *cellView = [[UIImageView alloc] initWithImage:cellImage];
cellView.contentMode = UIContentViewModeScaleToFill;
cell.backgroundView = cellView;
//set the background label to clear
cell.titleLabel.backgroundColor= [UIColor clearColor];
}
This will work also if you have set the UITableView to custom in attribute inspector.
This GitPro page does summarize the consequence of a git submodule update nicely
When you run
git submodule update
, it checks out the specific version of the project, but not within a branch. This is called having a detached head — it means the HEAD file points directly to a commit, not to a symbolic reference.
The issue is that you generally don’t want to work in a detached head environment, because it’s easy to lose changes.
If you do an initial submodule update, commit in that submodule directory without creating a branch to work in, and then run git submodule update again from the superproject without committing in the meantime, Git will overwrite your changes without telling you. Technically you won’t lose the work, but you won’t have a branch pointing to it, so it will be somewhat difficult to retrieve.
Note March 2013:
As mentioned in "git submodule tracking latest", a submodule now (git1.8.2) can track a branch.
# add submodule to track master branch
git submodule add -b master [URL to Git repo];
# update your submodule
git submodule update --remote
# or (with rebase)
git submodule update --rebase --remote
See "git submodule update --remote
vs git pull
".
MindTooth's answer illustrate a manual update (without local configuration):
git submodule -q foreach git pull -q origin master
In both cases, that will change the submodules references (the gitlink, a special entry in the parent repo index), and you will need to add, commit and push said references from the main repo.
Next time you will clone that parent repo, it will populate the submodules to reflect those new SHA1 references.
The rest of this answer details the classic submodule feature (reference to a fixed commit, which is the all point behind the notion of a submodule).
To avoid this issue, create a branch when you work in a submodule directory with git checkout -b work or something equivalent. When you do the submodule update a second time, it will still revert your work, but at least you have a pointer to get back to.
Switching branches with submodules in them can also be tricky. If you create a new branch, add a submodule there, and then switch back to a branch without that submodule, you still have the submodule directory as an untracked directory:
So, to answer your questions:
can I create branches/modifications and use push/pull just like I would in regular repos, or are there things to be cautious about?
You can create a branch and push modifications.
WARNING (from Git Submodule Tutorial): Always publish (push) the submodule change before publishing (push) the change to the superproject that references it. If you forget to publish the submodule change, others won't be able to clone the repository.
how would I advance the submodule referenced commit from say (tagged) 1.0 to 1.1 (even though the head of the original repo is already at 2.0)
The page "Understanding Submodules" can help
Git submodules are implemented using two moving parts:
- the
.gitmodules
file and- a special kind of tree object.
These together triangulate a specific revision of a specific repository which is checked out into a specific location in your project.
From the git submodule page
you cannot modify the contents of the submodule from within the main project
100% correct: you cannot modify a submodule, only refer to one of its commits.
This is why, when you do modify a submodule from within the main project, you:
A submodule enables you to have a component-based approach development, where the main project only refers to specific commits of other components (here "other Git repositories declared as sub-modules").
A submodule is a marker (commit) to another Git repository which is not bound by the main project development cycle: it (the "other" Git repo) can evolves independently.
It is up to the main project to pick from that other repo whatever commit it needs.
However, should you want to, out of convenience, modify one of those submodules directly from your main project, Git allows you to do that, provided you first publish those submodule modifications to its original Git repo, and then commit your main project refering to a new version of said submodule.
But the main idea remains: referencing specific components which:
The list of specific commits you are refering to in your main project defines your configuration (this is what Configuration Management is all about, englobing mere Version Control System)
If a component could really be developed at the same time as your main project (because any modification on the main project would involve modifying the sub-directory, and vice-versa), then it would be a "submodule" no more, but a subtree merge (also presented in the question Transferring legacy code base from cvs to distributed repository), linking the history of the two Git repo together.
Does that help understanding the true nature of Git Submodules?
I ran into this issue (twice) with nginx and none of the solutions in this post explained the issue. The blog post here by a nice gentleman named Marco nailed it, and I am pasting it here for anyone who also runs into what I was seeing. https://medium.com/@mrkdsgn/steps-to-install-a-go-daddy-ssl-certificate-on-nginx-on-ubuntu-14-04-ff942b9fd7ff
In my case, go-daddy was the CA and this is specific to how they issue the cert and the intermediate cert bundles.
With Nginx, if your CA included an intermediate certificate, you must create a single chained certificate file that contains your certificate and the CA’s intermediate certificates.
You can use this command to create a combined file called example.com.chained.crt:
cat example.com.crt intermediate.crt > example.com.chained.crt
I suspect you are running Android 6.0 Marshmallow (API 23) or later. If this is the case, you must implement runtime permissions before you try to read/write external storage.
None of these solutions worked for me inside a Weebly "add your own html" box. Not sure what they are doing with their code. But I found this solution at https://benmarshall.me/responsive-iframes/ and it works perfectly.
CSS
.iframe-container {
overflow: hidden;
padding-top: 56.25%;
position: relative;
}
.iframe-container iframe {
border: 0;
height: 100%;
left: 0;
position: absolute;
top: 0;
width: 100%;
}
/* 4x3 Aspect Ratio */
.iframe-container-4x3 {
padding-top: 75%;
}
HTML
<div class="iframe-container">
<iframe src="https://player.vimeo.com/video/106466360" allowfullscreen></iframe>
</div>
Some old gradle tools cannot copy .so files into build folder by somehow, manually copying these files into build folder as below can solve the problem:
build/intermediates/rs/{build config}/{support architecture}/
build config: beta/production/sit/uat
support architecture: armeabi/armeabi-v7a/mips/x86
It's a working example:
CREATE USER auto_exchange IDENTIFIED BY 123456;
GRANT RESOURCE TO auto_exchange;
GRANT CONNECT TO auto_exchange;
GRANT CREATE VIEW TO auto_exchange;
GRANT CREATE SESSION TO auto_exchange;
GRANT UNLIMITED TABLESPACE TO auto_exchange;
Is contextmenu
an event?
I would use onmousedown
or onclick
then grab the MouseEvent
's button property to determine which button was pressed (0 = left, 1 = middle, 2 = right).
All the other solutions broke for some situation for me..
See the winning answer breaking at:
http://plnkr.co/edit/6CSCA2fe4Gqt4jCBP2wu?p=preview
Eventually, I decided that the best solution was $(elem).is(':visible')
- however, this is not pure javascript. it is jquery..
so I peeked at their source and found what I wanted
jQuery.expr.filters.visible = function( elem ) {
return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
};
This is the source: https://github.com/jquery/jquery/blob/master/src/css/hiddenVisibleSelectors.js
Yes, kill should be fine if you're running Jenkins with the built-in Winstone container. This Jenkins Wiki page has some tips on how to set up control scripts for Jenkins.
Probably the only choice is to read it on the client side and transfer it manually to the server (GET/POST/AJAX). Regards Artur
You may see also how to play with back button and browser history at Malcan
ES8 way made easy:
const obj = { x: 'xxx', y: 1 };_x000D_
let arr = Object.values(obj); // ['xxx', 1]_x000D_
console.log(arr);
_x000D_
I had this same issue and I solved it as well by creating a custom renderer for iOS as Falko suggests, however, I avoided the styles modification for Android, I figured out a way to use a custom renderer for Android as well.
It is kind of funky how the selected flag is always false for the android view cell that's why I had to create a new private property to track it. but other than that I think this follows a more appropriate pattern if you want to use custom renderers for both platforms, In my case I did it for TextCell but I believe it applies the same way for other CellViews.
Xamarin Forms
using Xamarin.Forms;
public class CustomTextCell : TextCell
{
/// <summary>
/// The SelectedBackgroundColor property.
/// </summary>
public static readonly BindableProperty SelectedBackgroundColorProperty =
BindableProperty.Create("SelectedBackgroundColor", typeof(Color), typeof(CustomTextCell), Color.Default);
/// <summary>
/// Gets or sets the SelectedBackgroundColor.
/// </summary>
public Color SelectedBackgroundColor
{
get { return (Color)GetValue(SelectedBackgroundColorProperty); }
set { SetValue(SelectedBackgroundColorProperty, value); }
}
}
iOS
public class CustomTextCellRenderer : TextCellRenderer
{
public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
{
var cell = base.GetCell(item, reusableCell, tv);
var view = item as CustomTextCell;
cell.SelectedBackgroundView = new UIView
{
BackgroundColor = view.SelectedBackgroundColor.ToUIColor(),
};
return cell;
}
}
Android
public class CustomTextCellRenderer : TextCellRenderer
{
private Android.Views.View cellCore;
private Drawable unselectedBackground;
private bool selected;
protected override Android.Views.View GetCellCore(Cell item, Android.Views.View convertView, ViewGroup parent, Context context)
{
cellCore = base.GetCellCore(item, convertView, parent, context);
// Save original background to rollback to it when not selected,
// We assume that no cells will be selected on creation.
selected = false;
unselectedBackground = cellCore.Background;
return cellCore;
}
protected override void OnCellPropertyChanged(object sender, PropertyChangedEventArgs args)
{
base.OnCellPropertyChanged(sender, args);
if (args.PropertyName == "IsSelected")
{
// I had to create a property to track the selection because cellCore.Selected is always false.
// Toggle selection
selected = !selected;
if (selected)
{
var customTextCell = sender as CustomTextCell;
cellCore.SetBackgroundColor(customTextCell.SelectedBackgroundColor.ToAndroid());
}
else
{
cellCore.SetBackground(unselectedBackground);
}
}
}
}
...then, in the .xaml page, you need to add an XMLNS reference back to the new CustomViewCell...
xmlns:customuicontrols="clr-namespace:MyMobileApp.CustomUIControls"
And don't forget to make actual use of the new Custom comtrol in your XAML.
You don't have to restart your machine. Start cmd or PowerShell in elevated mode.
sc.exe queryex <SERVICE_NAME>
Then you'll get some info. A PID number will show.
taskkill /pid <SERVICE_PID> /f
Where /f is to force stop.
Now you can install or launch your service.
If you need to connect to LocalDB during development, you can use:
sqlcmd -S "(localdb)\MSSQLLocalDB" -d dbname -i file.sql
read the file and then do whatever you want java8 Files.lines(Paths.get("c://lines.txt")).collect(Collectors.toList());
In my case, the issue was new sites had an implicit deny of all IP addresses unless an explicit allow was created. To fix: Under the site in Features View: Under the IIS Section > IP Address and Domain Restrictions > Edit Feature Settings > Set 'Access for unspecified clients:' to 'Allow'
"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."
http://www.sightspecific.com/~mosh/www_faq/multrec.html
For a quick fix to your problem, change your ;
to a comma ,
and eliminate the spaces between email addresses
<a href='mailto:[email protected],[email protected]'>Email Us</a>
The ideal scenario is to have <add value="default.aspx" />
in config so the application can be deployed to any server without having to reconfigure. IMHO I think the implementation within IIS is poor.
We've used the following to make our default document setup more robust and as a result more SEO friendly by using canonical URL's:
<configuration>
<system.webServer>
<defaultDocument>
<files>
<remove value="default.aspx" />
<add value="default.aspx" />
</files>
</defaultDocument>
</system.webServer>
</configuration>
Works OK for us.
char* charP = createStr();
Would be correct if your function was correct. Unfortunately you are returning a pointer to a local variable in the function which means that it is a pointer to undefined data as soon as the function returns. You need to use heap allocation like malloc for the string in your function in order for the pointer you return to have any meaning. Then you need to remember to free it later.
Don't know exactly what kind of dataset you have, so I provide general answer.
x <- c(1,2,NA,3,4,5)
y <- c(1,2,3,NA,6,8)
my.data <- data.frame(x, y)
> my.data
x y
1 1 1
2 2 2
3 NA 3
4 3 NA
5 4 6
6 5 8
# Exclude rows with NA values
my.data[complete.cases(my.data),]
x y
1 1 1
2 2 2
5 4 6
6 5 8
This code will fulifil your need:
FileWriter fw=new FileWriter("C:\\file.json",true);
fw.write("ssssss");
fw.close();
Right click on the project in the Solution window of Visual Studio, select "Debugging" (on the left side), and enter the arguments into the field "Command Arguments":
This is how use SignarR in order to target a specific user (without using any provider):
private static ConcurrentDictionary<string, string> clients = new ConcurrentDictionary<string, string>();
public string Login(string username)
{
clients.TryAdd(Context.ConnectionId, username);
return username;
}
// The variable 'contextIdClient' is equal to Context.ConnectionId of the user,
// once logged in. You have to store that 'id' inside a dictionaty for example.
Clients.Client(contextIdClient).send("Hello!");
If ANSI_NULLS is set to "ON" and if we apply = , <> on NULL column value while writing select statement then it will not return any result.
Example
create table #tempTable (sn int, ename varchar(50))
insert into #tempTable
values (1, 'Manoj'), (2, 'Pankaj'), (3, NULL), (4, 'Lokesh'), (5, 'Gopal')
SET ANSI_NULLS ON
select * from #tempTable where ename is NULL -- (1 row(s) affected)
select * from #tempTable where ename = NULL -- (0 row(s) affected)
select * from #tempTable where ename is not NULL -- (4 row(s) affected)
select * from #tempTable where ename <> NULL -- (0 row(s) affected)
SET ANSI_NULLS OFF
select * from #tempTable where ename is NULL -- (1 row(s) affected)
select * from #tempTable where ename = NULL -- (1 row(s) affected)
select * from #tempTable where ename is not NULL -- (4 row(s) affected)
select * from #tempTable where ename <> NULL -- (4 row(s) affected)
I am converting Char Array to String
Char[] CharArray={ 'A', 'B', 'C'};
String text = String.copyValueOf(CharArray);
The solutions which use input="number"
step="0.01"
work great for me in Chrome, however do not work in some browsers, specifically Frontmotion Firefox 35 in my case.. which I must support.
My solution was to jQuery with Igor Escobar's jQuery Mask plugin, as follows:
$(document).ready(function () {
$('.usd_input').mask('00000.00', { reverse: true });
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js" integrity="sha512-pHVGpX7F/27yZ0ISY+VVjyULApbDlD0/X0rgGbTqCE7WFW5MezNTWG/dnhtbBuICzsd0WQPgpE4REBLv+UqChw==" crossorigin="anonymous"></script>
<input type="text" autocomplete="off" class="usd_input" name="dollar_amt">
_x000D_
This works well, of course one should check the submitted value afterward :) NOTE, if I did not have to do this for browser compatibility I would use the above answer by @Rich Bradshaw.
Try like this.It should work
Response.Redirect(String.Format("yourpage.aspx?strId={0}&strName={1}&strDate{2}", Server.UrlEncode(strId), Server.UrlEncode(strName),Server.UrlEncode(strDate)));
Using dialog methods:
$('.selectorUsedToCreateTheDialog').dialog('option', 'title', 'My New title');
Or directly, hacky though:
$("span.ui-dialog-title").text('My New Title');
For future reference, you can skip google with jQuery. The jQuery API will answer your questions most of the time. In this case, the Dialog API page. For the main library: http://api.jquery.com
Simple answer:
Use getReader() to read the body of the request
More info:
There are two methods for reading the data in the body:
getReader()
returns a BufferedReader that will allow you to read the body of the request.
getInputStream()
returns a ServletInputStream if you need to read binary data.
Note from the docs: "[Either method] may be called to read the body, not both."
A tad late, but even though the following is a work-around, it solves the requirement as this works just fine:
<?
function get_sys_usr()
{
$unique_name = uniqid(); // not-so-unique id
$native_path = "./temp/$unique_name.php";
$public_path = "http://example.com/temp/$unique_name.php";
$php_content = "<? echo get_current_user(); ?>";
$process_usr = "apache"; // fall-back
if (is_readable("./temp") && is_writable("./temp"))
{
file_put_contents($native_path,$php_content);
$process_usr = trim(file_get_contents($public_path));
unlink($native_path);
}
return $process_usr;
}
echo get_sys_usr(); // www-data
?>
The code-highlighting above is not accurate, please copy & paste in your favorite editor and view as PHP code, or save and test it yourself.
As you probably know, get_current_user()
returns the owner of the "current running script" - so if you did not "chown" a script on the server to the web-server-user it will most probably be "nobody", or if the developer-user exists on the same OS, it will rather display that username.
To work around this, we create a file with the current running process. If you just require()
this into the current running script, it will return the same as the parent-script as mentioned; so, we need to run it as a separate request to take effect.
In order to make this effective, consider running a design pattern that incorporates "runtime-mode", so when the server is in "development-mode or test-mode" then only it could run this function and save its output somewhere in an include, -or just plain text or database, or whichever.
Of course you can change some particulars of the code above as you wish to make it more dynamic, but the logic is as follows:
A simple way of "binarize" an image is to compare to a threshold: For example you can compare all elements in a matrix against a value with opencv in c++
cv::Mat img = cv::imread("image.jpg", CV_LOAD_IMAGE_GRAYSCALE);
cv::Mat bw = img > 128;
In this way, all pixels in the matrix greater than 128 now are white, and these less than 128 or equals will be black
Optionally, and for me gave good results is to apply blur
cv::blur( bw, bw, cv::Size(3,3) );
Later you can save it as said before with:
cv::imwrite("image_bw.jpg", bw);