import sys
try:
print("stuff")
except:
sys.exit(1) # exiing with a non zero value is better for returning from an error
Here's another solution which only works for contiguous enums. It gives the expected iteration, except for ugliness in the increment, which is where it belongs, since that's what's broken in C++.
enum Bar {
One = 1,
Two,
Three,
End_Bar // Marker for end of enum;
};
for (Bar foo = One; foo < End_Bar; foo = Bar(foo + 1))
{
// ...
}
From the documentation (MySQL 8) :
Type | Maximum length -----------+------------------------------------- TINYTEXT | 255 (2 8−1) bytes TEXT | 65,535 (216−1) bytes = 64 KiB MEDIUMTEXT | 16,777,215 (224−1) bytes = 16 MiB LONGTEXT | 4,294,967,295 (232−1) bytes = 4 GiB
Note that the number of characters that can be stored in your column will depend on the character encoding.
What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:
x = ["0", "1", "2"]
y = int(x[0]) #accessing the zeroth element
If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:
x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)
If your list elements are not strings, you'll have to convert them to strings before using str.join
:
x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)
Also, as stated above, make sure that you're not returning a nested list.
You can use this code snippet:
var New1 = EmpList.OrderBy(z => z.Age).ToList();
where New1
is a List<Employee>
.
EmpList
is variable of a List<Employee>
.
z
is a variable of Employee
type.
I think the easiest way is to create an interface to get the data from onpostexecute and run the Ui from interface :
Create an Interface :
public interface AsyncResponse {
void processFinish(String output);
}
Then in asynctask
@Override
protected void onPostExecute(String data) {
delegate.processFinish(data);
}
Then in yout main activity
@Override
public void processFinish(String data) {
// do things
}
I had to add a Handler to delay the exit:
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 200, mPendingIntent);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Runtime.getRuntime().exit(0);
}
}, 100);
You don't need order by in your sub query. Move it out into the main query, and include the column you want to order by in the subquery.
however, your query is just returning a count, so I don't see the point of the order by.
We can create a simple directive and disable the button until all the mandatory fields are filled.
angular.module('sampleapp').directive('disableBtn',
function() {
return {
restrict : 'A',
link : function(scope, element, attrs) {
var $el = $(element);
var submitBtn = $el.find('button[type="submit"]');
var _name = attrs.name;
scope.$watch(_name + '.$valid', function(val) {
if (val) {
submitBtn.removeAttr('disabled');
} else {
submitBtn.attr('disabled', 'disabled');
}
});
}
};
}
);
This command count number of non-blank lines. cat fileName | grep -v ^$ | wc -l
grep -v ^$ regular expression function is ignore blank lines.
Another Solution in Case You Don't Have Control Over Dynamic Content
This works if you didn't load your element through a directive (ie. like in the example in the commented jsfiddles).
Wrap up Your Content
Wrap your content in a div so that you can select it if you are using JQuery. You an also opt to use native javascript to get your element.
<div class="selector">
<grid-filter columnname="LastNameFirstName" gridname="HomeGrid"></grid-filter>
</div>
Use Angular Injector
You can use the following code to get a reference to $compile if you don't have one.
$(".selector").each(function () {
var content = $(this);
angular.element(document).injector().invoke(function($compile) {
var scope = angular.element(content).scope();
$compile(content)(scope);
});
});
Summary
The original post seemed to assume you had a $compile reference handy. It is obviously easy when you have the reference, but I didn't so this was the answer for me.
One Caveat of the previous code
If you are using a asp.net/mvc bundle with minify scenario you will get in trouble when you deploy in release mode. The trouble comes in the form of Uncaught Error: [$injector:unpr] which is caused by the minifier messing with the angular javascript code.
Here is the way to remedy it:
Replace the prevous code snippet with the following overload.
...
angular.element(document).injector().invoke(
[
"$compile", function($compile) {
var scope = angular.element(content).scope();
$compile(content)(scope);
}
]);
...
This caused a lot of grief for me before I pieced it together.
instead of using the brackets use the object operator for example my array based on database object is created like this in a class called DB:
class DB {
private static $_instance = null;
private $_pdo,
$_query,
$_error = false,
$_results,
$_count = 0;
private function __construct() {
try{
$this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') .';dbname=' . Config::get('mysql/db') , Config::get('mysql/username') ,Config::get('mysql/password') );
} catch(PDOException $e) {
$this->_error = true;
$newsMessage = 'Sorry. Database is off line';
$pagetitle = 'Teknikal Tim - Database Error';
$pagedescription = 'Teknikal Tim Database Error page';
include_once 'dbdown.html.php';
exit;
}
$headerinc = 'header.html.php';
}
public static function getInstance() {
if(!isset(self::$_instance)) {
self::$_instance = new DB();
}
return self::$_instance;
}
public function query($sql, $params = array()) {
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql)) {
$x = 1;
if(count($params)) {
foreach($params as $param){
$this->_query->bindValue($x, $param);
$x++;
}
}
}
if($this->_query->execute()) {
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
}
else{
$this->_error = true;
}
return $this;
}
public function action($action, $table, $where = array()) {
if(count($where) ===3) {
$operators = array('=', '>', '<', '>=', '<=');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if(in_array($operator, $operators)) {
$sql = "{$action} FROM {$table} WHERE {$field} = ?";
if(!$this->query($sql, array($value))->error()) {
return $this;
}
}
}
return false;
}
public function get($table, $where) {
return $this->action('SELECT *', $table, $where);
public function results() {
return $this->_results;
}
public function first() {
return $this->_results[0];
}
public function count() {
return $this->_count;
}
}
to access the information I use this code on the controller script:
<?php
$pagetitle = 'Teknikal Tim - Service Call Reservation';
$pagedescription = 'Teknikal Tim Sevice Call Reservation Page';
require_once $_SERVER['DOCUMENT_ROOT'] .'/core/init.php';
$newsMessage = 'temp message';
$servicecallsdb = DB::getInstance()->get('tt_service_calls', array('UserID',
'=','$_SESSION['UserID']));
if(!$servicecallsdb) {
// $servicecalls[] = array('ID'=>'','ServiceCallDescription'=>'No Service Calls');
} else {
$servicecalls = $servicecallsdb->results();
}
include 'servicecalls.html.php';
?>
then to display the information I check to see if servicecalls has been set and has a count greater than 0 remember it's not an array I am referencing so I access the records with the object operator "->" like this:
<?php include $_SERVER['DOCUMENT_ROOT'] .'/includes/header.html.php';?>
<!--Main content-->
<div id="mainholder"> <!-- div so that page footer can have a minum height from the
header -->
<h1><?php if(isset($pagetitle)) htmlout($pagetitle);?></h1>
<br>
<br>
<article>
<h2></h2>
</article>
<?php
if (isset($servicecalls)) {
if (count ($servicecalls) > 0){
foreach ($servicecalls as $servicecall) {
echo '<a href="/servicecalls/?servicecall=' .$servicecall->ID .'">'
.$servicecall->ServiceCallDescription .'</a>';
}
}else echo 'No service Calls';
}
?>
<a href="/servicecalls/?new=true">Raise New Service Call</a>
</div> <!-- Main content end-->
<?php include $_SERVER['DOCUMENT_ROOT'] .'/includes/footer.html.php'; ?>
In many cases the purpose of a Null value is to serve for a data value that was not present in a previous version of your application.
So say you have an xml file from your application "ReportMaster" version 1.
Now in ReportMaster version 2 a some more attributes have been added that may or not be defined.
If you use the 'no tag means null' representation you get automatic backward compatibility for reading your ReportMaster 1 xml file.
This is really obscure but works. 7za.exe is standalone version of 7zip and is available with install package.
# get files to be send
$logFiles = Get-ChildItem C:\Logging\*.* -Include *.log | where {$_.Name -match $yesterday}
foreach ($logFile in $logFiles)
{
Write-Host ("Processing " + $logFile.FullName)
# compress file
& ./7za.exe a -mmt=off ($logFile.FullName + ".7z") $logFile.FullName
}
I was working on a program that required me to check if the user correctly answered how many digits were in a number, so i had to develop a way to check the amount of digits in an integer. It ended up being a relatively easy thing to solve.
double check=0, exponent=1000;
while(check<=1)
{
check=number/pow(10, exponent);
exponent--;
}
exponent=exponent+2;
cout<<exponent<<endl;
This ended up being my answer which currently works with numbers with less than 10^1000 digits (can be changed by changing the value of exponent).
P.S. I know this answer is ten years late but I got here on 2020 so other people might use it.
Here is an implementation that work for me and removed all nans (assuming these are simple object (list or dict)):
from numpy import isnan
def remove_nans(my_obj, val=None):
if isinstance(my_obj, list):
for i, item in enumerate(my_obj):
if isinstance(item, list) or isinstance(item, dict):
my_obj[i] = remove_nans(my_obj[i], val=val)
else:
try:
if isnan(item):
my_obj[i] = val
except Exception:
pass
elif isinstance(my_obj, dict):
for key, item in my_obj.iteritems():
if isinstance(item, list) or isinstance(item, dict):
my_obj[key] = remove_nans(my_obj[key], val=val)
else:
try:
if isnan(item):
my_obj[key] = val
except Exception:
pass
return my_obj
For example you have Animal superclass and Cat subclass.Say your subclass has speak(); method.
class Animal{
public void walk(){
}
}
class Cat extends Animal{
@Override
public void walk(){
}
public void speak(){
}
public void main(String args[]){
Animal a=new Cat();
//a.speak(); Compile Error
// If you use speak method for "a" reference variable you should downcast. Like this:
((Cat)a).speak();
}
}
No need to increase the MaxConnections & InitialConnections. Just close your connections after after doing your work. For example if you are creating connection:
try {
connection = DriverManager.getConnection(
"jdbc:postgresql://127.0.0.1/"+dbname,user,pass);
} catch (SQLException e) {
e.printStackTrace();
return;
}
After doing your work close connection:
try {
connection.commit();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
For anyone looking to do this in vb (as I was and couldn't find anything)
From c In db.Company
Select c.Name Group By Name Into Group
Where Group.Count > 1
Your modification of sys.path
assumes the current working directory is always in main/
. This is not the case. Instead, just add the parent directory to sys.path
:
import sys
import os.path
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import gen_py.lib
Don't forget to include a file __init__.py
in gen_py and lib - otherwise, they won't be recognized as Python modules.
You're saying "if it's not set or it's different from add or it's different from delete". You realize that a != x && a != y
, with x != y
is necessarily false
since a
cannot be simultaneously two different values.
I've found this issue to be prevalent in Entity Framework when we instantiate an Entity manually rather than through DBContext which will resolve all the Navigation Properties. If there are Foreign Key references (Navigation Properties) between tables and you use those references in your lambda (e.g. ProductDetail.Products.ID) then that "Products" context remains null if you manually created the Entity.
You can always roll your own line reader. I have'nt benchmarked this snippet yet, but it correctly splits the incoming stream of chunks into lines without the trailing '\n'
var last = "";
process.stdin.on('data', function(chunk) {
var lines, i;
lines = (last+chunk).split("\n");
for(i = 0; i < lines.length - 1; i++) {
console.log("line: " + lines[i]);
}
last = lines[i];
});
process.stdin.on('end', function() {
console.log("line: " + last);
});
process.stdin.resume();
I did come up with this when working on a quick log parsing script that needed to accumulate data during the log parsing and I felt that it would nice to try doing this using js and node instead of using perl or bash.
Anyway, I do feel that small nodejs scripts should be self contained and not rely on third party modules so after reading all the answers to this question, each using various modules to handle line parsing, a 13 SLOC native nodejs solution might be of interest .
df =df['Date'].dt.dayofweek
dayofweek
is in numeric format
A nice solution is to user a SpannableStringBuilder and set the color that way. You can even use different colors on different parts of the string, add images etc.
Tested with the new support library.
See Android: Coloring part of a string using TextView.setText()?
There is no need for jQuery here, regular JavaScript will do:
var str = "Abc: Lorem ipsum sit amet";
str = str.substring(str.indexOf(":") + 1);
Or, the .split()
and .pop()
version:
var str = "Abc: Lorem ipsum sit amet";
str = str.split(":").pop();
Or, the regex version (several variants of this):
var str = "Abc: Lorem ipsum sit amet";
str = /:(.+)/.exec(str)[1];
Use addHeader
Instead of using setHeader
method,
response.addHeader("Access-Control-Allow-Origin", "*");
*
in above line will allow access to all domains
.
For allowing access to specific domain only
:
response.addHeader("Access-Control-Allow-Origin", "http://www.example.com");
Check this blog post
.
Currently, I am using Ubuntu 16.04 LTS. Me too was facing same problem while Fetching the Postgress Database values using Php so i resolved it by using the below commands.
Mine PHP version is 7.0, so i tried the below command.
apt-get install php-pgsql
Remember to restart Apache.
/etc/init.d/apache2 restart
Single quoted php string variable works.
$str = 'http://www.domain.com/data/images\flags/en.gif';
$str = str_replace('\\', '/', $str);
This is my solution.
The algorithm is mainly the same as the one in the book "Cracking the code interview" where this exercise comes from, but I tried to improve it a bit and make the code more understandable:
public static void removeDuplicates(char[] str) {
// if string has less than 2 characters, it can't contain
// duplicate values, so there's nothing to do
if (str == null || str.length < 2) {
return;
}
// variable which indicates the end of the part of the string
// which is 'cleaned' (all duplicates removed)
int tail = 0;
for (int i = 0; i < str.length; i++) {
boolean found = false;
// check if character is already present in
// the part of the array before the current char
for (int j = 0; j < i; j++) {
if (str[j] == str[i]) {
found = true;
break;
}
}
// if char is already present
// skip this one and do not copy it
if (found) {
continue;
}
// copy the current char to the index
// after the last known unique char in the array
str[tail] = str[i];
tail++;
}
str[tail] = '\0';
}
One of the important requirements from the book is to do it in-place (as in my solution), which means that no additional data structure should be used as a helper while processing the string. This improves performance by not wasting memory unnecessarily.
The right answer for this question is "css reset".
* {
margin: 0;
padding: 0;
}
It removes all default margin and padding for every object on the page, no holds barred, regardless of browser.
Use this function to convert from any format to any format
function reformatDate($date, $from_format = 'd/m/Y', $to_format = 'Y-m-d') {
$date_aux = date_create_from_format($from_format, $date);
return date_format($date_aux,$to_format);
}
A bit late to the party but Juval Lowy addresses this exact scenario in his book and the associated ServiceModelEx library.
Basically he defines ClientBase and ChannelFactory specialisations that allow specifying type-safe header values. I suggesst downloading the source and looking at the HeaderClientBase and HeaderChannelFactory classes.
John
class PushObjects {
testMethod(): Array<number> {
//declaration and initialisation of array onject
var objs: number[] = [1,2,3,4,5,7];
//push the elements into the array object
objs.push(100);
//pop the elements from the array
objs.pop();
return objs;
}
}
let pushObj = new PushObjects();
//create the button element from the dom object
let btn = document.createElement('button');
//set the text value of the button
btn.textContent = "Click here";
//button click event
btn.onclick = function () {
alert(pushObj.testMethod());
}
document.body.appendChild(btn);
Do it like this:
SSLSocket socket = (SSLSocket) sslFactory.createSocket(host, port);
socket.setEnabledProtocols(new String[]{"SSLv3", "TLSv1"});
A small addition to KTC's very informative main answer:
If you are using the free Visual Studio c++ 2010 Express, and managed to get that one to compile 64-bits binaries, and now want to use that to use a 64-bits version of the Boost libaries, you may end up with 32-bits libraries (your mileage may vary of course, but on my machine this is the sad case).
I could fix this using the following: inbetween the steps described above as
I inserted a call to 'setenv' to set the environment. For a release build, the above steps become:
I found this info here: http://boost.2283326.n4.nabble.com/64-bit-with-VS-Express-again-td3044258.html
The syntax for using an alias in an update statement on SQL Server is as follows:
UPDATE Q
SET Q.TITLE = 'TEST'
FROM HOLD_TABLE Q
WHERE Q.ID = 101;
The alias should not be necessary here though.
Use your console:
console.log(object);
Or if you are inspecting html dom elements use console.dir(object). Example:
let element = document.getElementById('alertBoxContainer');
console.dir(element);
Or if you have an array of js objects you could use:
console.table(objectArr);
If you are outputting a lot of console.log(objects) you can also write
console.log({ objectName1 });
console.log({ objectName2 });
This will help you label the objects written to console.
/
^ # start of string
( # first group start
(?:
(?:[^?+*{}()[\]\\|]+ # literals and ^, $
| \\. # escaped characters
| \[ (?: \^?\\. | \^[^\\] | [^\\^] ) # character classes
(?: [^\]\\]+ | \\. )* \]
| \( (?:\?[:=!]|\?<[=!]|\?>)? (?1)?? \) # parenthesis, with recursive content
| \(\? (?:R|[+-]?\d+) \) # recursive matching
)
(?: (?:[?+*]|\{\d+(?:,\d*)?\}) [?+]? )? # quantifiers
| \| # alternative
)* # repeat content
) # end first group
$ # end of string
/
This is a recursive regex, and is not supported by many regex engines. PCRE based ones should support it.
Without whitespace and comments:
/^((?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?<[=!]|\?>)?(?1)??\)|\(\?(?:R|[+-]?\d+)\))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*)$/
.NET does not support recursion directly. (The (?1)
and (?R)
constructs.) The recursion would have to be converted to counting balanced groups:
^ # start of string
(?:
(?: [^?+*{}()[\]\\|]+ # literals and ^, $
| \\. # escaped characters
| \[ (?: \^?\\. | \^[^\\] | [^\\^] ) # character classes
(?: [^\]\\]+ | \\. )* \]
| \( (?:\?[:=!]
| \?<[=!]
| \?>
| \?<[^\W\d]\w*>
| \?'[^\W\d]\w*'
)? # opening of group
(?<N>) # increment counter
| \) # closing of group
(?<-N>) # decrement counter
)
(?: (?:[?+*]|\{\d+(?:,\d*)?\}) [?+]? )? # quantifiers
| \| # alternative
)* # repeat content
$ # end of string
(?(N)(?!)) # fail if counter is non-zero.
Compacted:
^(?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?<[=!]|\?>|\?<[^\W\d]\w*>|\?'[^\W\d]\w*')?(?<N>)|\)(?<-N>))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*$(?(N)(?!))
From the comments:
Will this validate substitutions and translations?
It will validate just the regex part of substitutions and translations. s/<this part>/.../
It is not theoretically possible to match all valid regex grammars with a regex.
It is possible if the regex engine supports recursion, such as PCRE, but that can't really be called regular expressions any more.
Indeed, a "recursive regular expression" is not a regular expression. But this an often-accepted extension to regex engines... Ironically, this extended regex doesn't match extended regexes.
"In theory, theory and practice are the same. In practice, they're not." Almost everyone who knows regular expressions knows that regular expressions does not support recursion. But PCRE and most other implementations support much more than basic regular expressions.
using this with shell script in the grep command , it shows me some error.. grep: Invalid content of {} . I am making a script that could grep a code base to find all the files that contain regular expressions
This pattern exploits an extension called recursive regular expressions. This is not supported by the POSIX flavor of regex. You could try with the -P switch, to enable the PCRE regex flavor.
Regex itself "is not a regular language and hence cannot be parsed by regular expression..."
This is true for classical regular expressions. Some modern implementations allow recursion, which makes it into a Context Free language, although it is somewhat verbose for this task.
I see where you're matching
[]()/\
. and other special regex characters. Where are you allowing non-special characters? It seems like this will match^(?:[\.]+)$
, but not^abcdefg$
. That's a valid regex.
[^?+*{}()[\]\\|]
will match any single character, not part of any of the other constructs. This includes both literal (a
- z
), and certain special characters (^
, $
, .
).
I have edited your layout. Check this code now.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#33B5E5"
android:padding="5dp" >
<ImageView
android:id="@+id/icon"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_centerInParent="true"
android:background="@android:drawable/ic_lock_lock" />
<TextView
android:id="@+id/func_text"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:layout_gravity="center_vertical"
android:layout_toRightOf="@+id/icon"
android:gravity="center"
android:padding="5dp"
android:text="This is my test string............"
android:textColor="#FFFFFF" />
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentRight="true"
android:layout_centerInParent="true"
android:layout_gravity="center_vertical"
android:src="@android:drawable/ic_media_next" />
</RelativeLayout>
Use DATE()
function:
select * from follow_queue group by DATE(follow_date)
I think error is not coming from the specified line but from the first 3 lines. Try this instead :
node {
stage("first") {
def foo = "foo"
sh "echo ${foo}"
}
}
I think you had some extra lines that are not valid...
From declaractive pipeline model documentation, it seems that you have to use an environment
declaration block to declare your variables, e.g.:
pipeline {
environment {
FOO = "foo"
}
agent none
stages {
stage("first") {
sh "echo ${FOO}"
}
}
}
You say you've had problems with Navicat. For the record, I use Navicat and I haven't experienced the issue you describe. You might want to dig around, see if there's a reason for your problem and/or a solution, because given the question asked, my first recommendation would have been Navicat.
But if you want alternative suggestions, here are a few that I know of and have used:
MySQL has its own tool which you can download for free, called MySQL Workbench. Download it from here: http://wb.mysql.com/. My experience is that it's powerful, but I didn't really like the UI. But that's just my personal taste.
Another free program you might want to try is HeidiSQL. It's more similar to Navicat than MySQL Workbench. A colleague of mine loves it.
(interesting to note, by the way, that MariaDB (the forked version of MySQL) is currently shipped with HeidiSQL as its GUI tool)
Finally, if you're running a web server on your machine, there's always the option of a browser-based tool like PHPMyAdmin. It's actually a surprisingly powerful piece of software.
1: C is a type of computer programming language. While embedded C is a set of language extensions for the C Programming language.
2: C has a free-format program source code, in a desktop computer. while embedded C has different format based on embedded processor (micro- controllers/microprocessors).
3: C have normal optimization, in programming. while embedded C high level optimization in programming.
4: C programming must have required operating system. while embedded C may or may not be required operating system.
5: C can use resources from OS, memory, etc, i.e all resources from desktop computer can be used by C. while embedded C can use limited resources, like RAM, ROM, and I/Os on an embedded processor.
You can use setOnFocusChangeListener
, it will check when focus change
txt_membername.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View arg0, boolean arg1) {
if (arg1) {
//do something
} else {
if (txt_membername.getText().toString().length() == 0) {
txt_membername
.setError("Member name is not empty, Plz!");
}
}
}
});
LATERAL
join?The feature was introduced with PostgreSQL 9.3.
Quoting the manual:
Subqueries appearing in
FROM
can be preceded by the key wordLATERAL
. This allows them to reference columns provided by precedingFROM
items. (WithoutLATERAL
, each subquery is evaluated independently and so cannot cross-reference any otherFROM
item.)Table functions appearing in
FROM
can also be preceded by the key wordLATERAL
, but for functions the key word is optional; the function's arguments can contain references to columns provided by precedingFROM
items in any case.
Basic code examples are given there.
A LATERAL
join is more like a correlated subquery, not a plain subquery, in that expressions to the right of a LATERAL
join are evaluated once for each row left of it - just like a correlated subquery - while a plain subquery (table expression) is evaluated once only. (The query planner has ways to optimize performance for either, though.)
Related answer with code examples for both side by side, solving the same problem:
For returning more than one column, a LATERAL
join is typically simpler, cleaner and faster.
Also, remember that the equivalent of a correlated subquery is LEFT JOIN LATERAL ... ON true
:
There are things that a LATERAL
join can do, but a (correlated) subquery cannot (easily). A correlated subquery can only return a single value, not multiple columns and not multiple rows - with the exception of bare function calls (which multiply result rows if they return multiple rows). But even certain set-returning functions are only allowed in the FROM
clause. Like unnest()
with multiple parameters in Postgres 9.4 or later. The manual:
This is only allowed in the
FROM
clause;
So this works, but cannot (easily) be replaced with a subquery:
CREATE TABLE tbl (a1 int[], a2 int[]);
SELECT * FROM tbl, unnest(a1, a2) u(elem1, elem2); -- implicit LATERAL
The comma (,
) in the FROM
clause is short notation for CROSS JOIN
.
LATERAL
is assumed automatically for table functions.
About the special case of UNNEST( array_expression [, ... ] )
:
SELECT
listYou can also use set-returning functions like unnest()
in the SELECT
list directly. This used to exhibit surprising behavior with more than one such function in the same SELECT
list up to Postgres 9.6. But it has finally been sanitized with Postgres 10 and is a valid alternative now (even if not standard SQL). See:
Building on above example:
SELECT *, unnest(a1) AS elem1, unnest(a2) AS elem2
FROM tbl;
Comparison:
dbfiddle for pg 9.6 here
dbfiddle for pg 10 here
For the
INNER
andOUTER
join types, a join condition must be specified, namely exactly one ofNATURAL
,ON
join_condition, orUSING
(join_column [, ...]). See below for the meaning.
ForCROSS JOIN
, none of these clauses can appear.
So these two queries are valid (even if not particularly useful):
SELECT *
FROM tbl t
LEFT JOIN LATERAL (SELECT * FROM b WHERE b.t_id = t.t_id) t ON TRUE;
SELECT *
FROM tbl t, LATERAL (SELECT * FROM b WHERE b.t_id = t.t_id) t;
While this one is not:
SELECT *
FROM tbl t
LEFT JOIN LATERAL (SELECT * FROM b WHERE b.t_id = t.t_id) t;
That's why Andomar's code example is correct (the CROSS JOIN
does not require a join condition) and Attila's is was not.
Came across a nice tool for doing this.
Parses and loads environment files (containing ENV variable exports) into Node.js environment, i.e. process.env
- Uses this style:
.env
# some env variables
FOO=foo1
BAR=bar1
BAZ=1
QUX=
# QUUX=
If I'm understanding the type of window you're talking about, wouldn't $(window).unload() (for the dialog window) give you the hook you need?
(And if I misunderstood, and you're talking about a dialog box made via CSS rather than a pop-up browser window, then all the ways of closing that window are elements you could register click handers for.)
Edit: Ah, I see now you're talking about jquery-ui dialogs, which are made via CSS. You can hook the X which closes the window by registering a click handler for the element with the class ui-dialog-titlebar-close.
More useful, perhaps, is you tell you how to figure that out quickly. While displaying the dialog, just pop open FireBug and Inspect the elements that can close the window. You'll instantly see how they are defined and that gives you what you need to register the click handlers.
So to directly answer your question, I believe the answer is really "no" -- there's isn't a close event you can hook, but "yes" -- you can hook all the ways to close the dialog box fairly easily and get what you want.
Insert pull-right
into the class attribute and let bootstrap arrange the buttons.
For Bootstrap 2.3, see: http://getbootstrap.com/2.3.2/components.html#misc > Helper classes > .pull-right.
For Bootstrap 3, see: https://getbootstrap.com/docs/3.3/css/#helper-classes > Helper classes.
For Bootstrap 4, see: https://getbootstrap.com/docs/4.0/utilities/float/#responsive
The pull-right
command was removed and replaced with float-right
or in general to float-{sm,md,lg,xl}-{left,right,none}
First of all, from __future__ import print_function
needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print
as a function now. That's the whole point of from __future__ import print_function
; to bring the print
function from Python 3 into Python 2.6+.
from __future__ import print_function
import sys, os, time
for x in range(0,10):
print(x, sep=' ', end='') # No need for sep here, but okay :)
time.sleep(1)
__future__
statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:
A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.
The documentation also mentions that the only things that can precede a __future__
statement are the module docstring, comments, blank lines, and other future statements.
The order of execution of ng-click and ng-model is different with angular 1.2 vs 1.6
You must test, with 1.2 and 1.6,
for example, with angular 1.2, ng-click get execute before ng-model, with angular 1.6, ng-model maybe get excute before ng-click.
so you get 'true checked' / 'false uncheck' value maybe not you expect
> var x = 0.1
> var y = 0.2
> var cf = 10
> x * y
0.020000000000000004
> (x * cf) * (y * cf) / (cf * cf)
0.02
Quick solution:
var _cf = (function() {
function _shift(x) {
var parts = x.toString().split('.');
return (parts.length < 2) ? 1 : Math.pow(10, parts[1].length);
}
return function() {
return Array.prototype.reduce.call(arguments, function (prev, next) { return prev === undefined || next === undefined ? undefined : Math.max(prev, _shift (next)); }, -Infinity);
};
})();
Math.a = function () {
var f = _cf.apply(null, arguments); if(f === undefined) return undefined;
function cb(x, y, i, o) { return x + f * y; }
return Array.prototype.reduce.call(arguments, cb, 0) / f;
};
Math.s = function (l,r) { var f = _cf(l,r); return (l * f - r * f) / f; };
Math.m = function () {
var f = _cf.apply(null, arguments);
function cb(x, y, i, o) { return (x*f) * (y*f) / (f * f); }
return Array.prototype.reduce.call(arguments, cb, 1);
};
Math.d = function (l,r) { var f = _cf(l,r); return (l * f) / (r * f); };
> Math.m(0.1, 0.2)
0.02
You can check the full explanation here.
By default all the EditText
widgets in Android are multi-lined.
Here is some sample code:
<EditText
android:inputType="textMultiLine" <!-- Multiline input -->
android:lines="8" <!-- Total Lines prior display -->
android:minLines="6" <!-- Minimum lines -->
android:gravity="top|left" <!-- Cursor Position -->
android:maxLines="10" <!-- Maximum Lines -->
android:layout_height="wrap_content" <!-- Height determined by content -->
android:layout_width="match_parent" <!-- Fill entire width -->
android:scrollbars="vertical" <!-- Vertical Scroll Bar -->
/>
From the docs, the recommended way of getting a timezone aware datetime object from seconds since epoch is:
from datetime import datetime, timezone
datetime.fromtimestamp(timestamp, timezone.utc)
from datetime import datetime
import pytz
datetime.fromtimestamp(timestamp, pytz.utc)
I try this it solved.
AlertDialog.Builder builder = new AlertDialog.Builder(
this);
builder.setCancelable(true);
builder.setTitle("Opss!!");
builder.setMessage("You Don't have anough coins to withdraw. ");
builder.setMessage("Please read the Withdraw rules.");
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("OK",
(dialog, which) -> dialog.dismiss());
builder.create().show();
For powershell in Windows, you can add relative path + filename to --output
flag:
curl -L http://github.com/GorvGoyl/Notion-Boost-browser-extension/archive/master.zip --output build_firefox/master-repo.zip
here build_firefox is relative folder.
<?php
$string = '`~!@#$%^&^&*()_+{}[]|\/;:"< >,.?-<h1>You .</h1><p> text</p>'."'";
$string=strip_tags($string,"");
$string = preg_replace('/[^A-Za-z0-9\s.\s-]/','',$string);
echo $string = str_replace( array( '-', '.' ), '', $string);
?>
Edit To reflect what @Marc said in the comment below.
You can do a loop through all the posted values.
HTML:
<input type="checkbox" name="check_list[]" value="<?=$rowid?>" />
<input type="checkbox" name="check_list[]" value="<?=$rowid?>" />
<input type="checkbox" name="check_list[]" value="<?=$rowid?>" />
PHP:
foreach($_POST['check_list'] as $item){
// query to delete where item = $item
}
The solution compliant with the v4 of the framework is to set the proper breakpoint. Rather than using .table-responsive, you should be able to use .table-responsive-sm (to be just responsive on small devices)
You can use any of the available endpoints: table-responsive{-sm|-md|-lg|-xl}
You can set any pointer to NULL
, though NULL
is simply defined as 0 in C++:
myObject *foo = NULL;
Also note that NULL
is defined if you include standard headers, but is not built into the language itself. If NULL
is undefined, you can use 0 instead, or include this:
#ifndef NULL
#define NULL 0
#endif
As an aside, if you really want to set an object, not a pointer, to NULL
, you can read about the Null Object Pattern.
Unless you are writing directly to the slave (Server2) the only problem should be that Server2 is missing any updates that have happened since it was disconnected. Simply restarting the slave with "START SLAVE;" should get everything back up to speed.
function bindFirst(owner, event, handler) {
owner.unbind(event, handler);
owner.bind(event, handler);
var events = owner.data('events')[event];
events.unshift(events.pop());
owner.data('events')[event] = events;
}
Probably the cleanest way to do it in Java 8:
private int[] randomIntArray() {
Random rand = new Random();
return IntStream.range(0, 23).map(i -> rand.nextInt()).toArray();
}
If the order of the deduplicated array does not matter to you, you can use my pragmatic function:
Function DeDupArray(ia() As String)
Dim newa() As String
ReDim newa(999)
ni = -1
For n = LBound(ia) To UBound(ia)
dup = False
If n <= UBound(ia) Then
For k = n + 1 To UBound(ia)
If ia(k) = ia(n) Then dup = True
Next k
If dup = False And Trim(ia(n)) <> "" Then
ni = ni + 1
newa(ni) = ia(n)
End If
End If
Next n
If ni > -1 Then
ReDim Preserve newa(ni)
Else
ReDim Preserve newa(1)
End If
DeDupArray = newa
End Function
Sub testdedup()
Dim m(5) As String
Dim m2() As String
m(0) = "Horse"
m(1) = "Cow"
m(2) = "Dear"
m(3) = "Horse"
m(4) = "Joke"
m(5) = "Cow"
m2 = DeDupArray(m)
t = ""
For n = LBound(m2) To UBound(m2)
t = t & n & "=" & m2(n) & " "
Next n
MsgBox t
End Sub
From the test function, it will result in the following deduplicated array:
"0=Dear 1=Horse 2=Joke 3=Cow "
You keep on getting new a new string and continue the loop if it's not empty. Simply insert a control in the loop for an exit string.
while(!s1.equals("exit") && sc.hasNext()) {
// operate
}
If you want to declare the string inside the loop and not to do the operations in the loop body if the string is "exit":
while(sc.hasNext()) {
String s1 = sc.next();
if(s1.equals("exit")) {
break;
}
//operate
}
Use collectl
which has extensive process I/O monitoring including monitoring threads.
Be warned that there are I/O counters for I/O being written to cache and I/O going to disk. collectl
reports them separately. If you're not careful you can misinterpret the data. See http://collectl.sourceforge.net/Process.html
Of course, it shows a lot more than just process stats because you'd want one tool to provide everything rather than a bunch of different one that displays everything in different formats, right?
SQL is a standard and there are many database vendors like Microsoft,Oracle who implements this standard using their own proprietary language.
Microsoft uses T-SQL to implement SQL standard to interact with data whereas oracle uses PL/SQL.
Use like this.
List<String> stockList = new ArrayList<String>();
stockList.add("stock1");
stockList.add("stock2");
String[] stockArr = new String[stockList.size()];
stockArr = stockList.toArray(stockArr);
for(String s : stockArr)
System.out.println(s);
Since I found this via google searching for how to format json to make it more readable for troubleshooting.
ob_start() ; print_r( $json ); $ob_out=ob_get_contents(); ob_end_clean(); echo "\$json".str_replace( '}', "}\n", $ob_out );
Yes it is true.
If you create two instance of your class
Test t1 = new Test();
Test t2 = new Test();
Then t1.foo and t2.foo both synchronize on the same static object and hence block each other.
In addition, you need the "AllowOverride Options" directive for this to work. (Apache 2.2.15)
print self.id.__str__()
would work for you, although not that useful for you.
Your __str__
method will be more useful when you say want to print out a grid or struct representation as your program develops.
print self._grid.__str__()
def __str__(self):
"""
Return a string representation of the grid for debugging.
"""
grid_str = ""
for row in range(self._rows):
grid_str += str( self._grid[row] )
grid_str += '\n'
return grid_str
For IE9+
@media screen and (min-width:0\0) and (min-resolution: +72dpi) {
// IE9+ CSS
.selector{
color: red;
}
}
IE Edge 12+
@supports (-ms-ime-align: auto) {
.selector {
color: red;
}
}
This one works on Edge and all IEs
:-ms-lang(x), .selector { color: red; }
On OS X (10.9.4), cat
works, and is easier if your email is already in a file:
cat email_template.html | mail -s "$(echo -e "Test\nContent-Type: text/html")" [email protected]
As of Node.js 14.3.0 the top-level await is supported.
Required flag: --experimental-top-level-await
.
Further details: https://v8.dev/features/top-level-await
I have slightly improved answer, which handles extended CSS definitions like:
background-image: url(http://d36xtkk24g8jdx.cloudfront.net/bluebar/359de8f/images/shared/noise-1.png), -webkit-linear-gradient(top, rgb(81, 127, 164), rgb(48, 96, 136))
JavaScript code:
var bg = $("div").css("background-image")
bg = bg.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '')
Result:
"http://d36xtkk24g8jdx.cloudfront.net/bluebar/359de8f/images/shared/noise-1.png"
Since PyYAML's yaml.load()
function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:
import yaml
with open('tree.yaml', 'r') as f:
doc = yaml.load(f)
To access branch1 text
you would use:
txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"
because, in your YAML document, the value of the branch1
key is under the treeroot
key.
Given the latest RFC's on the matter (7231 and 7235) the use-case seems quite clear (italics added):
401 Unauthorized
The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource. The server generating a 401 response MUST send a WWW-Authenticate header field (Section 4.1) containing at least one challenge applicable to the target resource.
If the request included authentication credentials, then the 401 response indicates that authorization has been refused for those credentials. The user agent MAY repeat the request with a new or replaced Authorization header field (Section 4.2). If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user agent SHOULD present the enclosed representation to the user, since it usually contains relevant diagnostic information.
403 Forbidden
The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it. A server that wishes to make public why the request has been forbidden can describe that reason in the response payload (if any).
If authentication credentials were provided in the request, the server considers them insufficient to grant access. The client SHOULD NOT automatically repeat the request with the same credentials. The client MAY repeat the request with new or different credentials. However, a request might be forbidden for reasons unrelated to the credentials.
An origin server that wishes to "hide" the current existence of a forbidden target resource MAY instead respond with a status code of 404 (Not Found).
Using lodash
import omit from 'lodash/omit';
const prevObject = {test: false, test2: true};
// Removes test2 key from previous object
const nextObject = omit(prevObject, 'test2');
Using Ramda
R.omit(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, c: 3}
insert into EXCEPTION_CODES (CODE, MESSAGE)
select CODE, MESSAGE from Exception_code_tmp
For me this was the only one that worked perfectly (thanks to Paul O'Brien!): https://codepen.io/paulobrien/pen/gWoVzN
Here's the snippet:
// requires jquery library_x000D_
jQuery(document).ready(function() {_x000D_
jQuery(".main-table").clone(true).appendTo('#table-scroll').addClass('clone'); _x000D_
});
_x000D_
.table-scroll {_x000D_
position:relative;_x000D_
max-width:600px;_x000D_
margin:auto;_x000D_
overflow:hidden;_x000D_
border:1px solid #000;_x000D_
}_x000D_
.table-wrap {_x000D_
width:100%;_x000D_
overflow:auto;_x000D_
}_x000D_
.table-scroll table {_x000D_
width:100%;_x000D_
margin:auto;_x000D_
border-collapse:separate;_x000D_
border-spacing:0;_x000D_
}_x000D_
.table-scroll th, .table-scroll td {_x000D_
padding:5px 10px;_x000D_
border:1px solid #000;_x000D_
background:#fff;_x000D_
white-space:nowrap;_x000D_
vertical-align:top;_x000D_
}_x000D_
.table-scroll thead, .table-scroll tfoot {_x000D_
background:#f9f9f9;_x000D_
}_x000D_
.clone {_x000D_
position:absolute;_x000D_
top:0;_x000D_
left:0;_x000D_
pointer-events:none;_x000D_
}_x000D_
.clone th, .clone td {_x000D_
visibility:hidden_x000D_
}_x000D_
.clone td, .clone th {_x000D_
border-color:transparent_x000D_
}_x000D_
.clone tbody th {_x000D_
visibility:visible;_x000D_
color:red;_x000D_
}_x000D_
.clone .fixed-side {_x000D_
border:1px solid #000;_x000D_
background:#eee;_x000D_
visibility:visible;_x000D_
}_x000D_
.clone thead, .clone tfoot{background:transparent;}
_x000D_
<div id="table-scroll" class="table-scroll">_x000D_
<div class="table-wrap">_x000D_
<table class="main-table">_x000D_
<thead>_x000D_
<tr>_x000D_
<th class="fixed-side" scope="col"> </th>_x000D_
<th scope="col">Header 2</th>_x000D_
<th scope="col">Header 3</th>_x000D_
<th scope="col">Header 4</th>_x000D_
<th scope="col">Header 5</th>_x000D_
<th scope="col">Header 6</th>_x000D_
<th scope="col">Header 7</th>_x000D_
<th scope="col">Header 8</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<th class="fixed-side">Left Column</th>_x000D_
<td>Cell content<br>_x000D_
test</td>_x000D_
<td><a href="#">Cell content longer</a></td>_x000D_
<td>Cell content</td>_x000D_
<td>Cell content</td>_x000D_
<td>Cell content</td>_x000D_
<td>Cell content</td>_x000D_
<td>Cell content</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th class="fixed-side">Left Column</th>_x000D_
<td>Cell content</td>_x000D_
<td>Cell content longer</td>_x000D_
<td>Cell content</td>_x000D_
<td>Cell content</td>_x000D_
<td>Cell content</td>_x000D_
<td>Cell content</td>_x000D_
<td>Cell content</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th class="fixed-side">Left Column</th>_x000D_
<td>Cell content</td>_x000D_
<td>Cell content longer</td>_x000D_
<td>Cell content</td>_x000D_
<td>Cell content</td>_x000D_
<td>Cell content</td>_x000D_
<td>Cell content</td>_x000D_
<td>Cell content</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th class="fixed-side">Left Column</th>_x000D_
<td>Cell content</td>_x000D_
<td>Cell content longer</td>_x000D_
<td>Cell content</td>_x000D_
<td>Cell content</td>_x000D_
<td>Cell content</td>_x000D_
<td>Cell content</td>_x000D_
<td>Cell content</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th class="fixed-side">Left Column</th>_x000D_
<td>Cell content</td>_x000D_
<td>Cell content longer</td>_x000D_
<td>Cell content</td>_x000D_
<td>Cell content</td>_x000D_
<td>Cell content</td>_x000D_
<td>Cell content</td>_x000D_
<td>Cell content</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th class="fixed-side">Left Column</th>_x000D_
<td>Cell content</td>_x000D_
<td>Cell content longer</td>_x000D_
<td>Cell content</td>_x000D_
<td>Cell content</td>_x000D_
<td>Cell content</td>_x000D_
<td>Cell content</td>_x000D_
<td>Cell content</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
<tfoot>_x000D_
<tr>_x000D_
<th class="fixed-side"> </th>_x000D_
<td>Footer 2</td>_x000D_
<td>Footer 3</td>_x000D_
<td>Footer 4</td>_x000D_
<td>Footer 5</td>_x000D_
<td>Footer 6</td>_x000D_
<td>Footer 7</td>_x000D_
<td>Footer 8</td>_x000D_
</tr>_x000D_
</tfoot>_x000D_
</table>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<p>See <a href="https://codepen.io/paulobrien/pen/LBrMxa" target="blank">position Sticky version </a>with no JS</p>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>
_x000D_
Echoing justanotherdev's comment:
Mind-blowing and useful:
CTRL
+ SHIFT
+ p
(Mac: CMD
+ SHIFT
+ p
)>transform
pick upper/lower case and press enterI found for simple XML snips, use regular expression would save troubles. For example:
# <user><name>Happy Man</name>...</user>
import re
names = re.findall(r'<name>(\w+)<\/name>', xml_string)
# do some thing to names
To do it by XML parsing, as @Dan said, there is not one-for-all solution because the data is different. My suggestion is to use lxml. Although not finished to json, lxml.objectify give quiet good results:
>>> from lxml import objectify
>>> root = objectify.fromstring("""
... <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
... <a attr1="foo" attr2="bar">1</a>
... <a>1.2</a>
... <b>1</b>
... <b>true</b>
... <c>what?</c>
... <d xsi:nil="true"/>
... </root>
... """)
>>> print(str(root))
root = None [ObjectifiedElement]
a = 1 [IntElement]
* attr1 = 'foo'
* attr2 = 'bar'
a = 1.2 [FloatElement]
b = 1 [IntElement]
b = True [BoolElement]
c = 'what?' [StringElement]
d = None [NoneElement]
* xsi:nil = 'true'
You may still have trouble displaying the output in the Assistant Editor. Rather than wrapping the string in println()
, simply output the string. For example:
for index in 1...5 {
"The number is \(index)"
}
Will write (5 times)
in the playground area. This will allow you to display it in the Assistant Editor (via the little circle on the far right edge).
However, if you were to println("The number is \(index)")
you wouldn't be able to visualize it in the Assistant Editor.
From a Windows Server OS execute the following command for a dump of the entire Active Director:
csvde -f test.csv
This command is very broad and will give you more than necessary information. To constrain the records to only user records, you would instead want:
csvde -f test.csv -r objectClass=user
You can further restrict the command to give you only the fields you need relevant to the search requested such as:
csvde -f test.csv -r objectClass=user -l DN, sAMAccountName, department, memberOf
If you have an Exchange server and each user associated with a live person has a mailbox (as opposed to generic accounts for kiosk / lab workstations) you can use mailNickname in place of sAMAccountName.
Please check if the setting Generate Debug Info is Yes which under Project Propeties > Configuration Properties > Linker > Debugging tab. If not, try to change it to Yes.
Those perticular pdb's ( for ntdll.dll, mscoree.dll, kernel32.dll, etc ) are for the windows API and shouldn't be needed for simple apps. However, if you cannot find pdb's for your own compiled projects, I suggest making sure the Project Properties > Configuration Properties > Debugging > Working Directory uses the value from Project Properties > Configuration Properties > General > Output Directory .
You need to run Visual c++ in "Run as Administrator" mode.Right click on the executable and click "Run as Administrator"
Symbolic links give another name to a file, in a way similar to hard links. But a file can be deleted even if there are remaining symbolic links.
Another way could be:
ps -ef | grep -i 'redis-server'
kill -9 PID owned by redis
Works on *NIX & OSX
Ready-to-use solution:
public class GoogleServicesUtils {
public static void openAppInGooglePlay(Context context) {
final String appPackageName = context.getPackageName();
try {
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
} catch (android.content.ActivityNotFoundException e) { // if there is no Google Play on device
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}
}
}
Based on Eric's answer.
It's your choice. There are basically three ways in a Java web application archive (WAR):
So that you can load it by ClassLoader#getResourceAsStream()
with a classpath-relative path:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("foo.properties");
// ...
Properties properties = new Properties();
properties.load(input);
Here foo.properties
is supposed to be placed in one of the roots which are covered by the default classpath of a webapp, e.g. webapp's /WEB-INF/lib
and /WEB-INF/classes
, server's /lib
, or JDK/JRE's /lib
. If the propertiesfile is webapp-specific, best is to place it in /WEB-INF/classes
. If you're developing a standard WAR project in an IDE, drop it in src
folder (the project's source folder). If you're using a Maven project, drop it in /main/resources
folder.
You can alternatively also put it somewhere outside the default classpath and add its path to the classpath of the appserver. In for example Tomcat you can configure it as shared.loader
property of Tomcat/conf/catalina.properties
.
If you have placed the foo.properties
it in a Java package structure like com.example
, then you need to load it as below
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("com/example/foo.properties");
// ...
Note that this path of a context class loader should not start with a /
. Only when you're using a "relative" class loader such as SomeClass.class.getClassLoader()
, then you indeed need to start it with a /
.
ClassLoader classLoader = getClass().getClassLoader();
InputStream input = classLoader.getResourceAsStream("/com/example/foo.properties");
// ...
However, the visibility of the properties file depends then on the class loader in question. It's only visible to the same class loader as the one which loaded the class. So, if the class is loaded by e.g. server common classloader instead of webapp classloader, and the properties file is inside webapp itself, then it's invisible. The context class loader is your safest bet so you can place the properties file "everywhere" in the classpath and/or you intend to be able to override a server-provided one from the webapp on.
So that you can load it by ServletContext#getResourceAsStream()
with a webcontent-relative path:
InputStream input = getServletContext().getResourceAsStream("/WEB-INF/foo.properties");
// ...
Note that I have demonstrated to place the file in /WEB-INF
folder, otherwise it would have been public accessible by any webbrowser. Also note that the ServletContext
is in any HttpServlet
class just accessible by the inherited GenericServlet#getServletContext()
and in Filter
by FilterConfig#getServletContext()
. In case you're not in a servlet class, it's usually just injectable via @Inject
.
So that you can load it the usual java.io
way with an absolute local disk file system path:
InputStream input = new FileInputStream("/absolute/path/to/foo.properties");
// ...
Note the importance of using an absolute path. Relative local disk file system paths are an absolute no-go in a Java EE web application. See also the first "See also" link below.
Just weigh the advantages/disadvantages in your own opinion of maintainability.
If the properties files are "static" and never needs to change during runtime, then you could keep them in the WAR.
If you prefer being able to edit properties files from outside the web application without the need to rebuild and redeploy the WAR every time, then put it in the classpath outside the project (if necessary add the directory to the classpath).
If you prefer being able to edit properties files programmatically from inside the web application using Properties#store()
method, put it outside the web application. As the Properties#store()
requires a Writer
, you can't go around using a disk file system path. That path can in turn be passed to the web application as a VM argument or system property. As a precaution, never use getRealPath()
. All changes in deploy folder will get lost on a redeploy for the simple reason that the changes are not reflected back in original WAR file.
The letters 100000000000 make up a literal integer constant, but the value is too large for the type int
. You need to use a suffix to change the type of the literal, i.e.
long long num3 = 100000000000LL;
The suffix LL
makes the literal into type long long
. C is not "smart" enough to conclude this from the type on the left, the type is a property of the literal itself, not the context in which it is being used.
Every Ansible task when run can save its results into a variable. To do this, you have to specify which variable to save the results into. Do this with the register
parameter, independently of the module used.
Once you save the results to a variable you can use it later in any of the subsequent tasks. So for example if you want to get the standard output of a specific task you can write the following:
---
- hosts: localhost
tasks:
- shell: ls
register: shell_result
- debug:
var: shell_result.stdout_lines
Here register
tells ansible to save the response of the module into the shell_result
variable, and then we use the debug
module to print the variable out.
An example run would look like the this:
PLAY [localhost] ***************************************************************
TASK [command] *****************************************************************
changed: [localhost]
TASK [debug] *******************************************************************
ok: [localhost] => {
"shell_result.stdout_lines": [
"play.yml"
]
}
Responses can contain multiple fields. stdout_lines
is one of the default fields you can expect from a module's response.
Not all fields are available from all modules, for example for a module which doesn't return anything to the standard out you wouldn't expect anything in the stdout
or stdout_lines
values, however the msg
field might be filled in this case. Also there are some modules where you might find something in a non-standard variable, for these you can try to consult the module's documentation for these non-standard return values.
Alternatively you can increase the verbosity level of ansible-playbook. You can choose between different verbosity levels: -v
, -vvv
and -vvvv
. For example when running the playbook with verbosity (-vvv
) you get this:
PLAY [localhost] ***************************************************************
TASK [command] *****************************************************************
(...)
changed: [localhost] => {
"changed": true,
"cmd": "ls",
"delta": "0:00:00.007621",
"end": "2017-02-17 23:04:41.912570",
"invocation": {
"module_args": {
"_raw_params": "ls",
"_uses_shell": true,
"chdir": null,
"creates": null,
"executable": null,
"removes": null,
"warn": true
},
"module_name": "command"
},
"rc": 0,
"start": "2017-02-17 23:04:41.904949",
"stderr": "",
"stdout": "play.retry\nplay.yml",
"stdout_lines": [
"play.retry",
"play.yml"
],
"warnings": []
}
As you can see this will print out the response of each of the modules, and all of the fields available. You can see that the stdout_lines
is available, and its contents are what we expect.
To answer your main question about the jenkins_script
module, if you check its documentation, you can see that it returns the output in the output
field, so you might want to try the following:
tasks:
- jenkins_script:
script: (...)
register: jenkins_result
- debug:
var: jenkins_result.output
This is what finally ended up working for me
binding.rows.addItemDecoration(object: RecyclerView.ItemDecoration(){
val px = resources.getDimensionPixelSize(R.dimen.grid_spacing)
val spanCount = 2
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val index = parent.getChildLayoutPosition(view)
val isLeft = (index % spanCount == 0)
outRect.set(
if (isLeft) px else px/2,
0,
if (isLeft) px/2 else px,
px
)
}
})
Since there are only 2 columns for me (val spanCount = 2
), I can do with just isLeft
. If there were > 2 columns, then I'd need a isMiddle
as well, and the value for both sides would be px/2
.
I wish there was a way to get the app:spanCount
from directly from the RecyclerView
, but I don't believe there is.
Here is an implementation that I find very versatile:
In [1]: import pandas as pd
In [2]: df = pd.DataFrame([[0, 'the', 'quick', 'brown'],
...: [1, 'fox', 'jumps', 'over'],
...: [2, 'the', 'lazy', 'dog']],
...: columns=['c0', 'c1', 'c2', 'c3'])
In [3]: def str_join(df, sep, *cols):
...: from functools import reduce
...: return reduce(lambda x, y: x.astype(str).str.cat(y.astype(str), sep=sep),
...: [df[col] for col in cols])
...:
In [4]: df['cat'] = str_join(df, '-', 'c0', 'c1', 'c2', 'c3')
In [5]: df
Out[5]:
c0 c1 c2 c3 cat
0 0 the quick brown 0-the-quick-brown
1 1 fox jumps over 1-fox-jumps-over
2 2 the lazy dog 2-the-lazy-dog
Old answers stopped working in new android versions. Now I use the following:
adb shell "dumpsys activity activities | grep ResumedActivity"
I prefer onKeyUp
since it only fires when the key is released. onKeyDown
, on the other hand, will fire multiple times if for some reason the user presses and holds the key. For example, when listening for "pressing" the Enter
key to make a network request, you don't want that to fire multiple times since it can be expensive.
// handler could be passed as a prop
<input type="text" onKeyUp={handleKeyPress} />
handleKeyPress(e) {
if (e.key === 'Enter') {
// do whatever
}
}
Also, stay away from keyCode
since it will be deprecated some time.
The following way has helped me (includes react-hot, babel loaders and es2015, react presets):
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['react-hot', 'babel?presets[]=es2015&presets[]=react']
}
]
@gdbj's answer is a great explanation and the most up to date answer. Here's however a simpler approach.
So if you want to redirect all traffic from nginx listening to 80
to another container exposing 8080
, minimum configuration can be as little as:
nginx.conf:
server {
listen 80;
location / {
proxy_pass http://client:8080; # this one here
proxy_redirect off;
}
}
docker-compose.yml
version: "2"
services:
entrypoint:
image: some-image-with-nginx
ports:
- "80:80"
links:
- client # will use this one here
client:
image: some-image-with-api
ports:
- "8080:8080"
I think it's the boundary (i.e. character following) of the last match or the beginning or end of the string.
This can be done easily using ·
. You can color or size the dot according to the tags you wrap it with. For example, try and run this
<h2> I · love · Coding </h2>
Use this Format as per your requirements:
{
"address": "colombo",
"username": "hesh",
"password": "123",
"registetedDate": "2015-4-3",
"firstname": "hesh",
"contactNo": "07762",
"accountNo": "16161",
"lastName": "jay"
"arrayOneName" : [
{
"Id" : 1,
"Employee" : "EmpOne",
"Deptartment" : "HR"
},
{
"Id" : 2,
"Employee" : "EmpTwo",
"Deptartment" : "IT"
},
{
"Id" : 3,
"Employee" : "EmpThree",
"Deptartment" : "Sales"
}
],
"arrayTwoName": [
{
"Product": "3",
"Price": "6790"
}
],
"arrayThreeName" : [
"name1", "name2", "name3", "name4" // For Strings
],
"arrayFourName" : [
1, 2, 3, 4 // For Numbers
]
}
Remember to use this in POST with proper endpoint. Also, RAW selected and JSON(application/json) in Body Tab.
Like THIS:
Update 1:
I don't think multiple @RequestBody is allowed or possible.
@RequestBody parameter must have the entire body of the request and bind that to only one object.
You have to use something like Wrapper Object for this to work.
From MSDN:
Key events occur in the following order:
Furthermore, KeyPress gives you a chance to declare the action as "handled" to prevent it from doing anything.
.......... ^ <= pointer to "print head"
/* part1 */
printf("hello worl");
hello worl ^ <= pointer to "print head"
/* part2 */
printf("\b");
hello worl ^ <= pointer to "print head"
/* part3 */
printf("\b");
hello worl ^ <= pointer to "print head"
/* part4 */
printf("d\n");
hello wodl ^ <= pointer to "print head" on the next line
This actually works for me:
background-color: #6DB3F2;
background-image: url('images/checked.png');
You can also drop a solid shadow and set the background image:
background-image: url('images/checked.png');
box-shadow: inset 0 0 100% #6DB3F2;
If the first option is not working for some reason and you don't want to use the box shadow you can always use a pseudo element for the image without any extra HTML:
.btn{
position: relative;
background-color: #6DB3F2;
}
.btn:before{
content: "";
display: block;
width: 100%;
height: 100%;
position:absolute;
top:0;
left:0;
background-image: url('images/checked.png');
}
I'd look into using the System.TimeZoneInfo class if you are in .NET 3.5. See http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx. This should take into account the daylight savings changes correctly.
// Coordinated Universal Time string from
// DateTime.Now.ToUniversalTime().ToString("u");
string date = "2009-02-25 16:13:00Z";
// Local .NET timeZone.
DateTime localDateTime = DateTime.Parse(date);
DateTime utcDateTime = localDateTime.ToUniversalTime();
// ID from:
// "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Time Zone"
// See http://msdn.microsoft.com/en-us/library/system.timezoneinfo.id.aspx
string nzTimeZoneKey = "New Zealand Standard Time";
TimeZoneInfo nzTimeZone = TimeZoneInfo.FindSystemTimeZoneById(nzTimeZoneKey);
DateTime nzDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, nzTimeZone);
I got similar issue. The mistake i made was I did not add service in the providers array in app.module.ts. Hope this helps, Thank You.
I just ran over this one and I found by accident that CLOBs can be used in a like query:
UPDATE IMS_TEST
SET TEST_Category = 'just testing'
WHERE TEST_SCRIPT LIKE '%something%'
AND ID = '10000239'
This worked also for CLOBs greater than 4K
The Performance won't be great but that was no problem in my case.
use CHAR(10)
for New Line in SQL
char(9)
for Tab
and Char(13)
for Carriage Return
Here is the simplest solution based on [https://en.wikipedia.org/wiki/Coefficient_of_determination]
# 1. 'Actual' and 'Predicted' data
df <- data.frame(
y_actual = c(1:5),
y_predicted = c(0.8, 2.4, 2, 3, 4.8))
# 2. R2 Score components
# 2.1. Average of actual data
avr_y_actual <- mean(df$y_actual)
# 2.2. Total sum of squares
ss_total <- sum((df$y_actual - avr_y_actual)^2)
# 2.3. Regression sum of squares
ss_regression <- sum((df$y_predicted - avr_y_actual)^2)
# 2.4. Residual sum of squares
ss_residuals <- sum((df$y_actual - df$y_predicted)^2)
# 3. R2 Score
r2 <- 1 - ss_residuals / ss_total
Does this work?
Workbooks.Open Filename:=filepath, ReadOnly:=True
Or, as pointed out in a comment, to keep a reference to the opened workbook:
Dim book As Workbook
Set book = Workbooks.Open(Filename:=filepath, ReadOnly:=True)
What you want is this constructor:
std::string ( const string& str, size_t pos, size_t n = npos )
, passing pos as 0. Your const char* c-style string will get implicitly cast to const string for the first parameter.
const char *c_style = "012abd";
std::string cpp_style = new std::string(c_style, 0, 10);
This is a very useful question. It has 5 different helpful answers that say quite different but complementary things (surprising, eh?). This answer combines those answers into a more useful form as well as adding two more solutions.
There is no Oracle Express Edition for 64 bit Windows. See this official [but unanswered] forum thread. Therefore, these are the classes of solutions:
Try this to reload jqGrid with new data
jQuery("#grid").jqGrid('setGridParam',{datatype:'json'}).trigger('reloadGrid');
Using Crypto++, you could do the following:
#include <sha.h>
#include <iostream>
SHA256 sha;
while ( !f.eof() ) {
char buff[4096];
int numchars = f.read(...);
sha.Update(buff, numchars);
}
char hash[size];
sha.Final(hash);
cout << hash <<endl;
I have a need for something very similar, because I can't read in multi-gigabyte files just to compute a hash. In theory I could memory map them, but I have to support 32bit platforms - that's still problematic for large files.
You can add style for :after a like html code.
For example:
var value = 22;
body.append('<style>.wrapper:after{border-top-width: ' + value + 'px;}</style>');
The answer is in the JavaDoc of the equals()
method:
Unlike
compareTo
, this method considers twoBigDecimal
objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).
In other words: equals()
checks if the BigDecimal
objects are exactly the same in every aspect. compareTo()
"only" compares their numeric value.
As to why equals()
behaves this way, this has been answered in this SO question.
You should put this line in your application context:
<context:component-scan base-package="com.cinebot.service" />
Read more about Automatically detecting classes and registering bean definitions in documentation.
Try this:
foreach (string file in Directory.GetFiles(@"c:\directory\"))
File.Delete(file);
You are using wrong JSON. In this case you should use JSON that looks like this:
["orange", "apple"]
If you have to accept JSON in that form :
{"fruits":["apple","orange"]}
You'll have to create wrapper object:
public class FruitWrapper{
List<String> fruits;
//getter
//setter
}
and then your controller method should look like this:
@RequestMapping(value = "/saveFruits", method = RequestMethod.POST,
consumes = "application/json")
@ResponseBody
public ResultObject saveFruits(@RequestBody FruitWrapper fruits){
...
}
just type
cordova platform ls
This will list all the platforms installed along with its version and available for installation plus :)
I think you can do this with the hyperref
package, although I've not tried it myself. From the relevant LaTeX Wikibook section:
The
hyperref
package introduces another useful command;\autoref{}
. This command creates a reference with additional text corresponding to the targets type, all of which will be a hyperlink. For example, the command\autoref{sec:intro}
would create a hyperlink to the\label{sec:intro}
command, wherever it is. Assuming that this label is pointing to a section, the hyperlink would contain the text "section 3.4", or similar (capitalization rules will be followed, which makes this very convenient). You can customize the prefixed text by redefining\typeautorefname
to the prefix you want, as in:
\def\subsectionautorefname{section}
public class EMView extends Activity {
ImageView img,img1;
int column_index;
Intent intent=null;
// Declare our Views, so we can access them later
String logo,imagePath,Logo;
Cursor cursor;
//YOU CAN EDIT THIS TO WHATEVER YOU WANT
private static final int SELECT_PICTURE = 1;
String selectedImagePath;
//ADDED
String filemanagerstring;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
img= (ImageView)findViewById(R.id.gimg1);
((Button) findViewById(R.id.Button01))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// in onCreate or any event where your want the user to
// select a file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
}
});
}
//UPDATED
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
//OI FILE Manager
filemanagerstring = selectedImageUri.getPath();
//MEDIA GALLERY
selectedImagePath = getPath(selectedImageUri);
img.setImageURI(selectedImageUri);
imagePath.getBytes();
TextView txt = (TextView)findViewById(R.id.title);
txt.setText(imagePath.toString());
Bitmap bm = BitmapFactory.decodeFile(imagePath);
// img1.setImageBitmap(bm);
}
}
}
//UPDATED!
public String getPath(Uri uri) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
column_index = cursor
.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
imagePath = cursor.getString(column_index);
return cursor.getString(column_index);
}
}
There's a shorthand-type way to do this that I have been using recently. This might need to be configured, but it should work in most mainline PHP installations. If you're storing the link in a PHP variable, you can do it in the following manner based off the OP:
<html>
<body>
<?php
$link = "http://www.google.com";
?>
<a href="<?= $link ?>">Click here to go to Google.</a>
</body>
</html>
This will evaluate the variable as a string, in essence shorthand for echo $link;
<input attr1='a' attr2='b' attr3='c'>foo</input>
getAttribute(attr1)
you get 'a'
getAttribute(attr2)
you get 'b'
getAttribute(attr3)
you get 'c'
getText()
with no parameter you can only get 'foo'
I was trying to create a borderless window with WindowStyle="None"
but when I tested it, seems that appears a white bar in the top, after some research it appears to be a "Resize border", here is an image (I remarked in yellow):
After some research over the internet, and lots of difficult non xaml solutions, all the solutions that I found were code behind in C# and lots of code lines, I found indirectly the solution here: Maximum custom window loses drop shadow effect
<WindowChrome.WindowChrome>
<WindowChrome
CaptionHeight="0"
ResizeBorderThickness="5" />
</WindowChrome.WindowChrome>
Note : You need to use .NET 4.5 framework, or if you are using an older version use WPFShell, just reference the shell and use Shell:WindowChrome.WindowChrome
instead.
I used the WindowChrome
property of Window, if you use this that white "resize border" disappears, but you need to define some properties to work correctly.
CaptionHeight: This is the height of the caption area (headerbar) that allows for the Aero snap, double clicking behaviour as a normal title bar does. Set this to 0 (zero) to make the buttons work.
ResizeBorderThickness: This is thickness at the edge of the window which is where you can resize the window. I put to 5 because i like that number, and because if you put zero its difficult to resize the window.
After using this short code the result is this:
And now, the white border disappeared without using ResizeMode="NoResize"
and AllowsTransparency="True"
, also it shows a shadow in the window.
Later I will explain how to make to work the buttons (I didn't used images for the buttons) easily with simple and short code, Im new and i think that I can post to codeproject, because here I didn't find the place to post the tutorial.
Maybe there is another solution (I know that there are hard and difficult solutions for noobs like me) but this works for my personal projects.
Here is the complete code
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Concursos"
mc:Ignorable="d"
Title="Concuros" Height="350" Width="525"
WindowStyle="None"
WindowState="Normal"
ResizeMode="CanResize"
>
<WindowChrome.WindowChrome>
<WindowChrome
CaptionHeight="0"
ResizeBorderThickness="5" />
</WindowChrome.WindowChrome>
<Grid>
<Rectangle Fill="#D53736" HorizontalAlignment="Stretch" Height="35" VerticalAlignment="Top" PreviewMouseDown="Rectangle_PreviewMouseDown" />
<Button x:Name="Btnclose" Content="r" HorizontalAlignment="Right" VerticalAlignment="Top" Width="35" Height="35" Style="{StaticResource TempBTNclose}"/>
<Button x:Name="Btnmax" Content="2" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,0,35,0" Width="35" Height="35" Style="{StaticResource TempBTNclose}"/>
<Button x:Name="Btnmin" Content="0" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,0,70,0" Width="35" Height="35" Style="{StaticResource TempBTNclose}"/>
</Grid>
Thank you!
You can use mkdir:
#include <sys/stat.h>
#include <sys/types.h>
int result = mkdir("/home/me/test.txt", 0777);
No answer so far mentions eu-strip --strip-debug -f <out.debug> <input>
.
elfutils
package. <input>
file has been stripped of debug symbols which are now all in <out.debug>
.To loop all rows in a dataframe
and use values of each row conveniently, namedtuples
can be converted to ndarray
s. For example:
df = pd.DataFrame({'col1': [1, 2], 'col2': [0.1, 0.2]}, index=['a', 'b'])
Iterating over the rows:
for row in df.itertuples(index=False, name='Pandas'):
print np.asarray(row)
results in:
[ 1. 0.1]
[ 2. 0.2]
Please note that if index=True
, the index is added as the first element of the tuple, which may be undesirable for some applications.
slicing operator. http://docs.python.org/tutorial/introduction.html#strings and scroll down a bit
Open Anaconda Prompt (base):
conda update -n base -c defaults conda
conda create -n python38 python=3.8
conda activate python38
python
I'm not sure you understand what "exit" states
Terminates execution of the script. Shutdown functions and object destructors will always be executed even if exit is called.
It's normal to do that, it must clear it's memmory of all the variables and functions you called before. Not doing this would mean your memmory would remain stuck and ocuppied in your RAM, and if this would happen several times you would need to reboot and flush your RAM in order to have any left.
If you are trying to install Tensorflow with Anaconda on Windows, a free advice is to please uninstall anaconda and download a 64-bit Python version, ending with amd64 from releases page. For me, its python-3.7.8-amd64.exe
Then install Tensorflow in a virtual environment by following the instructions on official website of Tensorflow.
And for those of you using an anonymous expression:
await Task.Run(async () =>
{
SQLLiteUtils slu = new SQLiteUtils();
await slu.DeleteGroupAsync(groupname);
});
DTO vs VO
DTO - Data transfer objects are just data containers which are used to transport data between layers and tiers.
Analogy:
Simple Registration form with attributes username, password and email id.
- When this form is submitted in RegistrationServlet file you will get all the attributes from view layer to business layer where you pass the attributes to java beans and then to the DAO or the persistence layer.
- DTO's helps in transporting the attributes from view layer to business layer and finally to the persistence layer.
DTO was mainly used to get data transported across the network efficiently, it may be even from JVM to another JVM.
DTOs are often java.io.Serializable
- in order to transfer data across JVM.
VO - A Value Object [1][2] represents itself a fixed set of data and is similar to a Java enum. A Value Object's identity is based on their state rather than on their object identity and is immutable. A real world example would be Color.RED, Color.BLUE, SEX.FEMALE etc.
POJO vs JavaBeans
[1] The Java-Beanness of a POJO is that its private attributes are all accessed via public getters and setters that conform to the JavaBeans conventions. e.g.
private String foo;
public String getFoo(){...}
public void setFoo(String foo){...};
[2] JavaBeans must implement Serializable and have a no-argument constructor, whereas in POJO does not have these restrictions.
By useing this code below :
.classname{
background-image: url(images/paper.jpg);
background-position: center;
background-size: cover;
background-repeat: no-repeat;
}
Hope it works. Thanks
You cannot directly see the query result using mysql_query its only fires the query in mysql nothing else.
For getting the result you have to add a lil things in your script like
require_once('db.php');
$sql="SELECT * FROM modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) ) FROM modul1open) ORDER BY idM1O LIMIT 1";
$result = mysql_query($sql);
//echo [$result];
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
print_r($row);
}
This will give you result;
Should be pretty straightforward, its just the reverse of your previous method;
public static int GetEnumFromDescription(string description, Type enumType)
{
foreach (var field in enumType.GetFields())
{
DescriptionAttribute attribute
= Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))as DescriptionAttribute;
if(attribute == null)
continue;
if(attribute.Description == description)
{
return (int) field.GetValue(null);
}
}
return 0;
}
Usage:
Console.WriteLine((Animal)GetEnumFromDescription("Giant Panda",typeof(Animal)));
// stringValue can be anything in which present any number
`const stringValue = 'last_15_days';
// /\d+/g is regex which is used for matching number in string
// match helps to find result according to regex from string and return match value
const result = stringValue.match(/\d+/g);
console.log(result);`
output will be 15
If You want to learn more about regex here are some links:
https://www.w3schools.com/jsref/jsref_obj_regexp.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
https://www.tutorialspoint.com/javascript/javascript_regexp_object.htm
Your code looks pretty good.
Be careful, however, for your call to Range("H5")
is a shortcut command to Application.Range("H5")
, which is equivalent to Application.ActiveSheet.Range("H5")
. This could be fine, if the only changes are user-changes -- which is the most typical -- but it is possible for the worksheet's cell values to change when it is not the active sheet via programmatic changes, e.g. VBA.
With this in mind, I would utilize Target.Worksheet.Range("H5")
:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Target.Worksheet.Range("H5")) Is Nothing Then Macro
End Sub
Or you can use Me.Range("H5")
, if the event handler is on the code page for the worksheet in question (it usually is):
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Me.Range("H5")) Is Nothing Then Macro
End Sub
Hope this helps...
Most of the above solutions assume that the parent DateGridView
has .AutoSizeMode
not equal to Fill
. If you set the .AutoSizeMode
for the grid to be Fill
, you need to set the AutoSizeMode for each column to be None
if you want to fix a particular column width (and let the other columns Fill). I found a weird MS exception regarding a null object if you change a Column Width and the .AutoSizeMode
is not None
first.
This works
chart.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
... add some columns here
chart.Column[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
chart.Column[i].Width = 60;
This throws a null exception regarding some internal object regarding setting border thickness.
chart.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
... add some columns here
// chart.Column[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
chart.Column[i].Width = 60;
ASCII - Software allocates only 8 bit byte in memory for a given character. It works well for English & adopted (loanwords like façade) characters as their corresponding decimal values falls below 128 in the decimal value. Example C program.
UTF-8 - Software allocates 1 to 4 variable 8 bit bytes for a given character. What does mean by variable here? Let us say you are sending the character 'A' through your HTML pages in the browser (HTML is UTF-8), the corresponding decimal value of A is 65, when you convert it into decimal it becomes 01000010. This requires only 1 bytes, 1 byte memory is allocated even for special adopted English characters like 'ç' in a word façade. However, when you want to store European characters, it requires 2 bytes, so you need UTF-8. However, when you go for Asian characters, you require minimum of 2 bytes and maximum of 4 bytes. Similarly, Emoji's require 3 to 4 bytes. UTF-8 will solve all your needs.
UTF-16 will allocate minimum 2 bytes and maximum of 4 bytes per character, it will not allocate 1 or 3 bytes. Each character is either represented in 16 bit or 32 bit.
Then why exists UTF-16? Originally, Unicode was 16 bit not 8 bit. Java adopted the original version of UTF-16.
In a nutshell, you don't need UTF-16 anywhere unless it has been already been adopted by the language or platform you are working on.
Java program invoked by web browsers uses UTF-16 but the web browser sends characters using UTF-8.
Consider i
and n
to be the left and right operands respectively of a shift operator; the type of i
, after integer promotion, be T
. Assuming n
to be in [0, sizeof(i) * CHAR_BIT)
— undefined otherwise — we've these cases:
| Direction | Type | Value (i) | Result |
| ---------- | -------- | --------- | ------------------------ |
| Right (>>) | unsigned | = 0 | -8 ? (i ÷ 2n) |
| Right | signed | = 0 | -8 ? (i ÷ 2n) |
| Right | signed | < 0 | Implementation-defined† |
| Left (<<) | unsigned | = 0 | (i * 2n) % (T_MAX + 1) |
| Left | signed | = 0 | (i * 2n) ‡ |
| Left | signed | < 0 | Undefined |
† most compilers implement this as arithmetic shift
‡ undefined if value overflows the result type T; promoted type of i
First is the difference between logical and arithmetic shifts from a mathematical viewpoint, without worrying about data type size. Logical shifts always fills discarded bits with zeros while arithmetic shift fills it with zeros only for left shift, but for right shift it copies the MSB thereby preserving the sign of the operand (assuming a two's complement encoding for negative values).
In other words, logical shift looks at the shifted operand as just a stream of bits and move them, without bothering about the sign of the resulting value. Arithmetic shift looks at it as a (signed) number and preserves the sign as shifts are made.
A left arithmetic shift of a number X by n is equivalent to multiplying X by 2n and is thus equivalent to logical left shift; a logical shift would also give the same result since MSB anyway falls off the end and there's nothing to preserve.
A right arithmetic shift of a number X by n is equivalent to integer division of X by 2n ONLY if X is non-negative! Integer division is nothing but mathematical division and round towards 0 (trunc).
For negative numbers, represented by two's complement encoding, shifting right by n bits has the effect of mathematically dividing it by 2n and rounding towards -8 (floor); thus right shifting is different for non-negative and negative values.
for X = 0, X >> n = X / 2n = trunc(X ÷ 2n)
for X < 0, X >> n = floor(X ÷ 2n)
where ÷
is mathematical division, /
is integer division. Let's look at an example:
37)10 = 100101)2
37 ÷ 2 = 18.5
37 / 2 = 18 (rounding 18.5 towards 0) = 10010)2 [result of arithmetic right shift]
-37)10 = 11011011)2 (considering a two's complement, 8-bit representation)
-37 ÷ 2 = -18.5
-37 / 2 = -18 (rounding 18.5 towards 0) = 11101110)2 [NOT the result of arithmetic right shift]
-37 >> 1 = -19 (rounding 18.5 towards -8) = 11101101)2 [result of arithmetic right shift]
As Guy Steele pointed out, this discrepancy has led to bugs in more than one compiler. Here non-negative (math) can be mapped to unsigned and signed non-negative values (C); both are treated the same and right-shifting them is done by integer division.
So logical and arithmetic are equivalent in left-shifting and for non-negative values in right shifting; it's in right shifting of negative values that they differ.
Standard C99 §6.5.7:
Each of the operands shall have integer types.
The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behaviour is undefined.
short E1 = 1, E2 = 3;
int R = E1 << E2;
In the above snippet, both operands become int
(due to integer promotion); if E2
was negative or E2 = sizeof(int) * CHAR_BIT
then the operation is undefined. This is because shifting more than the available bits is surely going to overflow. Had R
been declared as short
, the int
result of the shift operation would be implicitly converted to short
; a narrowing conversion, which may lead to implementation-defined behaviour if the value is not representable in the destination type.
The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1×2E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and non-negative value, and E1×2E2 is representable in the result type, then that is the resulting value; otherwise, the behaviour is undefined.
As left shifts are the same for both, the vacated bits are simply filled with zeros. It then states that for both unsigned and signed types it's an arithmetic shift. I'm interpreting it as arithmetic shift since logical shifts don't bother about the value represented by the bits, it just looks at it as a stream of bits; but the standard talks not in terms of bits, but by defining it in terms of the value obtained by the product of E1 with 2E2.
The caveat here is that for signed types the value should be non-negative and the resulting value should be representable in the result type. Otherwise the operation is undefined. The result type would be the type of the E1 after applying integral promotion and not the destination (the variable which is going to hold the result) type. The resulting value is implicitly converted to the destination type; if it is not representable in that type, then the conversion is implementation-defined (C99 §6.3.1.3/3).
If E1 is a signed type with a negative value then the behaviour of left shifting is undefined. This is an easy route to undefined behaviour which may easily get overlooked.
The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a non-negative value, the value of the result is the integral part of the quotient of E1/2E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.
Right shift for unsigned and signed non-negative values are pretty straight forward; the vacant bits are filled with zeros. For signed negative values the result of right shifting is implementation-defined. That said, most implementations like GCC and Visual C++ implement right-shifting as arithmetic shifting by preserving the sign bit.
Unlike Java, which has a special operator >>>
for logical shifting apart from the usual >>
and <<
, C and C++ have only arithmetic shifting with some areas left undefined and implementation-defined. The reason I deem them as arithmetic is due to the standard wording the operation mathematically rather than treating the shifted operand as a stream of bits; this is perhaps the reason why it leaves those areas un/implementation-defined instead of just defining all cases as logical shifts.
The full list of readyState
values is:
State Description
0 The request is not initialized
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is complete
(from https://www.w3schools.com/js/js_ajax_http_response.asp)
In practice you almost never use any of them except for 4.
Some XMLHttpRequest implementations may let you see partially received responses in responseText
when readyState==3
, but this isn't universally supported and shouldn't be relied upon.
Please reference :Spring Data JPA @Query, if you are using Spring Data JPA version 2.0.4 and later. Sample like below:
@Query(value = "SELECT u FROM User u ORDER BY id")
Page<User> findAllUsersWithPagination(Pageable pageable);
To remove the "keep-alive" header in requests, I just created it from the Request object and then send it with Session
headers = {
'Host' : '1.2.3.4',
'User-Agent' : 'Test client (x86_64-pc-linux-gnu 7.16.3)',
'Accept' : '*/*',
'Accept-Encoding' : 'deflate, gzip',
'Accept-Language' : 'it_IT'
}
url = "https://stream.twitter.com/1/statuses/filter.json"
#r = requests.get(url, headers = headers) #this triggers keep-alive: True
s = requests.Session()
r = requests.Request('GET', url, headers)
I'm afraid that the first of those command lines unconditionally deleted from the working copy all the files that are in git's staging area. The second one unstaged all the files that were tracked but have now been deleted. Unfortunately this means that you will have lost any uncommitted modifications to those files.
If you want to get your working copy and index back to how they were at the last commit, you can (carefully) use the following command:
git reset --hard
I say "carefully" since git reset --hard
will obliterate uncommitted changes in your working copy and index. However, in this situation it sounds as if you just want to go back to the state at your last commit, and the uncommitted changes have been lost anyway.
Update: it sounds from your comments on Amber's answer that you haven't yet created any commits (since HEAD cannot be resolved), so this won't help, I'm afraid.
As for how those pipes work: git ls-files -z
and git diff --name-only --diff-filter=D -z
both output a list of file names separated with the byte 0
. (This is useful, since, unlike newlines, 0
bytes are guaranteed not to occur in filenames on Unix-like systems.) The program xargs
essentially builds command lines from its standard input, by default by taking lines from standard input and adding them to the end of the command line. The -0
option says to expect standard input to by separated by 0
bytes. xargs
may invoke the command several times to use up all the parameters from standard input, making sure that the command line never becomes too long.
As a simple example, if you have a file called test.txt
, with the following contents:
hello
goodbye
hello again
... then the command xargs echo whatever < test.txt
will invoke the command:
echo whatever hello goodbye hello again
Use ProcessBuilder to separate commands and arguments instead of spaces. This should work regardless of shell used:
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(final String[] args) throws IOException, InterruptedException {
//Build command
List<String> commands = new ArrayList<String>();
commands.add("/bin/cat");
//Add arguments
commands.add("/home/narek/pk.txt");
System.out.println(commands);
//Run macro on target
ProcessBuilder pb = new ProcessBuilder(commands);
pb.directory(new File("/home/narek"));
pb.redirectErrorStream(true);
Process process = pb.start();
//Read output
StringBuilder out = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null, previous = null;
while ((line = br.readLine()) != null)
if (!line.equals(previous)) {
previous = line;
out.append(line).append('\n');
System.out.println(line);
}
//Check result
if (process.waitFor() == 0) {
System.out.println("Success!");
System.exit(0);
}
//Abnormal termination: Log command parameters and output and throw ExecutionException
System.err.println(commands);
System.err.println(out.toString());
System.exit(1);
}
}
Sqlite helper class helps us to manage database creation and version management.
SQLiteOpenHelper takes care of all database management activities. To use it,
1.Override onCreate(), onUpgrade()
methods of SQLiteOpenHelper
. Optionally override onOpen() method.
2.Use this subclass to create either a readable or writable database and use the SQLiteDatabase's four API methods insert(), execSQL(), update(), delete()
to create, read, update and delete rows of your table.
Example to create a MyEmployees table and to select and insert records:
public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "DBName";
private static final int DATABASE_VERSION = 2;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table MyEmployees
( _id integer primary key,name text not null);";
public MyDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Method is called during creation of the database
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
// Method is called during an upgrade of the database,
@Override
public void onUpgrade(SQLiteDatabase database,int oldVersion,int newVersion){
Log.w(MyDatabaseHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
database.execSQL("DROP TABLE IF EXISTS MyEmployees");
onCreate(database);
}
}
Now you can use this class as below,
public class MyDB{
private MyDatabaseHelper dbHelper;
private SQLiteDatabase database;
public final static String EMP_TABLE="MyEmployees"; // name of table
public final static String EMP_ID="_id"; // id value for employee
public final static String EMP_NAME="name"; // name of employee
/**
*
* @param context
*/
public MyDB(Context context){
dbHelper = new MyDatabaseHelper(context);
database = dbHelper.getWritableDatabase();
}
public long createRecords(String id, String name){
ContentValues values = new ContentValues();
values.put(EMP_ID, id);
values.put(EMP_NAME, name);
return database.insert(EMP_TABLE, null, values);
}
public Cursor selectRecords() {
String[] cols = new String[] {EMP_ID, EMP_NAME};
Cursor mCursor = database.query(true, EMP_TABLE,cols,null
, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor; // iterate to get each value.
}
}
Now you can use MyDB class in you activity to have all the database operations. The create records will help you to insert the values similarly you can have your own functions for update and delete.
adb shell am broadcast -a android.intent.action.xxx
Mention xxx as the action that you mentioned in the manifest file.
Here you go. Just specify the chars you want to allow on the first line.
char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
StringBuilder sb = new StringBuilder(20);
Random random = new Random();
for (int i = 0; i < 20; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
String output = sb.toString();
System.out.println(output);
If you are using this to generate something sensitive like a password reset URL or session ID cookie or temporary password reset, be sure to use
java.security.SecureRandom
instead. Values produced byjava.util.Random
andjava.util.concurrent.ThreadLocalRandom
are mathematically predictable.
Use a BackgroundWorker. It will allow you to get callbacks on completion and allow you to track progress. You can set the Result value on the event arguments to the resulting value.
public void UseBackgroundWorker()
{
var worker = new BackgroundWorker();
worker.DoWork += DoWork;
worker.RunWorkerCompleted += WorkDone;
worker.RunWorkerAsync("input");
}
public void DoWork(object sender, DoWorkEventArgs e)
{
e.Result = e.Argument.Equals("input");
Thread.Sleep(1000);
}
public void WorkDone(object sender, RunWorkerCompletedEventArgs e)
{
var result = (bool) e.Result;
}
PRINT DATEDIFF(DAY, '1/1/2011', '3/1/2011')
will give you what you're after.
This gives the number of times the midnight boundary is crossed between the two dates. You may decide to need to add one to this if you're including both dates in the count - or subtract one if you don't want to include either date.
With django 1.11, simply delete all migration files from the migrations
folder of each application (all files except __init__.py
). Then
python3 manage.py makemigrations
.python3 manage.py migrate
.And voilla, your database has been completely reset.
Once I used double slash while calling the API then I got the same error.
I had to call http://localhost:8080/getSomething but I did Like http://localhost:8080//getSomething. I resolved it by removing extra slash.
You can use output parameters with sp_executesql.
DECLARE @dbName nvarchar(128) = 'myDb'
DECLARE @siteId int
DECLARE @SQL nvarchar(max) = N'SELECT TOP 1 @siteId = Id FROM ' + quotename(@dbName) + N'..myTbl'
exec sp_executesql @SQL, N'@siteId int out', @siteId out
select @siteId
This is an example for a RelativeLayout:
RelativeLayout relativeLayout=(RelativeLayout)vi.findViewById(R.id.RelativeLayoutLeft);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)relativeLayout.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
relativeLayout.setLayoutParams(params);
With another kind of layout (example LinearLayout) you just simply has to change RelativeLayout for LinearLayout.
In matrix multiplication there are 3 for loop, we are using since execution of each for loop requires time complexity O(n)
. So for three loops it becomes O(n^3)
With Java 8 you can simply convert your list to a stream allowing you to write:
import java.util.List;
import java.util.stream.Collectors;
List<Sample> list = new ArrayList<Sample>();
List<Sample> result = list.stream()
.filter(a -> Objects.equals(a.value3, "three"))
.collect(Collectors.toList());
Note that
a -> Objects.equals(a.value3, "three")
is a lambda expressionresult
is a List
with a Sample
typelist.parallelStream()
instead of list.stream()
(read this)If you can't use Java 8, you can use Apache Commons library and write:
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
Collection result = CollectionUtils.select(list, new Predicate() {
public boolean evaluate(Object a) {
return Objects.equals(((Sample) a).value3, "three");
}
});
// If you need the results as a typed array:
Sample[] resultTyped = (Sample[]) result.toArray(new Sample[result.size()]);
Note that:
Object
to Sample
at each iterationSample[]
, you need extra code (as shown in my sample)Bonus: A nice blog article talking about how to find element in list.
You do not need to pass the size parameter, just declare Varchar
already understands that it is MAX like:
cmd.Parameters.Add("@blah",SqlDbType.VarChar).Value = "some large text";
I accidentally deleted a whole bunch of data in the wrong environment and this post was one of the first ones I found.
Because I was simultaneously panicking and searching for a solution, I went for the first thing I saw - ApexSQL Logs, which was $2000 which was an acceptable cost.
However, I've since found out that Toad for Sql Server can generate undo scripts from transaction logs and it is only $655.
Lastly, found an even cheaper option SysToolsGroup Log Analyzer and it is only $300.
On RH systems, MySQL configuration file is located under /etc/my.cnf by default.
Very old question, but in case someone else stumbles across it, I would recommend trying:
$j("html, body").stop(true, true).animate({
scrollTop: $j('#main').offset().top
}, 300);
$('form[name="frmSave"]')
is correct. You mentioned you thought this would get all children with the name frmsave
inside the form; this would only happen if there was a space or other combinator between the form and the selector, eg: $('form [name="frmSave"]');
$('form[name="frmSave"]')
literally means find all forms with the name frmSave
, because there is no combinator involved.
Google recommends to use hreflang, read more info
Examples:
<link rel="alternate" href="http://example.com/en-ie" hreflang="en-ie" />
<link rel="alternate" href="http://example.com/en-ca" hreflang="en-ca" />
<link rel="alternate" href="http://example.com/en-au" hreflang="en-au" />
<link rel="alternate" href="http://example.com/en" hreflang="en" />
The previous answer is correct but I'll give you all the code as well.
Your app.config should look like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="ServicesSection" type="RT.Core.Config.ServiceConfigurationSection, RT.Core"/>
</configSections>
<ServicesSection>
<Services>
<add Port="6996" ReportType="File" />
<add Port="7001" ReportType="Other" />
</Services>
</ServicesSection>
</configuration>
Your ServiceConfig
and ServiceCollection
classes remain unchanged.
You need a new class:
public class ServiceConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("Services", IsDefaultCollection = false)]
[ConfigurationCollection(typeof(ServiceCollection),
AddItemName = "add",
ClearItemsName = "clear",
RemoveItemName = "remove")]
public ServiceCollection Services
{
get
{
return (ServiceCollection)base["Services"];
}
}
}
And that should do the trick. To consume it you can use:
ServiceConfigurationSection serviceConfigSection =
ConfigurationManager.GetSection("ServicesSection") as ServiceConfigurationSection;
ServiceConfig serviceConfig = serviceConfigSection.Services[0];
Since posting this question the readxl
package has been released. It supports both xls
and xlsx
format. Importantly, in contrast to other excel import packages, it works on Windows, Mac, and Linux without requiring installation of additional software.
So a function for importing all sheets in an Excel workbook would be:
library(readxl)
read_excel_allsheets <- function(filename, tibble = FALSE) {
# I prefer straight data.frames
# but if you like tidyverse tibbles (the default with read_excel)
# then just pass tibble = TRUE
sheets <- readxl::excel_sheets(filename)
x <- lapply(sheets, function(X) readxl::read_excel(filename, sheet = X))
if(!tibble) x <- lapply(x, as.data.frame)
names(x) <- sheets
x
}
This could be called with:
mysheets <- read_excel_allsheets("foo.xls")
Building on the answer provided by @mnel, here is a simple function that takes an Excel file as an argument and returns each sheet as a data.frame in a named list.
library(XLConnect)
importWorksheets <- function(filename) {
# filename: name of Excel file
workbook <- loadWorkbook(filename)
sheet_names <- getSheets(workbook)
names(sheet_names) <- sheet_names
sheet_list <- lapply(sheet_names, function(.sheet){
readWorksheet(object=workbook, .sheet)})
}
Thus, it could be called with:
importWorksheets('test.xls')
Your sample code seems to be OK. Thus, the root problem needs to be dug up somehow. Let's eliminate chance for typos in the script. First off, make sure you put Set-Strictmode -Version 2.0
in the beginning of your script. This will help you to catch misspelled variable names. Like so,
# Test.ps1
set-strictmode -version 2.0 # Comment this line and no error will be reported.
$foo = "bar"
set-content -path ./test.txt -value $fo # Error! Should be "$foo"
PS C:\temp> .\test.ps1
The variable '$fo' cannot be retrieved because it has not been set.
At C:\temp\test.ps1:3 char:40
+ set-content -path ./test.txt -value $fo <<<<
+ CategoryInfo : InvalidOperation: (fo:Token) [], RuntimeException
+ FullyQualifiedErrorId : VariableIsUndefined
The next part about question marks sounds like you have a problem with Unicode. What's the output when you type the file with Powershell like so,
$file = "\\server\share\file.txt"
cat $file
I faced similar issues with POST Request where GET Request was working fine on my backend which i am passing my variables etc. The problem lies in there that the backend does a lot of redirects, which didnt work with fopen or the php header methods.
So the only way i got it working was to put a hidden form and push over the values with a POST submit when the page is loaded.
echo
'<body onload="document.redirectform.submit()">
<form method="POST" action="http://someurl/todo.php" name="redirectform" style="display:none">
<input name="var1" value=' . $var1. '>
<input name="var2" value=' . $var2. '>
<input name="var3" value=' . $var3. '>
</form>
</body>';
To set a title for a button in Xcode using swift - 04: first create a method called setTitle with parameter title and UIController state like below ;
func setTitle(_ title : String?, for state : UIControl.State) {
}
and recall this method in your button action method like ;
yourButtonName.setTitle("String", for: .state)
If you want to replace NAs in factor variables, this might be useful:
n <- length(levels(data.vector))+1
data.vector <- as.numeric(data.vector)
data.vector[is.na(data.vector)] <- n
data.vector <- as.factor(data.vector)
levels(data.vector) <- c("level1","level2",...,"leveln", "NAlevel")
It transforms a factor-vector into a numeric vector and adds another artifical numeric factor level, which is then transformed back to a factor-vector with one extra "NA-level" of your choice.
You can use a list comprehension:
>>> a = [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]
>>> [x[0] for x in a]
[1, 22, 53, 44]
>>> [x[0] for x in a].index(53)
2
Add the css for .card
.card {
margin: 0 auto; /* Added */
float: none; /* Added */
margin-bottom: 10px; /* Added */
}
here is the pen
UPDATE:
You can use the class .mx-auto
available in bootstrap 4 to center cards.
You can do a form.serializeArray(), then add name-value pairs before posting:
var form = $(this).closest('form');
form = form.serializeArray();
form = form.concat([
{name: "customer_id", value: window.username},
{name: "post_action", value: "Update Information"}
]);
$.post('/change-user-details', form, function(d) {
if (d.error) {
alert("There was a problem updating your user details")
}
});
Here is simple example. A contact has one to many associated phone numbers. When a contact is deleted, I want all its associated phone numbers to also be deleted, so I use ON DELETE CASCADE. The one-to-many/many-to-one relationship is implemented with by the foreign key in the phone_numbers.
CREATE TABLE contacts
(contact_id BIGINT AUTO_INCREMENT NOT NULL,
name VARCHAR(75) NOT NULL,
PRIMARY KEY(contact_id)) ENGINE = InnoDB;
CREATE TABLE phone_numbers
(phone_id BIGINT AUTO_INCREMENT NOT NULL,
phone_number CHAR(10) NOT NULL,
contact_id BIGINT NOT NULL,
PRIMARY KEY(phone_id),
UNIQUE(phone_number)) ENGINE = InnoDB;
ALTER TABLE phone_numbers ADD FOREIGN KEY (contact_id) REFERENCES \
contacts(contact_id) ) ON DELETE CASCADE;
By adding "ON DELETE CASCADE" to the foreign key constraint, phone_numbers will automatically be deleted when their associated contact is deleted.
INSERT INTO table contacts(name) VALUES('Robert Smith');
INSERT INTO table phone_numbers(phone_number, contact_id) VALUES('8963333333', 1);
INSERT INTO table phone_numbers(phone_number, contact_id) VALUES('8964444444', 1);
Now when a row in the contacts table is deleted, all its associated phone_numbers rows will automatically be deleted.
DELETE TABLE contacts as c WHERE c.id=1; /* delete cascades to phone_numbers */
To achieve the same thing in Doctrine, to get the same DB-level "ON DELETE CASCADE" behavoir, you configure the @JoinColumn with the onDelete="CASCADE" option.
<?php
namespace Entities;
use Doctrine\Common\Collections\ArrayCollection;
/**
* @Entity
* @Table(name="contacts")
*/
class Contact
{
/**
* @Id
* @Column(type="integer", name="contact_id")
* @GeneratedValue
*/
protected $id;
/**
* @Column(type="string", length="75", unique="true")
*/
protected $name;
/**
* @OneToMany(targetEntity="Phonenumber", mappedBy="contact")
*/
protected $phonenumbers;
public function __construct($name=null)
{
$this->phonenumbers = new ArrayCollection();
if (!is_null($name)) {
$this->name = $name;
}
}
public function getId()
{
return $this->id;
}
public function setName($name)
{
$this->name = $name;
}
public function addPhonenumber(Phonenumber $p)
{
if (!$this->phonenumbers->contains($p)) {
$this->phonenumbers[] = $p;
$p->setContact($this);
}
}
public function removePhonenumber(Phonenumber $p)
{
$this->phonenumbers->remove($p);
}
}
<?php
namespace Entities;
/**
* @Entity
* @Table(name="phonenumbers")
*/
class Phonenumber
{
/**
* @Id
* @Column(type="integer", name="phone_id")
* @GeneratedValue
*/
protected $id;
/**
* @Column(type="string", length="10", unique="true")
*/
protected $number;
/**
* @ManyToOne(targetEntity="Contact", inversedBy="phonenumbers")
* @JoinColumn(name="contact_id", referencedColumnName="contact_id", onDelete="CASCADE")
*/
protected $contact;
public function __construct($number=null)
{
if (!is_null($number)) {
$this->number = $number;
}
}
public function setPhonenumber($number)
{
$this->number = $number;
}
public function setContact(Contact $c)
{
$this->contact = $c;
}
}
?>
<?php
$em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config);
$contact = new Contact("John Doe");
$phone1 = new Phonenumber("8173333333");
$phone2 = new Phonenumber("8174444444");
$em->persist($phone1);
$em->persist($phone2);
$contact->addPhonenumber($phone1);
$contact->addPhonenumber($phone2);
$em->persist($contact);
try {
$em->flush();
} catch(Exception $e) {
$m = $e->getMessage();
echo $m . "<br />\n";
}
If you now do
# doctrine orm:schema-tool:create --dump-sql
you will see that the same SQL will be generated as in the first, raw-SQL example
You can fake it like this:
-- with column headings
select column1, column2 from some_table;
-- without column headings
select column1 as '', column2 as '' from some_table;
I found this presentation to be very helpfull.
How I Distribute Python applications on Windows - py2exe & InnoSetup
From the site:
There are many deployment options for Python code. I'll share what has worked well for me on Windows, packaging command line tools and services using py2exe and InnoSetup. I'll demonstrate a simple build script which creates windows binaries and an InnoSetup installer in one step. In addition, I'll go over common errors which come up when using py2exe and hints on troubleshooting them. This is a short talk, so there will be a follow-up Open Space session to share experience and help each other solve distribution problems.
I think it's important to note another difference between Sort
and OrderBy
:
Suppose there exists a Person.CalculateSalary()
method, which takes a lot of time; possibly more than even the operation of sorting a large list.
Compare
// Option 1
persons.Sort((p1, p2) => Compare(p1.CalculateSalary(), p2.CalculateSalary()));
// Option 2
var query = persons.OrderBy(p => p.CalculateSalary());
Option 2 may have superior performance, because it only calls the CalculateSalary
method n times, whereas the Sort
option might call CalculateSalary
up to 2n log(n) times, depending on the sort algorithm's success.
In Snowflake (and likely other SQL engines), you can use LAST_DAY
.
select to_date('2015-05-08T23:39:20.123-07:00') as "DATE",
last_day("DATE", 'MONTH') as "LAST DAY OF MONTH";
Which returns:
DATE LAST DAY OF MONTH
2015-05-08 2015-05-31
You can try this if you want to override
var newArray= [444,555,666];
var oldArray =[11,22,33];
oldArray.forEach((name, index) => oldArray [index] = newArray[index]);
console.log(newArray);
The above method for Visual Studio didn't seem to apply to Visual Studio 2013, but I was able to find the described checkbox using the Project Menu and selecting my project (probably the last item on the submenu) to get to the dialog with the checkbox (on the Build tab).
This is all you need:
background-repeat: no-repeat;
For mobile application i did a solution by injecting javascript in the dialog view. There is a hidden web view in my ios app. That load the fb message send dialog api .. then i inject some javascript to set the "to" and "message" field and submit the form.. So that end user need not to do anything. Message sent to facebook inbox silently...
git cherry-pick C
where C is the commit hash for C. This applies the old commit on top of the newest one.
This is fairly easy to answer from the internet. Set system properties http.proxyHost
and http.proxyPort
. You can do this with System.setProperty()
, or from the command line with the -D
syntax.
This can be easily solved with the the utility make_axes_locatable
. I provide a minimal example that shows how this works and should be readily adaptable:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
m1 = np.random.rand(3, 3)
m2 = np.arange(0, 3*3, 1).reshape((3, 3))
fig = plt.figure(figsize=(16, 12))
ax1 = fig.add_subplot(121)
im1 = ax1.imshow(m1, interpolation='None')
divider = make_axes_locatable(ax1)
cax = divider.append_axes('right', size='5%', pad=0.05)
fig.colorbar(im1, cax=cax, orientation='vertical')
ax2 = fig.add_subplot(122)
im2 = ax2.imshow(m2, interpolation='None')
divider = make_axes_locatable(ax2)
cax = divider.append_axes('right', size='5%', pad=0.05)
fig.colorbar(im2, cax=cax, orientation='vertical');
From the API (http://msdn.microsoft.com/en-us/library/system.datetime_members(VS.71).aspx) it does not seem it can show the name of the time zone used.
document.getElementById("serverTime").innerHTML = ...;
you can copy this db file to somewhere in eclipse explorer (eg:sdcard or PC),and you can use sqlite to access and update this db file .
The ISO C99 standard specifies that these macros must only be defined if explicitly requested.
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
... now PRIu64 will work
I searched for the error in the web and came to this page. I am using Visual Studio 2015 and this is my first MVC project.
If you miss the @ symbol before the render section you will get the same error. I would like to share this for future beginners.
@RenderSection("headscripts", required: false)
Although View.getVisibility() does get the visibility, its not a simple true/false. A view can have its visibility set to one of three things.
View.VISIBLE The view is visible.
View.INVISIBLE The view is invisible, but any spacing it would normally take up will still be used. Its "invisible"
View.GONE The view is gone, you can't see it and it doesn't take up the "spot".
So to answer your question, you're looking for:
if (myImageView.getVisibility() == View.VISIBLE) {
// Its visible
} else {
// Either gone or invisible
}
Never mind, I figured it out - I used the Set()
method on Header()
(doh!)
My handler looks like this now:
func saveHandler(w http.ResponseWriter, r *http.Request) {
// allow cross domain AJAX requests
w.Header().Set("Access-Control-Allow-Origin", "*")
}
Maybe this will help someone as caffeine deprived as myself sometime :)
I've tried this in iOS 7 and it worked for me
- (void)viewDidLoad
{
[super viewDidLoad];
[self.tableView sizeToFit];
}
restart your computer and run $sudo deluser username... worked for me