You can use
jQuery(document).ready(function(){ ...... });
or
(function ($) { ...... }(jQuery));
As well for correctness of using ==
you can just unbox one of compared Integer
values before doing ==
comparison, like:
if ( firstInteger.intValue() == secondInteger ) {..
The second will be auto unboxed (of course you have to check for null
s first).
Looks it's one of the early asked question about Golang . And same time answers to never update . During these three to four years , too many new libraries and blog post has been out . Below are the few links what I felt useful .
Calling C++ Code From Go With SWIG
Just what it sounds like: a class that "wraps" the functionality of another class or API in a simpler or merely different API.
If you want to refer to a nested table by multiple keys you can just assign them to separate keys. The tables are not duplicated, and still reference the same values.
arr = {}
apples = {'a', "red", 5 }
arr.apples = apples
arr[1] = apples
This code block lets you iterate through all the key-value pairs in a table (http://lua-users.org/wiki/TablesTutorial):
for k,v in pairs(t) do
print(k,v)
end
I fixed this issue by using Product > Clean Build Folder
(CommandShiftK), which makes a new clean build, really odd.
Strange behavior with MS Excel
:
If i export to "text based, comma-separated format (csv
)" this is the mime-type I get after uploading on my webserver:
[name] => data.csv
[type] => application/vnd.ms-excel
So Microsoft seems to be doing own things again, regardless of existing standards: https://en.wikipedia.org/wiki/Comma-separated_values
You could try some sort of COALESCE trick, eg:
SELECT COALESCE( CASE WHEN condition1 THEN calculation1 ELSE NULL END, CASE WHEN condition2 THEN calculation2 ELSE NULL END, etc... )
myClub.distance = Console.ReadLine();
should be
myClub.mydistance = Console.ReadLine();
use your public properties that you have defined for others as well instead of the protected field members.
Just subtract the string address from what strchr returns:
char *string = "qwerty";
char *e;
int index;
e = strchr(string, 'e');
index = (int)(e - string);
Note that the result is zero based, so in above example it will be 2.
Internet Explorer specific, but rather good:
The advantage compared to urllib/BeautifulSoup is that it executes Javascript as well since it uses IE.
Use isset()
$matchFound = (isset($_GET["id"]) && trim($_GET["id"]) == 'link1');
$slide = $matchFound ? trim($_GET["id"]) : '';
EDIT: This is added for the completeness sake. $_GET in php is a reserved variable that is an associative array. Hence, you could also make use of 'array_key_exists(mixed $key, array $array)'. It will return a boolean that the key is found or not. So, the following also will be okay.
$matchFound = (array_key_exists("id", $_GET)) && trim($_GET["id"]) == 'link1');
$slide = $matchFound ? trim($_GET["id"]) : '';
Don't worry about any performance differences, they're going to be minimal in this case normally.
Method 2 is preferable because
it doesn't require mutating a collection that exists outside the lambda expression,
it's more readable because the different steps that are performed in the collection pipeline are written sequentially: first a filter operation, then a map operation, then collecting the result (for more info on the benefits of collection pipelines, see Martin Fowler's excellent article),
you can easily change the way values are collected by replacing the Collector
that is used. In some cases you may need to write your own Collector
, but then the benefit is that you can easily reuse that.
As it was mentioned above CasperJS is the best tool to fill and send forms. Simplest possible example of how to fill & submit form using fill() function:
casper.start("http://example.com/login", function() {
//searches and fills the form with id="loginForm"
this.fill('form#loginForm', {
'login': 'admin',
'password': '12345678'
}, true);
this.evaluate(function(){
//trigger click event on submit button
document.querySelector('input[type="submit"]').click();
});
});
#include <iostream>
#include <sstream>
std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;
while(std::getline(ss, token, ',')) {
std::cout << token << '\n';
}
abc
def
ghi
You can use display: inline-block
.
Place your cursor in the package name like shown below. Don't select it, just place it.
Then press Shift + F6 you will get a popup window as shown below select Rename package.
Enter your new name and select Refactor. (Note since my cursor is on "something", only something is renamed.)
That's it done.
I have this folder structure:
D:\JavaProjects\OlivePressApp\com\lynda\olivepress\Main.class D:\JavaProjects\OlivePressApp\com\lynda\olivepress\press\OlivePress.class D:\JavaProjects\OlivePressApp\com\lynda\olivepress\olives\Kalamata.class D:\JavaProjects\OlivePressApp\com\lynda\olivepress\olives\Ligurian.class D:\JavaProjects\OlivePressApp\com\lynda\olivepress\olives\Olive.class
Main.class
is in package com.lynda.olivepress
There are two other packages:
com.lynda.olivepress.press
com.lynda.olivepress.olive
1) Create a file named "Manifest.txt"
with Two Lines, First with Main-Class and a Second Empty Line.
Main-Class: com.lynda.olivepress.Main
D:\JavaProjects\OlivePressApp\ Manifest.txt
2) Create JAR with Manifest and Main-Class Entry Point
D:\JavaProjects\OlivePressApp>jar cfm OlivePressApp.jar Manifest.txt com/lynda/olivepress/Main.class com/lynda/olivepress/*
3) Run JAR
java -jar OlivePressApp.jar
Note: com/lynda/olivepress/*
means including the other two packages mentioned above, before point 1)
Best way is using BoxDecoration()
Advantage
Disadvantage
BoxDecoration
only use with Container
widget so you want to wrap your widget in Container()
Example
Container(
margin: EdgeInsets.all(10),
padding: EdgeInsets.all(10),
alignment: Alignment.center,
decoration: BoxDecoration(
color: Colors.orange,
border: Border.all(
color: Colors.pink[800],// set border color
width: 3.0), // set border width
borderRadius: BorderRadius.all(
Radius.circular(10.0)), // set rounded corner radius
boxShadow: [BoxShadow(blurRadius: 10,color: Colors.black,offset: Offset(1,3))]// make rounded corner of border
),
child: Text("My demo styling"),
)
private void btnEnter_Click(object sender, EventArgs e)
{
maskedTextBox1.Mask = "00/00/0000";
maskedTextBox1.ValidatingType = typeof(System.DateTime);
//if (!IsValidDOB(maskedTextBox1.Text))
if (!ValidateBirthday(maskedTextBox1.Text))
MessageBox.Show(" Not Valid");
else
MessageBox.Show("Valid");
}
// check date format dd/mm/yyyy. but not if year < 1 or > 2013.
public static bool IsValidDOB(string dob)
{
DateTime temp;
if (DateTime.TryParse(dob, out temp))
return (true);
else
return (false);
}
// checks date format dd/mm/yyyy and year > 1900!.
protected bool ValidateBirthday(String date)
{
DateTime Temp;
if (DateTime.TryParse(date, out Temp) == true &&
Temp.Year > 1900 &&
// Temp.Hour == 0 && Temp.Minute == 0 &&
//Temp.Second == 0 && Temp.Millisecond == 0 &&
Temp > DateTime.MinValue)
return (true);
else
return (false);
}
Stop this error you have to follow this simple steps
Then Run the code by using Shortcut key Ctrl+f5
**Other wise it still show error when you run it direct
For child-parent communication you should pass a function setting the state from parent to child, like this
class Parent extends React.Component {_x000D_
constructor(props) {_x000D_
super(props)_x000D_
_x000D_
this.handler = this.handler.bind(this)_x000D_
}_x000D_
_x000D_
handler() {_x000D_
this.setState({_x000D_
someVar: 'some value'_x000D_
})_x000D_
}_x000D_
_x000D_
render() {_x000D_
return <Child handler = {this.handler} />_x000D_
}_x000D_
}_x000D_
_x000D_
class Child extends React.Component {_x000D_
render() {_x000D_
return <Button onClick = {this.props.handler}/ >_x000D_
}_x000D_
}
_x000D_
This way the child can update the parent's state with the call of a function passed with props.
But you will have to rethink your components' structure, because as I understand components 5 and 3 are not related.
One possible solution is to wrap them in a higher level component which will contain the state of both component 1 and 3. This component will set the lower level state through props.
Perhaps a nice idiom for declaring constants for a class in Swift is to just use a struct named MyClassConstants like the following.
struct MyClassConstants{
static let testStr = "test"
static let testStrLength = countElements(testStr)
static let arrayOfTests: [String] = ["foo", "bar", testStr]
}
In this way your constants will be scoped within a declared construct instead of floating around globally.
I've added a static array constant, in response to a comment asking about static array initialization. See Array Literals in "The Swift Programming Language".
Notice that both string literals and the string constant can be used to initialize the array. However, since the array type is known the integer constant testStrLength
cannot be used in the array initializer.
Use this:
#include <stdlib.h>
#include <string.h>
int main()
{
const char *d1 = "11";
int d1int = atoi(d1);
printf("d1 = %d\n", d1);
return 0;
}
etc.
declaring the list (and initializing it with an empty arraylist)
List<Card> cardList = new ArrayList<Card>();
adding an element:
Card card;
cardList.add(card);
iterating over elements:
for(Card card : cardList){
System.out.println(card);
}
I did 2 things to solve this problem.
EDITOR=emacs crontab -e
(I have no idea why vim does not work)crontab -l
now prints the cronjobs. Now I only need to figure out why the cronjobs are still not running ;-)
Here is ready glow hover animation code snippet for this:
http://codepen.io/widhi_allan/pen/ltaCq
-webkit-filter: drop-shadow(0px 0px 0px rgba(255,255,255,0.80));
You're using JSTL 2.0 right? You don't need to put <c:out/>
around all variables. Have you tried something like this?
<c:forEach items="${myParams.items}" var="currentItem" varStatus="stat">
<c:set var="myVar" value="${myVar}${currentItem}" />
</c:forEach>
Edit: Beaten by the above
In modern browsers you can use Object.getOwnPropertyNames
to get all properties (both enumerable and non-enumerable) on an object. For instance:
function Person ( age, name ) {
this.age = age;
this.name = name;
}
Person.prototype.greet = function () {
return "My name is " + this.name;
};
Person.prototype.age = function () {
this.age = this.age + 1;
};
// ["constructor", "greet", "age"]
Object.getOwnPropertyNames( Person.prototype );
Note that this only retrieves own-properties, so it will not return properties found elsewhere on the prototype chain. That, however, doesn't appear to be your request so I will assume this approach is sufficient.
If you would only like to see enumerable properties, you can instead use Object.keys
. This would return the same collection, minus the non-enumerable constructor
property.
I had the same problem... I am a complete beginner
In my case it happened cause I was trying to do: git merge random_branch/file.txt
My problem was solved when I retired the file.txt and let just the branch name (lol) kkfdskfskdfs
git merge random_branch
worked pretty well
if mylist != []:
print(mylist[0])
else:
print(None)
You can Use Playlist
Right click on the test method -> Add to playlist -> New playlist
the execution order will be as you add them to the playlist but if you want to change it you have the file
So in simple words: Over clause can be used to select non aggregated values along with Aggregated ones.
Partition BY, ORDER BY inside, and ROWS or RANGE are part of OVER() by clause.
partition by is used to partition data and then perform these window, aggregated functions, and if we don't have partition by the then entire result set is considered as a single partition.
OVER clause can be used with Ranking Functions(Rank, Row_Number, Dense_Rank..), Aggregate Functions like (AVG, Max, Min, SUM...etc) and Analytics Functions like (First_Value, Last_Value, and few others).
Let's See basic syntax of OVER clause
OVER (
[ <PARTITION BY clause> ]
[ <ORDER BY clause> ]
[ <ROW or RANGE clause> ]
)
PARTITION BY: It is used to partition data and perform operations on groups with the same data.
ORDER BY: It is used to define the logical order of data in Partitions. When we don't specify Partition, entire resultset is considered as a single partition
: This can be used to specify what rows are supposed to be considered in a partition when performing the operation.
Let's take an example:
Here is my dataset:
Id Name Gender Salary
----------- -------------------------------------------------- ---------- -----------
1 Mark Male 5000
2 John Male 4500
3 Pavan Male 5000
4 Pam Female 5500
5 Sara Female 4000
6 Aradhya Female 3500
7 Tom Male 5500
8 Mary Female 5000
9 Ben Male 6500
10 Jodi Female 7000
11 Tom Male 5500
12 Ron Male 5000
So let me execute different scenarios and see how data is impacted and I'll come from difficult syntax to simple one
Select *,SUM(salary) Over(order by salary RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_sal from employees
Id Name Gender Salary sum_sal
----------- -------------------------------------------------- ---------- ----------- -----------
6 Aradhya Female 3500 3500
5 Sara Female 4000 7500
2 John Male 4500 12000
3 Pavan Male 5000 32000
1 Mark Male 5000 32000
8 Mary Female 5000 32000
12 Ron Male 5000 32000
11 Tom Male 5500 48500
7 Tom Male 5500 48500
4 Pam Female 5500 48500
9 Ben Male 6500 55000
10 Jodi Female 7000 62000
Just observe the sum_sal part. Here I am using order by Salary and using "RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW". In this case, we are not using partition so entire data will be treated as one partition and we are ordering on salary. And the important thing here is UNBOUNDED PRECEDING AND CURRENT ROW. This means when we are calculating the sum, from starting row to the current row for each row. But if we see rows with salary 5000 and name="Pavan", ideally it should be 17000 and for salary=5000 and name=Mark, it should be 22000. But as we are using RANGE and in this case, if it finds any similar elements then it considers them as the same logical group and performs an operation on them and assigns value to each item in that group. That is the reason why we have the same value for salary=5000. The engine went up to salary=5000 and Name=Ron and calculated sum and then assigned it to all salary=5000.
Select *,SUM(salary) Over(order by salary ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_sal from employees
Id Name Gender Salary sum_sal
----------- -------------------------------------------------- ---------- ----------- -----------
6 Aradhya Female 3500 3500
5 Sara Female 4000 7500
2 John Male 4500 12000
3 Pavan Male 5000 17000
1 Mark Male 5000 22000
8 Mary Female 5000 27000
12 Ron Male 5000 32000
11 Tom Male 5500 37500
7 Tom Male 5500 43000
4 Pam Female 5500 48500
9 Ben Male 6500 55000
10 Jodi Female 7000 62000
So with ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW The difference is for same value items instead of grouping them together, It calculates SUM from starting row to current row and it doesn't treat items with same value differently like RANGE
Select *,SUM(salary) Over(order by salary) as sum_sal from employees
Id Name Gender Salary sum_sal
----------- -------------------------------------------------- ---------- ----------- -----------
6 Aradhya Female 3500 3500
5 Sara Female 4000 7500
2 John Male 4500 12000
3 Pavan Male 5000 32000
1 Mark Male 5000 32000
8 Mary Female 5000 32000
12 Ron Male 5000 32000
11 Tom Male 5500 48500
7 Tom Male 5500 48500
4 Pam Female 5500 48500
9 Ben Male 6500 55000
10 Jodi Female 7000 62000
These results are the same as
Select *, SUM(salary) Over(order by salary RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_sal from employees
That is because Over(order by salary) is just a short cut of Over(order by salary RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) So wherever we simply specify Order by without ROWS or RANGE it is taking RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW as default.
Note: This is applicable only to Functions that actually accept RANGE/ROW. For example, ROW_NUMBER and few others don't accept RANGE/ROW and in that case, this doesn't come into the picture.
Till now we saw that Over clause with an order by is taking Range/ROWS and syntax looks something like this RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW And it is actually calculating up to the current row from the first row. But what If it wants to calculate values for the entire partition of data and have it for each column (that is from 1st row to last row). Here is the query for that
Select *,sum(salary) Over(order by salary ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) as sum_sal from employees
Id Name Gender Salary sum_sal
----------- -------------------------------------------------- ---------- ----------- -----------
1 Mark Male 5000 62000
2 John Male 4500 62000
3 Pavan Male 5000 62000
4 Pam Female 5500 62000
5 Sara Female 4000 62000
6 Aradhya Female 3500 62000
7 Tom Male 5500 62000
8 Mary Female 5000 62000
9 Ben Male 6500 62000
10 Jodi Female 7000 62000
11 Tom Male 5500 62000
12 Ron Male 5000 62000
Instead of CURRENT ROW, I am specifying UNBOUNDED FOLLOWING which instructs the engine to calculate till the last record of partition for each row.
Now coming to your point on what is OVER() with empty braces?
It is just a short cut for Over(order by salary ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
Here we are indirectly specifying to treat all my resultset as a single partition and then perform calculations from the first record to the last record of each partition.
Select *,Sum(salary) Over() as sum_sal from employees
Id Name Gender Salary sum_sal
----------- -------------------------------------------------- ---------- ----------- -----------
1 Mark Male 5000 62000
2 John Male 4500 62000
3 Pavan Male 5000 62000
4 Pam Female 5500 62000
5 Sara Female 4000 62000
6 Aradhya Female 3500 62000
7 Tom Male 5500 62000
8 Mary Female 5000 62000
9 Ben Male 6500 62000
10 Jodi Female 7000 62000
11 Tom Male 5500 62000
12 Ron Male 5000 62000
I did create a video on this and if you are interested you can visit it. https://www.youtube.com/watch?v=CvVenuVUqto&t=1177s
Thanks, Pavan Kumar Aryasomayajulu HTTP://xyzcoder.github.io
BEGIN
FOR r IN (select sid,serial# from v$session where username='user')
LOOP
EXECUTE IMMEDIATE 'alter system kill session ''' || r.sid || ',' || r.serial# || '''';
END LOOP;
END;
/
It works for me.
The name
attribute is used when sending data in a form submission. Different controls respond differently. For example, you may have several radio buttons with different id
attributes, but the same name
. When submitted, there is just the one value in the response - the radio button you selected.
Of course, there's more to it than that, but it will definitely get you thinking in the right direction.
*data interprets arguments as tuples, instead you have to pass **data which interprets the arguments as dictionary.
data = {'school':'DAV', 'class': '7', 'name': 'abc', 'city': 'pune'}
def my_function(**data):
schoolname = data['school']
cityname = data['city']
standard = data['class']
studentname = data['name']
You can call the function like this:
my_function(**data)
FYI this turned out to be an issue for me where I had two tables in a statement like the following:
SELECT * FROM table1
UNION ALL
SELECT * FROM table2
It worked, but then somewhere along the line the order of columns in one of the table definitions got changed. Changing the *
to SELECT column1, column2
fixed the issue. No idea how that happened, but lesson learned!
Slight adjustment to answers from ARobertson and Kenneth Wilson that worked for me.
Running R 3.6.0, with library(tidyverse) and library(dplyr) in my environment:
library(tidyverse)
library(dplyr)
> df %<>% mutate_if(is.character, as.numeric)
Error in df %<>% mutate_if(is.character, as.numeric) :
could not find function "%<>%"
I did some quick research and found this note in Hadley's "The tidyverse style guide".
The magrittr package provides the %<>% operator as a shortcut for modifying an object in place. Avoid this operator.
# Good x <- x %>% abs() %>% sort() # Bad x %<>% abs() %>% sort()
Solution
Based on that style guide:
df_clean <- df %>% mutate_if(is.character, as.numeric)
Working example
> df_clean <- df %>% mutate_if(is.character, as.numeric)
Warning messages:
1: NAs introduced by coercion
2: NAs introduced by coercion
3: NAs introduced by coercion
4: NAs introduced by coercion
5: NAs introduced by coercion
6: NAs introduced by coercion
7: NAs introduced by coercion
8: NAs introduced by coercion
9: NAs introduced by coercion
10: NAs introduced by coercion
> df_clean
# A tibble: 3,599 x 17
stack datetime volume BQT90 DBT90 DRT90 DLT90 FBT90 RT90 HTML90 RFT90 RLPP90 RAT90 SRVR90 SSL90 TCP90 group
<dbl> <dttm> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
On Windows, Subversion stores the auth data in %APPDATA%\Subversion\auth
. The passwords however are stored encrypted, not in plaintext.
You can decrypt those, but only if you log in to Windows as the same user for which the auth data was saved.
Someone even wrote a tool to decrypt those. Never tried the tool myself so I don't know how well it works, but you might want to try it anyway:
http://www.leapbeyond.com/ric/TSvnPD/
Update: In TortoiseSVN 1.9 and later, you can do it without any additional tools:
Settings Dialog
-> Saved Data
, then click the "Clear...
" button right of the text "Authentication Data
". A new dialog pops up, showing all stored authentication data where you can chose which one(s) to clear. Instead of clearing, hold down the Shift
and Ctrl
button, and then double click
on the list. A new column is shown in the dialog which shows the password in clear.
If you prefer to use Guice and you don't want to declare all the bindings, you can also try this adapter:
Here's a shorter version without the subselect:
SELECT COUNT(DISTINCT DocumentId, DocumentSessionId) FROM DocumentOutputItems
It works fine in MySQL, and I think that the optimizer has an easier time understanding this one.
Edit: Apparently I misread MSSQL and MySQL - sorry about that, but maybe it helps anyway.
This is round robin DNS. This is a quite simple solution for load balancing. Usually DNS servers rotate/shuffle the DNS records for each incoming DNS request. Unfortunately it's not a real solution for fail-over. If one of the servers fail, some visitors will still be directed to this failed server.
You can also use a shorter way:
<?php header('Content-Type: charset=utf-8'); ?>
See RFC 2616. It's valid to specify only character set.
you can try typescript's For
:
selectChildren(data , $event){
let parentChecked : boolean = data.checked;
for(let o of this.hierarchicalData){
for(let child of o){
child.checked = parentChecked;
}
}
}
The following is a solution for MySQL (not SQL Server), i couldn't easily find a solution to this on stackoverflow for mysql, so i figured maybe this could help someone...
ref: https://forums.mysql.com/read.php?10,285268,285286#msg-285286
original query...
SELECT StudentId FROM Student WHERE condition = xyz
original result set...
StudentId
1236
7656
8990
new query w/ concat...
SELECT group_concat(concat_ws(',', StudentId) separator '; ')
FROM Student
WHERE condition = xyz
concat string result set...
StudentId
1236; 7656; 8990
note: change the 'separator' to whatever you would like
GLHF!
In my case, there was an empty packages.config file in the soultion directory, after deleting this, update succeeded
If you do not want to install Xcode and/or MacPorts/Fink/Homebrew, you could always use the standalone installer: https://sourceforge.net/projects/git-osx-installer/
Assuming you are already in the directory, and that the "first 8 characters" from your comment hold true always. (Although "CHEESE_" is 7 characters... ? If so, change the 8 below to 7)
from glob import glob
from os import rename
for fname in glob('*.prj'):
rename(fname, fname[8:])
I think to keep controllers for Admin and Front in separate folders, the namespace will work well.
Please look on the below Laravel directory structure, that works fine for me.
app
--Http
----Controllers
------Admin
--------DashboardController.php
------Front
--------HomeController.php
The routes in "routes/web.php" file would be as below
/* All the Front-end controllers routes will work under Front namespace */
Route::group(['namespace' => 'Front'], function () {
Route::get('/home', 'HomeController@index');
});
And for Admin section, it will look like
/* All the admin routes will go under Admin namespace */
/* All the admin routes will required authentication,
so an middleware auth also applied in admin namespace */
Route::group(['namespace' => 'Admin'], function () {
Route::group(['middleware' => ['auth']], function() {
Route::get('/', ['as' => 'home', 'uses' => 'DashboardController@index']);
});
});
Hope this helps!!
Use display:none/block
, instead of visibility
, and add a margin-top/bottom
for the space you want to see ONLY when the inputs are shown
function yesnoCheck() {
if (document.getElementById('yesCheck').checked) {
document.getElementById('ifYes').style.display = 'block';
} else {
document.getElementById('ifYes').style.display = 'none';
}
}
and your HTML line for the ifYes
tag
<div id="ifYes" style="display:none;margin-top:3%;">If yes, explain:
Well, if you must have it all in one query, you could do a union:
SELECT distributor_id, COUNT() FROM ... UNION
SELECT COUNT() AS EXEC_COUNT FROM ... WHERE level = 'exec' UNION
SELECT COUNT(*) AS PERSONAL_COUNT FROM ... WHERE level = 'personal';
Or, if you can do after processing:
SELECT distributor_id, COUNT(*) FROM ... GROUP BY level;
You will get the count for each level and need to sum them all up to get the total.
This works for me
$('.someclass').click(function() {
$varName = $(this).data('fulltext');
console.log($varName);
});
Why not just:
names, counts = zip(*D.items())
plt.bar(names, counts)
The python cProfile and pstats modules offer great support for measuring time elapsed in certain functions without having to add any code around the existing functions.
For example if you have a python script timeFunctions.py:
import time
def hello():
print "Hello :)"
time.sleep(0.1)
def thankyou():
print "Thank you!"
time.sleep(0.05)
for idx in range(10):
hello()
for idx in range(100):
thankyou()
To run the profiler and generate stats for the file you can just run:
python -m cProfile -o timeStats.profile timeFunctions.py
What this is doing is using the cProfile module to profile all functions in timeFunctions.py and collecting the stats in the timeStats.profile file. Note that we did not have to add any code to existing module (timeFunctions.py) and this can be done with any module.
Once you have the stats file you can run the pstats module as follows:
python -m pstats timeStats.profile
This runs the interactive statistics browser which gives you a lot of nice functionality. For your particular use case you can just check the stats for your function. In our example checking stats for both functions shows us the following:
Welcome to the profile statistics browser.
timeStats.profile% stats hello
<timestamp> timeStats.profile
224 function calls in 6.014 seconds
Random listing order was used
List reduced from 6 to 1 due to restriction <'hello'>
ncalls tottime percall cumtime percall filename:lineno(function)
10 0.000 0.000 1.001 0.100 timeFunctions.py:3(hello)
timeStats.profile% stats thankyou
<timestamp> timeStats.profile
224 function calls in 6.014 seconds
Random listing order was used
List reduced from 6 to 1 due to restriction <'thankyou'>
ncalls tottime percall cumtime percall filename:lineno(function)
100 0.002 0.000 5.012 0.050 timeFunctions.py:7(thankyou)
The dummy example does not do much but give you an idea of what can be done. The best part about this approach is that I dont have to edit any of my existing code to get these numbers and obviously help with profiling.
You can get all keys / values and preserve the hierarchy with this
// get keys of an object or array
function getkeys(z){
var out=[];
for(var i in z){out.push(i)};
return out;
}
// print all inside an object
function allInternalObjs(data, name) {
name = name || 'data';
return getkeys(data).reduce(function(olist, k){
var v = data[k];
if(typeof v === 'object') { olist.push.apply(olist, allInternalObjs(v, name + '.' + k)); }
else { olist.push(name + '.' + k + ' = ' + v); }
return olist;
}, []);
}
// run with this
allInternalObjs({'a':[{'b':'c'},{'d':{'e':5}}],'f':{'g':'h'}}, 'ob')
This is a modification on (https://stackoverflow.com/a/25063574/1484447)
try this. There are in general three ways to use mysqldump—
in order to dump a set of one or more tables,
shell> mysqldump [options] db_name [tbl_name ...]
a set of one or more complete databases
shell> mysqldump [options] --databases db_name ...
or an entire MySQL server—as shown here:
shell> mysqldump [options] --all-databases
Just supply -s to your read call like so:
$ read -s PASSWORD
$ echo $PASSWORD
public string Type { get; set; }
is no different than doing
private string _Type;
public string Type
{
get { return _Type; }
set { _Type = value; }
}
Have you tried just "TYPE1"? I suppose Spring uses reflection to determine the type of "type" anyway, so the fully qualified name is redundant. Spring generally doesn't subscribe to redundancy!
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)
}
You can use following command and change AJAY SUNDRIYAL with your system name.This is only for your debug.keystore.This will work for you.
C:\Program Files\Java\jdk1.8.0_91\bin>keytool -list -v -keystore "c:\users\AJAY SUNDRIYAL\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
Here is another solution (only relevant declarations listed):
.text span {
display:inline-block;
margin-right:100%;
}
When the margin is expressed in percentage, that percentage is taken from the width of the parent node, so 100% means as wide as the parent, which results in the next element getting "pushed" to a new line.
Here's a basic jQuery plugin I wrote that selects all checkboxes on the page, except the checkbox/element that is to be used as the toggle:
(function($) {
// Checkbox toggle function for selecting all checkboxes on the page
$.fn.toggleCheckboxes = function() {
// Get all checkbox elements
checkboxes = $(':checkbox').not(this);
// Check if the checkboxes are checked/unchecked and if so uncheck/check them
if(this.is(':checked')) {
checkboxes.prop('checked', true);
} else {
checkboxes.prop('checked', false);
}
}
}(jQuery));
Then simply call the function on your checkbox or button element:
// Check all checkboxes
$('.check-all').change(function() {
$(this).toggleCheckboxes();
});
Open Oracle SQLDeveloper
Right click on connection tab and select new connection
Enter HR_ORCL in connection name and HR for the username and password.
Specify localhost for your Hostname and enter ORCL for the SID.
Click Test.
The status of the connection Test Successfully.
The connection was not saved however click on Save button to save the connection. And then click on Connect button to connect your database.
The connection is saved and you see the connection list.
This parameter is is working for me:
--enable-easy-off-store-extension-install
Do the following:
--enable-easy-off-store-extension-install
chrome.exe --enable-easy-off-store-extension-install
Here is the class for thread safe list without lock
public class ConcurrentList
{
private long _i = 1;
private ConcurrentDictionary<long, T> dict = new ConcurrentDictionary<long, T>();
public int Count()
{
return dict.Count;
}
public List<T> ToList()
{
return dict.Values.ToList();
}
public T this[int i]
{
get
{
long ii = dict.Keys.ToArray()[i];
return dict[ii];
}
}
public void Remove(T item)
{
T ov;
var dicItem = dict.Where(c => c.Value.Equals(item)).FirstOrDefault();
if (dicItem.Key > 0)
{
dict.TryRemove(dicItem.Key, out ov);
}
this.CheckReset();
}
public void RemoveAt(int i)
{
long v = dict.Keys.ToArray()[i];
T ov;
dict.TryRemove(v, out ov);
this.CheckReset();
}
public void Add(T item)
{
dict.TryAdd(_i, item);
_i++;
}
public IEnumerable<T> Where(Func<T, bool> p)
{
return dict.Values.Where(p);
}
public T FirstOrDefault(Func<T, bool> p)
{
return dict.Values.Where(p).FirstOrDefault();
}
public bool Any(Func<T, bool> p)
{
return dict.Values.Where(p).Count() > 0 ? true : false;
}
public void Clear()
{
dict.Clear();
}
private void CheckReset()
{
if (dict.Count == 0)
{
this.Reset();
}
}
private void Reset()
{
_i = 1;
}
}
In Swift 5:
var i = 9897
func timeString(time: TimeInterval) -> String {
let hour = Int(time) / 3600
let minute = Int(time) / 60 % 60
let second = Int(time) % 60
// return formated string
return String(format: "%02i:%02i:%02i", hour, minute, second)
}
To call function
timeString(time: TimeInterval(i))
Will return 02:44:57
You will have to make a call to the YouTube data API's video resource after you make the search call. You can put up to 50 video IDs in a search, so you won't have to call it for each element.
https://developers.google.com/youtube/v3/docs/videos/list
You'll want to set part=contentDetails
, because the duration is there.
For example, the following call:
https://www.googleapis.com/youtube/v3/videos?id=9bZkp7q19f0&part=contentDetails&key={YOUR_API_KEY}
Gives this result:
{
"kind": "youtube#videoListResponse",
"etag": "\"XlbeM5oNbUofJuiuGi6IkumnZR8/ny1S4th-ku477VARrY_U4tIqcTw\"",
"items": [
{
"id": "9bZkp7q19f0",
"kind": "youtube#video",
"etag": "\"XlbeM5oNbUofJuiuGi6IkumnZR8/HN8ILnw-DBXyCcTsc7JG0z51BGg\"",
"contentDetails": {
"duration": "PT4M13S",
"dimension": "2d",
"definition": "hd",
"caption": "false",
"licensedContent": true,
"regionRestriction": {
"blocked": [
"DE"
]
}
}
}
]
}
The time is formatted as an ISO 8601 string. PT stands for Time Duration, 4M is 4 minutes, and 13S is 13 seconds.
You're going to have a hard time writing to the same file you're reading from. One quick way is to simply do this:
File.WriteAllText("test.txt", File.ReadAllText("test.txt").Replace("some text","some other text"));
You can lay that out better with
string str = File.ReadAllText("test.txt");
str = str.Replace("some text","some other text");
File.WriteAllText("test.txt", str);
You probably want to use something like jQuery, which makes JS programming easier.
Something like:
$(document).ready(function(){
// Your code here
});
Would seem to do what you are after.
Use the -S (note: capital S) switch to GCC, and it will emit the assembly code to a file with a .s extension. For example, the following command:
gcc -O2 -S -c foo.c
Pretty sure you could've made that into a three line example. :)
If you want exact precision, use BigDecimal. Otherwise, you can use ints multiplied by 10 ^ whatever precision you want.
Try this extension method out. Hopefully this could help.
public static class DistinctHelper
{
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
var identifiedKeys = new HashSet<TKey>();
return source.Where(element => identifiedKeys.Add(keySelector(element)));
}
}
Usage:
var outputList = sourceList.DistinctBy(x => x.TargetProperty);
you can write multiple lines in case of different minutes, for example you want to run at 10:01 AM and 2:30 PM
1 10 * * * php -f /var/www/package/index.php controller function
30 14 * * * php -f /var/www/package/index.php controller function
but the following is the best solution for running cron multiple times in a day as minutes are same, you can mention hours like 10,30
.
30 10,14 * * * php -f /var/www/package/index.php controller function
The name
property is marked as protected
. This was added in TypeScript 1.3 and is now firmly established.
The makeSound
method is marked as abstract
, as is the class. You cannot directly instantiate an Animal
now, because it is abstract. This is part of TypeScript 1.6, which is now officially live.
abstract class Animal {
constructor(protected name: string) { }
abstract makeSound(input : string) : string;
move(meters) {
alert(this.name + " moved " + meters + "m.");
}
}
class Snake extends Animal {
constructor(name: string) { super(name); }
makeSound(input : string) : string {
return "sssss"+input;
}
move() {
alert("Slithering...");
super.move(5);
}
}
The old way of mimicking an abstract method was to throw an error if anyone used it. You shouldn't need to do this any more once TypeScript 1.6 lands in your project:
class Animal {
constructor(public name) { }
makeSound(input : string) : string {
throw new Error('This method is abstract');
}
move(meters) {
alert(this.name + " moved " + meters + "m.");
}
}
class Snake extends Animal {
constructor(name) { super(name); }
makeSound(input : string) : string {
return "sssss"+input;
}
move() {
alert("Slithering...");
super.move(5);
}
}
This is kind of overriding the thing of one page, but... You could use iframes in HTML.
<html>
<body>
<iframe src="page1.html" border="0"></iframe>
</body>
</html>
And page1.html would be your base page. Your still making multiple pages, but your browser just doesn't move. So lets say thats your index.html. You have tabs, you click page 2, your url wont change, but the page will. All in iframes. The only thing different, is that you can view the frame source as well.
For this problem the best solution I use is to have a CLR function in Sql Server 2005 that uses one of DateTime.Parse or ParseExact function to return the DateTime value with a specified format.
The main thing is that if you don't store in onSaveInstanceState()
then onRestoreInstanceState()
will not be called. This is the main difference between restoreInstanceState()
and onCreate()
. Make sure you really store something. Most likely this is your problem.
After inspecting the sample website you provided, I found that the author might achieve the effect by using a library called Stellar.js, take a look at the library site, cheers!
First of all i say that you should google this as it is defined in detail in many places
Local
These variables only exist inside the specific function that creates them. They are unknown to other functions and to the main program. As such, they are normally implemented using a stack. Local variables cease to exist once the function that created them is completed. They are recreated each time a function is executed or called.
Global
These variables can be accessed (ie known) by any function comprising the program. They are implemented by associating memory locations with variable names. They do not get recreated if the function is recalled.
/* Demonstrating Global variables */
#include <stdio.h>
int add_numbers( void ); /* ANSI function prototype */
/* These are global variables and can be accessed by functions from this point on */
int value1, value2, value3;
int add_numbers( void )
{
auto int result;
result = value1 + value2 + value3;
return result;
}
main()
{
auto int result;
value1 = 10;
value2 = 20;
value3 = 30;
result = add_numbers();
printf("The sum of %d + %d + %d is %d\n",
value1, value2, value3, final_result);
}
Sample Program Output
The sum of 10 + 20 + 30 is 60
The scope of global variables can be restricted by carefully placing the declaration. They are visible from the declaration until the end of the current source file.
#include <stdio.h>
void no_access( void ); /* ANSI function prototype */
void all_access( void );
static int n2; /* n2 is known from this point onwards */
void no_access( void )
{
n1 = 10; /* illegal, n1 not yet known */
n2 = 5; /* valid */
}
static int n1; /* n1 is known from this point onwards */
void all_access( void )
{
n1 = 10; /* valid */
n2 = 3; /* valid */
}
Static:
Static object is an object that persists from the time it's constructed until the end of the program. So, stack and heap objects are excluded. But global objects, objects at namespace scope, objects declared static inside classes/functions, and objects declared at file scope are included in static objects. Static objects are destroyed when the program stops running.
I suggest you to see this tutorial list
AUTO:
C, C++
(Called automatic variables.)
All variables declared within a block of code are automatic by default, but this can be made explicit with the auto keyword.[note 1] An uninitialized automatic variable has an undefined value until it is assigned a valid value of its type.[1]
Using the storage class register instead of auto is a hint to the compiler to cache the variable in a processor register. Other than not allowing the referencing operator (&) to be used on the variable or any of its subcomponents, the compiler is free to ignore the hint.
In C++, the constructor of automatic variables is called when the execution reaches the place of declaration. The destructor is called when it reaches the end of the given program block (program blocks are surrounded by curly brackets). This feature is often used to manage resource allocation and deallocation, like opening and then automatically closing files or freeing up memory.SEE WIKIPEDIA
If you are running puppet it may set /proc/sys/kernel/modules_disabled
to 1, inhibiting further module loading.
When the machine is reboot, it gets set back to 0, allowing for changes, such as loading the iptables modules. After a certain amount of time puppet will set it back to 1 to protect the system from kernel root kits.
Therefore, whatever modules that we are going to need should be loaded during or shortly after boot time.
Just download and install LocalDB 64BIT\SqlLocalDB.msi can also solve this problem. You don't really need to uninstall and reinstall SQL Server 2014 Express with Advanced Services.
@drop-shadow if you're using Hibernate, you can call Hibernate.initialize()
when you invoke the getStudents()
method:
Public class UniversityDaoImpl extends GenericDaoHibernate<University, Integer> implements UniversityDao {
//...
@Override
public University get(final Integer id) {
Query query = getQuery("from University u where idUniversity=:id").setParameter("id", id).setMaxResults(1).setFetchSize(1);
University university = (University) query.uniqueResult();
***Hibernate.initialize(university.getStudents());***
return university;
}
//...
}
Use the preprocessor #
operator:
#define CALL_DO_SOMETHING(VAR) do_something(#VAR, VAR);
You can use WhereNotIn in following way also:
ModelName::whereNotIn('book_price', [100,200])->get(['field_name1','field_name2']);
This will return collection of Record with specific fields
Personally, I'd use file_put_contents and file_get_contents (these are wrappers for fopen, fputs, etc).
Also, if you are going to write any structured data, such as arrays, I suggest you serialize and unserialize the files contents.
$file = '/tmp/file';
$content = serialize($my_variable);
file_put_contents($file, $content);
$content = unserialize(file_get_contents($file));
Yes, there's str_to_date
mysql> select str_to_date("03/02/2009","%d/%m/%Y");
+--------------------------------------+
| str_to_date("03/02/2009","%d/%m/%Y") |
+--------------------------------------+
| 2009-02-03 |
+--------------------------------------+
1 row in set (0.00 sec)
Old question, but I see that this thread was fairly recently active, so I'll go ahead and throw in my two cents:
Pretty much exactly what Mitch said. Assuming proper indexing, you can just go ahead and use square bracket notation as if you were accessing an array. In addition to using the numeric index, though, if your members have specific names, you can often do kind of a simultaneous search/access by typing something like:
var temp = list1["DesiredMember"];
The more you know, right?
Visual Studio 2015 doesn't install C++ by default. You have to rerun the setup, select Modify and then check Programming Language -> C++
You didn't select post_id
in the subquery. You have to select it in the subquery like this:
SELECT wp_woocommerce_order_items.order_id As No_Commande
FROM wp_woocommerce_order_items
LEFT JOIN
(
SELECT meta_value As Prenom, post_id -- <----- this
FROM wp_postmeta
WHERE meta_key = '_shipping_first_name'
) AS a
ON wp_woocommerce_order_items.order_id = a.post_id
WHERE wp_woocommerce_order_items.order_id =2198
Oops... Misunderstood the question...
Pause is the way to go
you can pipe commands into your patch file...
try
build.bat < responsefile.txt
you can try this and don't need JQuery: timeSolver.js
For example, add 5 day on today:
var newDay = timeSolver.add(new Date(),5,"day");
You also can add by hour, month...etc. please see for more infomation.
If you want use RegEx in .NET,
Regex rx = new Regex(@"^([\w]+)(\-)*");
var match = rx.Match("thisis-thefirst");
var text = match.Groups[1].Value;
Assert.AreEqual("thisis", text);
Forcefully Change History
Assuming you don't just want to delete the last commit, but you want to delete specific commits of the last n commits, go with:
git rebase -i HEAD~<number of commits to go back>
, so git rebase -i HEAD~5
if you want to see the last five commits.
Then in the text editor change the word pick
to drop
next to every commit you would like to remove. Save and quit the editor. Voila!
Additively Change History
Try git revert <commit hash>
. Revert will create a new commit that undoes the specified commit.
First change apache listen port 80 to 8080 apache in /etc/apache2/ports.conf include
Listen 1.2.3.4:80 to 1.2.3.4:8080
sudo service apache2 restart
or
sudo service httpd restart // in case of centos
then add nginx as reverse proxy server that will listen apache port
server {
listen 1.2.3.4:80;
server_name some.com;
access_log /var/log/nginx/something-access.log;
location / {
proxy_pass http://localhost:8080;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location ~* ^.+\.(jpg|js|jpeg|png)$ {
root /usr/share/nginx/html/;
}
location /404.html {
root /usr/share/nginx/html/40x.html;
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
# put code for static content like js/css/images/fonts
}
After changes restart nginx server
sudo service nginx restart
Now all traffic will be handled by nginx server and send all dynamic request to apache and static conten is served by nginx server.
For advance configuration like cache :
Some times eclipse may confuse with other projects in the same directory.
Just change package name (don't forget to change in Android manifest file also), ensure the package name is not used already in the directory. It may work.
$("#locationthemes").prop("checked")
In Python 3, TemporaryDirectory in the tempfile module can be used.
This is straight from the examples:
import tempfile
with tempfile.TemporaryDirectory() as tmpdirname:
print('created temporary directory', tmpdirname)
# directory and contents have been removed
If you would like to keep the directory a bit longer, you could do something like this:
import tempfile
temp_dir = tempfile.TemporaryDirectory()
print(temp_dir.name)
# use temp_dir, and when done:
temp_dir.cleanup()
The documentation also says that "On completion of the context or destruction of the temporary directory object the newly created temporary directory and all its contents are removed from the filesystem." So at the end of the program, for example, Python will clean up the directory if it wasn't explicitly removed. Python's unittest
may complain of ResourceWarning: Implicitly cleaning up <TemporaryDirectory...
if you rely on this, though.
Try Base64 encoding/decoding your binary data. Also look into CDATA sections
The reason for this error occurs is that you are using the CryptoListPresenter _presenter
without initializing.
I found that CryptoListPresenter _presenter
would have to be initialized to fix because _presenter.loadCurrencies()
is passing through a null variable at the time of instantiation;
there are two ways to initialize
Can be initialized during an declaration, like this
CryptoListPresenter _presenter = CryptoListPresenter();
In the second, initializing(with assigning some value) it when initState
is called, which the framework will call this method once for each state object.
@override
void initState() {
_presenter = CryptoListPresenter(...);
}
Following code might be useful if someone is using React and has a different component of Marker and want to remove marker from map.
export default function useGoogleMapMarker(props) {
const [marker, setMarker] = useState();
useEffect(() => {
// ...code
const marker = new maps.Marker({ position, map, title, icon });
// ...code
setMarker(marker);
return () => marker.setMap(null); // to remove markers when unmounts
}, []);
return marker;
}
demo: http://so.devilmaycode.it/jquery-convert-line-breaks-to-br-nl2br-equivalent
function nl2br (str, is_xhtml) {
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}
The shortest way (will print "not same" because String comparison is case sensitive):
def compareString = {
it == "india" ? "same" : "not same"
}
compareString("India")
var map_marker = $(".map-marker").children("img").attr("src") var pinImage = new google.maps.MarkerImage(map_marker);
var marker = new google.maps.Marker({
position: uluru,
map: map,
icon: pinImage
});
}
I was facing the same issue but I switched 26.0.0-beta1 dependencies to 26.1.0 and it's working now.
Just a note in case others have the same problem.
I had the same problem and found a different answer. I found that getting the height of a div that's height is determined by its contents needs to be initiated on window.load, or window.scroll not document.ready otherwise i get odd heights/smaller heights, i.e before the images have loaded. I also used outerHeight().
var currentHeight = 0;
$(window).load(function() {
//get the natural page height -set it in variable above.
currentHeight = $('#js_content_container').outerHeight();
console.log("set current height on load = " + currentHeight)
console.log("content height function (should be 374) = " + contentHeight());
});
A SELECT INTO
statement will throw an error if it returns anything other than 1 row. If it returns 0 rows, you'll get a no_data_found
exception. If it returns more than 1 row, you'll get a too_many_rows
exception. Unless you know that there will always be exactly 1 employee with a salary greater than 3000, you do not want a SELECT INTO
statement here.
Most likely, you want to use a cursor to iterate over (potentially) multiple rows of data (I'm also assuming that you intended to do a proper join between the two tables rather than doing a Cartesian product so I'm assuming that there is a departmentID
column in both tables)
BEGIN
FOR rec IN (SELECT EMPLOYEE.EMPID,
EMPLOYEE.ENAME,
EMPLOYEE.DESIGNATION,
EMPLOYEE.SALARY,
DEPARTMENT.DEPT_NAME
FROM EMPLOYEE,
DEPARTMENT
WHERE employee.departmentID = department.departmentID
AND EMPLOYEE.SALARY > 3000)
LOOP
DBMS_OUTPUT.PUT_LINE ('Employee Nnumber: ' || rec.EMPID);
DBMS_OUTPUT.PUT_LINE ('---------------------------------------------------');
DBMS_OUTPUT.PUT_LINE ('Employee Name: ' || rec.ENAME);
DBMS_OUTPUT.PUT_LINE ('---------------------------------------------------');
DBMS_OUTPUT.PUT_LINE ('Employee Designation: ' || rec.DESIGNATION);
DBMS_OUTPUT.PUT_LINE ('----------------------------------------------------');
DBMS_OUTPUT.PUT_LINE ('Employee Salary: ' || rec.SALARY);
DBMS_OUTPUT.PUT_LINE ('----------------------------------------------------');
DBMS_OUTPUT.PUT_LINE ('Employee Department: ' || rec.DEPT_NAME);
END LOOP;
END;
I'm assuming that you are just learning PL/SQL as well. In real code, you'd never use dbms_output
like this and would not depend on anyone seeing data that you write to the dbms_output
buffer.
@Robino was suggesting to add some tests which make sense, so here is a simple benchmark between 3 possible ways (maybe the most used ones) to convert an iterator to a list:
list(my_iterator)
[*my_iterator]
[e for e in my_iterator]
I have been using simple_bechmark library
from simple_benchmark import BenchmarkBuilder
from heapq import nsmallest
b = BenchmarkBuilder()
@b.add_function()
def convert_by_type_constructor(size):
list(iter(range(size)))
@b.add_function()
def convert_by_list_comprehension(size):
[e for e in iter(range(size))]
@b.add_function()
def convert_by_unpacking(size):
[*iter(range(size))]
@b.add_arguments('Convert an iterator to a list')
def argument_provider():
for exp in range(2, 22):
size = 2**exp
yield size, size
r = b.run()
r.plot()
As you can see there is very hard to make a difference between conversion by the constructor and conversion by unpacking, conversion by list comprehension is the “slowest” approach.
I have been testing also across different Python versions (3.6, 3.7, 3.8, 3.9) by using the following simple script:
import argparse
import timeit
parser = argparse.ArgumentParser(
description='Test convert iterator to list')
parser.add_argument(
'--size', help='The number of elements from iterator')
args = parser.parse_args()
size = int(args.size)
repeat_number = 10000
# do not wait too much if the size is too big
if size > 10000:
repeat_number = 100
def test_convert_by_type_constructor():
list(iter(range(size)))
def test_convert_by_list_comprehension():
[e for e in iter(range(size))]
def test_convert_by_unpacking():
[*iter(range(size))]
def get_avg_time_in_ms(func):
avg_time = timeit.timeit(func, number=repeat_number) * 1000 / repeat_number
return round(avg_time, 6)
funcs = [test_convert_by_type_constructor,
test_convert_by_unpacking, test_convert_by_list_comprehension]
print(*map(get_avg_time_in_ms, funcs))
The script will be executed via a subprocess from a Jupyter Notebook (or a script), the size parameter will be passed through command-line arguments and the script results will be taken from standard output.
from subprocess import PIPE, run
import pandas
simple_data = {'constructor': [], 'unpacking': [], 'comprehension': [],
'size': [], 'python version': []}
size_test = 100, 1000, 10_000, 100_000, 1_000_000
for version in ['3.6', '3.7', '3.8', '3.9']:
print('test for python', version)
for size in size_test:
command = [f'python{version}', 'perf_test_convert_iterator.py', f'--size={size}']
result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
constructor, unpacking, comprehension = result.stdout.split()
simple_data['constructor'].append(float(constructor))
simple_data['unpacking'].append(float(unpacking))
simple_data['comprehension'].append(float(comprehension))
simple_data['python version'].append(version)
simple_data['size'].append(size)
df_ = pandas.DataFrame(simple_data)
df_
You can get my full notebook from here.
In most of the cases, in my tests, unpacking shows to be faster, but the difference is so small that the results may change from a run to the other. Again, the comprehension approach is the slowest, in fact, the other 2 methods are up to ~ 60% faster.
It was already pointed in this comment and in this answer, but I'll try to give a more direct answer to the question:
from IPython.display import display
import numpy as np
import pandas as pd
n = 100
foo = pd.DataFrame(index=range(n))
foo['floats'] = np.random.randn(n)
with pd.option_context("display.max_rows", foo.shape[0]):
display(foo)
pandas.option_context is available since pandas 0.13.1 (pandas 0.13.1 release notes). According to this,
[it] allow[s] you to execute a codeblock with a set of options that revert to prior settings when you exit the with block.
| Basis | Linear | Logistic |
|-----------------------------------------------------------------|--------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------|
| Basic | The data is modelled using a straight line. | The probability of some obtained event is represented as a linear function of a combination of predictor variables. |
| Linear relationship between dependent and independent variables | Is required | Not required |
| The independent variable | Could be correlated with each other. (Specially in multiple linear regression) | Should not be correlated with each other (no multicollinearity exist). |
Where you have written the code
public class Main {
public static void main(String args[])
{
Calculate obj = new Calculate(1,2,'+');
obj.getAnswer();
}
}
Here you have to run the class "Main" instead of the class you created at the start of the program. To do so pls go to Run Configuration and search for this class name"Main" which is having the main method inside this(public static void main(String args[])). And you will get your output.
I met the same situation under windows, and searched for the solution.
Seeing this post Install mysql-python (Windows).
It points out installing such a pip environment is difficult, needs many other dependencies.
But I finally know that if we use mysqlclient
with a version down to 1.3.4
, it don't need that requirements any more, so try:
pip install mysqlclient==1.3.4
In iOS 9.1 and lower, go to Settings - General - Profiles - tap on your Profile - tap on Trust button.
In iOS 9.2+ & iOS 11+ go to: Settings - General - Profiles & Device Management - tap on your Profile - tap on Trust button.
In iOS 10+, go to: Settings - General - Device Management - tap on your Profile - tap on Trust button.
For your idea, actually you are approaching the success, but if you do like this should be fine:
for (int i=0;i<String_Array.length;i++) String_Array[i]=(String)Object_Array[i];
BTW, using the Arrays utility method is quite good and make the code elegant.
That's because endOf
mutates the original value.
Relevant quote:
Mutates the original moment by setting it to the end of a unit of time.
Here's an example function that gives you the output you want:
function getMonthDateRange(year, month) {
var moment = require('moment');
// month in moment is 0 based, so 9 is actually october, subtract 1 to compensate
// array is 'year', 'month', 'day', etc
var startDate = moment([year, month - 1]);
// Clone the value before .endOf()
var endDate = moment(startDate).endOf('month');
// just for demonstration:
console.log(startDate.toDate());
console.log(endDate.toDate());
// make sure to call toDate() for plain JavaScript date type
return { start: startDate, end: endDate };
}
References:
If you have <repositories/>
defined in your pom.xml apparently your local repository is ignored.
This code sample can be used to change date format. Here I want to change from yyyy-MM-dd to dd-MM-yyyy. Here pos
is position of column.
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
class Test{
public static void main( String[] args )
{
String input="D:\\somefolder\\somefile.xlsx";
String output="D:\\somefolder\\someoutfile.xlsx"
FileInputStream file = new FileInputStream(new File(input));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> iterator = sheet.iterator();
Cell cell = null;
Row row=null;
row=iterator.next();
int pos=5; // 5th column is date.
while(iterator.hasNext())
{
row=iterator.next();
cell=row.getCell(pos-1);
//CellStyle cellStyle = wb.createCellStyle();
XSSFCellStyle cellStyle = (XSSFCellStyle)cell.getCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(
createHelper.createDataFormat().getFormat("dd-MM-yyyy"));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d=null;
try {
d= sdf.parse(cell.getStringCellValue());
} catch (ParseException e) {
// TODO Auto-generated catch block
d=null;
e.printStackTrace();
continue;
}
cell.setCellValue(d);
cell.setCellStyle(cellStyle);
}
file.close();
FileOutputStream outFile =new FileOutputStream(new File(output));
workbook.write(outFile);
workbook.close();
outFile.close();
}}
Here is the best way to do it in compilation time. I have used the arg_var count answer from here.
#define PP_NARG(...) \
PP_NARG_(__VA_ARGS__,PP_RSEQ_N())
#define PP_NARG_(...) \
PP_ARG_N(__VA_ARGS__)
#define PP_ARG_N( \
_1, _2, _3, _4, _5, _6, _7, _8, _9,_10, \
_11,_12,_13,_14,_15,_16,_17,_18,_19,_20, \
_21,_22,_23,_24,_25,_26,_27,_28,_29,_30, \
_31,_32,_33,_34,_35,_36,_37,_38,_39,_40, \
_41,_42,_43,_44,_45,_46,_47,_48,_49,_50, \
_51,_52,_53,_54,_55,_56,_57,_58,_59,_60, \
_61,_62,_63,N,...) N
#define PP_RSEQ_N() \
63,62,61,60, \
59,58,57,56,55,54,53,52,51,50, \
49,48,47,46,45,44,43,42,41,40, \
39,38,37,36,35,34,33,32,31,30, \
29,28,27,26,25,24,23,22,21,20, \
19,18,17,16,15,14,13,12,11,10, \
9,8,7,6,5,4,3,2,1,0
#define TypedEnum(Name, ...) \
struct Name { \
enum { \
__VA_ARGS__ \
}; \
static const uint32_t Name##_MAX = PP_NARG(__VA_ARGS__); \
}
#define Enum(Name, ...) TypedEnum(Name, __VA_ARGS__)
To declare an enum:
Enum(TestEnum,
Enum_1= 0,
Enum_2= 1,
Enum_3= 2,
Enum_4= 4,
Enum_5= 8,
Enum_6= 16,
Enum_7= 32);
the max will be available here:
int array [TestEnum::TestEnum_MAX];
for(uint32_t fIdx = 0; fIdx < TestEnum::TestEnum_MAX; fIdx++)
{
array [fIdx] = 0;
}
Use "target" attribute and remove the 'compiler' attribute. See here. So it should go something like this:
<target name="compile">
<javac target="1.5" srcdir=.../>
</target>
Hope this helps
Here is one quick suggestion for creating variable names. If you want the variable not to conflict when being used in FireFox, do not use the variable name "_content" as this variable name is already being used by the browser. I found this out the hard way and had to change all of the places I used the variable "_content" in a large JavaScript application.
This is an example without using the onClick event. I simply pass a callback function to the child by props. With that callback the child call also send data back. I was inspired by the examples in the docs.
Small example (this is in a tsx files, so props and states must be declared fully, I deleted some logic out of the components, so it is less code).
*Update: Important is to bind this to the callback, otherwise the callback has the scope of the child and not the parent. Only problem: it is the "old" parent...
SymptomChoser is the parent:
interface SymptomChooserState {
// true when a symptom was pressed can now add more detail
isInDetailMode: boolean
// since when user has this symptoms
sinceDate: Date,
}
class SymptomChooser extends Component<{}, SymptomChooserState> {
state = {
isInDetailMode: false,
sinceDate: new Date()
}
helloParent(symptom: Symptom) {
console.log("This is parent of: ", symptom.props.name);
// TODO enable detail mode
}
render() {
return (
<View>
<Symptom name='Fieber' callback={this.helloParent.bind(this)} />
</View>
);
}
}
Symptom is the child (in the props of the child I declared the callback function, in the function selectedSymptom the callback is called):
interface SymptomProps {
// name of the symptom
name: string,
// callback to notify SymptomChooser about selected Symptom.
callback: (symptom: Symptom) => void
}
class Symptom extends Component<SymptomProps, SymptomState>{
state = {
isSelected: false,
severity: 0
}
selectedSymptom() {
this.setState({ isSelected: true });
this.props.callback(this);
}
render() {
return (
// symptom is not selected
<Button
style={[AppStyle.button]}
onPress={this.selectedSymptom.bind(this)}>
<Text style={[AppStyle.textButton]}>{this.props.name}</Text>
</Button>
);
}
}
I am trying to obtain a handle on one of the views in the Action Bar
I will assume that you mean something established via android:actionLayout
in your <item>
element of your <menu>
resource.
I have tried calling findViewById(R.id.menu_item)
To retrieve the View
associated with your android:actionLayout
, call findItem()
on the Menu
to retrieve the MenuItem
, then call getActionView()
on the MenuItem
. This can be done any time after you have inflated the menu resource.
You can use the memcpy()
,
void * memcpy ( void * destination, const void * source, size_t num );
memcpy()
copies the values of num
bytes from the location pointed by source
directly to the memory block pointed by destination
.
If the destination
and source
overlap, then you can use memmove()
.
void * memmove ( void * destination, const void * source, size_t num );
memmove()
copies the values of num
bytes from the location pointed by source
to the memory block pointed by destination
. Copying takes place as if an intermediate buffer were used, allowing the destination and source to overlap.
To flatten a MultiIndex inside a chain of other DataFrame methods, define a function like this:
def flatten_index(df):
df_copy = df.copy()
df_copy.columns = ['_'.join(col).rstrip('_') for col in df_copy.columns.values]
return df_copy.reset_index()
Then use the pipe
method to apply this function in the chain of DataFrame methods, after groupby
and agg
but before any other methods in the chain:
my_df \
.groupby('group') \
.agg({'value': ['count']}) \
.pipe(flatten_index) \
.sort_values('value_count')
After some research on this topic, I found that the error is occured basically if you have an instance of db created previously on your local sql server express. So whenever you have updates on db and try to update the db/run some code on db without running Update Database
command using Package Manager Console
; first of all, you have to delete previous db on our local sql express manually.
Also, this solution works unless you have AutomaticMigrationsEnabled = false;
in your Configuration.
If you work with a version control system (git,svn,etc.) and some other developers update db objects in production phase then this error rises whenever you update your code base and run the application.
As stated above, there are some solutions for this on code base. However, this is the most practical one for some cases.
Try this:
ioreg -p IOUSB -l -b | grep -E "@|PortNum|USB Serial Number"
pathMatch = 'full'
results in a route hit when the remaining, unmatched segments of the URL match is the prefix path
pathMatch = 'prefix'
tells the router to match the redirect route when the remaining URL begins with the redirect route's prefix path.
Ref: https://angular.io/guide/router#set-up-redirects
pathMatch: 'full'
means, that the whole URL path needs to match and is consumed by the route matching algorithm.
pathMatch: 'prefix'
means, the first route where the path matches the start of the URL is chosen, but then the route matching algorithm is continuing searching for matching child routes where the rest of the URL matches.
Using session
, I successfully passed a parameter (name
) from servlet #1 to servlet #2, using response.sendRedirect
in servlet #1. Servlet #1 code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
String name = request.getParameter("name");
String password = request.getParameter("password");
...
request.getSession().setAttribute("name", name);
response.sendRedirect("/todo.do");
In Servlet #2, you don't need to get name
back. It's already connected to the session. You could do String name = (String) request.getSession().getAttribute("name");
---but you don't need this.
If Servlet #2 calls a JSP, you can show name
this way on the JSP webpage:
<h1>Welcome ${name}</h1>
We are using Elasticsearch version 1.6 and I used this query from a co-worker to cover not null and not empty for a field:
{
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": {
"bool": {
"must": [
{
"exists": {
"field": "myfieldName"
}
},
{
"not": {
"filter": {
"term": {
"myfieldName": ""
}
}
}
}
]
}
}
}
}
}
You can use in swift 4 or 5
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd H:mm:ss"
let current_date_time = dateFormatter.string(from: date)
print("before add time-->",current_date_time)
//adding 5 miniuts
let addminutes = date.addingTimeInterval(5*60)
dateFormatter.dateFormat = "yyyy-MM-dd H:mm:ss"
let after_add_time = dateFormatter.string(from: addminutes)
print("after add time-->",after_add_time)
output:
before add time--> 2020-02-18 10:38:15
after add time--> 2020-02-18 10:43:15
Podfile.lock file right under Podfile within your project.
The main thing is , Force it to open through your favourite TextEditor, like Sublime or TextEdit [Open With -> Select Sublime] as it doesn't give an option straight away to open.
The FLAG_ACTIVITY_NO_ANIMATION
flag works fine for disabling the animation when starting activities.
To disable the similar animation that is triggered when calling finish()
on an Activity, i.e the animation slides from right to left instead, you can call overridePendingTransition(0, 0)
after calling finish()
and the next animation will be excluded.
This also works on the in-animation if you call overridePendingTransition(0, 0)
after calling startActivity(...)
.
This works for me in Ubuntu 12.04 and 15.10
if pip not installed:
sudo apt-get install python-pip
and then:
sudo apt-get update
sudo apt-get install libpq-dev python-dev
sudo pip install psycopg2
This line looks suspicious:
invaders[i] = inv;
You're never incrementing i
, so you keep assigning to invaders[0]
. If this is just an error you made when reducing your code to the example, check how you calculate i
in the real code; you could be exceeding the size of invaders
.
If as your comment suggests, you're creating 55 invaders
, then check that invaders
has been initialised correctly to handle this number.
From http://docs.python.org/library/csv.html#csv.writer:
If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.
In other words, when opening the file you pass 'wb' as opposed to 'w'.
You can also use a with
statement to close the file when you're done writing to it.
Tested example below:
from __future__ import with_statement # not necessary in newer versions
import csv
headers=['id', 'year', 'activity', 'lineitem', 'datum']
with open('file3.csv','wb') as fou: # note: 'wb' instead of 'w'
output = csv.DictWriter(fou,delimiter=',',fieldnames=headers)
output.writerow(dict((fn,fn) for fn in headers))
output.writerows(rows)
Those who installed node.js via the package manager can just run:
sudo apt-get purge nodejs
Optionally if you have installed it by adding the official NodeSource repository as stated in Installing Node.js via package manager, do:
sudo rm /etc/apt/sources.list.d/nodesource.list
If you want to clean up npm cache as well:
rm -rf ~/.npm
It is bad practice to try to remove things manually, as it can mess up the package manager, and the operating system itself. This answer is completely safe to follow
You want the :checkbox:checked
selector and map
to create an array of the values:
var checkedValues = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
If your checkboxes have a shared class it would be faster to use that instead, eg. $('.mycheckboxes:checked')
, or for a common name $('input[name="Foo"]:checked')
- Update -
If you don't need IE support then you can now make the map()
call more succinct by using an arrow function:
var checkedValues = $('input:checkbox:checked').map((i, el) => el.value).get();
It's very nice to see so many spirited approaches to this problem. Quite inspiring indeed!
I came across this topic searching for a simple iterative solution for deleting all nodes in my binary tree implementation. I tried some of them, and I tried something similar found elsewhere on the Net, but none of them were really to my liking.
The thing is, I am developing a database indexing module for a very specific purpose (Bitcoin Blockchain indexing), and my data is stored on disk, not in RAM. I swap in pages as needed, doing my own memory management. It's slower, but fast enough for the purpose, and with having storage on disk instead of RAM, I have no religious bearings against wasting space (hard disks are cheap).
For that reason my nodes in my binary tree have parent pointers. That's (all) the extra space I'm talking about. I need the parents because I need to iterate both ascending and descending through the tree for various purposes.
Having that in my mind, I quickly wrote down a little piece of pseudo-code on how it could be done, that is, a post-order traversal deleting nodes on the fly. It's implemented and tested, and became a part of my solution. And it's pretty fast too.
The thing is: It gets really, REALLY, simple when nodes have parent pointers, and furthermore since I can null out the parent's link to the "just departed" node.
Here's the pseudo-code for iterative post-order deletion:
Node current = root;
while (current)
{
if (current.left) current = current.left; // Dive down left
else if (current.right) current = current.right; // Dive down right
else
{
// Node "current" is a leaf, i.e. no left or right child
Node parent = current.parent; // assuming root.parent == null
if (parent)
{
// Null out the parent's link to the just departing node
if (parent.left == current) parent.left = null;
else parent.right = null;
}
delete current;
current = parent;
}
}
root = null;
If you are interested in a more theoretical approach to coding complex collections (such as my binary tree, which is really a self-balancing red-black-tree), then check out these links:
http://opendatastructures.org/versions/edition-0.1e/ods-java/6_2_BinarySearchTree_Unbala.html http://opendatastructures.org/versions/edition-0.1e/ods-java/9_2_RedBlackTree_Simulated_.html https://www.cs.auckland.ac.nz/software/AlgAnim/red_black.html
Happy coding :-)
Søren Fog http://iprotus.eu/
Although the other answers posted here work, I find the following approach more natural:
$obj = (object) [
'aString' => 'some string',
'anArray' => [ 1, 2, 3 ]
];
echo json_encode($obj);
C++11 brought us lambdas, which can be incredibly useful in this situation:
#define MACRO(X,Y) \
[&](x_, y_) { \
cout << "1st arg is:" << x_ << endl; \
cout << "2nd arg is:" << y_ << endl; \
cout << "Sum is:" << (x_ + y_) << endl; \
}((X), (Y))
You keep the generative power of macros, but have a comfy scope from which you can return whatever you want (including void
). Additionally, the issue of evaluating macro parameters multiple times is avoided.
I have looked around for a fix for this. I have a jquery mobile site that has a final print page and it combines dozens of pages. I tried all the fixes above but the only thing I could get to work is this:
<div style="clear:both!important;"/></div>
<div style="page-break-after:always"></div>
<div style="clear:both!important;"/> </div>
I used following code on my sample application to start new activity.
Button next = (Button) findViewById(R.id.TEST);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent( view.getContext(), MyActivity.class);
startActivityForResult(myIntent, 0);
}
});
I knew I am late to the party but below is the correct way to deal with this, the key is to use InputStreamBody
in place of FileBody
to upload multi-part file.
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("https://someserver.com/api/path/");
postRequest.addHeader("Authorization",authHeader);
//don't set the content type here
//postRequest.addHeader("Content-Type","multipart/form-data");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
File file = new File(filePath);
FileInputStream fileInputStream = new FileInputStream(file);
reqEntity.addPart("parm-name", new InputStreamBody(fileInputStream,"image/jpeg","file_name.jpg"));
postRequest.setEntity(reqEntity);
HttpResponse response = httpclient.execute(postRequest);
}catch(Exception e) {
Log.e("URISyntaxException", e.toString());
}
Yep, and if you have tried all the above solutions (what's more likely to happen) and none work for you, it may happen that Guzzle is not installed.
Laravel ships mailing tools, by which is required the Guzzle framework, but it won't be installed, and AS OF the documentation, will have to install it manually: https://laravel.com/docs/master/mail#driver-prerequisites
composer require guzzlehttp/guzzle
You must write schema name and table name in qutotation mark. As below:
select * from "schemaName"."tableName";
Use jQuery. You need to capture the click
event and then go on to the website.
$("#myHref").on('click', function() {_x000D_
alert("inside onclick");_x000D_
window.location = "http://www.google.com";_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<a href="#" id="myHref">Click me</a>
_x000D_
If you use Pycharm, renaming an app is very easy with refactoring(Shift
+F6
default) for all project files.
But make sure you delete the __pycache__
folders in the project directory & its sub-directories. Also be careful as it also renames comments too which you can exclude in the refactor preview window it will show you.
And you'll have to rename OldNameConfig(AppConfig): in apps.py
of your renamed app in addition.
If you do not want to lose data of your database, you'll have to manually do it with query in database like the aforementioned answer.
Lets assume this code is running in a thread:
private static ReentrantLock lock = new ReentrantLock();
void accessResource() {
lock.lock();
if( checkSomeCondition() ) {
accessResource();
}
lock.unlock();
}
Because the thread owns the lock it will allow multiple calls to lock(), so it re-enter the lock. This can be achieved with a reference count so it doesn't has to acquire lock again.
My solution is based on the TechNet article Fun Things You Can Do With the Get-ChildItem Cmdlet.
Get-ChildItem C:\foo | Where-Object {$_.mode -match "d"}
I used it in my script, and it works well.
Once I changed Options -Index
to Options +Index
in my conf file, I removed the welcome page and restarted services.
$ sudo rm -f /etc/httpd/conf.d/welcome.conf
$ sudo service httpd restart
I was able to see directory listings after that.
@IBAction func chooseProfilePicBtnClicked(sender: AnyObject) {
let alert:UIAlertController=UIAlertController(title: "Choose Image", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
let cameraAction = UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default)
{
UIAlertAction in
self.openCamera()
}
let gallaryAction = UIAlertAction(title: "Gallary", style: UIAlertActionStyle.Default)
{
UIAlertAction in
self.openGallary()
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel)
{
UIAlertAction in
}
// Add the actions
picker.delegate = self
alert.addAction(cameraAction)
alert.addAction(gallaryAction)
alert.addAction(cancelAction)
self.presentViewController(alert, animated: true, completion: nil)
}
func openCamera(){
if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)){
picker.sourceType = UIImagePickerControllerSourceType.Camera
self .presentViewController(picker, animated: true, completion: nil)
}else{
let alert = UIAlertView()
alert.title = "Warning"
alert.message = "You don't have camera"
alert.addButtonWithTitle("OK")
alert.show()
}
}
func openGallary(){
picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(picker, animated: true, completion: nil)
}
//MARK:UIImagePickerControllerDelegate
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){
picker .dismissViewControllerAnimated(true, completion: nil)
imageViewRef.image=info[UIImagePickerControllerOriginalImage] as? UIImage
}
func imagePickerControllerDidCancel(picker: UIImagePickerController){
print("picker cancel.")
}
Use the flex-grow
property to the main content div and give the dispaly: flex;
to its parent;
body {_x000D_
height: 100%;_x000D_
position: absolute;_x000D_
margin: 0;_x000D_
}_x000D_
section {_x000D_
height: 100%;_x000D_
display: flex;_x000D_
flex-direction : column;_x000D_
}_x000D_
header {_x000D_
background: tomato;_x000D_
}_x000D_
div {_x000D_
flex: 1; /* or flex-grow: 1 */;_x000D_
overflow-x: auto;_x000D_
background: gold;_x000D_
}_x000D_
footer {_x000D_
background: lightgreen;_x000D_
min-height: 60px;_x000D_
}
_x000D_
<section>_x000D_
<header>_x000D_
header: sized to content_x000D_
<br>(but is it really?)_x000D_
</header>_x000D_
<div>_x000D_
main content: fills remaining space<br>_x000D_
x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
</div>_x000D_
<footer>_x000D_
footer: fixed height in px_x000D_
</footer>_x000D_
</section>
_x000D_
For primitive types (including bytes), use System.Buffer.BlockCopy
instead of System.Array.Copy
. It's faster.
I timed each of the suggested methods in a loop executed 1 million times using 3 arrays of 10 bytes each. Here are the results:
System.Array.Copy
- 0.2187556 secondsSystem.Buffer.BlockCopy
- 0.1406286 secondsI increased the size of each array to 100 elements and re-ran the test:
System.Array.Copy
- 0.2812554 secondsSystem.Buffer.BlockCopy
- 0.2500048 secondsI increased the size of each array to 1000 elements and re-ran the test:
System.Array.Copy
- 1.0781457 secondsSystem.Buffer.BlockCopy
- 1.0156445 secondsFinally, I increased the size of each array to 1 million elements and re-ran the test, executing each loop only 4000 times:
System.Array.Copy
- 13.4533833 secondsSystem.Buffer.BlockCopy
- 13.1096267 secondsSo, if you need a new byte array, use
byte[] rv = new byte[a1.Length + a2.Length + a3.Length];
System.Buffer.BlockCopy(a1, 0, rv, 0, a1.Length);
System.Buffer.BlockCopy(a2, 0, rv, a1.Length, a2.Length);
System.Buffer.BlockCopy(a3, 0, rv, a1.Length + a2.Length, a3.Length);
But, if you can use an IEnumerable<byte>
, DEFINITELY prefer LINQ's Concat<> method. It's only slightly slower than the C# yield operator, but is more concise and more elegant.
IEnumerable<byte> rv = a1.Concat(a2).Concat(a3);
If you have an arbitrary number of arrays and are using .NET 3.5, you can make the System.Buffer.BlockCopy
solution more generic like this:
private byte[] Combine(params byte[][] arrays)
{
byte[] rv = new byte[arrays.Sum(a => a.Length)];
int offset = 0;
foreach (byte[] array in arrays) {
System.Buffer.BlockCopy(array, 0, rv, offset, array.Length);
offset += array.Length;
}
return rv;
}
*Note: The above block requires you adding the following namespace at the the top for it to work.
using System.Linq;
To Jon Skeet's point regarding iteration of the subsequent data structures (byte array vs. IEnumerable<byte>), I re-ran the last timing test (1 million elements, 4000 iterations), adding a loop that iterates over the full array with each pass:
System.Array.Copy
- 78.20550510 secondsSystem.Buffer.BlockCopy
- 77.89261900 secondsThe point is, it is VERY important to understand the efficiency of both the creation and the usage of the resulting data structure. Simply focusing on the efficiency of the creation may overlook the inefficiency associated with the usage. Kudos, Jon.
If you are using python 2.7 or later, the easiest way to do this is to use the subprocess.check_output()
command. Here is an example:
output = subprocess.check_output('ls')
To also redirect stderr you can use the following:
output = subprocess.check_output('ls', stderr=subprocess.STDOUT)
In the case that you want to pass parameters to the command, you can either use a list or use invoke a shell and use a single string.
output = subprocess.check_output(['ls', '-a'])
output = subprocess.check_output('ls -a', shell=True)
Simplified example (with counter):
With Me.lstbox
.ColumnCount = 2
.ColumnWidths = "60;60"
.AddItem
.List(i, 0) = Company_ID
.List(i, 1) = Company_name
i = i + 1
end with
Make sure to start the counter with 0, not 1 to fill up a listbox.
var str = 'Dude, he totally said that "You Rock!"';
var var1 = str.replace(/\"/g,"\\\"");
alert(var1);
Building on @Pvl's answer, you can include type safety on your returned value as well if you use overrides:
function dig<
T,
K1 extends keyof T
>(obj: T, key1: K1): T[K1];
function dig<
T,
K1 extends keyof T,
K2 extends keyof T[K1]
>(obj: T, key1: K1, key2: K2): T[K1][K2];
function dig<
T,
K1 extends keyof T,
K2 extends keyof T[K1],
K3 extends keyof T[K1][K2]
>(obj: T, key1: K1, key2: K2, key3: K3): T[K1][K2][K3];
function dig<
T,
K1 extends keyof T,
K2 extends keyof T[K1],
K3 extends keyof T[K1][K2],
K4 extends keyof T[K1][K2][K3]
>(obj: T, key1: K1, key2: K2, key3: K3, key4: K4): T[K1][K2][K3][K4];
function dig<
T,
K1 extends keyof T,
K2 extends keyof T[K1],
K3 extends keyof T[K1][K2],
K4 extends keyof T[K1][K2][K3],
K5 extends keyof T[K1][K2][K3][K4]
>(obj: T, key1: K1, key2: K2, key3: K3, key4: K4, key5: K5): T[K1][K2][K3][K4][K5];
function dig<
T,
K1 extends keyof T,
K2 extends keyof T[K1],
K3 extends keyof T[K1][K2],
K4 extends keyof T[K1][K2][K3],
K5 extends keyof T[K1][K2][K3][K4]
>(obj: T, key1: K1, key2?: K2, key3?: K3, key4?: K4, key5?: K5):
T[K1] |
T[K1][K2] |
T[K1][K2][K3] |
T[K1][K2][K3][K4] |
T[K1][K2][K3][K4][K5] {
let value: any = obj && obj[key1];
if (key2) {
value = value && value[key2];
}
if (key3) {
value = value && value[key3];
}
if (key4) {
value = value && value[key4];
}
if (key5) {
value = value && value[key5];
}
return value;
}
Example on playground.
You can reduce the server-side load by performing this logic client-side. View source on some Digg pages for reference. They have the server emit an epoch time value that gets processed by Javascript. This way you don't need to manage the end user's time zone. The new server-side code would be something like:
public string GetRelativeTime(DateTime timeStamp)
{
return string.Format("<script>printdate({0});</script>", timeStamp.ToFileTimeUtc());
}
You could even add a NOSCRIPT block there and just perform a ToString().
http://en.wikipedia.org/wiki/Post/Redirect/Get
The most common way to implement this pattern in ASP.Net is to use Response.Redirect(Request.RawUrl)
Consider the differences between Redirect and Transfer. Transfer really isn't telling the browser to forward to a clear form, it's simply returning a cleared form. That may or may not be what you want.
Response.Redirect() does not a waste round trip. If you post to a script that clears the form by Server.Transfer() and reload you will be asked to repost by most browsers since the last action was a HTTP POST. This may cause your users to unintentionally repeat some action, eg. place a second order which will have to be voided later.
This approaches uses string concatenation to produce a statement with all tables and their counts dynamically, like the example(s) given in the original question:
SELECT COUNT(*) AS Count,'[dbo].[tbl1]' AS TableName FROM [dbo].[tbl1]
UNION ALL SELECT COUNT(*) AS Count,'[dbo].[tbl2]' AS TableName FROM [dbo].[tbl2]
UNION ALL SELECT...
Finally this is executed with EXEC
:
DECLARE @cmd VARCHAR(MAX)=STUFF(
(
SELECT 'UNION ALL SELECT COUNT(*) AS Count,'''
+ QUOTENAME(t.TABLE_SCHEMA) + '.' + QUOTENAME(t.TABLE_NAME)
+ ''' AS TableName FROM ' + QUOTENAME(t.TABLE_SCHEMA) + '.' + QUOTENAME(t.TABLE_NAME)
FROM INFORMATION_SCHEMA.TABLES AS t
WHERE TABLE_TYPE='BASE TABLE'
FOR XML PATH('')
),1,10,'');
EXEC(@cmd);
According to this article on sqlserverstudymaterial;
Remember that "%Privileged time" is not based on 100%.It is based on number of processors.If you see 200 for sqlserver.exe and the system has 8 CPU then CPU consumed by sqlserver.exe is 200 out of 800 (only 25%).
If "% Privileged Time" value is more than 30% then it's generally caused by faulty drivers or anti-virus software. In such situations make sure the BIOS and filter drives are up to date and then try disabling the anti-virus software temporarily to see the change.
If "% User Time" is high then there is something consuming of SQL Server. There are several known patterns which can be caused high CPU for processes running in SQL Server including
Swift 4.x
func iOS_VERSION_EQUAL_TO(version: String) -> Bool {
return UIDevice.current.systemVersion.compare(version, options: NSString.CompareOptions.numeric) == ComparisonResult.orderedSame
}
func iOS_VERSION_GREATER_THAN(version: String) -> Bool {
return UIDevice.current.systemVersion.compare(version, options: NSString.CompareOptions.numeric) == ComparisonResult.orderedDescending
}
func iOS_VERSION_GREATER_THAN_OR_EQUAL_TO(version: String) -> Bool {
return UIDevice.current.systemVersion.compare(version, options: NSString.CompareOptions.numeric) != ComparisonResult.orderedAscending
}
func iOS_VERSION_LESS_THAN(version: String) -> Bool {
return UIDevice.current.systemVersion.compare(version, options: NSString.CompareOptions.numeric) == ComparisonResult.orderedAscending
}
func iOS_VERSION_LESS_THAN_OR_EQUAL_TO(version: String) -> Bool {
return UIDevice.current.systemVersion.compare(version, options: NSString.CompareOptions.numeric) != ComparisonResult.orderedDescending
}
Usage:
if iOS_VERSION_GREATER_THAN_OR_EQUAL_TO(version: "11.0") {
//Do something!
}
P.S. KVISH answer translated to Swift 4.x with renaming the functions as I am specifically using this snippet for the iOS app.
on ubuntu 18.04 ( virtualenv, python.3.6.x), the following reload snippet solved the problem for me:
main.py
import my_module # my_module.py
from importlib import reload # reload
reload(my_module)
print(my_module)
print(my_modeule.hello())
where:
|--main.py
|--my_module.py
for more documentation check : here
Checksum all files, including both content and their filenames
grep -ar -e . /your/dir | md5sum | cut -c-32
Same as above, but only including *.py files
grep -ar -e . --include="*.py" /your/dir | md5sum | cut -c-32
You can also follow symlinks if you want
grep -aR -e . /your/dir | md5sum | cut -c-32
Other options you could consider using with grep
-s, --no-messages suppress error messages
-D, --devices=ACTION how to handle devices, FIFOs and sockets;
-Z, --null print 0 byte after FILE name
-U, --binary do not strip CR characters at EOL (MSDOS/Windows)
Data view is good Feature of data table . We can filter the data table as per our requirements using data view . Below Functions is After binding data table to list box data source then filter by text box control . ( this condition you can change as per your needs .Contains(txtSearch.Text.Trim()) )
Private Sub BindClients()
okcl = 0
sql = "Select * from Client Order By cname"
Dim dacli As New SqlClient.SqlDataAdapter
Dim cmd As New SqlClient.SqlCommand()
cmd.CommandText = sql
cmd.CommandType = CommandType.Text
dacli.SelectCommand = cmd
dacli.SelectCommand.Connection = Me.sqlcn
Dim dtcli As New DataTable
dacli.Fill(dtcli)
dacli.Fill(dataTableClients)
lstboxc.DataSource = dataTableClients
lstboxc.DisplayMember = "cname"
lstboxc.ValueMember = "ccode"
okcl = 1
If dtcli.Rows.Count > 0 Then
ccode = dtcli.Rows(0)("ccode")
Call ClientDispData1()
End If
End Sub
Private Sub FilterClients()
Dim query As EnumerableRowCollection(Of DataRow) = From dataTableClients In
dataTableClients.AsEnumerable() Where dataTableClients.Field(Of String)
("cname").Contains(txtSearch.Text.Trim()) Order By dataTableClients.Field(Of
String)("cname") Select dataTableClients
Dim dataView As DataView = query.AsDataView()
lstboxc.DataSource = dataView
lstboxc.DisplayMember = "cname"
lstboxc.ValueMember = "ccode"
okcl = 1
If dataTableClients.Rows.Count > 0 Then
ccode = dataTableClients.Rows(0)("ccode")
Call ClientDispData1()
End If
End Sub
If you have to use an image as the transparent background, you might be able to work around it using a pseudo element:
html
<div class="wrap">
<p>I have 100% opacity</p>
</div>
css
.wrap, .wrap > * {
position: relative;
}
.wrap:before {
content: " ";
opacity: 0.2;
background: url("http://placehold.it/100x100/FF0000") repeat;
position: absolute;
width: 100%;
height: 100%;
}
Try parent_window.maxsize(x,x);
to set the maximum size. It shouldn't get larger even if you set the background, etc.
Edit: use parent_window.minsize(x,x)
also to set it to a constant size!
if someones is interested you can delete the form node from the DOM after the submission and it won't be there using the inspector.
https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/remove
I tried to use dplyr::rename and I get an error:
occ_5d <- dplyr::rename(occ_5d, rowname='code_5d')
Error: Unknown column `code_5d`
Call `rlang::last_error()` to see a backtrace
I instead used the base R function which turns out to be quite simple and effective:
names(occ_5d)[1] = "code_5d"
If scrollHeight could be trusted, then:
textarea.onkeyup=function() {
this.style.height='';
this.rows=this.value.split('\n').length;
this.style.height=this.scrollHeight+'px';
}
Just access the Priority
property of the object returned from the pipeline:
$var = (Get-WSManInstance -enumerate wmicimv2/win32_process).Priority
(This won't work if Get-WSManInstance
returns multiple objects.2)
For the second question: to get two properties there are several options, problably the simplest is to have have one variable* containing an object with two separate properties:
$var = (Get-WSManInstance -enumerate wmicimv2/win32_process | select -first 1 Priority, ProcessID)
and then use, assuming only one process:
$var.Priority
and
$var.ProcessID
If there are multiple processes $var
will be an array which you can index, so to get the properties of the first process (using the array literal syntax @(...)
so it is always a collection1):
$var = @(Get-WSManInstance -enumerate wmicimv2/win32_process | select -first 1 Priority, ProcessID)
and then use:
$var[0].Priority
$var[0].ProcessID
1 PowerShell helpfully for the command line, but not so helpfully in scripts has some extra logic when assigning the result of a pipeline to a variable: if no objects are returned then set $null
, if one is returned then that object is assigned, otherwise an array is assigned. Forcing an array returns an array with zero, one or more (respectively) elements.
2 This changes in PowerShell V3 (at the time of writing in Release Candidate), using a member property on an array of objects will return an array of the value of those properties.
The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
index.php
<html>
<body>
<form action="site2.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>
</body>
</html>
site2.php
<html>
<body>
Hello <?php echo $_POST["name"]; ?>!<br>
Your mail is <?php echo $_POST["mail"]; ?>.
</body>
</html>
output
Hello "name" !
Your email is "[email protected]" .
From SQL Server Management Studio
Right click the table you want to export and select "Select All Rows"
Right click the results window and select "Save Results As..."
In case of a multi-value return function you can't refer to fields or methods of a specific value of the result when calling the function.
And if one of them is an error
, it's there for a reason (which is the function might fail) and you should not bypass it because if you do, your subsequent code might also fail miserably (e.g. resulting in runtime panic).
However there might be situations where you know the code will not fail in any circumstances. In these cases you can provide a helper function (or method) which will discard the error
(or raise a runtime panic if it still occurs).
This can be the case if you provide the input values for a function from code, and you know they work.
Great examples of this are the template
and regexp
packages: if you provide a valid template or regexp at compile time, you can be sure they can always be parsed without errors at runtime. For this reason the template
package provides the Must(t *Template, err error) *Template
function and the regexp
package provides the MustCompile(str string) *Regexp
function: they don't return error
s because their intended use is where the input is guaranteed to be valid.
Examples:
// "text" is a valid template, parsing it will not fail
var t = template.Must(template.New("name").Parse("text"))
// `^[a-z]+\[[0-9]+\]$` is a valid regexp, always compiles
var validID = regexp.MustCompile(`^[a-z]+\[[0-9]+\]$`)
IF you can be certain Get()
will not produce error
for certain input values, you can create a helper Must()
function which would not return the error
but raise a runtime panic if it still occurs:
func Must(i Item, err error) Item {
if err != nil {
panic(err)
}
return i
}
But you should not use this in all cases, just when you're sure it succeeds. Usage:
val := Must(Get(1)).Value
Alternative / Simplification
You can even simplify it further if you incorporate the Get()
call into your helper function, let's call it MustGet
:
func MustGet(value int) Item {
i, err := Get(value)
if err != nil {
panic(err)
}
return i
}
Usage:
val := MustGet(1).Value
See some interesting / related questions:
On a Windows 10 x64 machine, I made the command prompt display non-English characters by:
Open an elevated command prompt (run CMD.EXE as administrator). Query your registry for available TrueType fonts to the console by:
REG query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont"
You'll see an output like:
0 REG_SZ Lucida Console
00 REG_SZ Consolas
936 REG_SZ *???
932 REG_SZ *MS ????
Now we need to add a TrueType font that supports the characters you need like Courier New. We do this by adding zeros to the string name, so in this case the next one would be "000":
REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont" /v 000 /t REG_SZ /d "Courier New"
Now we implement UTF-8 support:
REG ADD HKCU\Console /v CodePage /t REG_DWORD /d 65001 /f
Set default font to "Courier New":
REG ADD HKCU\Console /v FaceName /t REG_SZ /d "Courier New" /f
Set font size to 20:
REG ADD HKCU\Console /v FontSize /t REG_DWORD /d 20 /f
Enable quick edit if you like:
REG ADD HKCU\Console /v QuickEdit /t REG_DWORD /d 1 /f
There's an easier way, by extending an empty LatLngBounds
rather than creating one explicitly from two points. (See this question for more details)
Should look something like this, added to your code:
//create empty LatLngBounds object
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();
for (i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
//extend the bounds to include each marker's position
bounds.extend(marker.position);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
//now fit the map to the newly inclusive bounds
map.fitBounds(bounds);
//(optional) restore the zoom level after the map is done scaling
var listener = google.maps.event.addListener(map, "idle", function () {
map.setZoom(3);
google.maps.event.removeListener(listener);
});
This way, you can use an arbitrary number of points, and don't need to know the order beforehand.
Demo jsFiddle here: http://jsfiddle.net/x5R63/
GROUP BY 1
I've never known GROUP BY to support using ordinals, only ORDER BY. Either way, only MySQL supports GROUP BY's not including all columns without aggregate functions performed on them. Ordinals aren't recommended practice either because if they're based on the order of the SELECT - if that changes, so does your ORDER BY (or GROUP BY if supported).
There's no need to run GROUP BY
on the contents when you're using UNION
- UNION ensures that duplicates are removed; UNION ALL
is faster because it doesn't - and in that case you would need the GROUP BY...
Your query only needs to be:
SELECT a.id,
a.time
FROM dbo.TABLE_A a
UNION
SELECT b.id,
b.time
FROM dbo.TABLE_B b
Instead of myFile.js write your files like myFile.mjs. This extension comes with all the goodies of es6, but I mean I recommend you to you webpack and Babel
Run the following command to enable credential caching:
$ git config credential.helper store
$ git push https://github.com/owner/repo.git
Username for 'https://github.com': <USERNAME>
Password for 'https://[email protected]': <PASSWORD>
You should also specify caching expire,
git config --global credential.helper 'cache --timeout 7200'
After enabling credential caching, it will be cached for 7200 seconds (2 hour).
here you go Sir :-)
1
.myElement{
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-rendering: optimizeLegibility;
}
2
.myElement{
text-shadow: rgba(0,0,0,.01) 0 0 1px;
}
I want to work with exec_query
of the ActiveRecord
class, because it returns the mapping of the query transforming into object, so it gets very practical and productive to iterate with the objects when the subject is Raw SQL.
Example:
values = ActiveRecord::Base.connection.exec_query("select * from clients")
p values
and return this complete query:
[{"id": 1, "name": "user 1"}, {"id": 2, "name": "user 2"}, {"id": 3, "name": "user 3"}]
To get only list of values
p values.rows
[[1, "user 1"], [2, "user 2"], [3, "user 3"]]
To get only fields columns
p values.columns
["id", "name"]
Make sure to check the python version you are working on if it is 2 then only pip install works If it is 3. something then make sure to use pip3 install
With GCC 4.1.2, to print the whole of a std::vector<int> called myVector, do the following:
print *(myVector._M_impl._M_start)@myVector.size()
To print only the first N elements, do:
print *(myVector._M_impl._M_start)@N
Explanation
This is probably heavily dependent on your compiler version, but for GCC 4.1.2, the pointer to the internal array is:
myVector._M_impl._M_start
And the GDB command to print N elements of an array starting at pointer P is:
print P@N
Or, in a short form (for a standard .gdbinit):
p P@N
return n
from main
is equivalent to exit(n)
.
The valid returned is the rest of your program. It's meaning is OS dependent. On unix, 0 means normal termination and non-zero indicates that so form of error forced your program to terminate without fulfilling its intended purpose.
It's unusual that your example returns 0 (normal termination) when it seems to have run out of memory.
Try the below code to unprotect the workbook. It works for me just fine in excel 2010 but I am not sure if it will work in 2013.
Sub PasswordBreaker()
'Breaks worksheet password protection.
Dim i As Integer, j As Integer, k As Integer
Dim l As Integer, m As Integer, n As Integer
Dim i1 As Integer, i2 As Integer, i3 As Integer
Dim i4 As Integer, i5 As Integer, i6 As Integer
On Error Resume Next
For i = 65 To 66: For j = 65 To 66: For k = 65 To 66
For l = 65 To 66: For m = 65 To 66: For i1 = 65 To 66
For i2 = 65 To 66: For i3 = 65 To 66: For i4 = 65 To 66
For i5 = 65 To 66: For i6 = 65 To 66: For n = 32 To 126
ThisWorkbook.Unprotect Chr(i) & Chr(j) & Chr(k) & _
Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _
Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
If ThisWorkbook.ProtectStructure = False Then
MsgBox "One usable password is " & Chr(i) & Chr(j) & _
Chr(k) & Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & _
Chr(i3) & Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
Exit Sub
End If
Next: Next: Next: Next: Next: Next
Next: Next: Next: Next: Next: Next
End Sub
In the nav go View => Layout => Columns:2
(alt+shift+2
) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py
)
It appears you can also reopen the file using the command File -> New View into File
which will open the current file in a new tab
Set force Portrait or Landscape mode, Add lines respectively.
Import below line:
import android.content.pm.ActivityInfo;
Add Below line just above setContentView(R.layout.activity_main);
For Portrait:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//Set Portrait
For Landscap:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//Set Landscape
This will definitely work.
Try this to prevent client from any kind of vertical scrolling on hashchanged (inside your event handler):
var sct = document.body.scrollTop;
document.location.hash = '#next'; // or other manipulation
document.body.scrollTop = sct;
(browser redraw)
I just delete settings.lic file from project and start working!
$.get("/folder_name/filename.xml", function (xml) {_x000D_
var xmlInnerhtml = xml.documentElement.innerHTML;_x000D_
});
_x000D_
Sorry for answering so late.
I figured an answer alike to @xlm 's:
task run (type: JavaExec, dependsOn: classes){
if(project.hasProperty('myargs')){
args(myargs.split(','))
}
description = "Secure algorythm testing"
main = "main.Test"
classpath = sourceSets.main.runtimeClasspath
}
And invoke like:
gradle run -Pmyargs=-d,s
You can use JSONPath
Doing something like this:
results = JSONPath(null, TestObj, "$..[?(@.id=='A')]")
Note that JSONPath returns an array of results
(I have not tested the expression "$..[?(@.id=='A')]" btw. Maybe it needs to be fine-tuned with the help of a browser console)
There is no way to rename a folder through the GUI, the fastest (and easiest if you like GUI) way to achieve this is to perform an plain old copy. To achieve this: create the new folder on S3 using the GUI, get to your old folder, select all, mark "copy" and then navigate to the new folder and choose "paste". When done, remove the old folder.
This simple method is very fast because it is copies from S3 to itself (no need to re-upload or anything like that) and it also maintains the permissions and metadata of the copied objects like you would expect.
I would ALWAYS go with both the alt
and the title
attributes. Many developers have been using this pattern now for over 20 years to deal with IE and other issues. So this is not new knowledge. Its just been rediscovered by new developers that didn't bother to learn from the past.
In addition, in HTML5 you should start using the new HTML5 picture
element wrapped in figure
with full WPA-ARIA attributes for greater accessibility, as well as support of assistive technologies, screen readers, and the like. Because this element is not supported in many older browsers...BUT degrades gracefully...I recommend the following HTML design pattern now for images in HTML:
<figure aria-labelledby="picturecaption2">
<picture id="picture2">
<source srcset="image.webp" type="image/webp" media="(min-width: 800px)" />
<source srcset="image.gif" type="image/gif" />
<img id="image2" style="height:auto;max-width: 100%;" src="image.jpg" width="255" height="200" alt="image:The World Wide Web" title="The World Wide Web" loading="lazy" no-referrer="no-referrer" onerror="this.onerror=null;" />
</picture>
<figcaption id="picturecaption2"><small>"My Cool Picture" [<a href="http://creativecommons.org/licenses/" target="_blank">A License</a>] , via <a href="https://commons.wikimedia.org/wiki/" target="_blank">Wikimedia Commons</a></small></figcaption>
</figure>
The code above has many extra "goodies" beside alt
and title
, including ARIA attributes, support for WebP, a media query supporting higher resolution imagery, and a nice fallback pattern supporting older image formats. It shows a fully decorated image example that uses new technologies while still supporting old ones with progressive design patterns.
REMEMBER...ALWAYS SUPPORT THE OLD BROWSERS!
Vinay (above) gave an effective work-around. What's actually causing the button's OnClick event to not work following the OnClientClick event function is that MS has defined it where, once the button is disabled (in the function called by the OnClientClick event), the button "honors" this by not trying to complete the button's activity by calling the OnClick event's defined method.
I struggled several hours trying to figure this out. Once I removed the statement to disable the submit button (that was inside the OnClientClick function), the OnClick method was called with no further problem.
Microsoft, if you're listening, once the button is clicked it should complete it's assigned activity even if it is disabled part of the way through this activity. As long as it is not disabled when it is clicked, it should complete all assigned methods.
git rm --cached file
should do what you want.
You can read more details at git help rm
use Latin1_General_CS as your collation in your sql db
You should create new SSH key set for that Docker image, as you probably don't want to embed there your own private key. To make it work, you'll have to add that key to deployment keys in your git repository. Here's complete recipe:
Generate ssh keys with ssh-keygen -q -t rsa -N '' -f repo-key
which will give you repo-key and repo-key.pub files.
Add repo-key.pub to your repository deployment keys.
On GitHub, go to [your repository] -> Settings -> Deploy keys
Add something like this to your Dockerfile:
ADD repo-key / RUN \ chmod 600 /repo-key && \ echo "IdentityFile /repo-key" >> /etc/ssh/ssh_config && \ echo -e "StrictHostKeyChecking no" >> /etc/ssh/ssh_config && \ // your git clone commands here...
Note that above switches off StrictHostKeyChecking, so you don't need .ssh/known_hosts. Although I probably like more the solution with ssh-keyscan in one of the answers above.
I think i have the easiest approach... on pressing new in B..
Intent intent = new Intent(B.this, A.class);
intent.putExtra("NewClicked", true);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
and in A get it
if (getIntent().getBooleanExtra("NewClicked", false)) {
finish();// finish yourself and make a create a new Instance of yours.
Intent intent = new Intent(A.this,A.class);
startActivity(intent);
}
I would use the operator[].
map <char, int> m1;
m1['G'] ++; // If the element 'G' does not exist then it is created and
// initialized to zero. A reference to the internal value
// is returned. so that the ++ operator can be applied.
// If 'G' did not exist it now exist and is 1.
// If 'G' had a value of 'n' it now has a value of 'n+1'
So using this technique it becomes really easy to read all the character from a stream and count them:
map <char, int> m1;
std::ifstream file("Plop");
std::istreambuf_iterator<char> end;
for(std::istreambuf_iterator<char> loop(file); loop != end; ++loop)
{
++m1[*loop]; // prefer prefix increment out of habbit
}
this will remove the trailing commas and spaces
var str = ",'first string','more','even more'";
var trim = str.replace(/(^\s*,)|(,\s*$)/g, '');