Ran into this issue and was able to solve by 2 main steps:
brew cask upgrade chromedriver
chrome://settings/help or cmd
+ ,
then tacking on help at the end (your choice)
from there you should land on the About Chrome Page. Here you will need to verify that you are on the latest and greatest version (problem i was running into stemmed from a mismatch in the cli vs the current chrome version)
if you getting the error, you will see a update & relaunch
primary action button.
after chrome "relaunches" it will now have the newest version matching your cli
example:
Google Chrome is up to date
Version 80.0.3987.87 (Official Build) (64-bit)
I needed to install from a requirements file and was getting this error, but did not want to use the --user
option because I didn't want to install it the location described by @not2qubit. So I ran CMD as administrator and then enabled sharing of the following directory (right click > properties > Sharing > Share...):
C:\Users\<my user name>\AppData\Local\Temp
After doing this, I was able to install from my requirements file into the application directory (where I wanted it) instead of the crazy ..\AppData
dir without the error.
What I found to fix the issue regardless of kernel version, was taking the WGET options and having apt install them.
sudo apt-get install --reinstall linux-headers-$(uname -r)
Driver Version: 390.138 on Ubuntu server 18.04.4
To compile TensorFlow with SSE4.2 and AVX, you can use directly
bazel build --config=mkl --config="opt" --copt="-march=broadwell" --copt="-O3" //tensorflow/tools/pip_package:build_pip_package
I prefer to use nvidia-smi to monitor GPU usage. if it goes up significantly when you start you program, it's a strong sign that your tensorflow is using GPU.
Yeah, I'm using tf 2.0-beta and want to enable/disable the default logging. The environment variable and methods in tf1.X don't seem to exist anymore.
I stepped around in PDB and found this to work:
# close the TF2 logger
tf2logger = tf.get_logger()
tf2logger.error('Close TF2 logger handlers')
tf2logger.root.removeHandler(tf2logger.root.handlers[0])
I then add my own logger API (in this case file-based)
logtf = logging.getLogger('DST')
logtf.setLevel(logging.DEBUG)
# file handler
logfile='/tmp/tf_s.log'
fh = logging.FileHandler(logfile)
fh.setFormatter( logging.Formatter('fh %(asctime)s %(name)s %(filename)s:%(lineno)d :%(message)s') )
logtf.addHandler(fh)
logtf.info('writing to %s', logfile)
When I try to build docker image zeppelin-highcharts, I find that the base image openjdk:8 also does not have pandas installed. I solved it with this steps.
curl --silent --show-error --retry 5 https://bootstrap.pypa.io/get-pip.py | python
pip install pandas
I refered what-is-the-official-preferred-way-to-install-pip-and-virtualenv-systemwide
For Debian Jessie and Stretch installing the following packages resolves the issue:
sudo apt install libblas3 liblapack3 liblapack-dev libblas-dev
Your next issue is very likely going to be a missing Fortran compiler, resolve this by installing it like this:
sudo apt install gfortran
If you want an optimized scipy, you can also install the optional libatlas-base-dev
package:
sudo apt install libatlas-base-dev
If you have any issue with a missing Python.h file like this:
Python.h: No such file or directory
Then have a look at this post: https://stackoverflow.com/a/21530768/209532
Adding an answer as some others have upvoted in the comments of the accepted answer they are getting this exception when attempting to cast to ObjectNode (myself included):
Exception in thread "main" java.lang.ClassCastException:
com.fasterxml.jackson.databind.node.TextNode cannot be cast to com.fasterxml.jackson.databind.node.ObjectNode
The solution is to get the 'parent' node, and perform a put
, effectively replacing the entire node, regardless of original node type.
If you need to "modify" the node using the existing value of the node:
get
the value/array of the JsonNode
put
on the parent.Code, where the goal is to modify subfield
, which is the child node of NodeA
and Node1
:
JsonNode nodeParent = someNode.get("NodeA")
.get("Node1");
// Manually modify value of 'subfield', can only be done using the parent.
((ObjectNode) nodeParent).put('subfield', "my-new-value-here");
Credits:
I got this inspiration from here, thanks to wassgreen@
I had the same error code when I was running npm run build inside node docker container.
Locally it was working while inside a container I had set option to throw error when there is a warning during compilation while locally it wasn't set. So this error can mean anything that is connected with stopping the process being done by NPM
Intel now provides a Python distribution for Linux / Windows / OS X for free called "Intel distribution for Python".
Its a complete Python distribution (e.g. python.exe is included in the package) which includes some pre-installed modules compiled against Intel's MKL (Math Kernel Library) and thus optimized for faster performance.
The distribution includes the modules NumPy, SciPy, scikit-learn, pandas, matplotlib, Numba, tbb, pyDAAL, Jupyter, and others. The drawback is a bit of lateness in upgrading to more recent versions of Python. For example as of today (1 May 2017) the distribution provides CPython 3.5 while the 3.6 version is already out. But if you don't need the new features they should be perfectly fine.
Downloading the binaries for 64-bit from http://www.lfd.uci.edu/~gohlke/pythonlibs/, and installing it directly with pip
in this order:
pip install numpy-1.12.0+mkl-cp36-cp36m-win64.whl
pip install scipy-0.18.1-cp36-cp36m-win64.whl
pip install matplotlib-2.0.0-cp36-cp36m-win64.whl
Note that you must place command prompt in the folder where you put the .whl
files after downloading them, and you must run it as administrator,
worked for me on Windows 10 64-bit now python is up and running.
I had a similar exception at Swift 4.2. I spent around half an hour trying to find a bug in my code, but the issue has gone after closing Xcode and removing derived data folder. Here is the shortcut:
rm -rf ~/Library/Developer/Xcode/DerivedData
You are creating a dictionary first, then passing that dictionary to an OrderedDict
. For Python versions < 3.6 (*), by the time you do that, the ordering is no longer going to be correct. dict
is inherently not ordered.
Pass in a sequence of tuples instead:
ship = [("NAME", "Albatross"),
("HP", 50),
("BLASTERS", 13),
("THRUSTERS", 18),
("PRICE", 250)]
ship = collections.OrderedDict(ship)
What you see when you print the OrderedDict
is it's representation, and it is entirely correct. OrderedDict([('PRICE', 250), ('HP', 50), ('NAME', 'Albatross'), ('BLASTERS', 13), ('THRUSTERS', 18)])
just shows you, in a reproducable representation, what the contents are of the OrderedDict
.
(*): In the CPython 3.6 implementation, the dict
type was updated to use a more memory efficient internal structure that has the happy side effect of preserving insertion order, and by extension the code shown in the question works without issues. As of Python 3.7, the Python language specification has been updated to require that all Python implementations must follow this behaviour. See this other answer of mine for details and also why you'd still may want to use an OrderedDict()
for certain cases.
Use Bootstrap Affix:
/* Note: Try to remove the following lines to see the effect of CSS positioning */_x000D_
.affix {_x000D_
top: 0;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
.affix + .container-fluid {_x000D_
padding-top: 70px;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Bootstrap Example</title>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container-fluid" style="background-color:#F44336;color:#fff;height:200px;">_x000D_
<h1>Bootstrap Affix Example</h1>_x000D_
<h3>Fixed (sticky) navbar on scroll</h3>_x000D_
<p>Scroll this page to see how the navbar behaves with data-spy="affix".</p>_x000D_
<p>The navbar is attached to the top of the page after you have scrolled a specified amount of pixels.</p>_x000D_
</div>_x000D_
_x000D_
<nav class="navbar navbar-inverse" data-spy="affix" data-offset-top="197">_x000D_
<ul class="nav navbar-nav">_x000D_
<li class="active"><a href="#">Basic Topnav</a></li>_x000D_
<li><a href="#">Page 1</a></li>_x000D_
<li><a href="#">Page 2</a></li>_x000D_
<li><a href="#">Page 3</a></li>_x000D_
</ul>_x000D_
</nav>_x000D_
_x000D_
<div class="container-fluid" style="height:1000px">_x000D_
<h1>Some text to enable scrolling</h1>_x000D_
<h1>Some text to enable scrolling</h1>_x000D_
<h1>Some text to enable scrolling</h1>_x000D_
<h1>Some text to enable scrolling</h1>_x000D_
<h1>Some text to enable scrolling</h1>_x000D_
<h1>Some text to enable scrolling</h1>_x000D_
<h1>Some text to enable scrolling</h1>_x000D_
<h1>Some text to enable scrolling</h1>_x000D_
<h1>Some text to enable scrolling</h1>_x000D_
<h1>Some text to enable scrolling</h1>_x000D_
<h1>Some text to enable scrolling</h1>_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Here is another sample CURL - SOAP (WSDL) request for bank swift codes
Request
curl -X POST http://www.thomas-bayer.com/axis2/services/BLZService \
-H 'Content-Type: text/xml' \
-H 'SOAPAction: blz:getBank' \
-d '
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:blz="http://thomas-bayer.com/blz/">
<soapenv:Header/>
<soapenv:Body>
<blz:getBank>
<blz:blz>10020200</blz:blz>
</blz:getBank>
</soapenv:Body>
</soapenv:Envelope>'
Response
< HTTP/1.1 200 OK
< Server: Apache-Coyote/1.1
< Content-Type: text/xml;charset=UTF-8
< Date: Tue, 26 Mar 2019 08:14:59 GMT
< Content-Length: 395
<
<?xml version='1.0' encoding='UTF-8'?>
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<ns1:getBankResponse
xmlns:ns1="http://thomas-bayer.com/blz/">
<ns1:details>
<ns1:bezeichnung>BHF-BANK</ns1:bezeichnung>
<ns1:bic>BHFBDEFF100</ns1:bic>
<ns1:ort>Berlin</ns1:ort>
<ns1:plz>10117</ns1:plz>
</ns1:details>
</ns1:getBankResponse>
</soapenv:Body>
</soapenv:Envelope>
You may install your coinhsl library in one of your standard libraries directories and run 'ldconfig` before doing your ppyipopt install
I was working on a project that depended on numpy and scipy. In a clean installation of Fedora 23, using a python virtual environment for Python 3.4 (also worked for Python 2.7), and with the following in my setup.py (in the setup()
method)
setup_requires=[
'numpy',
],
install_requires=[
'numpy',
'scipy',
],
I found I had to run the following to get pip install -e .
to work:
pip install --upgrade pip
and
sudo dnf install atlas-devel gcc-{c++,gfortran} subversion redhat-rpm-config
The redhat-rpm-config
is for scipy's use of redhat-hardened-cc1
as opposed to the regular cc1
It can easily be done if u had declared a class that extends from Application
This class will be like a singleton, so when u need a context u can get it just like this:
I think this is the better answer and the cleaner
Here is my code from Utilities package:
public static String getAppNAme(){
return MyOwnApplication.getInstance().getString(R.string.app_name);
}
If you need to use the latest versions of SciPy rather than the packaged version, without going through the hassle of building BLAS and LAPACK, you can follow the below procedure.
Install linear algebra libraries from repository (for Ubuntu),
sudo apt-get install gfortran libopenblas-dev liblapack-dev
Then install SciPy, (after downloading the SciPy source): python setup.py install
or
pip install scipy
As the case may be.
well you can do this:
$(function(){
var $header = $('#header');
var $footer = $('#footer');
var $content = $('#content');
var $window = $(window).on('resize', function(){
var height = $(this).height() - $header.height() + $footer.height();
$content.height(height);
}).trigger('resize'); //on page load
});
see fiddle here: http://jsfiddle.net/maniator/JVKbR/
demo: http://jsfiddle.net/maniator/JVKbR/show/
I just posted this answer in the android-discuss google group
If you are just trying to add text to the view so that it displays "Step One: blast egg Step Two: fry egg" Then consider using t.appendText("Step Two: fry egg");
instead of t.setText("Step Two: fry egg");
If you want to completely change what is in the TextView
so that it says "Step One: blast egg" on startup and then it says "Step Two: fry egg" at a time later you can always use a
Runnable example sadboy gave
Good luck
I was working on a dataframe and having no luck with the provided answers, it always returned 0 rows, so I found and used grepl:
df = df[grepl("downlink",df$Transmit.direction),]
Which basically trimmed my dataframe to only the rows that contained "downlink" in the Transmit direction column. P.S. If anyone can guess as to why I'm not seeing the expected behavior, please leave a comment.
Specifically to the original question:
expr[grepl("hesc",expr$cell_type),]
expr[grepl("bj fibroblast|hesc",expr$cell_type),]
I just compared Apache Commons Math with jlapack.
Test: singular value decomposition of a random 1024x1024 matrix.
Machine: Intel(R) Core(TM)2 Duo CPU E6750 @ 2.66GHz, linux x64
Octave code: A=rand(1024); tic;[U,S,V]=svd(A);toc
results execution time --------------------------------------------------------- Octave 36.34 sec JDK 1.7u2 64bit jlapack dgesvd 37.78 sec apache commons math SVD 42.24 sec JDK 1.6u30 64bit jlapack dgesvd 48.68 sec apache commons math SVD 50.59 sec Native routines Lapack* invoked from C: 37.64 sec Intel MKL 6.89 sec(!)
My conclusion is that jlapack called from JDK 1.7 is very close to the native binary performance of lapack. I used the lapack binary library coming with linux distro and invoked the dgesvd routine to get the U,S and VT matrices as well. All tests were done using double precision on exactly the same matrix each run (except Octave).
Disclaimer - I'm not an expert in linear algebra, not affiliated to any of the libraries above and this is not a rigorous benchmark. It's a 'home-made' test, as I was interested comparing the performance increase of JDK 1.7 to 1.6 as well as commons math SVD to jlapack.
Cross-browser rotate for any element. Works in IE7 and IE8. In IE7 it looks like not working in JSFiddle but in my project worked also in IE7
var elementToRotate = $('#rotateMe');
var degreeOfRotation = 33;
var deg = degreeOfRotation;
var deg2radians = Math.PI * 2 / 360;
var rad = deg * deg2radians ;
var costheta = Math.cos(rad);
var sintheta = Math.sin(rad);
var m11 = costheta;
var m12 = -sintheta;
var m21 = sintheta;
var m22 = costheta;
var matrixValues = 'M11=' + m11 + ', M12='+ m12 +', M21='+ m21 +', M22='+ m22;
elementToRotate.css('-webkit-transform','rotate('+deg+'deg)')
.css('-moz-transform','rotate('+deg+'deg)')
.css('-ms-transform','rotate('+deg+'deg)')
.css('transform','rotate('+deg+'deg)')
.css('filter', 'progid:DXImageTransform.Microsoft.Matrix(sizingMethod=\'auto expand\','+matrixValues+')')
.css('-ms-filter', 'progid:DXImageTransform.Microsoft.Matrix(SizingMethod=\'auto expand\','+matrixValues+')');
Edit 13/09/13 15:00 Wrapped in a nice and easy, chainable, jquery plugin.
Example of use
$.fn.rotateElement = function(angle) {
var elementToRotate = this,
deg = angle,
deg2radians = Math.PI * 2 / 360,
rad = deg * deg2radians ,
costheta = Math.cos(rad),
sintheta = Math.sin(rad),
m11 = costheta,
m12 = -sintheta,
m21 = sintheta,
m22 = costheta,
matrixValues = 'M11=' + m11 + ', M12='+ m12 +', M21='+ m21 +', M22='+ m22;
elementToRotate.css('-webkit-transform','rotate('+deg+'deg)')
.css('-moz-transform','rotate('+deg+'deg)')
.css('-ms-transform','rotate('+deg+'deg)')
.css('transform','rotate('+deg+'deg)')
.css('filter', 'progid:DXImageTransform.Microsoft.Matrix(sizingMethod=\'auto expand\','+matrixValues+')')
.css('-ms-filter', 'progid:DXImageTransform.Microsoft.Matrix(SizingMethod=\'auto expand\','+matrixValues+')');
return elementToRotate;
}
$element.rotateElement(15);
JSFiddle: http://jsfiddle.net/RgX86/175/
Neither of the highest voted answers are correct on SQL Server 2000. Perhaps they were using a different version.
Here are the correct versions of both of them on SQL Server 2000.
select t.range as [score range], count(*) as [number of occurences]
from (
select case
when score between 0 and 9 then ' 0- 9'
when score between 10 and 19 then '10-19'
else '20-99' end as range
from scores) t
group by t.range
or
select t.range as [score range], count(*) as [number of occurrences]
from (
select user_id,
case when score >= 0 and score< 10 then '0-9'
when score >= 10 and score< 20 then '10-19'
else '20-99' end as range
from scores) t
group by t.range
I'm pretty sure it's an Adobe standard, bearing in mind the whole PDF standard is theirs to begin with; despite being open now.
My guess would be no for all PDF viewers supporting it, as some definitely will not have a JS engine. I doubt you can rely on full support outside the most recent versions of Acrobat (Reader). So I guess it depends on how you imagine it being used, if mainly via a browser display, then the majority of the market is catered for by Acrobat (Reader) and Chrome's built-in viewer - dare say there is documentation on whether Chrome's PDF viewer supports JS fully.
Sorry for necromancing the thread, but whenever you iterate over files by globbing, it's good practice to avoid the corner case where the glob does not match (which makes the loop variable expand to the (un-matching) glob pattern string itself).
For example:
for filename in Data/*.txt; do
[ -e "$filename" ] || continue
# ... rest of the loop body
done
Reference: Bash Pitfalls
First check if you have configured JDK correctly:
Secondly check if you have provided in path in Library's section
This should fix the problem
I may be wrong here but I had the same problem, after spending more time than I'm proud of I realised I had set chrome to block all pop ups and hence kept reloading without showing me the alert box. So close your window and open the page again.
If that doesn't work then you problem might be something deeper because all the solutions already given should work.
Basically one needs to create a custom background for a spinner. It should be something like this:
spinner_background.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<layer-list>
<item>
<color
android:color="@android:color/white"/>
</item>
<item>
<bitmap
android:gravity="center_vertical|right"
android:src="@drawable/ic_arrow_drop_down_black_24dp"/>
</item>
</layer-list>
</item>
</selector>
Then create a custom style for your spinner, where you specify the above selector as background:
<style name="Widget.App.Spinner" parent="@style/Widget.AppCompat.Spinner">
<item name="overlapAnchor">true</item>
<item name="android:background">@drawable/spinner_background</item>
</style>
And finally in your app theme you should override two attributes if you want it to be applied all across your app:
<item name="spinnerStyle">@style/Widget.App.Spinner</item>
<item name="android:spinnerStyle">@style/Widget.App.Spinner</item>
And that's pretty much it.
If you run the command:
sc queryex <service name>
where is the the name of the service, not the display name (spooler, not Print Spooler), at the cmd prompt it will return the PID of the process the service is running as. Take that PID and run
taskkill /F /PID <Service PID>
to force the PID to stop. Sometimes if the process hangs while stopping the GUI won't let you do anything with the service.
This is what worked for me. It can be found in git documentation here
If you are on your desired branch you can do this:
git fetch origin
# Fetches updates made to an online repository
git merge origin YOUR_BRANCH_NAME
# Merges updates made online with your local work
Use simple one line command, if you just want the list of files changed in the last commit:
git diff HEAD~1 --name-only
It should be :
public async Task<ActionResult> GetSomeJsonData()
{
var model = // ... get data or build model etc.
return Json(new { Data = model }, JsonRequestBehavior.AllowGet);
}
or more simply:
return Json(model, JsonRequestBehavior.AllowGet);
I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...
If your using Java8 you can use the IntStream:
int[] listOfNumbers = {5,4,13,7,7,8,9,10,5,92,11,3,4,2,1};
System.out.println(IntStream.of(listOfNumbers).sum());
Results: 181
Just 1 line of code which will sum the array.
This script is about creating tables with foreign key and I added referential integrity constraint sql-server.
create table exams
(
exam_id int primary key,
exam_name varchar(50),
);
create table question_bank
(
question_id int primary key,
question_exam_id int not null,
question_text varchar(1024) not null,
question_point_value decimal,
constraint question_exam_id_fk
foreign key references exams(exam_id)
ON DELETE CASCADE
);
Ways to Generate Getters & Setters -
1) Press Alt+Shift+S, then R
2) Right click -> Source -> Generate Getters & Setters
3) Go to Source menu -> Generate Getters & Setters
4) Go to Windows menu -> Preferences -> General -> Keys (Write Generate Getters & Setters on text field)
5) Click on error bulb of the field -> create getters & setters ...
6) Press Ctrl+3 and write getters & setters on text field then select option Generate Getters & Setters
if Mac OS press Alt+cmd+S then select Getters & Setters
Play around this piece of code. Focus on the concept, edit where necessary so that it can
<html>
<head>
<title> Delegate edit form</title>
</head>
<body>
Delegate update form </p>
<meta name="viewport" content="width=device-width; initial-scale=1.0">
<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />
<link href='http://fonts.googleapis.com/css?family=Droid+Serif|Ubuntu' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="js/flexslider/flexslider.css" />
<link rel="stylesheet" href="css/basic-style.css">
<script src="js/libs/modernizr-2.6.2.min.js"></script>
</head>
<body id="home">
<header class="wrapper clearfix">
<nav id="topnav" role="navigation">
<div class="menu-toggle">Menu</div>
<ul class="srt-menu" id="menu-main-navigation">
<li><a href="Swift_Landing.html">Home page</a></li>
</header>
</section>
<style>
form label {
display: inline-block;
width: 100px;
font-weight: bold;
}
</style>
</ul>
<?php
session_start();
$usernm="root";
$passwd="";
$host="localhost";
$database="swift";
$Username=$_SESSION['myssession'];
mysql_connect($host,$usernm,$passwd);
mysql_select_db($database);
$sql = "SELECT * FROM usermaster WHERE User_name='$Username'";
$result = mysql_query ($sql) or die (mysql_error ());
while ($row = mysql_fetch_array ($result)){
?>
<form action="Delegate_update.php" method="post">
Name
<input type="text" name="Namex" value="<?php echo $row ['Name']; ?> " size=10>
Username
<input type="text" name="Username" value="<?php echo $row ['User_name']; ?> " size=10>
Password
<input type="text" name="Password" value="<?php echo $row ['User_password']; ?>" size=17>
<input type="submit" name="submit" value="Update">
</form>
<?php
}
?>
</p>
</body>
</html>
Look here for the answer by TheMattster. I implemented it and it worked like a charm. In a nutshell, his solution suggests to add the COM dll as a resource to the project (so now it compiles into the project's dll), and upon the first run write it to a file (i.e. the dll file I wanted there in the first place).
The following is taken from his answer.
Step 1) Add the DLL as a resource (below as "Resources.DllFile"). To do this open project properties, select the resources tab, select "add existing file" and add the DLL as a resource.
Step 2) Add the name of the DLL as a string resource (below as "Resources.DllName").
Step 3) Add this code to your main form-load:
if (!File.Exists(Properties.Resources.DllName))
{
var outStream = new StreamWriter(Properties.Resources.DllName, false);
var binStream = new BinaryWriter(outStream.BaseStream);
binStream.Write(Properties.Resources.DllFile);
binStream.Close();
}
My problem was that not only I had to use the COM dll in my project, I also had to deploy it with my app using ClickOnce, and without being able to add reference to it in my project the above solution is practically the only one that worked.
There is an internal Bash variable called $PIPESTATUS
; it’s an array that holds the exit status of each command in your last foreground pipeline of commands.
<command> | tee out.txt ; test ${PIPESTATUS[0]} -eq 0
Or another alternative which also works with other shells (like zsh) would be to enable pipefail:
set -o pipefail
...
The first option does not work with zsh
due to a little bit different syntax.
Swift:
Map.setRegion(MKCoordinateRegion(center: locValue, latitudinalMeters: 200, longitudinalMeters: 200), animated: true)
locValue is your coordinate.
it is possible
public class ParallaxViewController<T extends View & Parallaxor> extends ParallaxController<T> implements AbsListView.OnScrollListener {
//blah
}
If you are using vscode and you are on Windows i would recommend you to click the option at the bottom-right of the window and set it to LF from CRLF. Because we should not turn off the configuration just for sake of removing errors on Windows
If you don't see LF / CLRF, then right click the status bar and select Editor End of Line.
nonatomic
property means @synthesize
d methods are not going to be generated threadsafe -- but this is much faster than the atomic
property since extra checks are eliminated.
strong
is used with ARC and it basically helps you , by not having to worry about the retain count of an object. ARC automatically releases it for you when you are done with it.Using the keyword strong
means that you own the object.
weak
ownership means that you don't own it and it just keeps track of the object till the object it was assigned to stays , as soon as the second object is released it loses is value. For eg. obj.a=objectB;
is used and a has weak property , than its value will only be valid till objectB remains in memory.
copy
property is very well explained here
strong,weak,retain,copy,assign
are mutually exclusive so you can't use them on one single object... read the "Declared Properties " section
hoping this helps you out a bit...
These days, there are quite a few modules available for this. I recently wrote a module to do this, because I wasn't satisfied with the numerous diffing modules I found. Its called odiff
: https://github.com/Tixit/odiff . I also listed a bunch of the most popular modules and why they weren't acceptable in the readme of odiff
, which you could take a look through if odiff
doesn't have the properties you want. Here's an example:
var a = [{a:1,b:2,c:3}, {x:1,y: 2, z:3}, {w:9,q:8,r:7}]
var b = [{a:1,b:2,c:3},{t:4,y:5,u:6},{x:1,y:'3',z:3},{t:9,y:9,u:9},{w:9,q:8,r:7}]
var diffs = odiff(a,b)
/* diffs now contains:
[{type: 'add', path:[], index: 2, vals: [{t:9,y:9,u:9}]},
{type: 'set', path:[1,'y'], val: '3'},
{type: 'add', path:[], index: 1, vals: [{t:4,y:5,u:6}]}
]
*/
startService(new Intent(this, MyService.class));
Just writing this line was not sufficient for me. Service still did not work. Everything had worked only after registering service at manifest
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
...
<service
android:name=".MyService"
android:label="My Service" >
</service>
</application>
You need the modal in your HTML. When the delete button is clicked it popup the modal. It's also important to prevent the click of that button from submitting the form. When the confirmation is clicked the form will submit.
_x000D_
_x000D_
$('button[name="remove_levels"]').on('click', function(e) {_x000D_
var $form = $(this).closest('form');_x000D_
e.preventDefault();_x000D_
$('#confirm').modal({_x000D_
backdrop: 'static',_x000D_
keyboard: false_x000D_
})_x000D_
.on('click', '#delete', function(e) {_x000D_
$form.trigger('submit');_x000D_
});_x000D_
$("#cancel").on('click',function(e){_x000D_
e.preventDefault();_x000D_
$('#confirm').modal.model('hide');_x000D_
});_x000D_
});
_x000D_
<link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://getbootstrap.com/2.3.2/assets/js/bootstrap.js"></script>_x000D_
<form action="#" method="POST">_x000D_
<button class='btn btn-danger btn-xs' type="submit" name="remove_levels" value="delete"><span class="fa fa-times"></span> delete</button>_x000D_
</form>_x000D_
_x000D_
<div id="confirm" class="modal">_x000D_
<div class="modal-body">_x000D_
Are you sure?_x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button type="button" data-dismiss="modal" class="btn btn-primary" id="delete">Delete</button>_x000D_
<button type="button" data-dismiss="modal" class="btn">Cancel</button>_x000D_
</div>_x000D_
</div>
_x000D_
In the simplest case, just do
X <- read.csv(url("http://some.where.net/data/foo.csv"))
plus which ever options read.csv()
may need.
Edit in Sep 2020 or 9 years later:
For a few years now R also supports directly passing the URL to read.csv
:
X <- read.csv("http://some.where.net/data/foo.csv")
End of 2020 edit. Original post continutes.
Long answer: Yes this can be done and many packages have use that feature for years. E.g. the tseries packages uses exactly this feature to download stock prices from Yahoo! for almost a decade:
R> library(tseries)
Loading required package: quadprog
Loading required package: zoo
‘tseries’ version: 0.10-24
‘tseries’ is a package for time series analysis and computational finance.
See ‘library(help="tseries")’ for details.
R> get.hist.quote("IBM")
trying URL 'http://chart.yahoo.com/table.csv? ## manual linebreak here
s=IBM&a=0&b=02&c=1991&d=5&e=08&f=2011&g=d&q=q&y=0&z=IBM&x=.csv'
Content type 'text/csv' length unknown
opened URL
.......... .......... .......... .......... ..........
.......... .......... .......... .......... ..........
.......... .......... .......... .......... ..........
.......... .......... .......... .......... ..........
.......... .......... .......... .......... ..........
........
downloaded 258 Kb
Open High Low Close
1991-01-02 112.87 113.75 112.12 112.12
1991-01-03 112.37 113.87 112.25 112.50
1991-01-04 112.75 113.00 111.87 112.12
1991-01-07 111.37 111.87 110.00 110.25
1991-01-08 110.37 110.37 108.75 109.00
1991-01-09 109.75 110.75 106.75 106.87
[...]
This is all exceedingly well documented in the manual pages for help(connection)
and help(url)
. Also see the manul on 'Data Import/Export' that came with R.
Think about expectations.
As a client app, you expect to know if something goes wrong on the server side. If the server needs to throw an error when blah
is missing or the requestedResource
value is incorrect than a 400 error would be appropriate.
For me, it helped to count the number of values per group. Copy the count table into a new object. Then filter for the max of the group based on the first grouping characteristic. For example:
count_table <- df %>%
group_by(A, B) %>%
count() %>%
arrange(A, desc(n))
count_table %>%
group_by(A) %>%
filter(n == max(n))
or
count_table %>%
group_by(A) %>%
top_n(1, n)
My best solution on R Markdown was to create a code chunk only to load libraries and exclude everything in the chunk.
{r results='asis', echo=FALSE, include=FALSE,}
knitr::opts_chunk$set(echo = TRUE, warning=FALSE)
#formating tables
library(xtable)
#data wrangling
library(dplyr)
#text processing
library(stringi)
I couldn't synchronize and change the speed my setIntervals too and I was about to post a question. But I think I've found a way. It should certainly be improved because I'm a beginner. So, I'd gladly read your comments/remarks about this.
<body onload="foo()">
<div id="count1">0</div>
<div id="count2">2nd counter is stopped</div>
<button onclick="speed0()">pause</button>
<button onclick="speedx(1)">normal speed</button>
<button onclick="speedx(2)">speed x2</button>
<button onclick="speedx(4)">speed x4</button>
<button onclick="startTimer2()">Start second timer</button>
</body>
<script>
var count1 = 0,
count2 = 0,
greenlight = new Boolean(0), //blocks 2nd counter
speed = 1000, //1second
countingSpeed;
function foo(){
countingSpeed = setInterval(function(){
counter1();
counter2();
},speed);
}
function counter1(){
count1++;
document.getElementById("count1").innerHTML=count1;
}
function counter2(){
if (greenlight != false) {
count2++;
document.getElementById("count2").innerHTML=count2;
}
}
function startTimer2(){
//while the button hasn't been clicked, greenlight boolean is false
//thus, the 2nd timer is blocked
greenlight = true;
counter2();
//counter2() is greenlighted
}
//these functions modify the speed of the counters
function speed0(){
clearInterval(countingSpeed);
}
function speedx(a){
clearInterval(countingSpeed);
speed=1000/a;
foo();
}
</script>
If you want the counters to begin to increase once the page is loaded, put counter1()
and counter2()
in foo()
before countingSpeed
is called. Otherwise, it takes speed
milliseconds before execution.
EDIT : Shorter answer.
<?php
// create a "numeric" array
$animals = array('monitor', 'cpu', 'mouse', 'ram', 'wifi', 'usb', 'pendrive');
//Normarl display
print_r($animals);
echo "<br/><br/>";
//If splice the array
//array_splice($animals, 2, 2);
unset($animals[3]); // you can unset the particular value
print_r($animals);
?>
A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.
Consider the following code:
void Foo(int i, float f)
{
// Do things
}
void Bar()
{
int anInt = 1;
Foo(anInt, 2.0);
}
Here i
and f
are the parameters, and anInt
and 2.0
are the arguments.
Just use plt.tight_layout()
before plt.show()
. It works well.
The SQL you want is
select name from studens where id in (1, 5, 8)
If you want to construct this from the python you could use
l = [1, 5, 8]
sql_query = 'select name from studens where id in (' + ','.join(map(str, l)) + ')'
The map function will transform the list into a list of strings that can be glued together by commas using the str.join method.
Alternatively:
l = [1, 5, 8]
sql_query = 'select name from studens where id in (' + ','.join((str(n) for n in l)) + ')'
if you prefer generator expressions to the map function.
UPDATE: S. Lott mentions in the comments that the Python SQLite bindings don't support sequences. In that case, you might want
select name from studens where id = 1 or id = 5 or id = 8
Generated by
sql_query = 'select name from studens where ' + ' or '.join(('id = ' + str(n) for n in l))
If you have already converted the string to a date format using pd.to_datetime you can just use:
df = df[(df['Date']> "2018-01-01") & (df['Date']< "2019-07-01")]
A php/ajax progress bar can be done. (Checkout the Html_Ajax library in pear). However this requires installing a custom module into php.
Other methods require using an iframe, through which php looks to see how much of the file has been uploaded. However this hidden iframe, may be blocked by some browsers addons because hidden iframes are often used to send malicious data to a users computer.
Your best bet is to use some form of flash progress bar if you do not have control over your server.
in my case it also need to install it's npm package
so
npm install react-native-debugger -g
This works in browser and nodejs Live browser demo
const cpFetch= require('cp-fetch');
const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=3s';
const chain = cpFetch(url, {timeout: 10000})
.then(response => response.json())
.then(data => console.log(`Done: `, data), err => console.log(`Error: `, err))
setTimeout(()=> chain.cancel(), 1000); // abort the request after 1000ms
The reload happens during the next layout pass, which normally happens when you return control to the run loop (after, say, your button action or whatever returns).
So one way to run something after the table view reloads is simply to force the table view to perform layout immediately:
[self.tableView reloadData];
[self.tableView layoutIfNeeded];
NSIndexPath* indexPath = [NSIndexPath indexPathForRow: ([self.tableView numberOfRowsInSection:([self.tableView numberOfSections]-1)]-1) inSection: ([self.tableView numberOfSections]-1)];
[self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
Another way is to schedule your after-layout code to run later using dispatch_async
:
[self.tableView reloadData];
dispatch_async(dispatch_get_main_queue(), ^{
NSIndexPath* indexPath = [NSIndexPath indexPathForRow: ([self.tableView numberOfRowsInSection:([self.tableView numberOfSections]-1)]-1) inSection:([self.tableView numberOfSections]-1)];
[self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
});
Upon further investigation, I find that the table view sends tableView:numberOfSections:
and tableView:numberOfRowsInSection:
to its data source before returning from reloadData
. If the delegate implements tableView:heightForRowAtIndexPath:
, the table view also sends that (for each row) before returning from reloadData
.
However, the table view does not send tableView:cellForRowAtIndexPath:
or tableView:headerViewForSection
until the layout phase, which happens by default when you return control to the run loop.
I also find that in a tiny test program, the code in your question properly scrolls to the bottom of the table view, without me doing anything special (like sending layoutIfNeeded
or using dispatch_async
).
Some people say that operator overloading in Java would lead to obsfuscation. Have those people ever stopped to look at some Java code doing some basic maths like increasing a financial value by a percentage using BigDecimal ? .... the verbosity of such an exercise becomes its own demonstration of obsfuscation. Ironically, adding operator overloading to Java would allow us to create our own Currency class which would make such mathematical code elegant and simple (less obsfuscated).
You can you use subprocess
to achieve this.
import subprocess
#This command could have multiple commands separated by a new line \n
some_command = "export PATH=$PATH://server.sample.mo/app/bin \n customupload abc.txt"
p = subprocess.Popen(some_command, stdout=subprocess.PIPE, shell=True)
(output, err) = p.communicate()
#This makes the wait possible
p_status = p.wait()
#This will give you the output of the command being executed
print "Command output: " + output
Using reduce()
from purrr
is slightly faster than rowSums
and definately faster than apply
, since you avoid iterating over all the rows and just take advantage of the vectorized operations:
library(purrr)
library(dplyr)
iris %>% mutate(Petal = reduce(select(., starts_with("Petal")), `+`))
See this for timings
my problem was this piece of javascript code
$('input').each(function(ele, indx){
this.value = this.value.toUpperCase();
});
Turns it was messing with viewstate hidden field so I changed it to below code and it worked
$('input:visible').each(function(ele, indx){
this.value = this.value.toUpperCase();
});
I use the version of NCover that comes with TestDriven.NET. It will allow you to easily right-click on your unit test class library, and hit Test With→Coverage, and it will pull up the report.
var str = "Text\",\"Text\",\"Text";
var newstr = str.Replace("\",\"", ";");
You can use Snap for downloading ngrok
. Follow the steps below:
Install Snap
by following command:
sudo apt install snapd
Install Ngrok
by following command:
sudo snap install ngrok
Now use ngrok
command from any directory, like this:
ngrok http 8080
jQuery is a JavaScript library.
Read
wiki-jQuery, github, jQuery vs. javascript?
What is JQuery?
Before JQuery, developers would create their own small frameworks (the group of code) this would allow all the developers to work around all the bugs and give them more time to work on features, so the JavaScript frameworks were born. Then came the collaboration stage, groups of developers instead of writing their own code would give it away for free and creating JavaScript code sets that everyone could use. That is what JQuery is, a library of JavaScript code. The best way to explain JQuery and its mission is well stated on the front page of the JQuery website which says:
JQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.
As you can see all JQuery is JavaScript. There is more than one type of JavaScript set of code sets like MooTools it is just that JQuery is the most popular.
Which is the best JavaScript or JQuery is a contentious discussion, really the answer is neither is best. They both have their roles I have worked on online applications where JQuery was not the right tool and what the application needed was straight JavaScript development. But for most websites JQuery is all that is needed. What a web developer needs to do is make an informed decision on what tools are best for their client. Someone first coming into web development does need some exposure to both technologies just using JQuery all the time does not teach the nuances of JavaScript and how it affects the DOM. Using JavaScript all the time slows projects down and because of the JQuery library has ironed most of the issues that JavaScript will have between each web browser it makes the deployment safe as it is sure to work across all platforms.
JavaScript is a language. jQuery is a library built with JavaScript to help JavaScript programmers who are doing common web tasks.
See here.
You can use array.nbytes
for numpy arrays, for example:
>>> import numpy as np
>>> from sys import getsizeof
>>> a = [0] * 1024
>>> b = np.array(a)
>>> getsizeof(a)
8264
>>> b.nbytes
8192
1.Close your project:Completely quit Xcode. 2.Go to your project location:there you will find two files in you root folder with varying extensions: Appname.xcodeproj and Appname.xcworkspace
Now open your project by Double clicking on file with the extensions xcworkspace.(***Appname.xcworkspace*)**
Yourproject will open in xcode. Now run your project again.
If you pay close attention when installing your pods,firebase makes it clear to open your project with your-project.xcworkspace after installing pods firebaseIOS Setup
$ cd your-project directory
$ pod init
Add to Podfile
pod 'Firebase/Core'
And finally:
$ pod install
$ open your-project.xcworkspace
Dont forget to add firebase to your AppDelegate
//Try this if you can't use -std=c++11:-
int number=55;
char tempStr[32] = {0};
sprintf(tempStr, "%d", number);
Read my answer if recently you have been using a VPN connection.
Today I had the same exact issue and learned how to fix it without removing any plugins. So I thought maybe I would share my own experience.
My issue definitely had something to do with Spring Framework
I was using a VPN connection over my internet connection. Once I disconnected my VPN, everything instantly turned right.
This could be a problem if you are using a custom 'Settings.xml', with a different <localRepository>
configured in it.
Eclipse will be using the default installation of MAVEN, and will be using the default location for the User to look for the local Maven repository, which on Linux systems would be '/home/${USER}/.m2/'
Eclipse can be easily configured to use the customized 'Settings.xml', by doing the following: Goto -> Window -> Preferences -> Select 'Maven' -> Select 'User Settings'
After this, you could proceed to select your project from the 'Project Explorer', right click, Select 'Maven' > 'Update Project'. Make sure that your project is selected (ticked) in the Window, and click 'OK'.
This should help to resolve the issue, if using custom 'Settings.xml' for Maven.
Hope it helps.
I was still confused after reading the other answers and comments. But the answer now seems simpler, so here you go.
Since Pandas version 0.9 (from 2012), you can read your csv with empty cells interpreted as empty strings by simply setting keep_default_na=False
:
pd.read_csv('test.csv', keep_default_na=False)
This issue is more clearly explained in
That was fixed on on Aug 19, 2012 for Pandas version 0.9 in
There is no mention about nine-patch files here. Yes, you have to create the file, however it's quite easy job and it's really "cross-version and transparency supporting" solution. If the file is placed to the drawable-nodpi
directory, it works px
based, and in the drawable-mdpi
works approximately as dp base (thanks to resample).
Example file for the original question (border-right:1px solid red;) is here:
Just place it to the drawable-nodpi
directory.
using count,
clickcount++;
if (clickcount == 1) {}
After coming back again clickcount set to zero.
Seeing as that the original question was on how to use awk
and every single one of the first 7 answers use sort
instead, and that this is the top hit on Google, here is how to use awk
.
Sample net.csv file with headers:
ip,hostname,user,group,encryption,aduser,adattr
192.168.0.1,gw,router,router,-,-,-
192.168.0.2,server,admin,admin,-,-,-
192.168.0.3,ws-03,user,user,-,-,-
192.168.0.4,ws-04,user,user,-,-,-
And sort.awk:
#!/usr/bin/awk -f
# usage: ./sort.awk -v f=FIELD FILE
BEGIN {
FS=","
}
# each line
{
a[NR]=$0 ""
s[NR]=$f ""
}
END {
isort(s,a,NR);
for(i=1; i<=NR; i++) print a[i]
}
#insertion sort of A[1..n]
function isort(S, A, n, i, j) {
for( i=2; i<=n; i++) {
hs = S[j=i]
ha = A[j=i]
while (S[j-1] > hs) {
j--;
S[j+1] = S[j]
A[j+1] = A[j]
}
S[j] = hs
A[j] = ha
}
}
To use it:
awk sort.awk f=3 < net.csv # OR
chmod +x sort.awk
./sort.awk f=3 net.csv
The clear way to do this is as follows if you do not mind writing the file again
with open("a.txt", 'r+') as fp:
lines = fp.readlines() # lines is list of line, each element '...\n'
lines.insert(0, one_line) # you can use any index if you know the line index
fp.seek(0) # file pointer locates at the beginning to write the whole file again
fp.writelines(lines) # write whole lists again to the same file
Note that this is not in-place replacement. It's writing a file again.
In summary, you read a file and save it to a list and modify the list and write the list again to a new file with the same filename.
the " < filename > " searches in standard C library locations
whereas "filename" searches in the current directory as well.
Ideally, you would use <...> for standard C libraries and "..." for libraries that you write and are present in the current directory.
Carbon has a bunch of comparison functions with mnemonic names:
Usage:
if($model->edited_at->greaterThan($model->created_at)){
// edited at is newer than created at
}
Valid for nesbot/carbon 1.36.2
if you are not sure what Carbon version you are on, run this
$composer show "nesbot/carbon"
documentation: https://carbon.nesbot.com/docs/#api-comparison
I tried some of the other solutions listed here, but during unit testing the code would throw exceptions I wanted to ignore. I ended up creating the following recursive search method that will ignore certain exceptions like PathTooLongException and UnauthorizedAccessException.
private IEnumerable<string> RecursiveFileSearch(string path, string pattern, ICollection<string> filePathCollector = null)
{
try
{
filePathCollector = filePathCollector ?? new LinkedList<string>();
var matchingFilePaths = Directory.GetFiles(path, pattern);
foreach(var matchingFile in matchingFilePaths)
{
filePathCollector.Add(matchingFile);
}
var subDirectories = Directory.EnumerateDirectories(path);
foreach (var subDirectory in subDirectories)
{
RecursiveFileSearch(subDirectory, pattern, filePathCollector);
}
return filePathCollector;
}
catch (Exception error)
{
bool isIgnorableError = error is PathTooLongException ||
error is UnauthorizedAccessException;
if (isIgnorableError)
{
return Enumerable.Empty<string>();
}
throw error;
}
}
The solution (http://expressjs.com/en/starter/static-files.html).
once done this the image folder no longer shalt put it. only be
background-image: url ( "/ image.png");
carpera that the image is already in the static files
supplementing @falsetru's answer : run id in the terminal to get your user_id and group_id
Go the directory/partition where you are facing the challenge. Open terminal, type id then press enter. This will show you your user_id and group_id
then type
chown -R user-id:group-id .
Replace user-id and group-id
. at the end indicates current partition / repository
// chown -R 1001:1001 . (that was my case)
For checking complete changes:
git diff <commit_Id_1> <commit_Id_2>
For checking only the changed/added/deleted files:
git diff <commit_Id_1> <commit_Id_2> --name-only
NOTE: For checking diff without commit in between, you don't need to put the commit ids.
Also:
func getTime() -> (hour: Int, minute: Int,second: Int) {
let hour = 1
let minute = 2
let second = 3
return ( hour, minute, second)
}
Then it's invoked as:
let time = getTime()
print("hour: \(time.hour), minute: \(time.minute), second: \(time.second)")
This is the standard way how to use it in the book The Swift Programming Language written by Apple.
or just like:
let time = getTime()
print("hour: \(time.0), minute: \(time.1), second: \(time.2)")
it's the same but less clearly.
The plugin that @DarinDimitrov posted, jquery-mousewheel
, is broken with jQuery 3+. It would be more advisable to use jquery-wheel
which works with jQuery 3+.
If you don't want to go the jQuery route, MDN highly cautions using the mousewheel
event as it's nonstandard and unsupported in many places. It instead says that you should use the wheel
event as you get much more specificity over exactly what the values you're getting mean. It's supported by most major browsers.
I've seen 3 other fixes so far:
The solution boils down to clean up the .metadata folder with correct contents
Use the namespace System.Net.Mail. Here is a link to the MSDN page
You can send emails using SmtpClient class.
I paraphrased the code sample, so checkout MSDNfor details.
MailMessage message = new MailMessage(
"[email protected]",
"[email protected]",
"Subject goes here",
"Body goes here");
SmtpClient client = new SmtpClient(server);
client.Send(message);
The best way to send many emails would be to put something like this in forloop and send away!
The string
class has a constructor that takes a NULL-terminated C-string:
char arr[ ] = "This is a test";
string str(arr);
// You can also assign directly to a string.
str = "This is another string";
// or
str = arr;
To calculate the current datetime:
DateTime theDate = DateTime.UtcNow;
string custom = theDate.ToString("d");
MessageBox.Show(custom);
If it's just a matter of easy reading, you could always define your own function :
is.not.null <- function(x) !is.null(x)
So you can use it all along your program.
is.not.null(3)
is.not.null(NULL)
if (StringA.ToUpperInvariant() == StringB.ToUpperInvariant()) {
People report ToUpperInvariant() is faster than ToLowerInvariant().
Yes, this is confusing...
According to this blog post, it looks like this is an omission from WPF.
To make it work you need to use a style:
<Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
<Border.Style>
<Style>
<Setter Property="Border.Background" Value="Blue"/>
<Style.Triggers>
<Trigger Property="Border.IsMouseOver" Value="True">
<Setter Property="Border.Background" Value="Green" />
</Trigger>
</Style.Triggers>
</Style>
</Border.Style>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
</Border>
I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.
This algorithm in Python gets you part of the way there.
Tell me what happens if the windows is a funny size.
Maybe what you should have is a list of all acceptable ratios (to the 3rd party component). Then, find the closest match to your window and return that ratio from the list.
I feel like these answers were written for Python 2, and in any case nobody's made mention of the standard resource
package that's available for Python 3. It provides commands for obtaining the resource limits of a given process (the calling Python process by default). This isn't the same as getting the current usage of resources by the system as a whole, but it could solve some of the same problems like e.g. "I want to make sure I only use X much RAM with this script."
If you are interested in only selecting one column this will work.
df[["item1"]].to_dict("records")
The below will NOT work and produces a TypeError: unsupported type: . I believe this is because it is trying to convert a series to a dict and not a Data Frame to a dict.
df["item1"].to_dict("records")
I had a requirement to only select one column and convert it to a list of dicts with the column name as the key and was stuck on this for a bit so figured I'd share.
var i = jsonObj.length;
while ( i --> 0 ) {
if ( jsonObj[i].Id === 3 ) {
jsonObj[ i ].Username = 'Thomas';
break;
}
}
Or, if the array is always ordered by the IDs:
jsonObj[ 2 ].Username = 'Thomas';
I found the next command
mvn dependency:copy-dependencies -Dclassifier=sources
here maven.apache.org
in code add below line:
spin27.setLayoutParams(new LinearLayout.LayoutParams(200, 120));
dtList = dtList.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList()
I assumed empty string and whitespace are like null. If not you can use IsNullOrEmpty
(allow whitespace), or s != null
These toolz are great for this kind of simple yet repetitive logic.
http://toolz.readthedocs.org/en/latest/api.html#toolz.dicttoolz.valmap
Gets you right where you want to be.
import toolz
def f(x):
return x+1
toolz.valmap(f, my_list)
An investment in learning VIM (my preference) or EMACS will pay off.
I suggest visiting Derek Wyatt's site, running through the VIM Tutor, and checking out the Steve Oualine PDF book.
Vim helps me move around and edit quicker than other editors I've used. My work IDEs are quite limited in what they allow one to do and are typically devoted to a particular environment. There are tasks that still require me to revisit the IDE (such as debuggers which are a compiled part of the IDE).
you can use
empty($result)
to check if the main array is empty or not.
But since you have a SimpleXMLElement object, you need to query the object if it is empty or not. See http://www.php.net/manual/en/simplexmlelement.count.php
ex:
if (empty($result) || !isset($result['Tags'])) {
return false;
}
if ( !($result['Tags'] instanceof SimpleXMLElement)) {
return false;
}
return ($result['Tags']->count());
To limit what you run as sudo, you could run
python non_sudo_stuff.py
sudo -E python -c "import os; os.system('sudo echo 1')"
without needing to store the password. The -E
parameter passes your current user's env to the process. Note that your shell will have sudo priveleges after the second command, so use with caution!
DEMO
In the content area you can provide whatever you want to display in it.
.black_overlay {_x000D_
display: none;_x000D_
position: absolute;_x000D_
top: 0%;_x000D_
left: 0%;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
background-color: black;_x000D_
z-index: 1001;_x000D_
-moz-opacity: 0.8;_x000D_
opacity: .80;_x000D_
filter: alpha(opacity=80);_x000D_
}_x000D_
.white_content {_x000D_
display: none;_x000D_
position: absolute;_x000D_
top: 25%;_x000D_
left: 25%;_x000D_
width: 50%;_x000D_
height: 50%;_x000D_
padding: 16px;_x000D_
border: 16px solid orange;_x000D_
background-color: white;_x000D_
z-index: 1002;_x000D_
overflow: auto;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<title>LIGHTBOX EXAMPLE</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<p>This is the main content. To display a lightbox click <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'">here</a>_x000D_
</p>_x000D_
<div id="light" class="white_content">This is the lightbox content. <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">Close</a>_x000D_
</div>_x000D_
<div id="fade" class="black_overlay"></div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
I would recommend taking advantage of the fact that nodeJS will always be ES5. Remember this isn't the browser folks you can depend on the language's implementation on being stable. That said I would recommend against ever using a for-in loop in nodeJS, unless you really want to do deep recursion up the prototype chain. For simple, traditional looping I would recommend making good use of Object.keys method, in ES5. If you view the following JSPerf test, especially if you use Chrome (since it has the same engine as nodeJS), you will get a rough idea of how much more performant using this method is than using a for-in loop (roughly 10 times faster). Here's a sample of the code:
var keys = Object.keys( obj );
for( var i = 0,length = keys.length; i < length; i++ ) {
obj[ keys[ i ] ];
}
I had this problem in my main project when I referenced a dll file.
The problem was that the main project that referenced the dll was targeting a lower framework version than that of the dll.
So I upped my target framework version (Right-click project -> Application -> Target framework) and the error disappeared.
Ok If I understand what your asking you would do this;
You have your DIV container called #main-container
and .my-element
that is within it. Use this to get you started;
#main-container {
position:relative;
}
/*To make the element absolute - floats above all else within the parent container do this.*/
.my-element {
position:absolute;
top:0;
right:10px;
}
/*To make the element apart of elements, something tangible that affects the position of other elements on the same level within the parent then do this;*/
.my-element {
float:right;
margin-right:10px;
}
By the way, it better practice to use classes if you referencing a lower level element within a page (I assume you are hence my name change above.
Ivan's answer above is good:
composer global show -i
Added info: if you get a message somewhat like:
Composer could not find a composer.json file in ~/.composer
...you might have no packages installed yet. If so, you can ignore the next part of the message containing:
... please create a composer.json file ...
...as once you install a package the message will go away.
Add a column called r
with type serial
. Index r
.
Assume we have 200,000 rows, we are going to generate a random number n
, where 0 < n
<= 200, 000.
Select rows with r > n
, sort them ASC
and select the smallest one.
Code:
select * from YOUR_TABLE
where r > (
select (
select reltuples::bigint AS estimate
from pg_class
where oid = 'public.YOUR_TABLE'::regclass) * random()
)
order by r asc limit(1);
The code is self-explanatory. The subquery in the middle is used to quickly estimate the table row counts from https://stackoverflow.com/a/7945274/1271094 .
In application level you need to execute the statement again if n
> the number of rows or need to select multiple rows.
use jackson to convert json input stream to the map or object http://jackson.codehaus.org/
there are also some other usefull libraries for json, you can google: json java
This may not be as slick as a one-liner, but I use it to perform date manipulation mainly for reports:
DECLARE @Date datetime
SET @Date = GETDATE()
-- Set all time components to zero
SET @Date = DATEADD(ms, -DATEPART(ms, @Date), @Date) -- milliseconds = 0
SET @Date = DATEADD(ss, -DATEPART(ss, @Date), @Date) -- seconds = 0
SET @Date = DATEADD(mi, -DATEPART(mi, @Date), @Date) -- minutes = 0
SET @Date = DATEADD(hh, -DATEPART(hh, @Date), @Date) -- hours = 0
-- Extra manipulation for month and year
SET @Date = DATEADD(dd, -DATEPART(dd, @Date) + 1, @Date) -- day = 1
SET @Date = DATEADD(mm, -DATEPART(mm, @Date) + 1, @Date) -- month = 1
I use this to get hourly, daily, monthly, and yearly dates used for reporting and performance indicators, etc.
I went through this post and everything didnt want to work correctly and eventually pieced the bits together from a few answers so I have a 100% working demo and will paste it here for reference - paste this into a php file and make sure includes are in the right place.
<?php if (isset($_GET['typeahead'])){
die(json_encode(array('options' => array('like','spike','dike','ikelalcdass'))));
}
?>
<link href="bootstrap.css" rel="stylesheet">
<input type="text" class='typeahead'>
<script src="jquery-1.10.2.js"></script>
<script src="bootstrap.min.js"></script>
<script>
$('.typeahead').typeahead({
source: function (query, process) {
return $.get('index.php?typeahead', { query: query }, function (data) {
return process(JSON.parse(data).options);
});
}
});
</script>
<div style="height: 100px;"> </div>
OR
<div id="foo"/> and set the style as #foo { height: 100px; }
<div class="bar"/> and set the style as .bar{ height: 100px; }
Your problem comes from the 32/64 bit version of your JDK/JRE... Your shared lib is searched for a 32 bit version.
Your default JDK is a 32 bit version. Try to install a 64 bit one by default and relaunch your `.sh file.
To add to Paul's answer, I found that to ultimately recover space, I have to push HEAD to a clean repository and that trims down the size of the .git/objects/pack directory.
i.e.
$ mkdir ...ABC.git $ cd ...ABC.git $ git init --bare
After the gc prune, also do:
$ git push ...ABC.git HEAD
Then you can do
$ git clone ...ABC.git
and the size of ABC/.git is reduced
Actually, some of the time consuming steps (e.g. git gc) aren't needed with the push to clean repository, i.e.:
$ git clone --no-hardlinks /XYZ /ABC $ git filter-branch --subdirectory-filter ABC HEAD $ git reset --hard $ git push ...ABC.git HEAD
you can follow BaseAdapter
and create your custome Xml
file and bind it with you BaseAdpter
and populate it with Listview
see here need to change xml
file as Require.
Swift is statically typed so the performSelector:
methods are to fall by the wayside.
Instead, use GCD to dispatch a suitable block to the relevant queue — in this case it'll presumably be the main queue since it looks like you're doing UIKit work.
EDIT: the relevant performSelector:
is also notably missing from the Swift version of the NSRunLoop
documentation ("1 Objective-C symbol hidden") so you can't jump straight in with that. With that and its absence from the Swiftified NSObject
I'd argue it's pretty clear what Apple is thinking here.
It looks much like a list of Django ORM model instances.
Why not sort them on query like this:
ut = Tag.objects.order_by('-count')
I would suggest using conda. Conda is an anconda specific package manager. If you want to know more about conda, read the conda docs.
Using conda in the command line, the command below would install scipy 0.17.
conda install scipy=0.17.0
You could also use Regular Expressions:
SELECT * FROM TABLE WHERE REGEXP_LIKE (TABLE.NAME,'IgNoReCaSe','i');
Modern way:
newParent.append(...oldParent.childNodes);
.append
is the replacement for .appendChild
. The main difference is that it accepts multiple nodes at once and even plain strings, like .append('hello!')
oldParent.childNodes
is iterable so it can be spread with ...
to become multiple parameters of .append()
Compatibility tables of both (in short: Edge 17+, Safari 10+):
If you want the k-th bit of n, then do
(n & ( 1 << k )) >> k
Here we create a mask, apply the mask to n, and then right shift the masked value to get just the bit we want. We could write it out more fully as:
int mask = 1 << k;
int masked_n = n & mask;
int thebit = masked_n >> k;
You can read more about bit-masking here.
Here is a program:
#include <stdio.h>
#include <stdlib.h>
int *get_bits(int n, int bitswanted){
int *bits = malloc(sizeof(int) * bitswanted);
int k;
for(k=0; k<bitswanted; k++){
int mask = 1 << k;
int masked_n = n & mask;
int thebit = masked_n >> k;
bits[k] = thebit;
}
return bits;
}
int main(){
int n=7;
int bitswanted = 5;
int *bits = get_bits(n, bitswanted);
printf("%d = ", n);
int i;
for(i=bitswanted-1; i>=0;i--){
printf("%d ", bits[i]);
}
printf("\n");
}
This code extract frames from the video and save the frames in .jpg formate
import cv2
import numpy as np
import os
# set video file path of input video with name and extension
vid = cv2.VideoCapture('VideoPath')
if not os.path.exists('images'):
os.makedirs('images')
#for frame identity
index = 0
while(True):
# Extract images
ret, frame = vid.read()
# end of frames
if not ret:
break
# Saves images
name = './images/frame' + str(index) + '.jpg'
print ('Creating...' + name)
cv2.imwrite(name, frame)
# next frame
index += 1
Static members are universal members. They can be accessed from anywhere.
test[,sort(names(test))]
sort on names of columns can work easily.
Actually, neither statement says anything about heap or stack. The code
Object o;
creates one of the following, depending on its context:
This means that the storage location is determined by the context in which the object is defined. In addition, the C++ standard does not talk about stack vs heap storage. Instead, it talks about storage duration, which can be either automatic, dynamic, static or thread-local. However, most implementations implement automatic storage via the call stack, and dynamic storage via the heap.
Local variables, which have automatic storage, are thus created on the stack. Static (and thread-local) objects are generally allocated in their own memory regions, neither on the stack nor on the heap. And member variables are allocated wherever the object they belong to is allocated. They have their containing object’s storage duration.
To illustrate this with an example:
struct Foo {
Object o;
};
Foo foo;
int main() {
Foo f;
Foo* p = new Foo;
Foo* pf = &f;
}
Now where is the object Foo::o
(that is, the subobject o
of an object of class Foo
) created? It depends:
foo.o
has static storage because foo
has static storage, and therefore lives neither on the stack nor on the heap.f.o
has automatic storage since f
has automatic storage (= it lives on the stack).p->o
has dynamic storage since *p
has dynamic storage (= it lives on the heap).pf->o
is the same object as f.o
because pf
points to f
.In fact, both p
and pf
in the above have automatic storage. A pointer’s storage is indistinguishable from any other object’s, it is determined by context. Furthermore, the initialising expression has no effect on the pointer storage.
The pointee (= what the pointer points to) is a completely different matter, and could refer to any kind of storage: *p
is dynamic, whereas *pf
is automatic.
Set objFSO=CreateObject("Scripting.FileSystemObject")
' How to write file
outFile="c:\test\autorun.inf"
Set objFile = objFSO.CreateTextFile(outFile,True)
objFile.Write "test string" & vbCrLf
objFile.Close
'How to read a file
strFile = "c:\test\file"
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
strLine= objFile.ReadLine
Wscript.Echo strLine
Loop
objFile.Close
'to get file path without drive letter, assuming drive letters are c:, d:, etc
strFile="c:\test\file"
s = Split(strFile,":")
WScript.Echo s(1)
Use the following to apply the changes to a file in a stash to your working tree.
git diff stash^! -- <filename> | git apply
This is generally better than using git checkout
because you won't lose any changes you made to file since you created the stash.
you could use replaceAll instead of remove and append replaceAll
var confirmBox = '<div class="modal fade confirm-modal">' +_x000D_
'<div class="modal-dialog modal-sm" role="document">' +_x000D_
'<div class="modal-content">' +_x000D_
'<button type="button" class="close m-4 c-pointer" data-dismiss="modal" aria-label="Close">' +_x000D_
'<span aria-hidden="true">×</span>' +_x000D_
'</button>' +_x000D_
'<div class="modal-body pb-5"></div>' +_x000D_
'<div class="modal-footer pt-3 pb-3">' +_x000D_
'<a href="#" class="btn btn-primary yesBtn btn-sm">OK</a>' +_x000D_
'<button type="button" class="btn btn-secondary abortBtn btn-sm" data-dismiss="modal">Abbrechen</button>' +_x000D_
'</div>' +_x000D_
'</div>' +_x000D_
'</div>' +_x000D_
'</div>';_x000D_
_x000D_
var dialog = function(el, text, trueCallback, abortCallback) {_x000D_
_x000D_
el.click(function(e) {_x000D_
_x000D_
var thisConfirm = $(confirmBox).clone();_x000D_
_x000D_
thisConfirm.find('.modal-body').text(text);_x000D_
_x000D_
e.preventDefault();_x000D_
$('body').append(thisConfirm);_x000D_
$(thisConfirm).modal('show');_x000D_
_x000D_
if (abortCallback) {_x000D_
$(thisConfirm).find('.abortBtn').click(function(e) {_x000D_
e.preventDefault();_x000D_
abortCallback();_x000D_
$(thisConfirm).modal('hide');_x000D_
});_x000D_
}_x000D_
_x000D_
if (trueCallback) {_x000D_
$(thisConfirm).find('.yesBtn').click(function(e) {_x000D_
e.preventDefault();_x000D_
trueCallback();_x000D_
$(thisConfirm).modal('hide');_x000D_
});_x000D_
} else {_x000D_
_x000D_
if (el.prop('nodeName') == 'A') {_x000D_
$(thisConfirm).find('.yesBtn').attr('href', el.attr('href'));_x000D_
}_x000D_
_x000D_
if (el.attr('type') == 'submit') {_x000D_
$(thisConfirm).find('.yesBtn').click(function(e) {_x000D_
e.preventDefault();_x000D_
el.off().click();_x000D_
});_x000D_
}_x000D_
}_x000D_
_x000D_
$(thisConfirm).on('hidden.bs.modal', function(e) {_x000D_
$(this).remove();_x000D_
});_x000D_
_x000D_
});_x000D_
}_x000D_
_x000D_
// custom confirm_x000D_
$(function() {_x000D_
$('[data-confirm]').each(function() {_x000D_
dialog($(this), $(this).attr('data-confirm'));_x000D_
});_x000D_
_x000D_
dialog($('#customCallback'), "dialog with custom callback", function() {_x000D_
_x000D_
alert("hi there");_x000D_
_x000D_
});_x000D_
_x000D_
});
_x000D_
.test {_x000D_
display:block;_x000D_
padding: 5p 10px;_x000D_
background:orange;_x000D_
color:white;_x000D_
border-radius:4px;_x000D_
margin:0;_x000D_
border:0;_x000D_
width:150px;_x000D_
text-align:center;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
example 1_x000D_
<a class="test" href="http://example" data-confirm="do you want really leave the website?">leave website</a><br><br>_x000D_
_x000D_
_x000D_
example 2_x000D_
<form action="">_x000D_
<button class="test" type="submit" data-confirm="send form to delete some files?">delete some files</button>_x000D_
</form><br><br>_x000D_
_x000D_
example 3_x000D_
<span class="test" id="customCallback">with callback</span>
_x000D_
Yes, what you are asking for is called AJAX or XMLHttpRequest. You can either use a library like jQuery to simplify making the call (due to cross-browser compatibility issues), or write your own handler.
In jQuery:
$.GET('url.asp', {data: 'here'}, function(data){ /* what to do with the data returned */ })
In plain vanilla javaScript (from w3c):
var xmlhttp;
function loadXMLDoc(url)
{
xmlhttp=null;
if (window.XMLHttpRequest)
{// code for all new browsers
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// code for IE5 and IE6
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp!=null)
{
xmlhttp.onreadystatechange=state_Change;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
else
{
alert("Your browser does not support XMLHTTP.");
}
}
function state_Change()
{
if (xmlhttp.readyState==4)
{// 4 = "loaded"
if (xmlhttp.status==200)
{// 200 = OK
//xmlhttp.data and shtuff
// ...our code here...
}
else
{
alert("Problem retrieving data");
}
}
}
you put resource-ref in the description tag in web.xml
You can use this in your MySQL WHERE clause to return records that were created within the last 7 days/week:
created >= DATE_SUB(CURDATE(),INTERVAL 7 day)
Also use NOW() in the subtraction to give hh:mm:ss resolution. So to return records created exactly (to the second) within the last 24hrs, you could do:
created >= DATE_SUB(NOW(),INTERVAL 1 day)
You have to consider the Turkish I problem when comparing characters/ lowercasing / uppercasing:
I suggest to convert to String and use toLowerCase with invariant culture (in most cases at least).
public final static Locale InvariantLocale = new Locale(Empty, Empty, Empty); str.toLowerCase(InvariantLocale)
See similar C# string.ToLower() and string.ToLowerInvariant()
Note: Don't use String.equalsIgnoreCase http://nikolajlindberg.blogspot.co.il/2008/03/beware-of-java-comparing-turkish.html
By definition, by multiplying a 1D vector by its transpose, you've created a singular matrix.
Each row is a linear combination of the first row.
Notice that the second row is just 8x the first row.
Likewise, the third row is 50x the first row.
There's only one independent row in your matrix.
The old-school (pre-PEP 3119) way to do this is just to raise NotImplementedError
in the abstract class when an abstract method is called.
class Abstract(object):
def foo(self):
raise NotImplementedError('subclasses must override foo()!')
class Derived(Abstract):
def foo(self):
print 'Hooray!'
>>> d = Derived()
>>> d.foo()
Hooray!
>>> a = Abstract()
>>> a.foo()
Traceback (most recent call last): [...]
This doesn't have the same nice properties as using the abc
module does. You can still instantiate the abstract base class itself, and you won't find your mistake until you call the abstract method at runtime.
But if you're dealing with a small set of simple classes, maybe with just a few abstract methods, this approach is a little easier than trying to wade through the abc
documentation.
Open the mysql terminal:
el@apollo:~$ mysql -u root -pthepassword yourdb
mysql>
Drop the function if it already exists
mysql> drop function if exists myfunc;
Query OK, 0 rows affected, 1 warning (0.00 sec)
Create the function
mysql> create function hello(id INT)
-> returns CHAR(50)
-> return 'foobar';
Query OK, 0 rows affected (0.01 sec)
Create a simple table to test it out with
mysql> create table yar (id INT);
Query OK, 0 rows affected (0.07 sec)
Insert three values into the table yar
mysql> insert into yar values(5), (7), (9);
Query OK, 3 rows affected (0.04 sec)
Records: 3 Duplicates: 0 Warnings: 0
Select all the values from yar, run our function hello each time:
mysql> select id, hello(5) from yar;
+------+----------+
| id | hello(5) |
+------+----------+
| 5 | foobar |
| 7 | foobar |
| 9 | foobar |
+------+----------+
3 rows in set (0.01 sec)
Verbalize and internalize what just happened:
You created a function called hello which takes one parameter. The parameter is ignored and returns a CHAR(50)
containing the value 'foobar'. You created a table called yar and added three rows to it. The select statement runs the function hello(5)
for each row returned by yar.
function foo(){
for i in {1..100};
do
echo $i;
sleep 1;
done;
}
cat <( foo ) # Will work
timeout 3 cat <( foo ) # Will Work
timeout 3 cat <( foo ) | sort # Wont work, As sort will fail
cat <( timeout 3 cat <( foo ) ) | sort -r # Will Work
To fully script-automate:
Create:
7z -mhc=on -mhe=on -pPasswordHere a %ZipDest% %WhatYouWantToZip%
Unzip:
7z x %ZipFile% -pPasswordHere
(Depending, you might need to: Set Path=C:\Program Files\7-Zip;%Path% )
Simply Check your string length
if (!yourString.length)
{
//your code
}
a message to NIL will return nil or 0, so no need to test for nil :).
Happy coding ...
Here are some suggestions:
For Android phones, any network: Root your phone, then install tcpdump on it. This app is a tcpdump wrapper that will install tcpdump and enable you to start captures using a GUI. Tip: You will need to make sure you supply the right interface name for the capture and this varies from one device to another, eg -i eth0 or -i tiwlan0 - or use -i any to log all interfaces
For Android 4.0+ phones: Android PCAP from Kismet uses the USB OTG interface to support packet capture without requiring root. I haven't tried this app, and there are some restrictions on the type of devices supported (see their page)
For Android phones: tPacketCapture uses the Android VPN service to intercept packets and capture them. I have used this app successfully, but it also seems to affect the performance with large traffic volumes (eg video streaming)
For IOS 5+ devices, any network: iOS 5 added a remote virtual interface (RVI) facility that lets you use Mac OS X packet trace programs to capture traces from an iOS device. See here for more details
For all phones, wi-fi only: Set up your PC as a wireless access point, then run wireshark on the PC
For all phones, wi-fi only: Get a capture device that can sniff wi-fi. This has the advantage of giving you 802.11x headers as well, but you may miss some of the packets
Capture using a VPN server: Its fairly easy to set-up your own VPN server using OpenVPN. You can then route your traffic through your server by setting up the mobile device as a VPN client and capture the traffic on the server end.
Having something in an anonymous namespace means it's local to this translation unit (.cpp file and all its includes) this means that if another symbol with the same name is defined elsewhere there will not be a violation of the One Definition Rule (ODR).
This is the same as the C way of having a static global variable or static function but it can be used for class definitions as well (and should be used rather than static
in C++).
All anonymous namespaces in the same file are treated as the same namespace and all anonymous namespaces in different files are distinct. An anonymous namespace is the equivalent of:
namespace __unique_compiler_generated_identifer0x42 {
...
}
using namespace __unique_compiler_generated_identifer0x42;
vw and vh stand for viewport width and viewport height respectively.
The difference between using width: 100vw
instead of width: 100%
is that while 100%
will make the element fit all the space available, the viewport width has a specific measure, in this case the width of the available screen, including the document margin.
If you set the style body { margin: 0 }
, 100vw should behave the same as 100%.
Using vw
as unit for everything in your website, including font sizes and heights, will make it so that the site is always displayed proportionally to the device's screen width regardless of it's resolution. This makes it super easy to ensure your website is displayed properly in both workstation and mobile.
You can set font-size: 1vw
(or whatever size suits your project) in your body
CSS and everything specified in rem
units will automatically scale according to the device screen, so it's easy to port existing projects and even frameworks (such as Bootstrap) to this concept.
When you run the code
listoflists.append((list, list[0]))
You are not (as I think you expect) adding a copy of list
to the end of listoflists
. What you are doing is adding a reference to list
to the end of listoflists
. Thus, every time you update list
, it updates every reference to list
, which in this case, is every item in listoflists
What you could do instead is something like this:
listoflists = []
for i in range(1, 10):
listoflists.append((range(i), 0))
Looking at the "effective POM" will probably help too. For instance, if you wanted to know what the path is for ${project.build.sourceDirectory}
you would find the related XML in the effective POM, such as:
<project>
<build>
<sourceDirectory>/my/path</sourceDirectory>
Also helpful - you can do a real time evaluation of properties via the command line execution of mvn help:evaluate
while in the same dir as the POM.
The problem is that you're trying start the animation too early in the view controller's lifecycle. In viewDidLoad
, the view has just been created, and hasn't yet been added to the view hierarchy, so attempting to animate one of its subviews
at this point produces bad results.
What you really should be doing is continuing to set the alpha of the view in viewDidLoad
(or where you create your views), and then waiting for the viewDidAppear
: method to be called. At this point, you can start your animations without any issue.
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
UIView.animate(withDuration: 1.5) {
self.myFirstLabel.alpha = 1.0
self.myFirstButton.alpha = 1.0
self.mySecondButton.alpha = 1.0
}
}
For example 8/12/1976. Copy your date column. Highlight the copied column and click Data> Text to Columns> Delimited> Next. In the delimiters column check "Other" and input / and then click Next and Finish. You'll have 3 columns and the first column will be 1/8. Highlight it and click the comma in the Number section and it will give you the month as 8.00, so then reduce it by clicking the comma in Home/Numbers and you'll now have 8 in the first column, 18 in the second column and 1976 in the third column. In the first empty cell to the right use the concatenate function and leave out the year column. If your month is column A, day is column B and year is column C, it will look like this: =concatenate(A2,"/",B2) and hit enter. It will look like 8/18, however, when you click on the cell you'll see the concatenate formula. Highlight the cell(s), then copy and paste special values. Now you can sort by date. It's really quick when you get the hang of it.
Generally impossible, because List<String>
and List<Integer>
share the same runtime class.
You might be able to reflect on the declared type of the field holding the list, though (if the declared type does not itself refer to a type parameter whose value you don't know).
The following code is looking for '\0', and under the assumptions of the question the array can be considered sorted since all non-'\0' precede all '\0'. This assumption won't hold if the array can contain '\0' within the data.
Find the location of the first zero-byte using a binary search, then slice.
You can find the zero-byte like this:
package main
import "fmt"
func FirstZero(b []byte) int {
min, max := 0, len(b)
for {
if min + 1 == max { return max }
mid := (min + max) / 2
if b[mid] == '\000' {
max = mid
} else {
min = mid
}
}
return len(b)
}
func main() {
b := []byte{1, 2, 3, 0, 0, 0}
fmt.Println(FirstZero(b))
}
It may be faster just to naively scan the byte array looking for the zero-byte, especially if most of your strings are short.
Take a look at this answer:
from numpy import matrix
from numpy import linalg
A = matrix( [[1,2,3],[11,12,13],[21,22,23]]) # Creates a matrix.
x = matrix( [[1],[2],[3]] ) # Creates a matrix (like a column vector).
y = matrix( [[1,2,3]] ) # Creates a matrix (like a row vector).
print A.T # Transpose of A.
print A*x # Matrix multiplication of A and x.
print A.I # Inverse of A.
print linalg.solve(A, x) # Solve the linear equation system.
Steps to do it on PgAdmin:
groupByKey:
Syntax:
sparkContext.textFile("hdfs://")
.flatMap(line => line.split(" ") )
.map(word => (word,1))
.groupByKey()
.map((x,y) => (x,sum(y)))
groupByKey can cause out of disk problems as data is sent over the network and collected on the reduce workers.
reduceByKey:
Syntax:
sparkContext.textFile("hdfs://")
.flatMap(line => line.split(" "))
.map(word => (word,1))
.reduceByKey((x,y)=> (x+y))
Data are combined at each partition, only one output for one key at each partition to send over the network. reduceByKey required combining all your values into another value with the exact same type.
aggregateByKey:
same as reduceByKey, which takes an initial value.
3 parameters as input i. initial value ii. Combiner logic iii. sequence op logic
Example:
val keysWithValuesList = Array("foo=A", "foo=A", "foo=A", "foo=A", "foo=B", "bar=C", "bar=D", "bar=D")
val data = sc.parallelize(keysWithValuesList)
//Create key value pairs
val kv = data.map(_.split("=")).map(v => (v(0), v(1))).cache()
val initialCount = 0;
val addToCounts = (n: Int, v: String) => n + 1
val sumPartitionCounts = (p1: Int, p2: Int) => p1 + p2
val countByKey = kv.aggregateByKey(initialCount)(addToCounts, sumPartitionCounts)
ouput: Aggregate By Key sum Results bar -> 3 foo -> 5
combineByKey:
3 parameters as input
Example:
val result = rdd.combineByKey(
(v) => (v,1),
( (acc:(Int,Int),v) => acc._1 +v , acc._2 +1 ) ,
( acc1:(Int,Int),acc2:(Int,Int) => (acc1._1+acc2._1) , (acc1._2+acc2._2))
).map( { case (k,v) => (k,v._1/v._2.toDouble) })
result.collect.foreach(println)
reduceByKey,aggregateByKey,combineByKey preferred over groupByKey
Reference: Avoid groupByKey
As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:
var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da
For Node.js v5.11.1 and below
Construct a new Buffer
and pass 'base64'
as the second argument:
var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da
If you want to be clean, you can check whether from
exists :
if (typeof Buffer.from === "function") {
// Node 5.10+
buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
// older Node versions, now deprecated
buf = new Buffer(b64string, 'base64'); // Ta-da
}
@WebWanderer 's answer is very close to the DateDiff using SQL server, but inaccurate. That is because of the usage of age() function.
e.g. days between '2019-07-29' and '2020-06-25' should return 332, however, using the age() function it will returns 327. Because the age() returns '10 mons 27 days" and it treats each month as 30 days which is incorrect.
You shold use the timestamp to get the accurate result. e.g.
ceil((select extract(epoch from (current_date::timestamp - <your_date>::timestamp)) / 86400))
Note: The answer below is written from the perspective of Windows PowerShell.
However, it applies to the cross-platform PowerShell Core edition (v6+) as well, except that the latter - commendably - consistently defaults to BOM-less UTF-8 character encoding, which is the most widely compatible one across platforms and cultures..
To complement bigtv's helpful answer helpful answer with a more concise alternative and background information:
# > $file is effectively the same as | Out-File $file
# Objects are written the same way they display in the console.
# Default character encoding is UTF-16LE (mostly 2 bytes per char.), with BOM.
# Use Out-File -Encoding <name> to change the encoding.
$env:computername > $file
# Set-Content calls .ToString() on each object to output.
# Default character encoding is "ANSI" (culture-specific, single-byte).
# Use Set-Content -Encoding <name> to change the encoding.
# Use Set-Content rather than Add-Content; the latter is for *appending* to a file.
$env:computername | Set-Content $file
When outputting to a text file, you have 2 fundamental choices that use different object representations and, in Windows PowerShell (as opposed to PowerShell Core), also employ different default character encodings:
Out-File
(or >
) / Out-File -Append
(or >>
):
Suitable for output objects of any type, because PowerShell's default output formatting is applied to the output objects.
The default encoding, which can be changed with the -Encoding
parameter, is Unicode
, which is UTF-16LE in which most characters are encoded as 2 bytes. The advantage of a Unicode encoding such as UTF-16LE is that it is a global alphabet, capable of encoding all characters from all human languages.
>
and >>
, via the $PSDefaultParameterValues
preference variable, taking advantage of the fact that >
and >>
are now effectively aliases of Out-File
and Out-File -Append
. To change to UTF-8, for instance, use:$PSDefaultParameterValues['Out-File:Encoding']='UTF8'
For writing strings and instances of types known to have meaningful string representations, such as the .NET primitive data types (Booleans, integers, ...).
.psobject.ToString()
method is called on each output object, which results in meaningless representations for types that don't explicitly implement a meaningful representation; [hashtable]
instances are an example:@{ one = 1 } | Set-Content t.txt
writes literal System.Collections.Hashtable
to t.txt
, which is the result of @{ one = 1 }.ToString()
.The default encoding, which can be changed with the -Encoding
parameter, is Default
, which is the system's "ANSI" code page, a the single-byte culture-specific legacy encoding for non-Unicode applications, most commonly Windows-1252.
Note that the documentation currently incorrectly claims that ASCII is the default encoding.
Note that Add-Content
's purpose is to append content to an existing file, and it is only equivalent to Set-Content
if the target file doesn't exist yet.
Furthermore, the default or specified encoding is blindly applied, irrespective of the file's existing contents' encoding.
Out-File
/ >
/ Set-Content
/ Add-Content
all act culture-sensitively, i.e., they produce representations suitable for the current culture (locale), if available (though custom formatting data is free to define its own, culture-invariant representation - see Get-Help about_format.ps1xml
).
This contrasts with PowerShell's string expansion (string interpolation in double-quoted strings), which is culture-invariant - see this answer of mine.
As for performance: Since Set-Content
doesn't have to apply default formatting to its input, it performs better.
As for the OP's symptom with Add-Content
:
Since $env:COMPUTERNAME
cannot contain non-ASCII characters, Add-Content
's output, using "ANSI" encoding, should not result in ?
characters in the output, and the likeliest explanation is that the ?
were part of the preexisting content in output file $file
, which Add-Content
appended to.
$this->db->where_in('id', ['20','15','22','42','86']);
Reference: where_in
@bdiamante's answer may only partially help you. If you still get a message after you've suppressed warnings, it's because the pandas
library itself is printing the message. There's not much you can do about it unless you edit the Pandas source code yourself. Maybe there's an option internally to suppress them, or a way to override things, but I couldn't find one.
Suppose that you want to ensure a clean working environment. At the top of your script, you put pd.reset_option('all')
. With Pandas 0.23.4, you get the following:
>>> import pandas as pd
>>> pd.reset_option('all')
html.border has been deprecated, use display.html.border instead
(currently both are identical)
C:\projects\stackoverflow\venv\lib\site-packages\pandas\core\config.py:619: FutureWarning: html.bord
er has been deprecated, use display.html.border instead
(currently both are identical)
warnings.warn(d.msg, FutureWarning)
: boolean
use_inf_as_null had been deprecated and will be removed in a future
version. Use `use_inf_as_na` instead.
C:\projects\stackoverflow\venv\lib\site-packages\pandas\core\config.py:619: FutureWarning:
: boolean
use_inf_as_null had been deprecated and will be removed in a future
version. Use `use_inf_as_na` instead.
warnings.warn(d.msg, FutureWarning)
>>>
Following the @bdiamante's advice, you use the warnings
library. Now, true to it's word, the warnings have been removed. However, several pesky messages remain:
>>> import warnings
>>> warnings.simplefilter(action='ignore', category=FutureWarning)
>>> import pandas as pd
>>> pd.reset_option('all')
html.border has been deprecated, use display.html.border instead
(currently both are identical)
: boolean
use_inf_as_null had been deprecated and will be removed in a future
version. Use `use_inf_as_na` instead.
>>>
In fact, disabling all warnings produces the same output:
>>> import warnings
>>> warnings.simplefilter(action='ignore', category=Warning)
>>> import pandas as pd
>>> pd.reset_option('all')
html.border has been deprecated, use display.html.border instead
(currently both are identical)
: boolean
use_inf_as_null had been deprecated and will be removed in a future
version. Use `use_inf_as_na` instead.
>>>
In the standard library sense, these aren't true warnings. Pandas implements its own warnings system. Running grep -rn
on the warning messages shows that the pandas
warning system is implemented in core/config_init.py
:
$ grep -rn "html.border has been deprecated"
core/config_init.py:207:html.border has been deprecated, use display.html.border instead
Further chasing shows that I don't have time for this. And you probably don't either. Hopefully this saves you from falling down the rabbit hole or perhaps inspires someone to figure out how to truly suppress these messages!
You may need to flush the table cache. For example:
DROP TABLE IF EXISTS `tablename` ;
FLUSH TABLES `tablename` ; /* or exclude `tablename` to flush all tables */
CREATE TABLE `tablename` ...
useful to windows users who use eclipse for c/c++ but run *.exe file and get an error: "missing libstdc++6.dll"
4 ways to solve it
Eclipse ->"Project" -> "Properties" -> "C/C++ Build" -> "Settings" -> "Tool Settings" -> "MinGW C++ Linker" -> "Misscellaneous" -> "Linker flags" (add '-static' to it)
Add '{{the path where your MinGW was installed}}/bin' to current user environment variable - "Path" in Windows, then reboot eclipse, and finally recompile.
Add '{{the path where your MinGW was installed}}/bin' to Windows environment variable - "Path", then reboot eclipse, and finally recompile.
Copy the file "libstdc++-6.dll" to the path where the *.exe file is running, then rerun. (this is not a good way)
Note: the file "libstdc++-6.dll" is in the folder '{{the path where your MinGW was installed}}/bin'
You may try with below query :
INSERT INTO errortable (dateupdated,table1id)
VALUES (to_date(to_char(sysdate,'dd/mon/yyyy hh24:mi:ss'), 'dd/mm/yyyy hh24:mi:ss' ),1083 );
To view the result of it:
SELECT to_char(hire_dateupdated, 'dd/mm/yyyy hh24:mi:ss')
FROM errortable
WHERE table1id = 1083;
You can try this:
SELECT EXTRACT(YEAR FROM field) FROM table WHERE id=1
In case of WSS 3.0 recently I experienced same issue. It was because of column that was accessed from code was not present in the wss list.
public static string ConvertIntoJson(DataTable dt)
{
var jsonString = new StringBuilder();
if (dt.Rows.Count > 0)
{
jsonString.Append("[");
for (int i = 0; i < dt.Rows.Count; i++)
{
jsonString.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
jsonString.Append("\"" + dt.Columns[j].ColumnName + "\":\""
+ dt.Rows[i][j].ToString().Replace('"','\"') + (j < dt.Columns.Count - 1 ? "\"," : "\""));
jsonString.Append(i < dt.Rows.Count - 1 ? "}," : "}");
}
return jsonString.Append("]").ToString();
}
else
{
return "[]";
}
}
public static string ConvertIntoJson(DataSet ds)
{
var jsonString = new StringBuilder();
jsonString.Append("{");
for (int i = 0; i < ds.Tables.Count; i++)
{
jsonString.Append("\"" + ds.Tables[i].TableName + "\":");
jsonString.Append(ConvertIntoJson(ds.Tables[i]));
if (i < ds.Tables.Count - 1)
jsonString.Append(",");
}
jsonString.Append("}");
return jsonString.ToString();
}
Some configuration parameters have changed in Apache 2.4. I had a similar issue when I was setting up a Zend Framework 2 application. After some research, here is the solution:
Incorrect Configuration
<VirtualHost *:80>
ServerName zf2-tutorial.localhost
DocumentRoot /path/to/zf2-tutorial/public
SetEnv APPLICATION_ENV "development"
<Directory /path/to/zf2-tutorial/public>
DirectoryIndex index.php
AllowOverride All
Order allow,deny #<-- 2.2 config
Allow from all #<-- 2.2 config
</Directory>
</VirtualHost>
Correct Configuration
<VirtualHost *:80>
ServerName zf2-tutorial.localhost
DocumentRoot /path/to/zf2-tutorial/public
SetEnv APPLICATION_ENV "development"
<Directory /path/to/zf2-tutorial/public>
DirectoryIndex index.php
AllowOverride All
Require all granted #<-- 2.4 New configuration
</Directory>
</VirtualHost>
If you are planning to migrate from Apache 2.2 to 2.4, here is a good reference: http://httpd.apache.org/docs/2.4/upgrading.html
An alternate way is to construct a view which is then queried just like a table. In many database managers using a view can result in better performance.
CREATE VIEW xyz SELECT q.question, a.alternative
FROM tbl_question AS q, tbl_alternative AS a
WHERE q.categoryid = a.categoryid
AND q._id = a.questionid;
This is from memory so there may be some syntactic issues. http://www.sqlite.org/lang_createview.html
I mention this approach because then you can use SQLiteQueryBuilder with the view as you implied that it was preferred.
SlickGrid has this functionality, see the tree demo.
If you want to build your own, here is an example (jsFiddle demo): Build your table with a data-depth
attribute to indicate the depth of the item in the tree (the levelX
CSS classes are just for styling indentation):
<table id="mytable">
<tr data-depth="0" class="collapse level0">
<td><span class="toggle collapse"></span>Item 1</td>
<td>123</td>
</tr>
<tr data-depth="1" class="collapse level1">
<td><span class="toggle"></span>Item 2</td>
<td>123</td>
</tr>
</table>
Then when a toggle link is clicked, use Javascript to hide all <tr>
elements until a <tr>
of equal or less depth is found (excluding those already collapsed):
$(function() {
$('#mytable').on('click', '.toggle', function () {
//Gets all <tr>'s of greater depth below element in the table
var findChildren = function (tr) {
var depth = tr.data('depth');
return tr.nextUntil($('tr').filter(function () {
return $(this).data('depth') <= depth;
}));
};
var el = $(this);
var tr = el.closest('tr'); //Get <tr> parent of toggle button
var children = findChildren(tr);
//Remove already collapsed nodes from children so that we don't
//make them visible.
//(Confused? Remove this code and close Item 2, close Item 1
//then open Item 1 again, then you will understand)
var subnodes = children.filter('.expand');
subnodes.each(function () {
var subnode = $(this);
var subnodeChildren = findChildren(subnode);
children = children.not(subnodeChildren);
});
//Change icon and hide/show children
if (tr.hasClass('collapse')) {
tr.removeClass('collapse').addClass('expand');
children.hide();
} else {
tr.removeClass('expand').addClass('collapse');
children.show();
}
return children;
});
});
The view containing UITextView will be assigned its size with setBounds
by AutoLayout. So, this is what I did. The superview is initially set up all the other constraints as they should be, and in the end I put one special constraint for UITextView's height, and I saved it in an instance variable.
_descriptionHeightConstraint = [NSLayoutConstraint constraintWithItem:_descriptionTextView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:0.f
constant:100];
[self addConstraint:_descriptionHeightConstraint];
In the setBounds
method, I then changed the value of the constant.
-(void) setBounds:(CGRect)bounds
{
[super setBounds:bounds];
_descriptionTextView.frame = bounds;
CGSize descriptionSize = _descriptionTextView.contentSize;
[_descriptionHeightConstraint setConstant:descriptionSize.height];
[self layoutIfNeeded];
}
You can also run ->select('DISTINCT `field`', FALSE)
and the second parameter tells CI
not to escape the first argument.
With the second parameter as false
, the output would be SELECT DISTINCT `field`
instead of without the second parameter, SELECT `DISTINCT` `field`
Are you sure, that specified database and table exists? Did you try to look at your database using any database client? For example command-line MySQL client bundled with MySQL server. Or if you a developer newbie, there are dozens of a GUI and web interface clients (HeidiSQL, MySQL Workbench, phpMyAdmin and many more). So first check, if your table creation script was successful and had created what it have to.
BTW why do you have a script for creating the database structure? It's usualy a nonrecurring operation, so write the script to do this is unneeded. It's useful only in case of need of repeatedly creating and manipulating the database structure on the fly.
Here this should help you
The below jsfiddle link will help you understand how to rotate a image.I used the same one to rotate the dial of a clock.
var rotation = function (){
$("#image").rotate({
angle:0,
animateTo:360,
callback: rotation,
easing: function (x,t,b,c,d){
return c*(t/d)+b;
}
});
}
rotation();
Where: • t: current time,
• b: begInnIng value,
• c: change In value,
• d: duration,
• x: unused
No easing (linear easing): function(x, t, b, c, d) { return b+(t/d)*c ; }
"... that are independent of their timezone"
var timezone = d.getTimezoneOffset() // difference in minutes from GMT
Make sure that the htaccess file is readable by apache:
chmod 644 /var/www/abc/.htaccess
And make sure the directory it's in is readable and executable:
chmod 755 /var/www/abc/
The problem is that there is no app installed to handle opening the PDF. You should use the Intent Chooser, like so:
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+ filename);
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file),"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "Open File");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
// Instruct the user to install a PDF reader here, or something
}
Just wrap floated elements in a <div>
and give it this CSS:
.wrapper {
display: table;
margin: auto;
}
If all the above methods are not working, you probably install anaconda with root privileges. Remove it with sudo rm -rf /root/anaconda3
and reinstall without sudo
.
The symlink solution for this stopped working for me in zsh today. I ended up creating an alias in my .zshrc
file instead:
alias atom='sh /Applications/Atom.app/Contents/Resources/app/atom.sh'
signup to github and then use:
https://import.github.com/new.
instructions:
once you have a git repo on github you can download zip
if [ -n "$PID" -a -e /proc/$PID ]; then
echo "process exists"
fi
or
if [ -n "$(ps -p $PID -o pid=)" ]
In the latter form, -o pid=
is an output format to display only the process ID column with no header. The quotes are necessary for non-empty string operator -n
to give valid result.
This is code that I have effectively used before, passing "/"
as the strPath parameter.
public static Cookie eraseCookie(String strCookieName, String strPath) {
Cookie cookie = new Cookie(strCookieName, "");
cookie.setMaxAge(0);
cookie.setPath(strPath);
return cookie;
}
In my case I did a "Convert to application" to the wrong folder on iis. My application was set in a subfolder of where it should have been.
DECLARE @JCnt int=null
SEt @JCnt=(SELECT COUNT( ISNUll(EmpCode,0)) FROM tbl_Employees WHERE EmpCode=1 )
UPDATE #TempCode
SET janCA= CASE WHEN @JCnt>0 THEN (SELECT SUM (ISNUll(Amount,0)) FROM tbl_Salary WHERE Code=1 )ELSE 0 END
WHERE code=1
Also, I had this issue using Laravel, but fixed by changing my database schema to allow "null" inputs on a table where I plan to collect the information from separate forms:
public function up()
{
Schema::create('trip_table', function (Blueprint $table) {
$table->increments('trip_id')->unsigned();
$table->time('est_start');
$table->time('est_end');
$table->time('act_start')->nullable();
$table->time('act_end')->nullable();
$table->date('Trip_Date');
$table->integer('Starting_Miles')->nullable();
$table->integer('Ending_Miles')->nullable();
$table->string('Bus_id')->nullable();
$table->string('Event');
$table->string('Desc')->nullable();
$table->string('Destination');
$table->string('Departure_location');
$table->text('Drivers_Comment')->nullable();
$table->string('Requester')->nullable();
$table->integer('driver_id')->nullable();
$table->timestamps();
});
}
The ->nullable(); Added to the end. This is using Laravel. Hope this helps someone, thanks!
If you have data already present in both the tables and you want to update a table column values based on some condition then use this
UPDATE Table1 set Name=(select t2.Name from Table2 t2 where t2.id=Table1.id)
I had an implementation where I needed to take this technique a step farther, and wanted to outline my work. The below code does the same thing but uses SASS, Bourbon, and an image sprite.
@mixin sprite($position){
@include background(url('image.png') no-repeat ($position), linear-gradient(#color1, #color2));
}
a.button-1{
@include sprite(0 0);
}
a.button-2{
@include sprite (0 -20px);
}
a.button-2{
@include sprite (0 -40px);
}
SASS and Bourbon take care of the cross browser code, and now all I have to declare is the sprite position per button. It is easy to extend this principal for the buttons active and hover states.
Try using double quotes if it's a char variable:
DEFINE stupidvar = "'stupidvarcontent'";
or
DEFINE stupidvar = 'stupidvarcontent';
SELECT stupiddata
FROM stupidtable
WHERE stupidcolumn = '&stupidvar'
upd:
SQL*Plus: Release 10.2.0.1.0 - Production on Wed Aug 25 17:13:26 2010
Copyright (c) 1982, 2005, Oracle. All rights reserved.
SQL> conn od/od@etalon
Connected.
SQL> define var = "'FL-208'";
SQL> select code from product where code = &var;
old 1: select code from product where code = &var
new 1: select code from product where code = 'FL-208'
CODE
---------------
FL-208
SQL> define var = 'FL-208';
SQL> select code from product where code = &var;
old 1: select code from product where code = &var
new 1: select code from product where code = FL-208
select code from product where code = FL-208
*
ERROR at line 1:
ORA-06553: PLS-221: 'FL' is not a procedure or is undefined
You'll have it in your connection string like:
"mysql:host=$host;dbname=$db;charset=utf8"
HOWEVER, prior to PHP 5.3.6, the charset option was ignored. If you're running an older version of PHP, you must do it like this:
$dbh = new PDO("mysql:$connstr", $user, $password);
$dbh->exec("set names utf8");
You can dynamically retrieve a temp path using as following and better to use it instead of using hard coded string value for temp location.It will return the temp folder or temp file as you want.
string filePath = Path.Combine(Path.GetTempPath(),"SaveFile.txt");
or
Path.GetTempFileName();
DB to C#
EnumDisplayStatus status = (EnumDisplayStatus)int.Parse(GetValueFromDb());
C# to DB
string dbStatus = ((int)status).ToString();
if you want to run the command in async mode - and print the results. you can you this class:
public static class ExecuteCmd
{
/// <summary>
/// Executes a shell command synchronously.
/// </summary>
/// <param name="command">string command</param>
/// <returns>string, as output of the command.</returns>
public static void ExecuteCommandSync(object command)
{
try
{
// create the ProcessStartInfo using "cmd" as the program to be run, and "/c " as the parameters.
// Incidentally, /c tells cmd that we want it to execute the command that follows, and then exit.
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
// The following commands are needed to redirect the standard output.
//This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();
// Display the command output.
Console.WriteLine(result);
}
catch (Exception objException)
{
// Log the exception
Console.WriteLine("ExecuteCommandSync failed" + objException.Message);
}
}
/// <summary>
/// Execute the command Asynchronously.
/// </summary>
/// <param name="command">string command.</param>
public static void ExecuteCommandAsync(string command)
{
try
{
//Asynchronously start the Thread to process the Execute command request.
Thread objThread = new Thread(new ParameterizedThreadStart(ExecuteCommandSync));
//Make the thread as background thread.
objThread.IsBackground = true;
//Set the Priority of the thread.
objThread.Priority = ThreadPriority.AboveNormal;
//Start the thread.
objThread.Start(command);
}
catch (ThreadStartException )
{
// Log the exception
}
catch (ThreadAbortException )
{
// Log the exception
}
catch (Exception )
{
// Log the exception
}
}
}
I would use XMLHTTP request to retrieve page content as much faster. Then it is easy enough to use querySelectorAll to apply a CSS class selector to grab by class name. Then you access the child elements by tag name and index.
Option Explicit
Public Sub GetInfo()
Dim sResponse As String, html As HTMLDocument, elements As Object, i As Long
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", "https://www.hsbc.com/about-hsbc/leadership", False
.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
.send
sResponse = StrConv(.responseBody, vbUnicode)
End With
Set html = New HTMLDocument
With html
.body.innerHTML = sResponse
Set elements = .querySelectorAll(".profile-col1")
For i = 0 To elements.Length - 1
Debug.Print String(20, Chr$(61))
Debug.Print elements.item(i).getElementsByTagName("a")(0).innerText
Debug.Print elements.item(i).getElementsByTagName("p")(0).innerText
Debug.Print elements.item(i).getElementsByTagName("p")(1).innerText
Next
End With
End Sub
References:
VBE > Tools > References > Microsoft HTML Object Library
If you encounter an issue in which pylab.show()
freezes the IPython window (this may be Mac OS X specific; not sure), you can cmd-c in the IPython window, switch to the plot window, and it will break out.
Apparently, future calls to pylab.show()
will not freeze the IPython window, only the first call. Unfortunately, I've found that the behavior of the plot window / interactions with show() changes every time I reinstall matplotlib, so this solution may not always hold.
Tip: Try to remove dependencies of jQuery in your projects as much as you can - VanillaJS.
document.firstElementChild
returns <html>
tag then the classList
attribute returns all classes added to it.
if(document.firstElementChild.classList.contains("your-class")){
// <html> has 'your-class'
} else {
// <html> doesn't have 'your-class'
}
For me I had to put the whole interval in single quotes not just the value of the interval.
select id,
title,
created_at + interval '1 day' * claim_window as deadline from projects
Instead of
select id,
title,
created_at + interval '1' day * claim_window as deadline from projects
properties-maven-plugin plugin may help:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0.0</version>
<executions>
<execution>
<goals>
<goal>set-system-properties</goal>
</goals>
<configuration>
<properties>
<property>
<name>my.property.name</name>
<value>my.property.value</value>
</property>
</properties>
</configuration>
</execution>
</executions>
</plugin>
For newest version of IntelliJ, i think option has changed a bit.
My current version of IntelliJ:
IntelliJ IDEA 2017.3.5 (Community Edition)
Build #IC-173.4674.33, built on March 6, 2018
JRE: 1.8.0_152-release-1024-b15 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Hope this will help.
Declare PtrSafe Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" _
(ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, _
ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
Sub Example()
DownloadFile$ = "someFile.ext" 'here the name with extension
URL$ = "http://some.web.address/" & DownloadFile 'Here is the web address
LocalFilename$ = "C:\Some\Path" & DownloadFile !OR! CurrentProject.Path & "\" & DownloadFile 'here the drive and download directory
MsgBox "Download Status : " & URLDownloadToFile(0, URL, LocalFilename, 0, 0) = 0
End Sub
I found the above when looking for downloading from FTP with username and address in URL. Users supply information and then make the calls.
This was helpful because our organization has Kaspersky AV which blocks active
FTP.exe, but not web connections. We were unable to develop in house with ftp.exe and this was our solution. Hope this helps other looking for info!
(originally from Ways to sort lists of objects in Java based on multiple fields)
Original working code in this gist
Java 8 solves this nicely by lambda's (though Guava and Apache Commons might still offer more flexibility):
Collections.sort(reportList, Comparator.comparing(Report::getReportKey)
.thenComparing(Report::getStudentNumber)
.thenComparing(Report::getSchool));
Thanks to @gaoagong's answer below.
Note that one advantage here is that the getters are evaluated lazily (eg. getSchool()
is only evaluated if relevant).
Collections.sort(pizzas, new Comparator<Pizza>() {
@Override
public int compare(Pizza p1, Pizza p2) {
int sizeCmp = p1.size.compareTo(p2.size);
if (sizeCmp != 0) {
return sizeCmp;
}
int nrOfToppingsCmp = p1.nrOfToppings.compareTo(p2.nrOfToppings);
if (nrOfToppingsCmp != 0) {
return nrOfToppingsCmp;
}
return p1.name.compareTo(p2.name);
}
});
This requires a lot of typing, maintenance and is error prone. The only advantage is that getters are only invoked when relevant.
ComparatorChain chain = new ComparatorChain(Arrays.asList(
new BeanComparator("size"),
new BeanComparator("nrOfToppings"),
new BeanComparator("name")));
Collections.sort(pizzas, chain);
Obviously this is more concise, but even more error prone as you lose your direct reference to the fields by using Strings instead (no typesafety, auto-refactorings). Now if a field is renamed, the compiler won’t even report a problem. Moreover, because this solution uses reflection, the sorting is much slower.
Collections.sort(pizzas, new Comparator<Pizza>() {
@Override
public int compare(Pizza p1, Pizza p2) {
return ComparisonChain.start().compare(p1.size, p2.size).compare(p1.nrOfToppings, p2.nrOfToppings).compare(p1.name, p2.name).result();
// or in case the fields can be null:
/*
return ComparisonChain.start()
.compare(p1.size, p2.size, Ordering.natural().nullsLast())
.compare(p1.nrOfToppings, p2.nrOfToppings, Ordering.natural().nullsLast())
.compare(p1.name, p2.name, Ordering.natural().nullsLast())
.result();
*/
}
});
This is much better, but requires some boiler plate code for the most common use case: null-values should be valued less by default. For null-fields, you have to provide an extra directive to Guava what to do in that case. This is a flexible mechanism if you want to do something specific, but often you want the default case (ie. 1, a, b, z, null).
And as noted in the comments below, these getters are all evaluated immediately for each comparison.
Collections.sort(pizzas, new Comparator<Pizza>() {
@Override
public int compare(Pizza p1, Pizza p2) {
return new CompareToBuilder().append(p1.size, p2.size).append(p1.nrOfToppings, p2.nrOfToppings).append(p1.name, p2.name).toComparison();
}
});
Like Guava’s ComparisonChain, this library class sorts easily on multiple fields, but also defines default behavior for null values (ie. 1, a, b, z, null). However, you can’t specify anything else either, unless you provide your own Comparator.
Again, as noted in the comments below, these getters are all evaluated immediately for each comparison.
Ultimately it comes down to flavor and the need for flexibility (Guava’s ComparisonChain) vs. concise code (Apache’s CompareToBuilder).
I found a nice solution that combines multiple comparators in order of priority on CodeReview in a MultiComparator
:
class MultiComparator<T> implements Comparator<T> {
private final List<Comparator<T>> comparators;
public MultiComparator(List<Comparator<? super T>> comparators) {
this.comparators = comparators;
}
public MultiComparator(Comparator<? super T>... comparators) {
this(Arrays.asList(comparators));
}
public int compare(T o1, T o2) {
for (Comparator<T> c : comparators) {
int result = c.compare(o1, o2);
if (result != 0) {
return result;
}
}
return 0;
}
public static <T> void sort(List<T> list, Comparator<? super T>... comparators) {
Collections.sort(list, new MultiComparator<T>(comparators));
}
}
Ofcourse Apache Commons Collections has a util for this already:
ComparatorUtils.chainedComparator(comparatorCollection)
Collections.sort(list, ComparatorUtils.chainedComparator(comparators));
It is easier to compare dates using the java.util.Calendar
.
Here is what you might do:
Calendar toDate = Calendar.getInstance();
Calendar nowDate = Calendar.getInstance();
toDate.set(<set-year>,<set-month>,<set-day>);
if(!toDate.before(nowDate)) {
//display your report
} else {
// don't display the report
}
There is no best way, it depends on your use case.
Person
(you should start the name with a capital letter) is called the constructor function. This is similar to classes in other OO languages.Update: As requested examples for the third way.
Dependent properties:
The following does not work as this
does not refer to book
. There is no way to initialize a property with values of other properties in a object literal:
var book = {
price: somePrice * discount,
pages: 500,
pricePerPage: this.price / this.pages
};
instead, you could do:
var book = {
price: somePrice * discount,
pages: 500
};
book.pricePerPage = book.price / book.pages;
// or book['pricePerPage'] = book.price / book.pages;
Dynamic property names:
If the property name is stored in some variable or created through some expression, then you have to use bracket notation:
var name = 'propertyName';
// the property will be `name`, not `propertyName`
var obj = {
name: 42
};
// same here
obj.name = 42;
// this works, it will set `propertyName`
obj[name] = 42;
Note the output while doing the merge - it is saying Fast Forward
In such situations, you want to do:
git merge v1.0 --no-commit --no-ff
This can be done by the below code.
CREATE TABLE TestTable
(FirstCol INT NOT NULL)
GO
------------------------------
-- Option 1
------------------------------
-- Adding New Column
ALTER TABLE TestTable
ADD SecondCol INT
GO
-- Updating it with Default
UPDATE TestTable
SET SecondCol = 0
GO
-- Alter
ALTER TABLE TestTable
ALTER COLUMN SecondCol INT NOT NULL
GO
Use NSError to communicate failures rather than exceptions.
Quick points about NSError:
NSError allows for C style error codes (integers) to clearly identify the root cause and hopefully allow the error handler to overcome the error. You can wrap error codes from C libraries like SQLite in NSError instances very easily.
NSError also has the benefit of being an object and offers a way to describe the error in more detail with its userInfo dictionary member.
But best of all, NSError CANNOT be thrown so it encourages a more proactive approach to error handling, in contrast to other languages which simply throw the hot potato further and further up the call stack at which point it can only be reported to the user and not handled in any meaningful way (not if you believe in following OOP's biggest tenet of information hiding that is).
Reference Link: Reference
This will return TRUE
for #VALUE!
errors (ERROR.TYPE = 3) and FALSE
for anything else.
=IF(ISERROR(A1),ERROR.TYPE(A1)=3)
As far as I know, it's the main entry point to your node package (library) for npm. It's needed if your npm project becomes a node package (library) which can be installed via npm by others.
Let's say you have a library with a build/, dist/, or lib/ folder. In this folder, you got the following compiled file for your library:
-lib/
--bundle.js
Then in your package.json, you tell npm how to access the library (node package):
{
"name": "my-library-name",
"main": "lib/bundle.js",
...
}
After installing the node package with npm to your JS project, you can import functionalities from your bundled bundle.js file:
import { add, subtract } from 'my-library-name';
This holds also true when using Code Splitting (e.g. Webpack) for your library. For instance, this webpack.config.js makes use of code splitting the project into multiple bundles instead of one.
module.exports = {
entry: {
main: './src/index.js',
add: './src/add.js',
subtract: './src/subtract.js',
},
output: {
path: `${__dirname}/lib`,
filename: '[name].js',
library: 'my-library-name',
libraryTarget: 'umd',
},
...
}
Still, you would define one main entry point to your library in your package.json:
{
"name": "my-library-name",
"main": "lib/main.js",
...
}
Then when using the library, you can import your files from your main entry point:
import { add, subtract } from 'my-library-name';
However, you can also bypass the main entry point from the package.json and import the code splitted bundles:
import add from 'my-library-name/lib/add';
import subtract from 'my-library-name/lib/subtract';
After all, the main property in your package.json only points to your main entry point file of your library.
Here's the shortest solution, based on vh
. Please note that vh
is not supported in some older browsers.
CSS:
div {
width: 100%;
height: 100vh;
}
HTML:
<div>This div is fullscreen :)</div>
This will works to show your window in full screen
Note: For this to work, you need Query from http://code.jquery.com/jquery-2.1.1.min.js
Or make have javascript link like this.
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<div id="demo-element">
<span>Full Screen Mode Disabled</span>
<button id="go-button">Enable Full Screen</button>
</div>
<script>
function GoInFullscreen(element) {
if(element.requestFullscreen)
element.requestFullscreen();
else if(element.mozRequestFullScreen)
element.mozRequestFullScreen();
else if(element.webkitRequestFullscreen)
element.webkitRequestFullscreen();
else if(element.msRequestFullscreen)
element.msRequestFullscreen();
}
function GoOutFullscreen() {
if(document.exitFullscreen)
document.exitFullscreen();
else if(document.mozCancelFullScreen)
document.mozCancelFullScreen();
else if(document.webkitExitFullscreen)
document.webkitExitFullscreen();
else if(document.msExitFullscreen)
document.msExitFullscreen();
}
function IsFullScreenCurrently() {
var full_screen_element = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement || null;
if(full_screen_element === null)
return false;
else
return true;
}
$("#go-button").on('click', function() {
if(IsFullScreenCurrently())
GoOutFullscreen();
else
GoInFullscreen($("#demo-element").get(0));
});
$(document).on('fullscreenchange webkitfullscreenchange mozfullscreenchange MSFullscreenChange', function() {
if(IsFullScreenCurrently()) {
$("#demo-element span").text('Full Screen Mode Enabled');
$("#go-button").text('Disable Full Screen');
}
else {
$("#demo-element span").text('Full Screen Mode Disabled');
$("#go-button").text('Enable Full Screen');
}
});</script>
get_the_post_thumbnail function returns html not url of featured image. You should use get_post_thumbnail_id to get post id of featured image and then use wp_get_attachment_image_src to get url of featured image.
Try this:
<?php
$args = array( 'post_type' => 'product', 'posts_per_page' => 80, 'product_cat' => 'profiler', 'orderby' => 'rand' );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>
<div class="dvThumb col-xs-4 col-sm-3 col-md-3 profiler-select profiler<?php echo the_title(); ?>" data-profile="<?php echo $loop->post->ID; ?>">
<?php $featured_image = wp_get_attachment_image_src( get_post_thumbnail_id($loop->post->ID)); ?>
<?php if($featured_image) { ?>
<img src="<?php $featured_image[0]; ?>" data-id="<?php echo $loop->post->ID; ?>">
<?php } ?>
<p><?php the_title(); ?></p>
<span class="price"><?php echo $product->get_price_html(); ?></span>
</div>
<?php endwhile; ?>
Dowlnoad sqlite manager and install it from Here.Open the sqlite file using that browser.
I wrote a script which displays diff between two commits, works well on Ubuntu.
https://gist.github.com/jacobabrahamb4/a60624d6274ece7a0bd2d141b53407bc
#!/usr/bin/env python
import sys, subprocess, os
TOOLS = ['bcompare', 'meld']
def execute(command):
return subprocess.check_output(command)
def getTool():
for tool in TOOLS:
try:
out = execute(['which', tool]).strip()
if tool in out:
return tool
except subprocess.CalledProcessError:
pass
return None
def printUsageAndExit():
print 'Usage: python bdiff.py <project> <commit_one> <commit_two>'
print 'Example: python bdiff.py <project> 0 1'
print 'Example: python bdiff.py <project> fhejk7fe d78ewg9we'
print 'Example: python bdiff.py <project> 0 d78ewg9we'
sys.exit(0)
def getCommitIds(name, first, second):
commit1 = None
commit2 = None
try:
first_index = int(first) - 1
second_index = int(second) - 1
if int(first) < 0 or int(second) < 0:
print "Cannot handle negative values: "
sys.exit(0)
logs = execute(['git', '-C', name, 'log', '--oneline', '--reverse']).splitlines()
if first_index >= 0:
commit1 = logs[first_index].split(' ')[0]
if second_index >= 0:
commit2 = logs[second_index].split(' ')[0]
except ValueError:
if first is not '0':
commit1 = first
if second is not '0':
commit2 = second
return commit1, commit2
def validateCommitIds(name, commit1, commit2):
if not commit1 and not commit2:
print "Nothing to do, exit!"
return False
try:
if commit1:
execute(['git', '-C', name, 'cat-file', '-t', commit1])
if commit2:
execute(['git', '-C', name, 'cat-file', '-t', commit2])
except subprocess.CalledProcessError:
return False
return True
def cleanup(commit1, commit2):
execute(['rm', '-rf', '/tmp/'+(commit1 if commit1 else '0'), '/tmp/'+(commit2 if commit2 else '0')])
def checkoutCommit(name, commit):
if commit:
execute(['git', 'clone', name, '/tmp/'+commit])
execute(['git', '-C', '/tmp/'+commit, 'checkout', commit])
else:
execute(['mkdir', '/tmp/0'])
def compare(tool, commit1, commit2):
execute([tool, '/tmp/'+(commit1 if commit1 else '0'), '/tmp/'+(commit2 if commit2 else '0')])
if __name__=='__main__':
tool = getTool()
if not tool:
print "No GUI diff tools, install bcompare or meld"
sys.exit(0)
if len(sys.argv) is not 4:
printUsageAndExit()
name, first, second = None, 0, 0
try:
name, first, second = sys.argv[1], sys.argv[2], sys.argv[3]
except IndexError:
printUsageAndExit()
commit1, commit2 = getCommitIds(name, first, second)
if validateCommitIds(name, commit1, commit2) is False:
sys.exit(0)
cleanup(commit1, commit2)
try:
checkoutCommit(name, commit1)
checkoutCommit(name, commit2)
compare(tool, commit1, commit2)
except KeyboardInterrupt:
pass
finally:
cleanup(commit1, commit2)
sys.exit(0)
Because you have a very simple CORS policy (Allow all requests from XXX domain), you don't need to make it so complicated. Try doing the following first (A very basic implementation of CORS).
If you haven't already, install the CORS nuget package.
Install-Package Microsoft.AspNetCore.Cors
In the ConfigureServices method of your startup.cs, add the CORS services.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(); // Make sure you call this previous to AddMvc
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
Then in your Configure method of your startup.cs, add the following :
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// Make sure you call this before calling app.UseMvc()
app.UseCors(
options => options.WithOrigins("http://example.com").AllowAnyMethod()
);
app.UseMvc();
}
Now give it a go. Policies are for when you want different policies for different actions (e.g. different hosts or different headers). For your simple example you really don't need it. Start with this simple example and tweak as you need to from there.
Further reading : http://dotnetcoretutorials.com/2017/01/03/enabling-cors-asp-net-core/
I recommend using justext library:
https://github.com/miso-belica/jusText
Usage: Python2:
import requests
import justext
response = requests.get("http://planet.python.org/")
paragraphs = justext.justext(response.content, justext.get_stoplist("English"))
for paragraph in paragraphs:
print paragraph.text
Python3:
import requests
import justext
response = requests.get("http://bbc.com/")
paragraphs = justext.justext(response.content, justext.get_stoplist("English"))
for paragraph in paragraphs:
print (paragraph.text)
Simple to me is like this:
$Time = Get-Date -Format "yyyy-MM-dd HH:mm K"
$Description = "Done on time"
"$Time,$Description"|Add-Content -Path $File # Keep no space between content variables
If you have a lot of columns, then create a variable like $NewRow
like:
$Time = Get-Date -Format "yyyy-MM-dd HH:mm K"
$Description = "Done on time"
$NewRow = "$Time,$Description" # No space between variables, just use comma(,).
$NewRow | Add-Content -Path $File # Keep no space between content variables
Please note the difference between Set-Content
(overwrites the existing contents) and Add-Content
(appends to the existing contents) of the file.
--save, -g and changing package.json scripts did not work for me. Here's what did: running npm start
(or using npx nodemon
) within the command line. I use visual studio code terminal.
When it is successful you will see this message:
[nodemon] 1.18.9
[nodemon] to restart at any time, enter rs
[nodemon] watching: .
[nodemon] starting node app.js
Good luck!
In ASPNET Core you do it in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<BloggingContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("BloggingDatabase")));
}
where your connection is defined in appsettings.json
{
"ConnectionStrings": {
"BloggingDatabase": "..."
},
}
Example from MS docs
I think the traditional way is flexible and fairly easy to understand:
Markup
<div class="flex-grid">
<div class="col-4">.col-4</div>
<div class="col-4">.col-4</div>
<div class="col-4">.col-4</div>
<div class="col-4">.col-4</div>
<div class="col-4">.col-4</div>
<div class="col-4">.col-4</div>
<div class="col-3">.col-3</div>
<div class="col-9">.col-9</div>
<div class="col-6">.col-6</div>
<div class="col-6">.col-6</div>
</div>
Create grid.css file:
.flex-grid {
display: flex;
flex-flow: wrap;
}
.col-1 {flex: 0 0 8.3333%}
.col-2 {flex: 0 0 16.6666%}
.col-3 {flex: 0 0 25%}
.col-4 {flex: 0 0 33.3333%}
.col-5 {flex: 0 0 41.6666%}
.col-6 {flex: 0 0 50%}
.col-7 {flex: 0 0 58.3333%}
.col-8 {flex: 0 0 66.6666%}
.col-9 {flex: 0 0 75%}
.col-10 {flex: 0 0 83.3333%}
.col-11 {flex: 0 0 91.6666%}
.col-12 {flex: 0 0 100%}
[class*="col-"] {
margin: 0 0 10px 0;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
@media (max-width: 400px) {
.flex-grid {
display: block;
}
}
I've created an example (jsfiddle)
Try to resize the window under 400px, it's responsive!!
You can use the ThenBy and ThenByDescending extension methods:
foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)
For TextView and it's descendants (e.g., Button) you can get the display size from the WindowManager and then set the TextView height to be some fraction of it:
Button btn = new Button (this);
android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
btn.setHeight((int)(display.getHeight()*0.68));
In Python 3.6, It can be done as:-
if (len(dict_1)==len(dict_2):
for i in dict_1.items():
ret=bool(i in dict_2.items())
ret variable will be true if all the items of dict_1 in present in dict_2
You can make a symbolic link of your module to the standard path, so depmod will see it and you'll be able load it as any other module.
sudo ln -s /path/to/module.ko /lib/modules/`uname -r`
sudo depmod -a
sudo modprobe module
If you add the module name to /etc/modules it will be loaded any time you boot.
Anyway I think that the proper configuration is to copy the module to the standard paths.
The problem with calling async void is that
you don’t even get the task back. You have no way of knowing when the function’s task has completed. —— Crash course in async and await | The Old New Thing
Here are the three ways to call an async function:
async Task<T> SomethingAsync() { ... return t; } async Task SomethingAsync() { ... } async void SomethingAsync() { ... }
In all the cases, the function is transformed into a chain of tasks. The difference is what the function returns.
In the first case, the function returns a task that eventually produces the t.
In the second case, the function returns a task which has no product, but you can still await on it to know when it has run to completion.
The third case is the nasty one. The third case is like the second case, except that you don't even get the task back. You have no way of knowing when the function's task has completed.
The async void case is a "fire and forget": You start the task chain, but you don't care about when it's finished. When the function returns, all you know is that everything up to the first await has executed. Everything after the first await will run at some unspecified point in the future that you have no access to.
After spending lot of time I have solved the problem
string strDate = PreocessDate(data);
string[] dateString = strDate.Split('/');
DateTime enter_date = Convert.ToDateTime(dateString[1]+"/"+dateString[0]+"/"+dateString[2]);