Short answer: Don't do it.
Redesign your app so that it can run in both portrait and landscape mode. There is no such thing as a UI that can't be designed to work in both portrait and landscape; only lazy or unimaginative developers.
The reason why is rather simple. You want your app to be usable by as wide an audience as possible on as many different devices as possible. By forcing a particular screen orientation, you prevent your app from running (usably) on devices that don't support that orientation and you frustrate and alienate potential customers who prefer a different orientation.
Example: You design your app to force portrait mode. A customer downloads the app on a 2-in-1 device which they use predominantly in landscape mode.
Consequence 1: Your app is unusable, or your customer is forced to undock their device, rotate it, and use it in an orientation that is not familiar or comfortable for them.
Consequence 2: The customer gets frustrated by your app's non-intuitive design and finds an alternative or ditches the app entirely.
I'm fighting with this with an app right now and as a consumer and a developer, I hate it. As useful as the app is, as fantastic as the features are that it offers, I absolutely hate the app because it forces me to use an orientation that is counter to every other way that I use my device.
You don't want your customers to hate your app.
I know this doesn't directly answer the question, so I want to explain it in a little more detail for those who are curious.
There is a tendency for developers to be really good at writing code and really terrible at design. This question, though it sounds like a code question and the asker certainly feels like it's a code question, is really a design question.
The question really is "Should I lock the screen orientation in my app?" The asker chose to design the UI to function and look good only in portrait mode. I suspect it was to save development time or because the app's workflow is particularly conducive to a portrait layout (common for mobile games). But those reasons neglect all the real important factors that motivate proper design.
Customer engagement - you want your customers to feel pulled into your app, not pushed out of it. The app should transition smoothly from whatever your customer was doing prior to opening your app. (This is the reason most platforms have consistent design principles, so most apps look more or less alike though they don't have to.)
Customer response - you want your customers to react positively to your app. They should enjoy using it. Even if it's a payroll app for work, it should be a pleasure for them to open it and clock in. The app should save your customers time and reduce frustration over alternatives. (Apps that annoy users build resentment against your app which grows into resentment against your brand.)
Customer conversion - you want your customers to be able to quickly and easily move from browsing to interacting. This is the ultimate goal of any app, to convert impressions into revenue. (Apps that don't generate revenue are a waste of your time to build, from a business perspective.)
A poorly designed UI reduces customer engagement and response which ultimately results in lower revenue. In a mobile-centric world (and particularly on the subject of portrait/landscape display modes), this explains why responsive web design is such a big deal. Walmart Canada introduced responsive design on their website in November 2013 and saw a 20% increase in customer conversion. O'Neill Clothing implemented responsive web design and revenue from customers using iOS devices increased 101.25%, and 591.42% from customers using Android devices.
There is also a tendency for developers to focus intently on implementing a particular solution (such as locking display orientation), and most of the developers on this site will be all too glad to help implement that solution, without questioning whether that is even the best solution to the problem.
Locking your screen orientation is the UI design equivalent of implementing a do-while loop. Are you really sure you want to do it that way, or is there a better alternative?
Don't force your app into a single display mode. Invest the extra time and effort to make it responsive.
I install go launcher on mine, (Windows 8)=> preferences => Screens => Screen orientation => vertical (disable QWE keyboard)
Swift 3.0 version of Tommy's answer
let imageToDisplay = UIImage.init(cgImage: originalImage.cgImage!, scale: originalImage.scale, orientation: UIImageOrientation.up)
In some devices void onConfigurationChanged()
may crash. User will use this code to get current screen orientation.
public int getScreenOrientation()
{
Display getOrient = getActivity().getWindowManager().getDefaultDisplay();
int orientation = Configuration.ORIENTATION_UNDEFINED;
if(getOrient.getWidth()==getOrient.getHeight()){
orientation = Configuration.ORIENTATION_SQUARE;
} else{
if(getOrient.getWidth() < getOrient.getHeight()){
orientation = Configuration.ORIENTATION_PORTRAIT;
}else {
orientation = Configuration.ORIENTATION_LANDSCAPE;
}
}
return orientation;
}
And use
if (orientation==1) // 1 for Configuration.ORIENTATION_PORTRAIT
{ // 2 for Configuration.ORIENTATION_LANDSCAPE
//your code // 0 for Configuration.ORIENTATION_SQUARE
}
Old post I know. Whatever the orientation may be or is swapped etc. I designed this function that is used to set the device in the right orientation without the need to know how the portrait and landscape features are organised on the device.
private void initActivityScreenOrientPortrait()
{
// Avoid screen rotations (use the manifests android:screenOrientation setting)
// Set this to nosensor or potrait
// Set window fullscreen
this.activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
DisplayMetrics metrics = new DisplayMetrics();
this.activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
// Test if it is VISUAL in portrait mode by simply checking it's size
boolean bIsVisualPortrait = ( metrics.heightPixels >= metrics.widthPixels );
if( !bIsVisualPortrait )
{
// Swap the orientation to match the VISUAL portrait mode
if( this.activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT )
{ this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); }
else { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ); }
}
else { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); }
}
Works like a charm!
For my case handling UIDeviceOrientationDidChangeNotification
was not good solution as it is called more frequent and UIDeviceOrientation
is not always equal to UIInterfaceOrientation
because of (FaceDown, FaceUp).
I handle it using UIApplicationDidChangeStatusBarOrientationNotification
:
//To add the notification
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didChangeOrientation:)
//to remove the
[[NSNotificationCenter defaultCenter]removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
...
- (void)didChangeOrientation:(NSNotification *)notification
{
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if (UIInterfaceOrientationIsLandscape(orientation)) {
NSLog(@"Landscape");
}
else {
NSLog(@"Portrait");
}
}
Using Android Studio 3.4.1, it no longer creates layout-land
folder. It will create a folder and put two layout files together.
Screen.lockOrientation()
solves this problem, though support is less than universal at the time (April 2017):
https://www.w3.org/TR/screen-orientation/
https://developer.mozilla.org/en-US/docs/Web/API/Screen.lockOrientation
From other member and my problem:
Camera Rotation issue depend on different Devices and certain Version.
Version 1.6: to fix the Rotation Issue, and it is good for most of devices
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
{
p.set("orientation", "portrait");
p.set("rotation",90);
}
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
{
p.set("orientation", "landscape");
p.set("rotation", 90);
}
Version 2.1: depend on kind of devices, for example, Cannt fix the issue with XPeria X10, but it is good for X8, and Mini
Camera.Parameters parameters = camera.getParameters();
parameters.set("orientation", "portrait");
camera.setParameters(parameters);
Version 2.2: not for all devices
camera.setDisplayOrientation(90);
I had a similar problem.
When I entered
<activity android:name="MyActivity" android:screenOrientation="landscape"></activity>
In the manifest file this caused that activity to display in landscape. However when I returned to previous activities they displayed in lanscape even though they were set to portrait. However by adding
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
immediately after the OnCreate section of the target activity resolved the problem. So I now use both methods.
May be it will helpful:
<Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="160" Margin="10,55,0,0" VerticalAlignment="Top" Width="492"/>
Found a very easily implemented fix. Set the focus to a text element that has a font size of 50px on completion of the form. It does not seem to work if the text element is hidden but hiding this element is easily done by setting the elements color properties to have no opacity.
You can group your specific layout under the correct folder structure as follows.
layout-land-target_version
ie
layout-land-19 // target KitKat
likewise you can create your layouts.
Hope this will help you
*nix provides a nice little command which makes our lives a lot easier.
GET:
with JSON:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource
with XML:
curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource
POST:
For posting data:
curl --data "param1=value1¶m2=value2" http://hostname/resource
For file upload:
curl --form "[email protected]" http://hostname/resource
RESTful HTTP Post:
curl -X POST -d @filename http://hostname/resource
For logging into a site (auth):
curl -d "username=admin&password=admin&submit=Login" --dump-header headers http://localhost/Login
curl -L -b headers http://localhost/
Pretty-printing the curl results:
For JSON:
If you use npm
and nodejs
, you can install json
package by running this command:
npm install -g json
Usage:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | json
If you use pip
and python
, you can install pjson
package by running this command:
pip install pjson
Usage:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | pjson
If you use Python 2.6+, json tool is bundled within.
Usage:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | python -m json.tool
If you use gem
and ruby
, you can install colorful_json
package by running this command:
gem install colorful_json
Usage:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | cjson
If you use apt-get
(aptitude package manager of your Linux distro), you can install yajl-tools
package by running this command:
sudo apt-get install yajl-tools
Usage:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | json_reformat
For XML:
If you use *nix with Debian/Gnome envrionment, install libxml2-utils
:
sudo apt-get install libxml2-utils
Usage:
curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | xmllint --format -
or install tidy
:
sudo apt-get install tidy
Usage:
curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | tidy -xml -i -
Saving the curl response to a file
curl http://hostname/resource >> /path/to/your/file
or
curl http://hostname/resource -o /path/to/your/file
For detailed description of the curl command, hit:
man curl
For details about options/switches of the curl command, hit:
curl -h
Or use diff
method of numpy:
import numpy as np
def allthesame(l):
return np.all(np.diff(l)==0)
And to call:
print(allthesame([1,1,1]))
Output:
True
Update to MySQL 8.0.16 to use checks
:
As of MySQL 8.0.16, CREATE TABLE permits the core features of table and column CHECK constraints, for all storage engines. CREATE TABLE permits the following CHECK constraint syntax, for both table constraints and column constraints
If you sent a pull request on a repository where you don't have the rights to close it, you can delete the branch from where the pull request originated. That will cancel the pull request.
Checking the install state for the product via MsiQueryProductState is pretty much equivalent to checking the registry directly, but you still need the GUID for the ProductCode.
As mentioned elsewhere, one drawback with these approaches is that each update has its own ProductCode!
Thankfully, MSI provides an UpgradeCode which identifies a 'family' of products. You can use orca to open up one of the MSIs to extract this information. For example, the UpgradeCode for VS2015's redistributable is {65E5BD06-6392-3027-8C26-853107D3CF1A}
You can use MsiEnumRelatedProducts to get all Product IDs for that UpgradeCode. In practice, since each redist update replaces the previous one, this will only yield one ProductCode - such as {B5FC62F5-A367-37A5-9FD2-A6E137C0096F}
for VS2015 Update 2 x86.
Regardless, you can then check the version via MsiGetProductInfo(productCode, INSTALLPROPERTY_VERSIONSTRING, ...) or similar functions to compare with the version you want, eg to check for an equivalent or later version.
Note that within a C++ application, you can also use _VC_CRT_MAJOR_VERSION
, _VC_CRT_MINOR_VERSION
, _VC_CRT_BUILD_VERSION
if you #include <crtversion.h>
-- this way you can determine calculate the CRT version that your binary was built with.
If script execution order is not the issue, another possible cause of the problem is that the element is not being selected properly:
getElementById
requires the passed string to be the ID verbatim, and nothing else. If you prefix the passed string with a #
, and the ID does not start with a #
, nothing will be selected:
<div id="foo"></div>
// Error, selected element will be null:
document.getElementById('#foo')
// Fix:
document.getElementById('foo')
Similarly, for getElementsByClassName
, don't prefix the passed string with a .
:
<div class="bar"></div>
// Error, selected element will be undefined:
document.getElementsByClassName('.bar')[0]
// Fix:
document.getElementsByClassName('bar')[0]
With querySelector, querySelectorAll, and jQuery, to match an element with a particular class name, put a .
directly before the class. Similarly, to match an element with a particular ID, put a #
directly before the ID:
<div class="baz"></div>
// Error, selected element will be null:
document.querySelector('baz')
$('baz')
// Fix:
document.querySelector('.baz')
$('.baz')
The rules here are, in most cases, identical to those for CSS selectors, and can be seen in detail here.
To match an element which has two or more attributes (like two class names, or a class name and a data-
attribute), put the selectors for each attribute next to each other in the selector string, without a space separating them (because a space indicates the descendant selector). For example, to select:
<div class="foo bar"></div>
use the query string .foo.bar
. To select
<div class="foo" data-bar="someData"></div>
use the query string .foo[data-bar="someData"]
. To select the <span>
below:
<div class="parent">
<span data-username="bob"></span>
</div>
use div.parent > span[data-username="bob"]
.
Capitalization and spelling does matter for all of the above. If the capitalization is different, or the spelling is different, the element will not be selected:
<div class="result"></div>
// Error, selected element will be null:
document.querySelector('.results')
$('.Result')
// Fix:
document.querySelector('.result')
$('.result')
You also need to make sure the methods have the proper capitalization and spelling. Use one of:
$(selector)
document.querySelector
document.querySelectorAll
document.getElementsByClassName
document.getElementsByTagName
document.getElementById
Any other spelling or capitalization will not work. For example, document.getElementByClassName
will throw an error.
Make sure you pass a string to these selector methods. If you pass something that isn't a string to querySelector
, getElementById
, etc, it almost certainly won't work.
If the HTML attributes on elements you want to select are surrounded by quotes, they must be plain straight quotes (either single or double); curly quotes like ‘
or ”
will not work if you're trying to select by ID, class, or attribute.
I really recommend using some sort of library, but you asked for it, you get it:
var p = document.querySelector('p'); // element to make resizable
p.addEventListener('click', function init() {
p.removeEventListener('click', init, false);
p.className = p.className + ' resizable';
var resizer = document.createElement('div');
resizer.className = 'resizer';
p.appendChild(resizer);
resizer.addEventListener('mousedown', initDrag, false);
}, false);
var startX, startY, startWidth, startHeight;
function initDrag(e) {
startX = e.clientX;
startY = e.clientY;
startWidth = parseInt(document.defaultView.getComputedStyle(p).width, 10);
startHeight = parseInt(document.defaultView.getComputedStyle(p).height, 10);
document.documentElement.addEventListener('mousemove', doDrag, false);
document.documentElement.addEventListener('mouseup', stopDrag, false);
}
function doDrag(e) {
p.style.width = (startWidth + e.clientX - startX) + 'px';
p.style.height = (startHeight + e.clientY - startY) + 'px';
}
function stopDrag(e) {
document.documentElement.removeEventListener('mousemove', doDrag, false);
document.documentElement.removeEventListener('mouseup', stopDrag, false);
}
Remember that this may not run in all browsers (tested only in Firefox, definitely not working in IE <9).
If you want to get the data exactly like what you get by Writer
(for example ignoring fields with persist:false
config), use the following code (Note: I tested it in Ext 5.1)
var arr = [];
this.store.each(function (record) {
arr.push(this.store.getProxy().getWriter().getRecordData(record))
});
you can also use vmware-mount from VMwares VDDK (Virtual Disk Development Kit): http://communities.vmware.com/community/vmtn/developer/forums/vddk
this allows you to mount VMDK files as disk drives in windows or linux
Imagine it like this: When your sub-class inherits properties from a super-class, they don't magically appear. You still have to construct the object. So, you call the base constructor. Imagine if you class inherits a variable, which your super-class constructor initializes to an important value. If we didn't do this, your code could fail because the variable wasn't initialized.
returning an array of pointers pointing to starting elements of all rows is the only decent way of returning 2d array.
Yes, your conclusion is correct. socket.recv
is a blocking call.
socket.recv(1024)
will read at most 1024 bytes, blocking if no data is waiting to be read. If you don't read all data, an other call to socket.recv
won't block.
socket.recv
will also end with an empty string if the connection is closed or there is an error.
If you want a non-blocking socket, you can use the select module (a bit more complicated than just using sockets) or you can use socket.setblocking
.
I had issues with socket.setblocking
in the past, but feel free to try it if you want.
I'm hoping someone can provide some concrete examples of best use cases for each.
Use Retrofit if you are communicating with a Web service. Use the peer library Picasso if you are downloading images. Use OkHTTP if you need to do HTTP operations that lie outside of Retrofit/Picasso.
Volley roughly competes with Retrofit + Picasso. On the plus side, it is one library. On the minus side, it is one undocumented, an unsupported, "throw the code over the wall and do an I|O presentation on it" library.
EDIT - Volley is now officially supported by Google. Kindly refer Google Developer Guide
From what I've read, seems like OkHTTP is the most robust of the 3
Retrofit uses OkHTTP automatically if available. There is a Gist from Jake Wharton that connects Volley to OkHTTP.
and could handle the requirements of this project (mentioned above).
Probably you will use none of them for "streaming download of audio and video", by the conventional definition of "streaming". Instead, Android's media framework will handle those HTTP requests for you.
That being said, if you are going to attempt to do your own HTTP-based streaming, OkHTTP should handle that scenario; I don't recall how well Volley would handle that scenario. Neither Retrofit nor Picasso are designed for that.
static void Main(string[] args)
{
foreach (int value in Enum.GetValues(typeof(DaysOfWeek)))
{
Console.WriteLine(((DaysOfWeek)value).ToString());
}
foreach (string value in Enum.GetNames(typeof(DaysOfWeek)))
{
Console.WriteLine(value);
}
Console.ReadLine();
}
public enum DaysOfWeek
{
monday,
tuesday,
wednesday
}
Heads up, you might need to restart LAMP, Apache or whatever your using to make this take affect. Racked our brains for a while on this one, seemed to make no affect until services were restarted, presumably because the website was caching.
Your arguments are in the wrong order. The connection comes first according to the docs
<?php
require("constants.php");
// 1. Create a database connection
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$connection) {
error_log("Failed to connect to MySQL: " . mysqli_error($connection));
die('Internal server error');
}
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
error_log("Database selection failed: " . mysqli_error($connection));
die('Internal server error');
}
?>
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
}
Yes, it is extremely useful in browsers that support it, but the "limiting" is as a convenience to users (so they are not overwhelmed with irrelevant files) rather than as a way to prevent them from uploading things you don't want them uploading.
It is supported in
Here is a list of content types you can use with it, followed by the corresponding file extensions (though of course you can use any file extension):
application/envoy evy
application/fractals fif
application/futuresplash spl
application/hta hta
application/internet-property-stream acx
application/mac-binhex40 hqx
application/msword doc
application/msword dot
application/octet-stream *
application/octet-stream bin
application/octet-stream class
application/octet-stream dms
application/octet-stream exe
application/octet-stream lha
application/octet-stream lzh
application/oda oda
application/olescript axs
application/pdf pdf
application/pics-rules prf
application/pkcs10 p10
application/pkix-crl crl
application/postscript ai
application/postscript eps
application/postscript ps
application/rtf rtf
application/set-payment-initiation setpay
application/set-registration-initiation setreg
application/vnd.ms-excel xla
application/vnd.ms-excel xlc
application/vnd.ms-excel xlm
application/vnd.ms-excel xls
application/vnd.ms-excel xlt
application/vnd.ms-excel xlw
application/vnd.ms-outlook msg
application/vnd.ms-pkicertstore sst
application/vnd.ms-pkiseccat cat
application/vnd.ms-pkistl stl
application/vnd.ms-powerpoint pot
application/vnd.ms-powerpoint pps
application/vnd.ms-powerpoint ppt
application/vnd.ms-project mpp
application/vnd.ms-works wcm
application/vnd.ms-works wdb
application/vnd.ms-works wks
application/vnd.ms-works wps
application/winhlp hlp
application/x-bcpio bcpio
application/x-cdf cdf
application/x-compress z
application/x-compressed tgz
application/x-cpio cpio
application/x-csh csh
application/x-director dcr
application/x-director dir
application/x-director dxr
application/x-dvi dvi
application/x-gtar gtar
application/x-gzip gz
application/x-hdf hdf
application/x-internet-signup ins
application/x-internet-signup isp
application/x-iphone iii
application/x-javascript js
application/x-latex latex
application/x-msaccess mdb
application/x-mscardfile crd
application/x-msclip clp
application/x-msdownload dll
application/x-msmediaview m13
application/x-msmediaview m14
application/x-msmediaview mvb
application/x-msmetafile wmf
application/x-msmoney mny
application/x-mspublisher pub
application/x-msschedule scd
application/x-msterminal trm
application/x-mswrite wri
application/x-netcdf cdf
application/x-netcdf nc
application/x-perfmon pma
application/x-perfmon pmc
application/x-perfmon pml
application/x-perfmon pmr
application/x-perfmon pmw
application/x-pkcs12 p12
application/x-pkcs12 pfx
application/x-pkcs7-certificates p7b
application/x-pkcs7-certificates spc
application/x-pkcs7-certreqresp p7r
application/x-pkcs7-mime p7c
application/x-pkcs7-mime p7m
application/x-pkcs7-signature p7s
application/x-sh sh
application/x-shar shar
application/x-shockwave-flash swf
application/x-stuffit sit
application/x-sv4cpio sv4cpio
application/x-sv4crc sv4crc
application/x-tar tar
application/x-tcl tcl
application/x-tex tex
application/x-texinfo texi
application/x-texinfo texinfo
application/x-troff roff
application/x-troff t
application/x-troff tr
application/x-troff-man man
application/x-troff-me me
application/x-troff-ms ms
application/x-ustar ustar
application/x-wais-source src
application/x-x509-ca-cert cer
application/x-x509-ca-cert crt
application/x-x509-ca-cert der
application/ynd.ms-pkipko pko
application/zip zip
audio/basic au
audio/basic snd
audio/mid mid
audio/mid rmi
audio/mpeg mp3
audio/x-aiff aif
audio/x-aiff aifc
audio/x-aiff aiff
audio/x-mpegurl m3u
audio/x-pn-realaudio ra
audio/x-pn-realaudio ram
audio/x-wav wav
image/bmp bmp
image/cis-cod cod
image/gif gif
image/ief ief
image/jpeg jpe
image/jpeg jpeg
image/jpeg jpg
image/pipeg jfif
image/svg+xml svg
image/tiff tif
image/tiff tiff
image/x-cmu-raster ras
image/x-cmx cmx
image/x-icon ico
image/x-portable-anymap pnm
image/x-portable-bitmap pbm
image/x-portable-graymap pgm
image/x-portable-pixmap ppm
image/x-rgb rgb
image/x-xbitmap xbm
image/x-xpixmap xpm
image/x-xwindowdump xwd
message/rfc822 mht
message/rfc822 mhtml
message/rfc822 nws
text/css css
text/h323 323
text/html htm
text/html html
text/html stm
text/iuls uls
text/plain bas
text/plain c
text/plain h
text/plain txt
text/richtext rtx
text/scriptlet sct
text/tab-separated-values tsv
text/webviewhtml htt
text/x-component htc
text/x-setext etx
text/x-vcard vcf
video/mpeg mp2
video/mpeg mpa
video/mpeg mpe
video/mpeg mpeg
video/mpeg mpg
video/mpeg mpv2
video/quicktime mov
video/quicktime qt
video/x-la-asf lsf
video/x-la-asf lsx
video/x-ms-asf asf
video/x-ms-asf asr
video/x-ms-asf asx
video/x-msvideo avi
video/x-sgi-movie movie
x-world/x-vrml flr
x-world/x-vrml vrml
x-world/x-vrml wrl
x-world/x-vrml wrz
x-world/x-vrml xaf
x-world/x-vrml xof
You need to correctly separate static data from instance data. In your code, onLoan
and setLoanItem()
are instance members. If you want to reference/call them you must do so via an instance. So you either want
public void loanItem() {
this.media.setLoanItem("Yes");
}
or
public void loanItem(Media object) {
object.setLoanItem("Yes");
}
depending on how you want to pass that instance around.
> I have a .key file which is PEM formatted private key file.
> ...
> Here's some asn1parse of the .key file...
That it appears OK with asn1parse
leads me to believe its not PEM encoded.
Is there anything more I can try?
Because it appears to be ASN.1, try:
$ openssl rsa -in server.key -inform DER -modulus -noout
Notice the -inform DER
to switch between encodings.
list multiplication works.
>>> [0] * 10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Replacing fragments in a viewpager is quite involved but is very possible and can look super slick. First, you need to let the viewpager itself handle the removing and adding of the fragments. What is happening is when you replace the fragment inside of SearchFragment, your viewpager retains its fragment views. So you end up with a blank page because the SearchFragment gets removed when you try to replace it.
The solution is to create a listener inside of your viewpager that will handle changes made outside of it so first add this code to the bottom of your adapter.
public interface nextFragmentListener {
public void fragment0Changed(String newFragmentIdentification);
}
Then you need to create a private class in your viewpager that becomes a listener for when you want to change your fragment. For example you could add something like this. Notice that it implements the interface that was just created. So whenever you call this method, it will run the code inside of the class below.
private final class fragmentChangeListener implements nextFragmentListener {
@Override
public void fragment0Changed(String fragment) {
//I will explain the purpose of fragment0 in a moment
fragment0 = fragment;
manager.beginTransaction().remove(fragAt0).commit();
switch (fragment){
case "searchFragment":
fragAt0 = SearchFragment.newInstance(listener);
break;
case "searchResultFragment":
fragAt0 = Fragment_Table.newInstance(listener);
break;
}
notifyDataSetChanged();
}
There are two main things to point out here:
Notice the listeners that are placed in the 'newInstance(listener)constructor. These are how you will callfragment0Changed(String newFragmentIdentification)`. The following code shows how you create the listener inside of your fragment.
static nextFragmentListener listenerSearch;
public static Fragment_Journals newInstance(nextFragmentListener listener){
listenerSearch = listener;
return new Fragment_Journals();
}
You could call the change inside of your onPostExecute
private class SearchAsyncTask extends AsyncTask<Void, Void, Void>{
protected Void doInBackground(Void... params){
.
.//some more operation
.
}
protected void onPostExecute(Void param){
listenerSearch.fragment0Changed("searchResultFragment");
}
}
This would trigger the code inside of your viewpager to switch your fragment at position zero fragAt0 to become a new searchResultFragment. There are two more small pieces you would need to add to the viewpager before it became functional.
One would be in the getItem override method of the viewpager.
@Override
public Fragment getItem(int index) {
switch (index) {
case 0:
//this is where it will "remember" which fragment you have just selected. the key is to set a static String fragment at the top of your page that will hold the position that you had just selected.
if(fragAt0 == null){
switch(fragment0){
case "searchFragment":
fragAt0 = FragmentSearch.newInstance(listener);
break;
case "searchResultsFragment":
fragAt0 = FragmentSearchResults.newInstance(listener);
break;
}
}
return fragAt0;
case 1:
// Games fragment activity
return new CreateFragment();
}
Now without this final piece you would still get a blank page. Kind of lame, but it is an essential part of the viewPager. You must override the getItemPosition method of the viewpager. Ordinarily this method will return POSITION_UNCHANGED which tells the viewpager to keep everything the same and so getItem will never get called to place the new fragment on the page. Here's an example of something you could do
public int getItemPosition(Object object)
{
//object is the current fragment displayed at position 0.
if(object instanceof SearchFragment && fragAt0 instanceof SearchResultFragment){
return POSITION_NONE;
//this condition is for when you press back
}else if{(object instanceof SearchResultFragment && fragAt0 instanceof SearchFragment){
return POSITION_NONE;
}
return POSITION_UNCHANGED
}
Like I said, the code gets very involved, but you basically have to create a custom adapter for your situation. The things I mentioned will make it possible to change the fragment. It will likely take a long time to soak everything in so I would be patient, but it will all make sense. It is totally worth taking the time because it can make a really slick looking application.
Here's the nugget for handling the back button. You put this inside your MainActivity
public void onBackPressed() {
if(mViewPager.getCurrentItem() == 0) {
if(pagerAdapter.getItem(0) instanceof FragmentSearchResults){
((Fragment_Table) pagerAdapter.getItem(0)).backPressed();
}else if (pagerAdapter.getItem(0) instanceof FragmentSearch) {
finish();
}
}
You will need to create a method called backPressed() inside of FragmentSearchResults that calls fragment0changed. This in tandem with the code I showed before will handle pressing the back button. Good luck with your code to change the viewpager. It takes a lot of work, and as far as I have found, there aren't any quick adaptations. Like I said, you are basically creating a custom viewpager adapter, and letting it handle all of the necessary changes using listeners
Try this:
var t = this.Controls.OfType<TextBox>().AsEnumerable<TextBox>();
foreach (TextBox item in t)
{
item.Text = "";
}
This should technically be achievable using window.location.reload()
:
HTML:
<button (click)="refresh()">Refresh</button>
TS:
refresh(): void {
window.location.reload();
}
Update:
Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload()
is executed.
I don't believe MySQL supports dynamic sql. You can do "prepared" statements which is similar, but different.
Here is an example:
mysql> PREPARE stmt FROM
-> 'select count(*)
-> from information_schema.schemata
-> where schema_name = ? or schema_name = ?'
;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> EXECUTE stmt
-> USING @schema1,@schema2
+----------+
| count(*) |
+----------+
| 2 |
+----------+
1 row in set (0.00 sec)
mysql> DEALLOCATE PREPARE stmt;
The prepared statements are often used to see an execution plan for a given query. Since they are executed with the execute command and the sql can be assigned to a variable you can approximate the some of the same behavior as dynamic sql.
Here is a good link about this:
Don't forget to deallocate the stmt
using the last line!
Good Luck!
You can use:
DATEDIFF ( day , startdate , enddate ) = 0
Or:
DATEPART( day, startdate ) = DATEPART(day, enddate)
AND
DATEPART( month, startdate ) = DATEPART(month, enddate)
AND
DATEPART( year, startdate ) = DATEPART(year, enddate)
Or:
CONVERT(DATETIME,CONVERT(VARCHAR(12), startdate, 105)) = CONVERT(DATETIME,CONVERT(VARCHAR(12), enddate, 105))
var _login = function (loginData) {_x000D_
_x000D_
var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password;_x000D_
_x000D_
var deferred = $q.defer();_x000D_
_x000D_
$http.post(serviceBase + 'token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (response) {_x000D_
_x000D_
localStorageService.set('authorizationData', { token: response.access_token, userName: loginData.userName });_x000D_
_x000D_
_authentication.isAuth = true;_x000D_
_authentication.userName = loginData.userName;_x000D_
_x000D_
deferred.resolve(response);_x000D_
_x000D_
}).error(function (err, status) {_x000D_
_logOut();_x000D_
deferred.reject(err);_x000D_
});_x000D_
_x000D_
return deferred.promise;_x000D_
_x000D_
};_x000D_
_x000D_
EDIT: Even though this answer is marked as the correct answer (in 2013), currently, as answered by @user2511630 below, you can drag-n-drop apk files directly into the emulator to install them.
Original Answer:
You can install .apk files to emulator regardless of what you are using (Eclipse or Android Studio)
here's what I always do: (For full beginners)
1- Run the emulator, and wait until it's completely started.
2- Go to your sdk installation folder then go to platform-tools (you should see an executable called adb.exe)
3- create a new file and call it run.bat, edit the file with notepad and write CMD in it and save it.
4- copy your desired apk to the same folder
5- now open run.bat and write adb install "your_apk_file.apk"
6- wait until the installation is complete
7- voila your apk is installed to your emulator.
Note: to re-install the application if it already existe use adb install -r "your_apk_file.apk"
sorry for the detailed instruction as I said for full beginners
Hope this help.
Regards,
Tarek
You can also get BLOB object directly from XMLHttpRequest. Setting responseType to blob makes the trick. Here is my code:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost/image.jpg");
xhr.responseType = "blob";
xhr.onload = response;
xhr.send();
And the response function looks like this:
function response(e) {
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(this.response);
document.querySelector("#image").src = imageUrl;
}
We just have to make an empty image element in HTML:
<img id="image"/>
I don't think there's a way to do this, unless you're writing a browser extension. You could try using window.open
and hoping that the user has their browser set to open new windows in new tabs.
Circle Time! :) Easy way of making a circle with a hollow center : use border-radius, give the element a border and no background so you can see through it :
div {_x000D_
display: inline-block;_x000D_
margin-left: 5px;_x000D_
height: 100px;_x000D_
border-radius: 100%;_x000D_
width:100px;_x000D_
border:solid black 2px;_x000D_
}_x000D_
_x000D_
body{_x000D_
background:url('http://lorempixel.com/output/people-q-c-640-480-1.jpg');_x000D_
background-size:cover;_x000D_
}
_x000D_
<div></div>
_x000D_
I once copied these files to the database storage folder for a mysql database which was working, started the db and waited for it to "repair" the files, then extracted them with mysqldump.
What about this?
>>> first_element, last_element = some_list[0], some_list[-1]
netstat -ano|find ":port_no"
will give you the list.
a: Displays all connections and listening ports.
n: Displays addresses and port numbers in numerical form.
o: Displays the owning process ID associated with each connection .
example : netstat -ano | find ":1900"
This gives you the result like this.
UDP 107.109.121.196:1900 *:* 1324
UDP 127.0.0.1:1900 *:* 1324
UDP [::1]:1900 *:* 1324
UDP [fe80::8db8:d9cc:12a8:2262%13]:1900 *:* 1324
As stated by Luke you need to use a server side language, like php. This is a really simple php example:
<?php
if ($_GET['run']) {
# This code will run if ?run=true is set.
exec("/path/to/name.sh");
}
?>
<!-- This link will add ?run=true to your URL, myfilename.php?run=true -->
<a href="?run=true">Click Me!</a>
Save this as myfilename.php
and place it on a machine with a web server with php installed. The same thing can be accomplished with asp, java, ruby, python, ...
The simplest and shorter method would be the following.
string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
if(stringArray.Contains(value))
{
// Do something if the value is available in Array.
}
1 for month is February. The 30th of February is changed to 1st of March. You should set 0 for month. The best is to use the constant defined in Calendar:
c1.set(2000, Calendar.JANUARY, 30);
Starting from Python 3.3 this becomes super easy with the datetime.timestamp()
method. This of course will only be useful if you need the number of seconds from 1970-01-01 UTC.
from datetime import datetime
dt = datetime.today() # Get timezone naive now
seconds = dt.timestamp()
The return value will be a float representing even fractions of a second. If the datetime is timezone naive (as in the example above), it will be assumed that the datetime object represents the local time, i.e. It will be the number of seconds from current time at your location to 1970-01-01 UTC.
To clarify a point in Thomas' excellent answer, it should be mentioned that append()
is thread safe.
This is because there is no concern that data being read will be in the same place once we go to write to it. The append()
operation does not read data, it only writes data to the list.
Printing the exception's stack trace in itself doesn't constitute bad practice, but only printing the stace trace when an exception occurs is probably the issue here -- often times, just printing a stack trace is not enough.
Also, there's a tendency to suspect that proper exception handling is not being performed if all that is being performed in a catch
block is a e.printStackTrace
. Improper handling could mean at best an problem is being ignored, and at worst a program that continues executing in an undefined or unexpected state.
Example
Let's consider the following example:
try {
initializeState();
} catch (TheSkyIsFallingEndOfTheWorldException e) {
e.printStackTrace();
}
continueProcessingAssumingThatTheStateIsCorrect();
Here, we want to do some initialization processing before we continue on to some processing that requires that the initialization had taken place.
In the above code, the exception should have been caught and properly handled to prevent the program from proceeding to the continueProcessingAssumingThatTheStateIsCorrect
method which we could assume would cause problems.
In many instances, e.printStackTrace()
is an indication that some exception is being swallowed and processing is allowed to proceed as if no problem every occurred.
Why has this become a problem?
Probably one of the biggest reason that poor exception handling has become more prevalent is due to how IDEs such as Eclipse will auto-generate code that will perform a e.printStackTrace
for the exception handling:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
(The above is an actual try-catch
auto-generated by Eclipse to handle an InterruptedException
thrown by Thread.sleep
.)
For most applications, just printing the stack trace to standard error is probably not going to be sufficient. Improper exception handling could in many instances lead to an application running in a state that is unexpected and could be leading to unexpected and undefined behavior.
Feel free to disregard this solution as subtracting a list from an Index does not preserve the order of the original Index, if that's important.
In [61]: df.reindex(columns=pd.Index(['x', 'y']).append(df.columns - ['x', 'y']))
Out[61]:
x y a b
0 3 -1 1 2
1 6 -2 2 4
2 9 -3 3 6
3 12 -4 4 8
If you really want your includes method on an ArrayList, just add it:
ArrayList.metaClass.includes = { i -> i in delegate }
c:>pscp source_file_name userid@server_name:/path/destination_file_name.
c:>pscp november2012 [email protected]:/mydata/november2012.
Enjoy
Does an implicit conversion occur between Task<> and int?
Nope. This is just part of how async
/await
works.
Any method declared as async
has to have a return type of:
void
(avoid if possible)Task
(no result beyond notification of completion/failure)Task<T>
(for a logical result of type T
in an async manner)The compiler does all the appropriate wrapping. The point is that you're asynchronously returning urlContents.Length
- you can't make the method just return int
, as the actual method will return when it hits the first await
expression which hasn't already completed. So instead, it returns a Task<int>
which will complete when the async method itself completes.
Note that await
does the opposite - it unwraps a Task<T>
to a T
value, which is how this line works:
string urlContents = await getStringTask;
... but of course it unwraps it asynchronously, whereas just using Result
would block until the task had completed. (await
can unwrap other types which implement the awaitable pattern, but Task<T>
is the one you're likely to use most often.)
This dual wrapping/unwrapping is what allows async to be so composable. For example, I could write another async method which calls yours and doubles the result:
public async Task<int> AccessTheWebAndDoubleAsync()
{
var task = AccessTheWebAsync();
int result = await task;
return result * 2;
}
(Or simply return await AccessTheWebAsync() * 2;
of course.)
The good solution for this error please run this command
composer install --ignore-platform-reqs
The best plugin so far is Bootstrap Multiselect
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery Multi Select Dropdown with Checkboxes</title>
<link rel="stylesheet" href="css/bootstrap-3.1.1.min.css" type="text/css" />
<link rel="stylesheet" href="css/bootstrap-multiselect.css" type="text/css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="js/bootstrap-3.1.1.min.js"></script>
<script type="text/javascript" src="js/bootstrap-multiselect.js"></script>
</head>
<body>
<form id="form1">
<div style="padding:20px">
<select id="chkveg" multiple="multiple">
<option value="cheese">Cheese</option>
<option value="tomatoes">Tomatoes</option>
<option value="mozarella">Mozzarella</option>
<option value="mushrooms">Mushrooms</option>
<option value="pepperoni">Pepperoni</option>
<option value="onions">Onions</option>
</select>
<br /><br />
<input type="button" id="btnget" value="Get Selected Values" />
<script type="text/javascript">
$(function() {
$('#chkveg').multiselect({
includeSelectAllOption: true
});
$('#btnget').click(function(){
alert($('#chkveg').val());
});
});
</script>
</div>
</form>
</body>
</html>
Here's the DEMO
$(function() {_x000D_
_x000D_
$('#chkveg').multiselect({_x000D_
includeSelectAllOption: true_x000D_
});_x000D_
_x000D_
$('#btnget').click(function() {_x000D_
alert($('#chkveg').val());_x000D_
});_x000D_
});
_x000D_
.multiselect-container>li>a>label {_x000D_
padding: 4px 20px 3px 20px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://davidstutz.de/bootstrap-multiselect/dist/js/bootstrap-multiselect.js"></script>_x000D_
<link href="https://davidstutz.de/bootstrap-multiselect/docs/css/bootstrap-3.3.2.min.css" rel="stylesheet"/>_x000D_
<link href="https://davidstutz.de/bootstrap-multiselect/dist/css/bootstrap-multiselect.css" rel="stylesheet"/>_x000D_
<script src="https://davidstutz.de/bootstrap-multiselect/docs/js/bootstrap-3.3.2.min.js"></script>_x000D_
_x000D_
<form id="form1">_x000D_
<div style="padding:20px">_x000D_
_x000D_
<select id="chkveg" multiple="multiple">_x000D_
<option value="cheese">Cheese</option>_x000D_
<option value="tomatoes">Tomatoes</option>_x000D_
<option value="mozarella">Mozzarella</option>_x000D_
<option value="mushrooms">Mushrooms</option>_x000D_
<option value="pepperoni">Pepperoni</option>_x000D_
<option value="onions">Onions</option>_x000D_
</select>_x000D_
_x000D_
<br /><br />_x000D_
_x000D_
<input type="button" id="btnget" value="Get Selected Values" />_x000D_
</div>_x000D_
</form>
_x000D_
It's certainly possible to grab a screenshot using the .NET Framework. The simplest way is to create a new Bitmap
object and draw into that using the Graphics.CopyFromScreen
method.
Sample code:
using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height))
using (Graphics g = Graphics.FromImage(bmpScreenCapture))
{
g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
0, 0,
bmpScreenCapture.Size,
CopyPixelOperation.SourceCopy);
}
Caveat: This method doesn't work properly for layered windows. Hans Passant's answer here explains the more complicated method required to get those in your screen shots.
Properties are pretty useful since you can use them with assignment but then can include validation as well. You can see this code where you use the decorator @property and also @<property_name>.setter to create the methods:
# Python program displaying the use of @property
class AgeSet:
def __init__(self):
self._age = 0
# using property decorator a getter function
@property
def age(self):
print("getter method called")
return self._age
# a setter function
@age.setter
def age(self, a):
if(a < 18):
raise ValueError("Sorry your age is below eligibility criteria")
print("setter method called")
self._age = a
pkj = AgeSet()
pkj.age = int(input("set the age using setter: "))
print(pkj.age)
There are more details in this post I wrote about this as well: https://pythonhowtoprogram.com/how-to-create-getter-setter-class-properties-in-python-3/
df.shape
, where df
is your DataFrame.
I used display:table to fix a similar issue. It almost works for this, leaving a small vertical scroll bar. If you're trying to populate that flexible column with something other than an iframe it works fine (not
Take the following HTML
<body>
<div class="outer">
<div class="banner">Banner</div>
<div class="iframe-container">
<iframe src="http: //www.google.com.tw" style="width:100%; height:100%;border:0;"></iframe>
</div>
</div>
</body>
Change the outer div to use display:table and ensure it has a width and height set.
.outer {
display: table;
height: 100%;
width: 100%;
}
Make the banner a table-row and set its height to whatever your preference is:
.banner {
display: table-row;
height: 30px;
background: #eee;
}
Add an extra div around your iframe (or whatever content you need) and make it a table-row with height set to 100% (setting its height is critical if you want to embed an iframe to fill the height)
.iframe-container {
display: table-row;
height: 100%;
}
Below is a jsfiddle showing it at work (without an iframe because that doesn't seem to work in the fiddle)
In Android Studio 3.5.3, the Device File Explorer can be found in View -> Tool Windows.
It can also be opened using the vertical tabs on the right-hand side of the main window.
It's really easy to do: reliable and not messy:
Try Clients.Client.Send(BufferByte) Catch verror As Exception BufferString = verror.ToString End Try If BufferString <> "" Then EventLog.Text &= "User disconnected: " + vbNewLine Clients.Close() End If
Use:
dateTimePicker.Value.ToString("yyyy/MM/dd")
Refer to the following link:
http://www.vbdotnetforums.com/schedule-time/15001-datetimepicker-format.html
Try this:
var count =0;
$('input[name="radioGroup"]').each(function(){
if (this.checked)
{
count++;
}
});
If any of radio button checked than you will get 1
I had the same problem and I fixed it by using the
By default forever places all of the files it needs into /$HOME/.forever. If you would like to change that location just set the FOREVER_ROOT environment variable when you are running forever:
FOREVER_ROOT=/etc/forever forever start index.js
I encountered the same error while using SpringBoot 2.1.4, along with Spring Security 5 (I believe). After one day of trying everything that Google had to offer, I discovered the cause of error in my case. I had a setup of micro-services, with the Auth server being different from the Resource Server. I had the following lines in my application.yml which prevented 'auto-configuration' despite of having included dependencies spring-boot-starter-security
, spring-security-oauth2
and spring-security-jwt
. I had included the following in the properties (during development) which caused the error.
spring:
autoconfigure:
exclude: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
Commenting it out solved it for me.
#spring:
# autoconfigure:
# exclude: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
Hope, it helps someone.
For me, the problem was that I was in recording mode. To exit from recording mode press q. Then Esc worked as expected for me.
You can use dijkstra's algorithm with negative edges not including negative cycle, but you must allow a vertex can be visited multiple times and that version will lose it's fast time complexity.
In that case practically I've seen it's better to use SPFA algorithm which have normal queue and can handle negative edges.
You'll have to use an HttpServletRequestWrapper:
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
final HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(httpRequest) {
@Override
public String getHeader(String name) {
final String value = request.getParameter(name);
if (value != null) {
return value;
}
return super.getHeader(name);
}
};
chain.doFilter(wrapper, response);
}
Depending on what you want to do you may need to implement other methods of the wrapper like getHeaderNames
for instance. Just be aware that this is trusting the client and allowing them to manipulate any HTTP header. You may want to sandbox it and only allow certain header values to be modified this way.
Here's a fairly complete solution for recursively encoding and decoding datetime.datetime and datetime.date objects using the standard library json
module. This needs Python >= 2.6 since the %f
format code in the datetime.datetime.strptime() format string is only supported in since then. For Python 2.5 support, drop the %f
and strip the microseconds from the ISO date string before trying to convert it, but you'll loose microseconds precision, of course. For interoperability with ISO date strings from other sources, which may include a time zone name or UTC offset, you may also need to strip some parts of the date string before the conversion. For a complete parser for ISO date strings (and many other date formats) see the third-party dateutil module.
Decoding only works when the ISO date strings are values in a JavaScript literal object notation or in nested structures within an object. ISO date strings, which are items of a top-level array will not be decoded.
I.e. this works:
date = datetime.datetime.now()
>>> json = dumps(dict(foo='bar', innerdict=dict(date=date)))
>>> json
'{"innerdict": {"date": "2010-07-15T13:16:38.365579"}, "foo": "bar"}'
>>> loads(json)
{u'innerdict': {u'date': datetime.datetime(2010, 7, 15, 13, 16, 38, 365579)},
u'foo': u'bar'}
And this too:
>>> json = dumps(['foo', 'bar', dict(date=date)])
>>> json
'["foo", "bar", {"date": "2010-07-15T13:16:38.365579"}]'
>>> loads(json)
[u'foo', u'bar', {u'date': datetime.datetime(2010, 7, 15, 13, 16, 38, 365579)}]
But this doesn't work as expected:
>>> json = dumps(['foo', 'bar', date])
>>> json
'["foo", "bar", "2010-07-15T13:16:38.365579"]'
>>> loads(json)
[u'foo', u'bar', u'2010-07-15T13:16:38.365579']
Here's the code:
__all__ = ['dumps', 'loads']
import datetime
try:
import json
except ImportError:
import simplejson as json
class JSONDateTimeEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, (datetime.date, datetime.datetime)):
return obj.isoformat()
else:
return json.JSONEncoder.default(self, obj)
def datetime_decoder(d):
if isinstance(d, list):
pairs = enumerate(d)
elif isinstance(d, dict):
pairs = d.items()
result = []
for k,v in pairs:
if isinstance(v, basestring):
try:
# The %f format code is only supported in Python >= 2.6.
# For Python <= 2.5 strip off microseconds
# v = datetime.datetime.strptime(v.rsplit('.', 1)[0],
# '%Y-%m-%dT%H:%M:%S')
v = datetime.datetime.strptime(v, '%Y-%m-%dT%H:%M:%S.%f')
except ValueError:
try:
v = datetime.datetime.strptime(v, '%Y-%m-%d').date()
except ValueError:
pass
elif isinstance(v, (dict, list)):
v = datetime_decoder(v)
result.append((k, v))
if isinstance(d, list):
return [x[1] for x in result]
elif isinstance(d, dict):
return dict(result)
def dumps(obj):
return json.dumps(obj, cls=JSONDateTimeEncoder)
def loads(obj):
return json.loads(obj, object_hook=datetime_decoder)
if __name__ == '__main__':
mytimestamp = datetime.datetime.utcnow()
mydate = datetime.date.today()
data = dict(
foo = 42,
bar = [mytimestamp, mydate],
date = mydate,
timestamp = mytimestamp,
struct = dict(
date2 = mydate,
timestamp2 = mytimestamp
)
)
print repr(data)
jsonstring = dumps(data)
print jsonstring
print repr(loads(jsonstring))
You must reload your TableView in main thread only. Otherwise your app will be crashed or will be updated after some time. For every UI update it is recommended to use main thread.
//To update UI only this below code is enough
//If you want to do changes in UI use this
DispatchQueue.main.async(execute: {
//Update UI
self.tableView.reloadData()//Your tableView here
})
//Perform some task and update UI immediately.
DispatchQueue.global(qos: .userInitiated).async {
// Call your function here
DispatchQueue.main.async {
// Update UI
self.tableView.reloadData()
}
}
//To call or execute function after some time and update UI
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
//Here call your function
//If you want to do changes in UI use this
DispatchQueue.main.async(execute: {
//Update UI
self.tableView.reloadData()
})
}
Simpiest way to get list of modified files and save it to some text file is:
git diff --name-only HEAD^ > modified_files.txt
Using FilenameUtils
in Apache Commons IO :
String name1 = FilenameUtils.getName("/ab/cd/xyz.txt");
String name2 = FilenameUtils.getName("c:\\ab\\cd\\xyz.txt");
This is a little bit fancy... but it works:
Step 1: Create a Powershell Profile:
FILE: install_profile.ps1
# THIS SCRIPT BLOWS AWAY YOUR DEFAULT POWERSHELL PROFILE SCRIPT
# AND INSTALLS A POINTER TO A GLOBAL POWERSHELL PROFILE
$ErrorActionPreference = "Stop"
function print ([string]$msg)
{
Write-Host -ForegroundColor Green $msg
}
print ""
# User's Powershell Profile
$psdir = "$env:USERPROFILE\Documents\WindowsPowerShell"
$psfile = $psdir + "\Microsoft.PowerShell_profile.ps1"
print "Creating Directory: $psdir"
md $psdir -ErrorAction SilentlyContinue | out-null
# this is your auto-generated powershell profile to be installed
$content = @(
"",
". ~/Documents/tools/profile.ps1",
""
)
print "Creating File: $psfile"
[System.IO.File]::WriteAllLines($psfile, $content)
print ""
# Make sure Powershell profile is readable
Set-ExecutionPolicy -Scope CurrentUser Unrestricted
Step 2: then in tools ~/Documents/tools/profile.ps1:
function Do-ActualThing {
# do actual thing
}
Set-Alias MyAlias Do-ActualThing
Step 3:
$ Set-ExecutionPolicy -Scope CurrentUser Unrestricted $ . ./install_profile.ps1
The accepted solution is pretty good, but has the one issue that it also deletes local branches that were not yet merged into a remote.
If you look at the output of you will see something like
$ git branch --merged master -v
api_doc 3a05427 [gone] Start of describing the Java API
bla 52e080a Update wording.
branch-1.0 32f1a72 [maven-release-plugin] prepare release 1.0.1
initial_proposal 6e59fb0 [gone] Original proposal, converted to AsciiDoc.
issue_248 be2ba3c Skip unit-for-type checking. This needs more work. (#254)
master be2ba3c Skip unit-for-type checking. This needs more work. (#254)
Branches bla
and issue_248
are local branches that would be deleted silently.
But you can also see the word [gone]
, which indicate branches that had been pushed to a remote (which is now gone) and thus denote branches can be deleted.
The original answer can thus be changed to (split into multiline for shorter line length)
git branch --merged master -v | \
grep "\\[gone\\]" | \
sed -e 's/^..//' -e 's/\S* .*//' | \
xargs git branch -d
to protect the not yet merged branches. Also the grepping for master to protect it, is not needed, as this has a remote at origin and does not show up as gone.
C# does not support inline methods (or functions) in the way dynamic languages like python do. However anonymous methods and lambdas can be used for similar purposes including when you need to access a variable in the containing method like in the example below.
static void Main(string[] args)
{
int a = 1;
Action inline = () => a++;
inline();
//here a = 2
}
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Create random datetime object."""
from datetime import datetime
import random
def create_random_datetime(from_date, to_date, rand_type='uniform'):
"""
Create random date within timeframe.
Parameters
----------
from_date : datetime object
to_date : datetime object
rand_type : {'uniform'}
Examples
--------
>>> random.seed(28041990)
>>> create_random_datetime(datetime(1990, 4, 28), datetime(2000, 12, 31))
datetime.datetime(1998, 12, 13, 23, 38, 0, 121628)
>>> create_random_datetime(datetime(1990, 4, 28), datetime(2000, 12, 31))
datetime.datetime(2000, 3, 19, 19, 24, 31, 193940)
"""
delta = to_date - from_date
if rand_type == 'uniform':
rand = random.random()
else:
raise NotImplementedError('Unknown random mode \'{}\''
.format(rand_type))
return from_date + rand * delta
if __name__ == '__main__':
import doctest
doctest.testmod()
Use this code in any fragment button listener:
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
On PostgreSQL (and many other RDBMS), you can do it with regular ALTER TABLE
statement:
=> SELECT * FROM Test1;
id | foo | bar
----+-----+-----
2 | 1 | 2
=> ALTER TABLE Test1 RENAME COLUMN foo TO baz;
ALTER TABLE
=> SELECT * FROM Test1;
id | baz | bar
----+-----+-----
2 | 1 | 2
Use:
document.location.href = "http://yoursite.com" + document.getElementById('somefield');
That would get the value of some text field or hidden field, and add it to your site URL to get a new URL (href). You can modify this to suit your needs.
A CLASS should be used for multiple elements that you want the same styling for. An ID should be for a unique element. See this tutorial.
You should refer to the W3C standards if you want to be a strict conformist, or if you want your pages to be validated to the standards.
Reset (Clear) Form throught Javascript
& jQuery
:
Example Javascript:
document.getElementById("client").reset();
Example jQuery:
You may try using trigger()
Reference Link
$('#client.frm').trigger("reset");
Use Actions -
The user-facing API for emulating complex user gestures.
See Actions#pause method.
If you use ggplot2
the preferred way of saving is to use ggsave
. First you have to plot, after creating the plot you call ggsave
:
ggplot(...)
ggsave("plot.png")
The format of the image is determined by the extension you choose for the filename. Additional parameters can be passed to ggsave
, notably width
, height
, and dpi
.
IntelliJ IDEA and Android Studio have plugins for this:
These plugins generate Android Parcelable boilerplate code based on fields in the class.
May be easier using a java.util.HashSet. For example:
List <String> list = new ArrayList<String>();
list.add("behold");
list.add("bend");
list.add("bet");
//Load the list into a hashSet
Set<String> set = new HashSet<String>(list);
if (set.contains("bend"))
{
System.out.println("String found!");
}
This answer is a bit orthogonal to the the OP, but --
libsass bindings don't install properly with the node-sass wrapper on Node v4.0.0. I got the same error message as in the question (Error: 'libsass' bindings not found. Try reinstalling 'node-sass')
but I ended up uninstalling Node v4.0.0 and installing v0.12.7 using nvm, via this script:
https://gist.github.com/brock/5b1b70590e1171c4ab54
and now libsass and node-sass are behaving properly.
In C++11, use std::stoi
as:
std::string s = "10";
int i = std::stoi(s);
Note that std::stoi
will throw exception of type std::invalid_argument
if the conversion cannot be performed, or std::out_of_range
if the conversion results in overflow(i.e when the string value is too big for int
type). You can use std::stol
or std:stoll
though in case int
seems too small for the input string.
In C++03/98, any of the following can be used:
std::string s = "10";
int i;
//approach one
std::istringstream(s) >> i; //i is 10 after this
//approach two
sscanf(s.c_str(), "%d", &i); //i is 10 after this
Note that the above two approaches would fail for input s = "10jh"
. They will return 10 instead of notifying error. So the safe and robust approach is to write your own function that parses the input string, and verify each character to check if it is digit or not, and then work accordingly. Here is one robust implemtation (untested though):
int to_int(char const *s)
{
if ( s == NULL || *s == '\0' )
throw std::invalid_argument("null or empty string argument");
bool negate = (s[0] == '-');
if ( *s == '+' || *s == '-' )
++s;
if ( *s == '\0')
throw std::invalid_argument("sign character only.");
int result = 0;
while(*s)
{
if ( *s < '0' || *s > '9' )
throw std::invalid_argument("invalid input string");
result = result * 10 - (*s - '0'); //assume negative number
++s;
}
return negate ? result : -result; //-result is positive!
}
This solution is slightly modified version of my another solution.
For ruby or rails developers there is a nice gem available called street_address. I have been using this on one of my project and it does the work I need.
The only Issue I had was whenever an address is in this format P. O. Box 1410 Durham, NC 27702
it returned nil and therefore I had to replace "P. O. Box" with '' and after this it were able to parse it.
javatuples is a dedicated project for tuples in Java.
Unit<A> (1 element)
Pair<A,B> (2 elements)
Triplet<A,B,C> (3 elements)
show GCC defines on Windows:
gcc -dM -E - <NUL:
on Linux:
gcc -dM -E - </dev/null
Predefined macros in MinGW:
WIN32 _WIN32 __WIN32 __WIN32__ __MINGW32__ WINNT __WINNT __WINNT__ _X86_ i386 __i386
on UNIXes:
unix __unix__ __unix
I think you're going to need separate lines for each segment:
import numpy as np
import matplotlib.pyplot as plt
x, y = np.random.random(size=(2,10))
for i in range(0, len(x), 2):
plt.plot(x[i:i+2], y[i:i+2], 'ro-')
plt.show()
(The numpy
import is just to set up some random 2x10 sample data)
mongodb.com -> new project -> new cluster -> new collection -> connect -> IP address: 0.0.0.0/0 & db cred -> connect your application -> copy connection string and paste in .env file of your node app and make sure to replace "" with the actual password for the user and also replace "/test" with your db name
create new file .env
CONNECTIONSTRING=x --> const client = new MongoClient(CONNECTIONSTRING)
PORT=8080
JWTSECRET=mysuper456secret123phrase
Following code works..
datePickerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog(0);
}
});
@Override
@Deprecated
protected Dialog onCreateDialog(int id) {
return new DatePickerDialog(this, datePickerListener, year, month, day);
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
day = selectedDay;
month = selectedMonth;
year = selectedYear;
datePickerButton.setText(selectedDay + " / " + (selectedMonth + 1) + " / "
+ selectedYear);
}
};
This normally happens when the transaction is started and either it is not committed or it is not rollback.
In case the error comes in your stored procedure, this can lock the database tables because transaction is not completed due to some runtime errors in the absence of exception handling You can use Exception handling like below. SET XACT_ABORT
SET XACT_ABORT ON
SET NoCount ON
Begin Try
BEGIN TRANSACTION
//Insert ,update queries
COMMIT
End Try
Begin Catch
ROLLBACK
End Catch
HTML are markup languages, basically they are set of tags like <html>
, <body>
, which is used to present a website using css, and javascript as a whole. All these, happen in the clients system or the user you will be browsing the website.
Now, Connecting to a database, happens on whole another level. It happens on server, which is where the website is hosted.
So, in order to connect to the database and perform various data related actions, you have to use server-side scripts, like php, jsp, asp.net etc.
Now, lets see a snippet of connection using MYSQLi Extension of PHP
$db = mysqli_connect('hostname','username','password','databasename');
This single line code, is enough to get you started, you can mix such code, combined with HTML tags to create a HTML page, which is show data based pages. For example:
<?php
$db = mysqli_connect('hostname','username','password','databasename');
?>
<html>
<body>
<?php
$query = "SELECT * FROM `mytable`;";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($result)) {
// Display your datas on the page
}
?>
</body>
</html>
In order to insert new data into the database, you can use phpMyAdmin
or write a INSERT
query and execute them.
I disagree with this kind of path
GET /companies/{companyId}/departments
If you want to get departments, I think it's better to use a /departments resource
GET /departments?companyId=123
I suppose you have a companies
table and a departments
table then classes to map them in the programming language you use. I also assume that departments could be attached to other entities than companies, so a /departments resource is straightforward, it's convenient to have resources mapped to tables and also you don't need as many endpoints since you can reuse
GET /departments?companyId=123
for any kind of search, for instance
GET /departments?name=xxx
GET /departments?companyId=123&name=xxx
etc.
If you want to create a department, the
POST /departments
resource should be used and the request body should contain the company ID (if the department can be linked to only one company).
Not sure why the question was down-voted, but I had the same issue and following the blog post recommended solve the issue. One thing I should add is that in my case, once I ran:
npm config set prefix /usr/local
I confirmed the npm root -g
was pointing to /usr/local/lib/node_modules/npm
, but in order to install gulp
in /usr/local/lib/node_modules
, I had to use sudo
:
sudo npm install gulp -g
Currently some browsers do support multithreading. So, if you need that you could use specific libraries. For example, view the next materials:
https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers (support background threads);
https://keithwhor.github.io/multithread.js/ (the library).
The reason why you get your error is because a "1 by n" matrix is different from an array of length n.
I recommend using hstack()
and vstack()
instead.
Like this:
import numpy as np
a = np.arange(32).reshape(4,8) # 4 rows 8 columns matrix.
b = a[:,-1:] # last column of that matrix.
result = np.hstack((a,b)) # stack them horizontally like this:
#array([[ 0, 1, 2, 3, 4, 5, 6, 7, 7],
# [ 8, 9, 10, 11, 12, 13, 14, 15, 15],
# [16, 17, 18, 19, 20, 21, 22, 23, 23],
# [24, 25, 26, 27, 28, 29, 30, 31, 31]])
Notice the repeated "7, 15, 23, 31" column.
Also, notice that I used a[:,-1:]
instead of a[:,-1]
. My version generates a column:
array([[7],
[15],
[23],
[31]])
Instead of a row array([7,15,23,31])
Edit: append()
is much slower. Read this answer.
Try
File.open("out.txt", "w") do |f|
f.write(data_you_want_to_write)
end
without using the
File.new "out.txt"
Background images sure can present data! In fact, this is often recommended where presenting visual icons is more compact and user-friendly than an equivalent list of text blurbs. Any use of image sprites can benefit from this approach.
It is quite common for hotel listings icons to display amenities. Imagine a page which listed 50 hotel and each hotel had 10 amenities. A CSS Sprite would be perfect for this sort of thing -- better user experience because it's faster. But how do you implement ALT tags for these images? Example site.
The answer is that they don't use alt
text at all, but instead use the title
attribute on the containing div.
HTML
<div class="hotwire-fitness" title="Fitness Centre"></div>
CSS
.hotwire-fitness {
float: left;
margin-right: 5px;
background: url(/prostyle/images/new_amenities.png) -71px 0;
width: 21px;
height: 21px;
}
According to the W3C (see links above), the title attribute serves much of the same purpose as the alt attribute
Title
Values of the title attribute may be rendered by user agents in a variety of ways. For instance, visual browsers frequently display the title as a "tool tip" (a short message that appears when the pointing device pauses over an object). Audio user agents may speak the title information in a similar context. For example, setting the attribute on a link allows user agents (visual and non-visual) to tell users about the nature of the linked resource:
alt
The alt attribute is defined in a set of tags (namely, img, area and optionally for input and applet) to allow you to provide a text equivalent for the object.
A text equivalent brings the following benefits to your website and its visitors in the following common situations:
- nowadays, Web browsers are available in a very wide variety of platforms with very different capacities; some cannot display images at all or only a restricted set of type of images; some can be configured to not load images. If your code has the alt attribute set in its images, most of these browsers will display the description you gave instead of the images
- some of your visitors cannot see images, be they blind, color-blind, low-sighted; the alt attribute is of great help for those people that can rely on it to have a good idea of what's on your page
- search engine bots belong to the two above categories: if you want your website to be indexed as well as it deserves, use the alt attribute to make sure that they won't miss important sections of your pages.
You could try
try{
if(webDriver.switchTo().alert() != null){
Alert alert = webDriver.switchTo().alert();
alert.getText();
//etc.
}
}catch(Exception e){}
If that doesn't work, you could try looping through all the window handles and see if the alert exists. I'm not sure if the alert opens as a new window using selenium.
for(String s: webDriver.getWindowHandles()){
//see if alert exists here.
}
You can explicitly define the width
and height
of images, but the results may not be the best looking.
.food1 img {
width:100%;
height: 230px;
}
...per your comment, you could also just block any overflow
- see this example to see an image restricted by height and cut off because it's too wide.
.top1 {
height:390px;
background-color:#FFFFFF;
margin-top:10px;
overflow: hidden;
}
.top1 img {
height:100%;
}
Since image is deprecated, you should use varbinary.
per Microsoft (thanks for the link @Christopher)
ntext , text, and image data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.
Fixed and variable-length data types for storing large non-Unicode and Unicode character and binary data. Unicode data uses the UNICODE UCS-2 character set.
How about like this:
char* cmd = "./foo 1 2 3";
system(cmd);
Using the credentials helper command-line option:
git -c credential.helper='!f() { echo "password=mysecretpassword"; }; f' fetch origin
In WPF an image is typically loaded from a Stream or an Uri.
BitmapImage supports both and an Uri can even be passed as constructor argument:
var uri = new Uri("http://...");
var bitmap = new BitmapImage(uri);
If the image file is located in a local folder, you would have to use a file://
Uri. You could create such a Uri from a path like this:
var path = Path.Combine(Environment.CurrentDirectory, "Bilder", "sas.png");
var uri = new Uri(path);
If the image file is an assembly resource, the Uri must follow the the Pack Uri scheme:
var uri = new Uri("pack://application:,,,/Bilder/sas.png");
In this case the Visual Studio Build Action for sas.png
would have to be Resource
.
Once you have created a BitmapImage
and also have an Image control like in this XAML
<Image Name="image1" />
you would simply assign the BitmapImage to the Source
property of that Image control:
image1.Source = bitmap;
@last_run_time
is a 9.4. User-Defined Variables and last_run_time datetime
one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.
Try: SELECT last_run_time;
UPDATE
Example:
/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$
CREATE PROCEDURE `sp_test`()
BEGIN
DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
DECLARE last_run_time DATETIME DEFAULT NULL;
DECLARE current_run_time DATETIME DEFAULT NOW();
-- Define the last run time
SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);
-- if there is no last run time found then use yesterday as starting point
IF(last_run_time IS NULL) THEN
SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
END IF;
SELECT last_run_time;
-- Insert variables in table2
INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$
DELIMITER ;
The primary key is used to work with different tables. This is the foundation of relational databases. If you have a book database it's better to create 2 tables - 1) books and 2) authors with INT primary key "id". Then you use id in books instead of authors name.
The unique key is used if you don't want to have repeated entries. For example you may have title in your book table and want to be sure there is only one entry for each title.
The code was most likely compiled with a later JDK (without using cross-compilation options) and is being run on an earlier JRE. While upgrading the JRE is one solution, it would be better to use the cross-compilation options to ensure the code will run on whatever JRE is intended as the minimum version for the app.
use flask 0.9 instead
use the following commands
sudo pip uninstall flask
sudo pip install flask==0.9
You can use rownum :
SELECT * FROM table WHERE rownum > 10 and rownum <= 20
PATH
is an environment variable, and can be displayed with the echo command:
echo $PATH
It's a list of paths separated by the colon character ':
'
The which
command tells you which file gets executed when you run a command:
which lshw
sometimes what you get is a path to a symlink; if you want to trace that link to where the actual executable lives, you can use readlink
and feed it the output of which
:
readlink -f $(which lshw)
The -f
parameter instructs readlink
to keep following the symlink recursively.
Here's an example from my machine:
$ which firefox
/usr/bin/firefox
$ readlink -f $(which firefox)
/usr/lib/firefox-3.6.3/firefox.sh
You can put overflow:hidden
onto the property with the text indent, and that dotted line, that spans out of the page, will dissapear.
I've seen a couple of posts about removing outlines all together. Be careful when doing this as you could lower the accessibility of the site.
a:active { outline: none; }
I personally would use this attribute only, as if the :hover
attribute has the same css properties it will prevent the outlines showing for people who are using the keyboard for navigation.
Hope this solves your problem.
Suppose access a proxy server A(eg. nginx), and the server A forwards the request to another server B(eg. tomcat).
If this process continues for a long time (more than the proxy server read timeout setting), A still did not get a completed response of B. It happens.
for nginx, You can configure the proxy_read_timeout(in location) property to solve his.But this is usually not a good idea, if you set the value too high. This may hide the real error.You'd better improve the design to really solve this problem.
import * as express from "express";
This is the suggested way of doing it because it is the standard for JavaScript (ES6/2015) since last year.
In any case, in your tsconfig.json file, you should target the module option to commonjs which is the format supported by nodejs.
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]);
You don't need to use regex, LIKE
is sufficient:
WHERE my_field LIKE '[a-zA-Z][a-zA-Z]%'
Assuming that by "alphabetical" you mean only latin characters, not anything classified as alphabetical in Unicode.
Note - if your collation is case sensitive, it's important to specify the range as [a-zA-Z]
. [a-z]
may exclude A
or Z
. [A-Z]
may exclude a
or z
.
Hey, What you can do is apply a fixed width to both the containers and then use another div class where clear:both, like
div#left {
width: 600px;
float: left;
}
div#right {
width: 240px;
float: right;
}
div.clear {
clear:both;
}
place a the clear div under left and right container.
This works for me with org.springframework.jdbc-3.0.6.RELEASE.jar. I could not find this anywhere in the Spring docs (maybe I'm just lazy) but I found (trial and error) that the TRACE level did the magic.
I'm using log4j-1.2.15 along with slf4j (1.6.4) and properties file to configure the log4j:
log4j.logger.org.springframework.jdbc.core = TRACE
This displays both the SQL statement and bound parameters like this:
Executing prepared SQL statement [select HEADLINE_TEXT, NEWS_DATE_TIME from MY_TABLE where PRODUCT_KEY = ? and NEWS_DATE_TIME between ? and ? order by NEWS_DATE_TIME]
Setting SQL statement parameter value: column index 1, parameter value [aaa], value class [java.lang.String], SQL type unknown
Setting SQL statement parameter value: column index 2, parameter value [Thu Oct 11 08:00:00 CEST 2012], value class [java.util.Date], SQL type unknown
Setting SQL statement parameter value: column index 3, parameter value [Thu Oct 11 08:00:10 CEST 2012], value class [java.util.Date], SQL type unknown
Not sure about the SQL type unknown but I guess we can ignore it here
For just an SQL (i.e. if you're not interested in bound parameter values) DEBUG
should be enough.
1.84E-07 is the exact value, represented using scientific notation, also known as exponential notation.
1.845E-07 is the same as 0.0000001845. Excel will display a number very close to 0 as 0, unless you modify the formatting of the cell to display more decimals.
C# however will get the actual value from the cell. The ToString method use the e-notation when converting small numbers to a string.
You can specify a format string if you don't want to use the e-notation.
For such a simple XML structure, you may not want to involve a full blown XML module. Consider a string template for the simplest structures, or Jinja for something a little more complex. Jinja can handle looping over a list of data to produce the inner xml of your document list. That is a bit trickier with raw python string templates
For a Jinja example, see my answer to a similar question.
Here is an example of generating your xml with string templates.
import string
from xml.sax.saxutils import escape
inner_template = string.Template(' <field${id} name="${name}">${value}</field${id}>')
outer_template = string.Template("""<root>
<doc>
${document_list}
</doc>
</root>
""")
data = [
(1, 'foo', 'The value for the foo document'),
(2, 'bar', 'The <value> for the <bar> document'),
]
inner_contents = [inner_template.substitute(id=id, name=name, value=escape(value)) for (id, name, value) in data]
result = outer_template.substitute(document_list='\n'.join(inner_contents))
print result
Output:
<root>
<doc>
<field1 name="foo">The value for the foo document</field1>
<field2 name="bar">The <value> for the <bar> document</field2>
</doc>
</root>
The downer of the template approach is that you won't get escaping of <
and >
for free. I danced around that problem by pulling in a util from xml.sax
For me the only thing that works is to add to repositories
maven {
url "https://maven.google.com"
}
It should look like this:
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
}
use a negative character class:
[^,;]+
Generally speaking, a software product isn't your "property already", as you said in the comment. Most of the times (I won't be irresponsible to say anything in open), it's licensed to you. A license to use some thing is not the same thing as owning (property rights) that very same thing.
That's because there are authorship, copyright, intellectual property rights applicable to it. I don't know how things work in United States (or in your country), but it's generally accepted that the work of a mind, a creative work, must not be changed in its nature as such to make the expression of art to be different than that expression that the author intended. That applies for example, in some cases, to architectural work (in most countries, you can't change the appearance of a building to "desfigure" the work of art of the architect, without his prior consent). Exceptions are made, obviously, when the author expressly authorizes such changes (e.g., Creative Commons licenses, open source licenses etc.).
Anyway, that's why you see in most EULAs the typical sentence: "this software is licensed, not sold". That's the purpose and reason why.
Now that you understand the reasons why you can't wander around changing other people's art, let me be technical.
There are possible ways to decompile Java programs. You can use dex2jar
, it provides a somewhat good start for you to start looking for things and changes. And perhaps rebuild the code by mounting back the pieces together. Good luck, as most people obfuscate their codes to make that harder.
However, let me say that it's still forbidden to change programs, as I said above. And it's extremely unethical. It makes me sad that people do that with no scruples (not saying it's your case, just warning you). It shouldn't need people to be at the other side to understand that. Or maybe that's just me, who lives in a country where piracy is rampant.
The tools are always out there. But the conscience, unfortunately, not always.
edit: in case it isn't clear enough already, I do NOT approve the use of these programs. I use them myself to check how hard my own applications are to be reverse engineered. But I also think that explaning is always better than denial (better be here).
The accepted answer will return all the parent nodes too. To get only the actual nodes with ABC even if the string is after
:
//*[text()[contains(.,'ABC')]]/text()[contains(.,"ABC")]
This is what I needed:
public static byte[] encode(byte[] arr, String fromCharsetName) {
return encode(arr, Charset.forName(fromCharsetName), Charset.forName("UTF-8"));
}
public static byte[] encode(byte[] arr, String fromCharsetName, String targetCharsetName) {
return encode(arr, Charset.forName(fromCharsetName), Charset.forName(targetCharsetName));
}
public static byte[] encode(byte[] arr, Charset sourceCharset, Charset targetCharset) {
ByteBuffer inputBuffer = ByteBuffer.wrap( arr );
CharBuffer data = sourceCharset.decode(inputBuffer);
ByteBuffer outputBuffer = targetCharset.encode(data);
byte[] outputData = outputBuffer.array();
return outputData;
}
That's because abc
is undefined at the moment of the template rendering. You can use safe navigation operator (?
) to "protect" template until HTTP call is completed:
{{abc?.xyz?.name}}
You can read more about safe navigation operator here.
Update:
Safe navigation operator can't be used in arrays, you will have to take advantage of NgIf
directive to overcome this problem:
<div *ngIf="arr && arr.length > 0">
{{arr[0].name}}
</div>
Read more about NgIf
directive here.
Don't try to scan text with nextLine(); AFTER using nextInt() with the same scanner! It doesn't work well with Java Scanner, and many Java developers opt to just use another Scanner for integers. You can call these scanners scan1 and scan2 if you want.
Do remember that, with iOS 8, the onscreen keyboard's size can vary. Don't assume that the onscreen keyboard will always be visible (with a specific height) or invisible.
Now, with iOS 8, the user can also swipe the text-prediction area on and off... and when they do this, it would kick off an app's keyboardWillShow
event again.
This will break a lot of legacy code samples, which recommended writing a keyboardWillShow
event, which merely measures the current height of the onscreen keyboard, and shifting your controls up or down on the page by this (absolute) amount.
In other words, if you see any sample code, which just tells you to add a keyboardWillShow
event, measure the keyboard height, then resize your controls' heights by this amount, this will no longer always work.
In my example above, I used the sample code from the following site, which animates the vertical constraints constant
value.
In my app, I added a constraint to my UITextView
, set to the bottom of the screen. When the screen first appeared, I stored this initial vertical distance.
Then, whenever my keyboardWillShow
event gets kicked off, I add the (new) keyboard height to this original constraint value (so the constraint resizes the control's height).
Yeah. It's ugly.
And I'm a little annoyed/surprised that XCode 6's horribly-painful AutoLayout doesn't just allow us to attach the bottoms of controls to either the bottom of the screen, or the top of onscreen keyboard.
Perhaps I'm missing something.
Other than my sanity.
More generic way in case qs
has more than one dictionaries:
[int(v) for lst in qs for k, v in lst.items()]
--
>>> qs = [{u'a': 15L, u'b': 9L, u'a': 16L}, {u'a': 20, u'b': 35}]
>>> result_list = [int(v) for lst in qs for k, v in lst.items()]
>>> result_list
[16, 9, 20, 35]
GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH
. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:
export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH
Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).
try this:
grep -P '^(tomcat!?)' tst1.txt
It will search for specific word in txt file. Here we are trying to search word tomcat
Use System.DateTime.DaysInMonth, from code sample:
const int July = 7;
const int Feb = 2;
// daysInJuly gets 31.
int daysInJuly = System.DateTime.DaysInMonth(2001, July);
// daysInFeb gets 28 because the year 1998 was not a leap year.
int daysInFeb = System.DateTime.DaysInMonth(1998, Feb);
// daysInFebLeap gets 29 because the year 1996 was a leap year.
int daysInFebLeap = System.DateTime.DaysInMonth(1996, Feb);
Change /img/stuvi-logo.png
to img/stuvi-logo.png
{{ HTML::image('img/stuvi-logo.png', 'alt text', array('class' => 'css-class')) }}
Which produces the following HTML.
<img src="http://your.url/img/stuvi-logo.png" class="css-class" alt="alt text">
ArrayList<Matrices> list = new ArrayList<Matrices>();
list.add( new Matrices(1,1,10) );
list.add( new Matrices(1,2,20) );
All pages of the resulting document will be scaled to that size. The resulting file size is nearly identical to the original PDF, so I conclude, that image resolutions/compressions are not changed.
Hints:
I am not sure whether the "Export as PDF" menu item is available by default or only if Adobe Acrobat is installed.
My first trial was to use Preview App and print (!) into a new PDF, but this leads to additional margins around the page content.
There is another the error happening which related to the order when calling initializing global variables. I've had the sample of code has similar error FailedPreconditionError (see above for traceback): Attempting to use uninitialized value W
def linear(X, n_input, n_output, activation = None):
W = tf.Variable(tf.random_normal([n_input, n_output], stddev=0.1), name='W')
b = tf.Variable(tf.constant(0, dtype=tf.float32, shape=[n_output]), name='b')
if activation != None:
h = tf.nn.tanh(tf.add(tf.matmul(X, W),b), name='h')
else:
h = tf.add(tf.matmul(X, W),b, name='h')
return h
from tensorflow.python.framework import ops
ops.reset_default_graph()
g = tf.get_default_graph()
print([op.name for op in g.get_operations()])
with tf.Session() as sess:
# RUN INIT
sess.run(tf.global_variables_initializer())
# But W hasn't in the graph yet so not know to initialize
# EVAL then error
print(linear(np.array([[1.0,2.0,3.0]]).astype(np.float32), 3, 3).eval())
You should change to following
from tensorflow.python.framework import ops
ops.reset_default_graph()
g = tf.get_default_graph()
print([op.name for op in g.get_operations()])
with tf.Session() as
# NOT RUNNING BUT ASSIGN
l = linear(np.array([[1.0,2.0,3.0]]).astype(np.float32), 3, 3)
# RUN INIT
sess.run(tf.global_variables_initializer())
print([op.name for op in g.get_operations()])
# ONLY EVAL AFTER INIT
print(l.eval(session=sess))
try running:
su -c "Your command right here" -s /bin/sh username
This will run the command as username given that you have permissions to sudo as that user.
I faced the same problem. Follow these steps:
Using JQuery:
var color = $('#myDivID').css("background-color");
You can see all the version of a module with npm view
.
eg: To list all versions of bootstrap including beta.
npm view bootstrap versions
But if the version list is very big it will truncate. An --json
option will print all version including beta versions as well.
npm view bootstrap versions --json
If you want to list only the stable versions not the beta then use singular version
npm view bootstrap@* versions
Or
npm view bootstrap@* versions --json
And, if you want to see only latest version then here you go.
npm view bootstrap version
The standard approach is to give the centered element fixed dimensions, and place it absolutely:
<div class='fullscreenDiv'>
<div class="center">Hello World</div>
</div>?
.center {
position: absolute;
width: 100px;
height: 50px;
top: 50%;
left: 50%;
margin-left: -50px; /* margin is -0.5 * dimension */
margin-top: -25px;
}?
A MIME type is a label used to identify a type of data. It is used so software can know how to handle the data. It serves the same purpose on the Internet that file extensions do on Microsoft Windows.
So if a server says "This is text/html" the client can go "Ah, this is an HTML document, I can render that internally", while if the server says "This is application/pdf" the client can go "Ah, I need to launch the FoxIt PDF Reader plugin that the user has installed and that has registered itself as the application/pdf handler."
You'll most commonly find them in the headers of HTTP messages (to describe the content that an HTTP server is responding with or the formatting of the data that is being POSTed in a request) and in email headers (to describe the message format and attachments).
You need to set permissions within SSRS in two places to give yourself initial access. The set-up program only gives access to Builtin\Administrators, to gain access in order to do this you need to right click you browser link and choose Run as administrator.
ZIP FILE via Cross-platform Java without manifest and META-INF folder:
jar -cMf {yourfile.zip} {yourfolder}
With androidx, the classic support libraries no longer work.
Simple solution is to use following code
In your build.gradle
file
android{
...
...
defaultConfig {
...
...
multiDexEnabled true
}
...
}
dependencies {
...
...
implementation 'androidx.multidex:multidex:2.0.1'
}
And in your manifest just add name attribute to the application tag
<manifest ...>
<application
android:name="androidx.multidex.MultiDexApplication"
...
...>
...
...
</application>
</manifest>
If your application is targeting API 21 or above multidex is enables by default.
Now if you want to get rid of many of the issues you face trying to support multidex - first try using code shrinking by setting minifyEnabled true
.
Try this. Copy this into a batch file - such as send.bat - and then simply run send.bat
to send the message from the temperature program to the prismcom program.
temperature.exe > msg.txt
set /p msg= < msg.txt
prismcom.exe usb "%msg%"
The answer by @Dayerman and @h_rules is right. To give an elaborated example with code, In drawable folder, create an xml file called button_disabled.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="10dp">
<solid android:color="@color/silver"/>
<corners
android:bottomRightRadius="20dp"
android:bottomLeftRadius="20dp"
android:topLeftRadius="20dp"
android:topRightRadius="20dp"/>
</shape>
Then in Java,
((Button) findViewById(R.id.my_button)).setEnabled(false);
((Button) findViewById(R.id.my_button)).setBackgroundResource(R.drawable.button_disabled);
This will set the button's property to disabled and sets the color to silver.
[The color is defined in color.xml as:
<resources>
<color name="silver">#C0C0C0</color>
</resources>
I don't try changing sequence via setval
. But using ALTER
I was issued how to write sequence name properly. And this only work for me:
Check required sequence name using SELECT * FROM information_schema.sequences;
ALTER SEQUENCE public."table_name_Id_seq" restart {number};
In my case it was ALTER SEQUENCE public."Services_Id_seq" restart 8;
Also there is a page on wiki.postgresql.org where describes a way to generate sql script to fix sequences in all database tables at once. Below the text from link:
Save this to a file, say 'reset.sql'
SELECT 'SELECT SETVAL(' || quote_literal(quote_ident(PGT.schemaname) || '.' || quote_ident(S.relname)) || ', COALESCE(MAX(' ||quote_ident(C.attname)|| '), 1) ) FROM ' || quote_ident(PGT.schemaname)|| '.'||quote_ident(T.relname)|| ';' FROM pg_class AS S, pg_depend AS D, pg_class AS T, pg_attribute AS C, pg_tables AS PGT WHERE S.relkind = 'S' AND S.oid = D.objid AND D.refobjid = T.oid AND D.refobjid = C.attrelid AND D.refobjsubid = C.attnum AND T.relname = PGT.tablename ORDER BY S.relname;
Run the file and save its output in a way that doesn't include the usual headers, then run that output. Example:
psql -Atq -f reset.sql -o temp psql -f temp rm temp
And the output will be a set of sql commands which look exactly like this:
SELECT SETVAL('public."SocialMentionEvents_Id_seq"', COALESCE(MAX("Id"), 1) ) FROM public."SocialMentionEvents";
SELECT SETVAL('public."Users_Id_seq"', COALESCE(MAX("Id"), 1) ) FROM public."Users";
Let me just add a warning to all the existing answers:
When using the SELECT ... FROM syntax, you should keep in mind that it is proprietary syntax for T-SQL and is non-deterministic. The worst part is, that you get no warning or error, it just executes smoothly.
Full explanation with example is in the documentation:
Use caution when specifying the FROM clause to provide the criteria for the update operation. The results of an UPDATE statement are undefined if the statement includes a FROM clause that is not specified in such a way that only one value is available for each column occurrence that is updated, that is if the UPDATE statement is not deterministic.
Unfortunately in HTML 5 the 'pattern' attribute is linked to only 4-5 attributes. However if you are willing to use a "text" field instead and convert to number later, this might help you;
This limits an input from 1 character (numberic) to 3.
<input name=quantity type=text pattern='[0-9]{1,3}'>
The CSS basically allows for confirmation with an "Thumbs up" or "Down".
Here is a way to center content both vertically and horizontally in any situation, which is useful when you do not know the width or height or both:
CSS
#container {
display: table;
width: 300px; /* not required, just for example */
height: 400px; /* not required, just for example */
}
#update {
display: table-cell;
vertical-align: middle;
text-align: center;
}
HTML
<div id="container">
<a id="update" href="#">
<i class="icon-refresh"></i>
</a>
</div>
Note that the width and height values are just for demonstration here, you can change them to anything you want (or remove them entirely) and it will still work because the vertical centering here is a product of the way the table-cell
display property works.
Just add the cloaking CSS to the head of the page or to one of your CSS files:
[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak, .ng-hide {
display: none !important;
}
Then you can use the ngCloak directive according to normal Angular practice, and it will work even before Angular itself is loaded.
This is exactly what Angular does: the code at the end of angular.js adds the above CSS rules to the head of the page.
A standard SQL approach would be
UPDATE ud
SET assid = (SELECT assid FROM sale s WHERE ud.id=s.id)
On SQL Server you can use a join
UPDATE ud
SET assid = s.assid
FROM ud u
JOIN sale s ON u.id=s.id
I fixed it by manually selecting a provisioning profile in the build settings for the test target.
Test target settings -> Build settings -> Code signing -> Code sign identity. Previously, it was set to "Don't code sign".
Converting an int to a byte in Python 3:
n = 5
bytes( [n] )
>>> b'\x05'
;) guess that'll be better than messing around with strings
source: http://docs.python.org/3/library/stdtypes.html#binaryseq
This one is I think more efficient to check prime number :
function prime(num){
if(num == 1) return true;
var t = num / 2;
var k = 2;
while(k <= t) {
if(num % k == 0) {
return false
} else {
k++;
}
}
return true;
}
console.log(prime(37))
Figure sizes are specified in inches and can be included as a global option of the document output format. For example:
---
title: "My Document"
output:
html_document:
fig_width: 6
fig_height: 4
---
And the plot's size in the graphic device can be increased at the chunk level:
```{r, fig.width=14, fig.height=12} #Expand the plot width to 14 inches
ggplot(aes(x=mycolumn1, y=mycolumn2)) + #specify the x and y aesthetic
geom_line(size=2) + #makes the line thicker
theme_grey(base_size = 25) #increases the size of the font
```
You can also use the out.width
and out.height
arguments to directly define the size of the plot in the output file:
```{r, out.width="200px", out.height="200px"} #Expand the plot width to 200 pixels
ggplot(aes(x=mycolumn1, y=mycolumn2)) + #specify the x and y aesthetic
geom_line(size=2) + #makes the line thicker
theme_grey(base_size = 25) #increases the size of the font
```
You can use the "file" command if you actually want to find out information about the file rather than rely on the extensions.
If you feel comfortable with using the extension you can use grep to see if it matches.
If you want to learn about win32, WTL http://wtl.sourceforge.net/ is the pretty lightweight equivalent to MFC, but you have to love template to use it.
If you want something simple MFC is already integrated with VS, also it has a large base of extra code and workarounds of know bugs in the net already.
Also Qt is really great framework it have a nice set of tools, dialog editor, themes, and a lot of other stuff, plus your application will be ready to be cross platform, although it will require some time to get accustomed.
You also have Gtk, wxWindow, and you will have no problems if you have already used it on linux.
Assuming that you have a DHCP server running at your router I would use:
# /etc/network/interfaces
auto lo eth0
iface lo inet loopback
iface eth0 inet dhcp
After changing the file issue (as root):
/etc/init.d/networking restart
<div class="form-group">
<label class="font-normal MyText">MyText to copy</label>
<button type="button" class="btn btn-default btn-xs btnCopy" data="MyText">Copy</button>
</div>
$(".btnCopy").click(function () {
var element = $(this).attr("data");
copyToClipboard($('.' + element));
});
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
The default execution policy, "Restricted", prevents all scripts from running, including scripts that you write on the local computer.
The execution policy is saved in the registry, so you need to change it only once on each computer.
To change the execution policy, use the following procedure:
Start Windows PowerShell with the "Run as administrator" option.
At the command prompt, type:
Set-ExecutionPolicy AllSigned
-or-
Set-ExecutionPolicy RemoteSigned
The change is effective immediately.
To run a script, type the full name and the full path to the script file.
For example, to run the Get-ServiceLog.ps1
script in the C:\Scripts
directory, type:
C:\Scripts\Get-ServiceLog.ps1
And to the Python file, you have two points. Try to add your Python folder to your PATH and the extension .py
.
To PATHEXT from go properties of computer. Then click on advanced system protection. Then environment variable. Here you will find the two points.
You can also pass in '0' as the value for the column to auto-increment, the correct value will be used when the record is created. This is so much easier than temporary tables.
Source: Copying rows in MySQL (see the second comment, by TRiG, to the first solution, by Lore)
Try this:
const strippedString = htmlString.replace(/(<([^>]+)>)/gi, "");
console.log(strippedString);
Typing in 0%
takes you to the beginning.
100%
takes you to the end.
50%
takes you half way.
Also You can use
$value = $("#txt").val();
if($value == "")
{
//Your Code Here
}
else
{
//Your code
}
Try it. It work.
This works great - i have access to the request object and the email array
$emails = ['[email protected]', '[email protected]'];
Mail::send('emails.lead', ['name' => $name, 'email' => $email, 'phone' => $phone], function ($message) use ($request, $emails)
{
$message->from('[email protected]', 'Joe Smoe');
// $message->to( $request->input('email') );
$message->to( $emails);
//Add a subject
$message->subject("New Email From Your site");
});
The maximum value that a Java Integer
can handle is 2147483657, or 2^31-1. The hexadecimal number AA0F245C is 2853119068 as a decimal number, and is far too large, so you need to use
Long.parseLong("AA0F245C", 16);
to make it work.
refer here: https://nathanhoad.net/how-to-colours-in-git/
steps:
Open ~/.gitconfig for editing
vi ~/.gitconfig
Paste following code:
[color]
ui = auto
[color "branch"]
current = yellow reverse
local = yellow
remote = green
[color "diff"]
meta = yellow bold
frag = magenta bold
old = red bold
new = green bold
[color "status"]
added = yellow
changed = green
untracked = cyan
Save the file.
Just change any file in your local repo and do
git status
If you're using RStudio, please consider never using the rm(list = ls())
approach!* Instead, you should build your workflow around frequently employing the Ctrl
+Shift
+F10
shortcut to restart your R session. This is the fastest way to both nuke the current set of user-defined variables AND to clear loaded packages, devices, etc. The reproducibility of your work will increase markedly by adopting this habit.
See this excellent thread on Rstudio community for (h/t @kierisi) for a more thorough discussion (the main gist is captured by what I've stated already).
I must admit my own first few years of R coding featured script after script starting with the rm
"trick" -- I'm writing this answer as advice to anyone else who may be starting out their R careers.
*of course there are legitimate uses for this -- much like attach
-- but beginning users will be much better served (IMO) crossing that bridge at a later date.
You can just grab them as with any CSS attribute:
alert($("#mybox").css("padding-right"));
alert($("#mybox").css("margin-bottom"));
You can set them with a second attribute in the css method:
$("#mybox").css("padding-right", "20px");
EDIT: If you need just the pixel value, use parseInt(val, 10)
:
parseInt($("#mybox").css("padding-right", "20px"), 10);
you have to import Microsoft.AspNetCore.Identity & System.Security.Claims
// to get current user ID
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
// to get current user info
var user = await _userManager.FindByIdAsync(userId);
Use Asynchronous operations with BeginRead/BeginWrite and AsyncCallback.
List.copyOf
? unmodifiable listYou asked:
Is there no other way to assign a copy of a list
Java 9 brought the List.of
methods for using literals to create an unmodifiable List
of unknown concrete class.
LocalDate today = LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) ;
List< LocalDate > dates = List.of(
today.minusDays( 1 ) , // Yesterday
today , // Today
today.plusDays( 1 ) // Tomorrow
);
Along with that we also got List.copyOf
. This method too returns an unmodifiable List
of unknown concrete class.
List< String > colors = new ArrayList<>( 4 ) ; // Creates a modifiable `List`.
colors.add ( "AliceBlue" ) ;
colors.add ( "PapayaWhip" ) ;
colors.add ( "Chartreuse" ) ;
colors.add ( "DarkSlateGray" ) ;
List< String > masterColors = List.copyOf( colors ) ; // Creates an unmodifiable `List`.
By “unmodifiable” we mean the number of elements in the list, and the object referent held in each slot as an element, is fixed. You cannot add, drop, or replace elements. But the object referent held in each element may or may not be mutable.
colors.remove( 2 ) ; // SUCCEEDS.
masterColors.remove( 2 ) ; // FAIL - ERROR.
See this code run live at IdeOne.com.
dates.toString(): [2020-02-02, 2020-02-03, 2020-02-04]
colors.toString(): [AliceBlue, PapayaWhip, DarkSlateGray]
masterColors.toString(): [AliceBlue, PapayaWhip, Chartreuse, DarkSlateGray]
You asked about object references. As others said, if you create one list and assign it to two reference variables (pointers), you still have only one list. Both point to the same list. If you use either pointer to modify the list, both pointers will later see the changes, as there is only one list in memory.
So you need to make a copy of the list. If you want that copy to be unmodifiable, use the List.copyOf
method as discussed in this Answer. In this approach, you end up with two separate lists, each with elements that hold a reference to the same content objects. For example, in our example above using String
objects to represent colors, the color objects are floating around in memory somewhere. The two lists hold pointers to the same color objects. Here is a diagram.
The first list colors
is modifiable. This means that some elements could be removed as seen in code above, where we removed the original 3rd element Chartreuse
(index of 2 = ordinal 3). And elements can be added. And the elements can be changed to point to some other String
such as OliveDrab
or CornflowerBlue
.
In contrast, the four elements of masterColors
are fixed. No removing, no adding, and no substituting another color. That List
implementation is unmodifiable.
I not be able to find squid number in sonar 5.6, with this annotation also works:
@SuppressWarnings({"pmd:AvoidCatchingGenericException", "checkstyle:com.puppycrawl.tools.checkstyle.checks.coding.IllegalCatchCheck"})
Looks like Facebook disabled passing parameters to the sharer.
We have changed the behavior of the sharer plugin to be consistent with other plugins and features on our platform.
The sharer will no longer accept custom parameters and facebook will pull the information that is being displayed in the preview the same way that it would appear on facebook as a post from the url OG meta tags.
Here's the URL to the post: https://developers.facebook.com/x/bugs/357750474364812/
Update:
The plugin previously mentioned has been abandoned, but it apparently has an up-to-date fork here.
Old Answer:
I use the Android Studio plugin named Android Drawable Importer
:
To use it after installed, right click your res/drawable folder and select New > Batch Drawable Import
:
Then select your image via the +
button and set the Resolution to be xxhdpi (or whatever the resolution of your source image is).
In latin1 each character is exactly one byte long. In utf8 a character can consist of more than one byte. Consequently utf8 has more characters than latin1 (and the characters they do have in common aren't necessarily represented by the same byte/bytesequence).
I found a smooth solution using java 8 and polygenelubricants' solution.
parameters.entrySet().stream()
.map(p -> urlEncodeUTF8(p.getKey()) + "=" + urlEncodeUTF8(p.getValue()))
.reduce((p1, p2) -> p1 + "&" + p2)
.orElse("");
for c in np.hsplit(array, array.shape[1]):
some_fun(c)
Follow download wizard
Follow the screens one by one to select type of package (curl executable), OS (Win64), flavor (Generic), CPU (x86_64) and the download link.
unzip download and find curl.exe (I found it in src folder, one may find it in bin folder for different OS/flavor)
To make it available from the command line, add the executable path to the system path (Adding directory to PATH Environment Variable in Windows).
Enjoy curl.
right click on the project and select Manage NuGet Packages..
In that select Json.NET
and install
After installation,
use the following namespace
using Newtonsoft.Json;
then use the following to deserialize
JsonConvert.DeserializeObject
yes you can . you need to refer both JS file
to the .aspx
page
<script language="javascript" type="text/javascript" src="JScript1.js">
</script>
<script language="javascript" type="text/javascript" src="JScript2.js">
</script>
JScript1.js
function ani1() {
alert("1");
ani2();
}
JScript2.js
function ani2() {
alert("2");
}
Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "]
with array("title" => "Welcome ")
df.info() function will give you result something like as below. If you are using read_csv method of Pandas without sep parameter or sep with ",".
raw_data = pd.read_csv("a1:\aa2/aaa3/data.csv")
raw_data.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5144 entries, 0 to 5143
Columns: 145 entries, R_fighter to R_age
We can use the IIFE to swap two value without extra parameter
var a = 5, b =8;_x000D_
b = (function(a){ _x000D_
return a _x000D_
}(a, a=b));_x000D_
_x000D_
document.write("a: " + a+ " b: "+ b);
_x000D_
Just found base64-arraybuffer, a small npm package with incredibly high usage, 5M downloads last month (2017-08).
https://www.npmjs.com/package/base64-arraybuffer
For anyone looking for something of a best standard solution, this may be it.
Yes, you can do this. The knack you need is the concept that there are two ways of getting tables out of the table server. One way is ..
FROM TABLE A
The other way is
FROM (SELECT col as name1, col2 as name2 FROM ...) B
Notice that the select clause and the parentheses around it are a table, a virtual table.
So, using your second code example (I am guessing at the columns you are hoping to retrieve here):
SELECT a.attr, b.id, b.trans, b.lang
FROM attribute a
JOIN (
SELECT at.id AS id, at.translation AS trans, at.language AS lang, a.attribute
FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
Notice that your real table attribute
is the first table in this join, and that this virtual table I've called b
is the second table.
This technique comes in especially handy when the virtual table is a summary table of some kind. e.g.
SELECT a.attr, b.id, b.trans, b.lang, c.langcount
FROM attribute a
JOIN (
SELECT at.id AS id, at.translation AS trans, at.language AS lang, at.attribute
FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
JOIN (
SELECT count(*) AS langcount, at.attribute
FROM attributeTranslation at
GROUP BY at.attribute
) c ON (a.id = c.attribute)
See how that goes? You've generated a virtual table c
containing two columns, joined it to the other two, used one of the columns for the ON
clause, and returned the other as a column in your result set.
If you have the options -H
and -n
available (man grep
is your friend):
$ cat file
foo
bar
foobar
$ grep -H foo file
file:foo
file:foobar
$ grep -Hn foo file
file:1:foo
file:3:foobar
Options:
-H, --with-filename
Print the file name for each match. This is the default when there is more than one file to search.
-n, --line-number
Prefix each line of output with the 1-based line number within its input file. (-n is specified by POSIX.)
-H
is a GNU extension, but -n
is specified by POSIX
I used the code from the most upvoted answer:
startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
It opens the device settings in the same window, thus got the users of my android application (finnmglas/Launcher) for android stuck in there.
The answer for 2020 and beyond (in Kotlin):
startActivity(Intent(Settings.ACTION_SETTINGS))
It works in my app, should also be working in yours without any unwanted consequences.
Very short,
What is the purpose of DI? With dependency injection, objects don't define their dependencies themselves, the dependencies are injected to them as needed.
How does it benefit ? The objects don't need to know where and how to get their dependencies, which results in loose coupling between objects, which makes them a lot easier to test.
How is it implemented ? Usually a container manages the lifecycle of objects and their dependencies based on a configuration file or annotations.
Inspired by Jon Skeet, I have extended his solution with the following:
Extension Method:
public static void Execute<TSource, TKey>(this IEnumerable<TSource> source, Action<TKey> applyBehavior, Func<TSource, TKey> keySelector)
{
foreach (var item in source)
{
var target = keySelector(item);
applyBehavior(target);
}
}
Client:
var jobs = new List<Job>()
{
new Job { Id = "XAML Developer" },
new Job { Id = "Assassin" },
new Job { Id = "Narco Trafficker" }
};
jobs.Execute(ApplyFilter, j => j.Id);
. . .
public void ApplyFilter(string filterId)
{
Debug.WriteLine(filterId);
}
Instead of catching the error, wouldn't it be possible to test in or before the myplotfunction()
function first if the error will occur (i.e. if the breaks are unique) and only plot it for those cases where it won't appear?!
It seems that for full page reload $window.location.href
is the preferred way.
It does not cause a full page reload when the browser URL is changed. To reload the page after changing the URL, use the lower-level API, $window.location.href.
I've created a module called cors-bypass
, that allows you to do this without the need for a server. It uses postMessage
to send cross-domain events, which is used to provide mock HTTP APIs (fetch
, WebSocket
, XMLHTTPRequest
etc.).
It fundamentally does the same as the answer by Endless, but requires no code changes to use it.
Example usage:
import { Client, WebSocket } from 'cors-bypass'
const client = new Client()
await client.openServerInNewTab({
serverUrl: 'http://random-domain.com/server.html',
adapterUrl: 'https://your-site.com/adapter.html'
})
const ws = new WebSocket('ws://echo.websocket.org')
ws.onopen = () => ws.send('hello')
ws.onmessage = ({ data }) => console.log('received', data)
Using the jQuery.validate
library should be pretty simple to set up.
Specify the following settings in your Web.config
file:
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
When you build up your view, you would define things like this:
@Html.LabelFor(Model => Model.EditPostViewModel.Title, true)
@Html.TextBoxFor(Model => Model.EditPostViewModel.Title,
new { @class = "tb1", @Style = "width:400px;" })
@Html.ValidationMessageFor(Model => Model.EditPostViewModel.Title)
NOTE: These need to be defined within a form element
Then you would need to include the following libraries:
<script src='@Url.Content("~/Scripts/jquery.validate.js")' type='text/javascript'></script>
<script src='@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")' type='text/javascript'></script>
This should be able to set you up for client side validation
NOTE: This is only for additional server side validation on top of jQuery.validation
library
Perhaps something like this could help:
[ValidateAjax]
public JsonResult Edit(EditPostViewModel data)
{
//Save data
return Json(new { Success = true } );
}
Where ValidateAjax
is an attribute defined as:
public class ValidateAjaxAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.HttpContext.Request.IsAjaxRequest())
return;
var modelState = filterContext.Controller.ViewData.ModelState;
if (!modelState.IsValid)
{
var errorModel =
from x in modelState.Keys
where modelState[x].Errors.Count > 0
select new
{
key = x,
errors = modelState[x].Errors.
Select(y => y.ErrorMessage).
ToArray()
};
filterContext.Result = new JsonResult()
{
Data = errorModel
};
filterContext.HttpContext.Response.StatusCode =
(int) HttpStatusCode.BadRequest;
}
}
}
What this does is return a JSON object specifying all of your model errors.
Example response would be
[{
"key":"Name",
"errors":["The Name field is required."]
},
{
"key":"Description",
"errors":["The Description field is required."]
}]
This would be returned to your error handling callback of the $.ajax
call
You can loop through the returned data to set the error messages as needed based on the Keys returned (I think something like $('input[name="' + err.key + '"]')
would find your input element
Try this code to 100% work....
UIImageView * imageview = [[UIImageView alloc] initWithFrame:CGRectMake(20,100, 80, 80)];
imageview.image = [UIImage imageNamed:@"myimage.jpg"];
[self.view addSubview:imageview];
You can use Arrays.fill(array, -1)
.
echo stat | nc localhost 2181 | grep Mode
echo srvr | nc localhost 2181 | grep Mode #(From 3.3.0 onwards)
Above will work in whichever modes Zookeeper is running (standalone or embedded).
If zookeeper is running in standalone mode, its a JVM process. so -
jps | grep Quorum
will display list of jvm processes; something like this for zookeeper with process ID
HQuorumPeer
Here is what I did and it works perfectly on every version of Android.
toolbar.xml
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="56dp"
android:background="@color/primary_color"
app:theme="@style/ThemeOverlay.AppCompat"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
<TextView
android:id="@+id/toolbar_title"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp" <!-- Add margin -->
android:layout_marginStart="16dp"
android:gravity="left|center"
android:text="Toolbar Title" <!-- Your title text -->
android:textColor="@color/white" <!-- Matches default title styles -->
android:textSize="20sp"
android:fontFamily="sans-serif-medium"/>
</android.support.v7.widget.Toolbar>
MyActivity.java (To hide default toolbar title)
getSupportActionBar().setDisplayShowTitleEnabled(false); // Hide default toolbar title
Result with Keylines Shown
This is called type assertion in TypeScript, and since TypeScript 1.6, there are two ways to express this:
// Original syntax
var markerSymbolInfo = <MarkerSymbolInfo> symbolInfo;
// Newer additional syntax
var markerSymbolInfo = symbolInfo as MarkerSymbolInfo;
Both alternatives are functionally identical. The reason for introducing the as
-syntax is that the original syntax conflicted with JSX, see the design discussion here.
If you are in a position to choose, just use the syntax that you feel more comfortable with. I personally prefer the as
-syntax as it feels more fluent to read and write.
From Stack Overflow question What is the Python 3 equivalent of "python -m SimpleHTTPServer":
The following works for me:
python -m http.server [<portNo>]
Because I am using Python 3 the module SimpleHTTPServer
has been replaced by http.server
, at least in Windows.
Not all browsers support event capturing (for example, Internet Explorer versions less than 9 don't) but all do support event bubbling, which is why it is the phase used to bind handlers to events in all cross-browser abstractions, jQuery's included.
The nearest to what you are looking for in jQuery is using bind()
(superseded by on()
in jQuery 1.7+) or the event-specific jQuery methods (in this case, click()
, which calls bind()
internally anyway). All use the bubbling phase of a raised event.