There might be a better way, but this here's one approach:
row
0 00000 UNITED STATES
1 01000 ALABAMA
2 01001 Autauga County, AL
3 01003 Baldwin County, AL
4 01005 Barbour County, AL
df = pd.DataFrame(df.row.str.split(' ',1).tolist(),
columns = ['flips','row'])
flips row
0 00000 UNITED STATES
1 01000 ALABAMA
2 01001 Autauga County, AL
3 01003 Baldwin County, AL
4 01005 Barbour County, AL
As mentioned by joanq MariaDB now seems to support CHECK constraints among other goodies:
"Support for CHECK CONSTRAINT (MDEV-7563)."
https://mariadb.com/kb/en/mariadb/mariadb-1021-release-notes/
It's important to understand that there is a distinction between an object's prototype (which is available via
Object.getPrototypeOf(obj)
, or via the deprecated__proto__
property) and theprototype
property on constructor functions. The former is the property on each instance, and the latter is the property on the constructor. That is,Object.getPrototypeOf(new Foobar())
refers to the same object asFoobar.prototype
.
Reference: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes
What are you going to do with the URI?
If you're just going to use it with an HttpGet for example, you can just use the string directly when creating the HttpGet instance.
HttpGet get = new HttpGet("http://stackoverflow.com");
My personal opinion: Go for Swing together with the NetBeans platform.
If you need advanced components (more than NetBeans offers) you can easily integrate SwingX without problems (or JGoodies) as the NetBeans platform is completely based on Swing.
I would not start a large desktop application (or one that is going to be large) without a good platform that is build upon the underlying UI framework.
The other option is SWT together with the Eclipse RCP, but it's harder (though not impossible) to integrate "pure" Swing components into such an application.
The learning curve is a bit steep for the NetBeans platform (although I guess that's true for Eclipse as well) but there are some good books around which I would highly recommend.
Solution: Remove height: 100%
in .item-inner and add display: flex
in .item
Handlebars supports {{else if}}
blocks as of 3.0.0.
Handlebars v3.0.0 or greater:
{{#if FriendStatus.IsFriend}}
<div class="ui-state-default ui-corner-all" title=".ui-icon-mail-closed"><span class="ui-icon ui-icon-mail-closed"></span></div>
{{else if FriendStatus.FriendRequested}}
<div class="ui-state-default ui-corner-all" title=".ui-icon-check"><span class="ui-icon ui-icon-check"></span></div>
{{else}}
<div class="ui-state-default ui-corner-all" title=".ui-icon-plusthick"><span class="ui-icon ui-icon-plusthick"></span></div>
{{/if}}
Prior to Handlebars v3.0.0, however, you will have to either define a helper that handles the branching logic or nest if
statements manually:
{{#if FriendStatus.IsFriend}}
<div class="ui-state-default ui-corner-all" title=".ui-icon-mail-closed"><span class="ui-icon ui-icon-mail-closed"></span></div>
{{else}}
{{#if FriendStatus.FriendRequested}}
<div class="ui-state-default ui-corner-all" title=".ui-icon-check"><span class="ui-icon ui-icon-check"></span></div>
{{else}}
<div class="ui-state-default ui-corner-all" title=".ui-icon-plusthick"><span class="ui-icon ui-icon-plusthick"></span></div>
{{/if}}
{{/if}}
As of jQuery 1.7, the .live()
method is deprecated. Use .on()
to attach event handlers.
Example -
$( document ).on( events, selector, data, handler );
IE11 do accept Java according to the link below : http://windows.microsoft.com/en-us/internet-explorer/install-java#ie=ie-11
And firefox also intended to remove NPAPI by the end of 2016 according to : https://blog.mozilla.org/futurereleases/2015/10/08/npapi-plugins-in-firefox/
There's the --dry-run
flag which will allow you to preview the changes, and/or you can use the Angular Console App to generate the cli flags for you, using their easy GUI. It auto-previews everything before you commit to it.
In an easy language,
1. A description of an Intent and Target action to perform. First you have to create an intent and then you have to pass an specific java class which you want to execute, to the Intent.
2. You can call those java class which is your class action class by PendingIntent.getActivity, PendingIntent.getActivities(Context, int, Intent[], int), PendingIntent.getBroadcast(Context, int, Intent, int), and PendingIntent.getService(Context, int, Intent, int);
Here you see that Intent which is comes from the step 1
3. You should keep in mind that...By giving a PendingIntent to another application, you are granting it the right to perform the operation you have specified.
That is what I learned after a long reading.
Simply run the command:
C:>python .\file_name.py
Assuming the file name is within same folder and Python has already been added to environment variables.
You're swapping endianness between your two methods. You have intToByteArray(int a)
assigning the low-order bits into ret[0]
, but then byteArrayToInt(byte[] b)
assigns b[0]
to the high-order bits of the result. You need to invert one or the other, like:
public static byte[] intToByteArray(int a)
{
byte[] ret = new byte[4];
ret[3] = (byte) (a & 0xFF);
ret[2] = (byte) ((a >> 8) & 0xFF);
ret[1] = (byte) ((a >> 16) & 0xFF);
ret[0] = (byte) ((a >> 24) & 0xFF);
return ret;
}
by default <UL/>
contains default padding
therefore try adding style to padding:0px
in css class or inline css
All my tests were working fine. But for some reason I had set my environment variable to non-test:
export RAILS_ENV=something_non_test
I forgot to unset this variable because of which I started getting ActionController::InvalidAuthenticityToken
exception.
After unsetting $RAILS_ENV
, my tests started working again.
In addition to the answers above, you could use a small extension method:
public static class Extensions
{
public static void Run(this string fileName,
string workingDir=null, params string[] arguments)
{
using (var p = new Process())
{
var args = p.StartInfo;
args.FileName = fileName;
if (workingDir!=null) args.WorkingDirectory = workingDir;
if (arguments != null && arguments.Any())
args.Arguments = string.Join(" ", arguments).Trim();
else if (fileName.ToLowerInvariant() == "explorer")
args.Arguments = args.WorkingDirectory;
p.Start();
}
}
}
and use it like so:
// open explorer window with given path
"Explorer".Run(path);
// open a shell (remanins open)
"cmd".Run(path, "/K");
The easiest way to overwrite a text file is to use a public static field.
this will overwrite the file every time because your only using false the first time through.`
public static boolean appendFile;
Use it to allow only one time through the write sequence for the append field of the write code to be false.
// use your field before processing the write code
appendFile = False;
File fnew=new File("../playlist/"+existingPlaylist.getText()+".txt");
String source = textArea.getText();
System.out.println(source);
FileWriter f2;
try {
//change this line to read this
// f2 = new FileWriter(fnew,false);
// to read this
f2 = new FileWriter(fnew,appendFile); // important part
f2.write(source);
// change field back to true so the rest of the new data will
// append to the new file.
appendFile = true;
f2.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The best way is to do a mongodump
then mongorestore
. You can select the collection via:
mongodump -d some_database -c some_collection
[Optionally, zip the dump (zip some_database.zip some_database/* -r
) and scp
it elsewhere]
Then restore it:
mongorestore -d some_other_db -c some_or_other_collection dump/some_collection.bson
Existing data in some_or_other_collection
will be preserved. That way you can "append" a collection from one database to another.
Prior to version 2.4.3, you will also need to add back your indexes after you copy over your data. Starting with 2.4.3, this process is automatic, and you can disable it with --noIndexRestore
.
This is Good Example for Fade In and Fade Out Animation with Alpha Effect
UPDATED :
check this answer may this help you
You're calling writer.close();
after you've done writing to it. Once a stream is closed, it can not be written to again. Usually, the way I go about implementing this is by moving the close out of the write to method.
public void writeToFile(){
String file_text= pedStatusText + " " + gatesStatus + " " + DrawBridgeStatusText;
try {
writer.write(file_text);
writer.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And add a method cleanUp
to close the stream.
public void cleanUp() {
writer.close();
}
This means that you have the responsibility to make sure that you're calling cleanUp
when you're done writing to the file. Failure to do this will result in memory leaks and resource locking.
EDIT: You can create a new stream each time you want to write to the file, by moving writer
into the writeToFile()
method..
public void writeToFile() {
FileWriter writer = new FileWriter("status.txt", true);
// ... Write to the file.
writer.close();
}
Use os.environ[str(DEBUSSY)]
for both reading and writing (http://docs.python.org/library/os.html#os.environ).
As for reading, you have to parse the number from the string yourself of course.
As I am new, I can't comment on other answers.
If someone is looking for an answer to make this work (and can use javascript - as it seems to be required to make this work at the moment) this approach has worked pretty well for me and it accounts for mobile orientation change as well. I use Jquery for the example code but should be doable with vanillaJS.
-First, I use a script to detect if the device is touch or hover. Bare-bones example:
if ("ontouchstart" in document.documentElement) {
document.body.classList.add('touch-device');
} else {
document.body.classList.add('hover-device');
}
This adds class to the body element according to the device type (hover or touch) that can be used later for the height script.
-Next use this code to set height of the device on load and on orientation change:
if (jQuery('body').hasClass("touch-device")) {
//Loading height on touch-device
function calcFullHeight() {
jQuery('.hero-section').css("height", $(window).height());
}
(function($) {
calcFullHeight();
jQuery(window).on('orientationchange', function() {
// 500ms timeout for getting the correct height after orientation change
setTimeout(function() {
calcFullHeight();
}, 500);
});
})(jQuery);
} else {
jQuery('.hero-section').css("height", "100vh");
}
-Timeout is set so that the device would calculate the new height correctly on orientation change. If there is no timeout, in my experience the height will not be correct. 500ms might be an overdo but has worked for me.
-100vh on hover-devices is a fallback if the browser overrides the CSS 100vh.
It seems impossible to get value without loading product model. If you take a look at file app/code/core/Mage/Eav/Model/Entity/Attribute/Frontend/Abstract.php you'll see the method
public function getValue(Varien_Object $object)
{
$value = $object->getData($this->getAttribute()->getAttributeCode());
if (in_array($this->getConfigField('input'), array('select','boolean'))) {
$valueOption = $this->getOption($value);
if (!$valueOption) {
$opt = new Mage_Eav_Model_Entity_Attribute_Source_Boolean();
if ($options = $opt->getAllOptions()) {
foreach ($options as $option) {
if ($option['value'] == $value) {
$valueOption = $option['label'];
}
}
}
}
$value = $valueOption;
}
elseif ($this->getConfigField('input')=='multiselect') {
$value = $this->getOption($value);
if (is_array($value)) {
$value = implode(', ', $value);
}
}
return $value;
}
As you can see this method requires loaded object to get data from it (3rd line).
I know this is an older question, but I wanted to post an answer for users with the same question:
curl -H 'Cache-Control: no-cache' http://www.example.com
This curl command servers in its header request to return non-cached data from the web server.
If by "restart", you mean to start a new 4 second interval at this moment, then you must stop and restart the timer.
function myFn() {console.log('idle');}
var myTimer = setInterval(myFn, 4000);
// Then, later at some future time,
// to restart a new 4 second interval starting at this exact moment in time
clearInterval(myTimer);
myTimer = setInterval(myFn, 4000);
You could also use a little timer object that offers a reset feature:
function Timer(fn, t) {
var timerObj = setInterval(fn, t);
this.stop = function() {
if (timerObj) {
clearInterval(timerObj);
timerObj = null;
}
return this;
}
// start timer using current settings (if it's not already running)
this.start = function() {
if (!timerObj) {
this.stop();
timerObj = setInterval(fn, t);
}
return this;
}
// start with new or original interval, stop current interval
this.reset = function(newT = t) {
t = newT;
return this.stop().start();
}
}
Usage:
var timer = new Timer(function() {
// your function here
}, 5000);
// switch interval to 10 seconds
timer.reset(10000);
// stop the timer
timer.stop();
// start the timer
timer.start();
Working demo: https://jsfiddle.net/jfriend00/t17vz506/
A UDF will only return a value it won't allow you to change the properties of a cell/sheet/workbook. Move your code to a Worksheet_Change event or similar to change properties.
Eg
Private Sub worksheet_change(ByVal target As Range)
target.Font.Bold = True
End Sub
How about this: location.href.slice(0, - ((location.search + location.hash).length))
If you are using read only input field, you can use ng-value with filter.
for example:
ng-value="price | number:8"
try this css:
/* Show in default resolution screen*/
#container2 {
width: 960px;
position: relative;
margin:0 auto;
line-height: 1.4em;
}
/* If in mobile screen with maximum width 479px. The iPhone screen resolution is 320x480 px (except iPhone4, 640x960) */
@media only screen and (max-width: 479px){
#container2 { width: 90%; }
}
Here the demo: http://jsfiddle.net/ongisnade/CG9WN/
Extending your code (assuming that the XML you want to send is in xmlString
) :
String xmlString = "</xml>";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(this.url);
httpRequest.setHeader("Content-Type", "application/xml");
StringEntity xmlEntity = new StringEntity(xmlString);
httpRequest.setEntity(xmlEntity );
HttpResponse httpresponse = httpclient.execute(httppost);
If you're really bent upon converting Integer to String value, I suggest use String.valueOf(YourIntegerVariable). More details can be found at: http://www.tutorialspoint.com/java/java_string_valueof.htm
I written in main activity like this,
override fun onSupportNavigateUp(): Boolean {
return findNavController(R.id.my_nav_host_fragment).navigateUp(appBarConfiguration)
}
As of matplotlib v1.4.0rc4
, a remove
method has been added to the legend object.
Usage:
ax.get_legend().remove()
or
legend = ax.legend(...)
...
legend.remove()
See here for the commit where this was introduced.
Iterate through a copy of the list:
>>> a = ["a", "b", "c", "d", "e"]
>>> for item in a[:]:
print item
if item == "b":
a.remove(item)
a
b
c
d
e
>>> print a
['a', 'c', 'd', 'e']
numpy.fromiter()
is what you are looking for:
big_array = numpy.fromiter(xrange(5), dtype="int")
It also works with generator expressions, e.g.:
big_array = numpy.fromiter( (i*(i+1)/2 for i in xrange(5)), dtype="int" )
If you know the length of the array in advance, you can specify it with an optional 'count' argument.
You can do this the following two ways:
1) Using loop
attribute in video element (mentioned in the first answer):
2) and you can use the ended
media event:
window.addEventListener('load', function(){
var newVideo = document.getElementById('videoElementId');
newVideo.addEventListener('ended', function() {
this.currentTime = 0;
this.play();
}, false);
newVideo.play();
});
The "0x" counts towards the eight character count. You need "%#010x"
.
Note that #
does not append the 0x to 0 - the result will be 0000000000
- so you probably actually should just use "0x%08x"
anyway.
This doesn't quite yet look like what I want, but I accomplished something like
this by stacking nav pills in the leftmost two spans. This is what my app's
app/views/layouts/application.html.erb
file looks like:
<!DOCTYPE html>
...
<body>
<!-- top navigation bar -->
<div class="navbar navbar-fixed-top">
...
</div>
<div class="container-fluid">
<!-- the navigation buttons bar on the left -->
<div class="sidebar-nav span2"> <!-- we reserve 2 spans out of 12 for this -->
<ul class="nav nav-pills nav-stacked">
<li class="<%= current_page?(root_path) ? 'active' : 'inactive' %>">
<%= link_to "Home", root_path %>
</li>
<li class="<%= current_page?(section_a_path) ? 'active' : 'inactive' %>">
<%= link_to "Section A", section_a_path %>
</li>
<li class="<%= current_page?(section_b_path) ? 'active' : 'inactive' %>">
<%= link_to "Section B", section_b_path %>
</li>
</ul>
</div>
<div class="container-fluid span10"> <!-- use the remaining 10 spans -->
<%= flash_messages %>
<%= yield :layout %> <!-- the content page sees a full 12 spans -->
</div>
</div> <!-- class="container-fluid" -->
...
</body>
</html>
Now the stacked pills appear on the top left, below the navbar. When the user clicks on
one of them, the corresponding page loads. From the point of view of
application.html.erb
, that page has the 10 rightmost spans available for it,
but from the page's view, it has the full 12 spans available.
The button corresponding to the page currently being displayed is rendered as
active, and the others as inactive. Specify the colours for active and inactive
buttons in file app/assets/stylesheets/custom.css.scss
(in this case, the
colour for a disabled state is also defined):
@import "bootstrap";
...
$spray: #81c9e2;
$grey_light: #dddddd;
...
.nav-pills {
.inactive > a, .inactive > a:hover {
background-color: $spray;
}
.disabled > a, .disabled > a:hover {
background-color: $grey_light;
}
}
The active pill's colour is not defined, so it appears as the default blue.
File custom.css.scss
is included because of the line *= require_tree .
in
file app/assets/stylesheets/application.css
.
It's a "native (platform-specific) size integer." It's internally represented as void*
but exposed as an integer. You can use it whenever you need to store an unmanaged pointer and don't want to use unsafe
code. IntPtr.Zero
is effectively NULL
(a null pointer).
Why not just
private double translateSlider(int sliderval) {
if(sliderval > 4 || sliderval < 0)
return 1.0d;
return (1.0d - ((double)sliderval/10.0d));
}
Or similar?
Everyone explained pretty well on it. Let me answer when should this class be used.
When Should You Use NoSuchElementException?
Java includes a few different ways to iterate through elements in a collection. The first of these classes, Enumeration, was introduced in JDK1.0
and is generally considered deprecated in favor of newer iteration classes, like Iterator and ListIterator.
As with most programming languages, the Iterator class includes a hasNext()
method that returns a boolean indicating if the iteration has anymore elements. If hasNext()
returns true
, then the next()
method will return the next element in the iteration. Unlike Enumeration, Iterator also has a remove()
method, which removes the last element that was obtained via next()
.
While Iterator is generalized for use with all collections in the Java Collections Framework
, ListIterator
is more specialized and only works with List-based collections, like ArrayList
, LinkedList
, and so forth. However, ListIterator
adds even more functionality by allowing iteration to traverse in both directions via hasPrevious()
and previous()
methods.
Extracting the Year say from ['2018-03-04']
df['Year'] = pd.DatetimeIndex(df['date']).year
The df['Year'] creates a new column. While if you want to extract the month just use .month
Try this, it works for me.
inline std::string trim(std::string& str)
{
str.erase(0, str.find_first_not_of(' ')); //prefixing spaces
str.erase(str.find_last_not_of(' ')+1); //surfixing spaces
return str;
}
DEMO : http://jsfiddle.net/shfj70qp/
//dd/mm/yyyy
var date = new Date();
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();
console.log(month+"/"+day+"/"+year);
My personal experience was that I had installed the Team Foundation Server client for 2017 first (was using it as a Proof of Concept for our QA team, while I was still using VS2015), then followed it up with Installing Visual Studio 2017 later to begin development.
What I ended up with on my Start Menu was a Visual Studio 2017 and a Visual Studio 2017 (2). The Visual Studio 2017 (2) had all the templates I was missing. Following the steps found in the First answer to this question (which were clear and easy to follow) did not fix my issue. I had thought that launching the client would upgrade to the Development Client, but it did not. I renamed it to Visual Studio Professional, and now have everything I need. Not sure if this happens to anyone else, but it was what happened to me, so I hope this helps someone.
This code works well in Swift 3.1 and Xcode 8.3.2
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
self.collectionView.collectionViewLayout = layout
self.collectionView!.contentInset = UIEdgeInsets(top: -10, left: 0, bottom:0, right: 0)
if let layout = self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.itemSize = CGSize(width: self.view.frame.size.width-40, height: self.collectionView.frame.size.height-10)
layout.invalidateLayout()
}
}
For my purposes, in the context of a container view controller, I've found that
- (BOOL)isVisible {
return (self.isViewLoaded && self.view.window && self.parentViewController != nil);
}
works well.
Microsoft has their own Command Line Standard specification:
This document is focused at developers of command line utilities. Collectively, our goal is to present a consistent, composable command line user experience. Achieving that allows a user to learn a core set of concepts (syntax, naming, behaviors, etc) and then be able to translate that knowledge into working with a large set of commands. Those commands should be able to output standardized streams of data in a standardized format to allow easy composition without the burden of parsing streams of output text. This document is written to be independent of any specific implementation of a shell, set of utilities or command creation technologies; however, Appendix J - Using Windows Powershell to implement the Microsoft Command Line Standard shows how using Windows PowerShell will provide implementation of many of these guidelines for free.
The stack is "implemented" by means of the stack pointer, which (assuming x86 architecture here) points into the stack segment. Every time something is pushed on the stack (by means of pushl, call, or a similar stack opcode), it is written to the address the stack pointer points to, and the stack pointer decremented (stack is growing downwards, i.e. smaller addresses). When you pop something off the stack (popl, ret), the stack pointer is incremented and the value read off the stack.
In a user-space application, the stack is already set up for you when your application starts. In a kernel-space environment, you have to set up the stack segment and the stack pointer first...
It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.
Look at the definition of sys.all_parameters
:
default_value
sql_variant
Ifhas_default_value
is 1, the value of this column is the value of the default for the parameter; otherwise,NULL
.
That is, whatever the default for a parameter is, it has to fit in that column.
As Alex K pointed out in the comments, you can just do:
CREATE PROCEDURE [dbo].[problemParam]
@StartDate INT = NULL,
@EndDate INT = NULL
AS
BEGIN
SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))
provided that NULL
isn't intended to be a valid value for @StartDate
.
As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE()
within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.
for the GitLab Enterprise Edition 9.3.0
By default, master branch is protected so unprotect :)
1-Select you "project"
2-Select "Repository"
3-Select "branches"
4-Select "Project Settings"
5-In "Protected Branches" click to "expand"
6-and after click in "unprotect" button
Substring
has two Overloading methods:
public string Substring(int startIndex);//The substring starts at a specified character position and continues to the end of the string.
public string Substring(int startIndex, int length);//The substring starts at a specified character position and taking length no of character from the startIndex.
So for this scenario, you may use the first method like this below:
var str = "hello world!";
str = str.Substring(10);
Here the output is:
d!
If you may apply defensive coding by checking its length.
I faced the same issue and got the same deprecation warning. I was using a numpy array of [23, 276] when I got the message. I tried reshaping it as per the warning and end up in nowhere. Then I select each row from the numpy array (as I was iterating over it anyway) and assigned it to a list variable. It worked then without any warning.
array = []
array.append(temp[0])
Then you can use the python list object (here 'array') as an input to sk-learn functions. Not the most efficient solution, but worked for me.
We can add for all devices with platform specific size
<link rel="apple-touch-icon" sizes="57x57" href="fav_icons/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="fav_icons/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="fav_icons/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="fav_icons/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="fav_icons/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="fav_icons/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="fav_icons/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="fav_icons/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="fav_icons/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="fav_icons/android-icon-192x192.pn">
<link rel="icon" type="image/png" sizes="32x32" href="fav_icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="fav_icons/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="fav_icons/favicon-16x16.png">
Is there also a way to pass coords directly to google maps to display?
You can use the geo URI
prefix:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("geo:" + latitude + "," + longitude));
startActivity(intent);
I am promoting my comment to an answer:
The easy way is:
You could draw in the original 'frame' itself instead of using gray image.
The hard way (method you were trying to implement):
backtorgb = cv2.cvtColor(gray,cv2.COLOR_GRAY2RGB)
is the correct syntax.
This error happened to me because I had @@model instead of @model... copy & paste error in my case. Changing to @model fixed it for me.
You can do the same on document ready
event like below
<script>
$(document).ready(function(){
var number = 112;
$("yourClass/Element/id...").html(number);
// $("yourClass/Element/id...").text(number);
});
</script>
or you can simply do it using document.write(number);
.
Short answer: You can't.
Long answer: You could use a modal to display a popup with the image you need.
You can refer to this as an example to a modal.
Based off a few answers already given here I decided to mostly back JoelFan's answer. I love extension methods and these have been working great for me when none of the other solutions would using them to compare my complex classes.
using System.IO;
using System.Xml.Serialization;
static class ObjectHelpers
{
public static string SerializeObject<T>(this T toSerialize)
{
XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
using (StringWriter textWriter = new StringWriter())
{
xmlSerializer.Serialize(textWriter, toSerialize);
return textWriter.ToString();
}
}
public static bool EqualTo(this object obj, object toCompare)
{
if (obj.SerializeObject() == toCompare.SerializeObject())
return true;
else
return false;
}
public static bool IsBlank<T>(this T obj) where T: new()
{
T blank = new T();
T newObj = ((T)obj);
if (newObj.SerializeObject() == blank.SerializeObject())
return true;
else
return false;
}
}
if (record.IsBlank())
throw new Exception("Record found is blank.");
if (record.EqualTo(new record()))
throw new Exception("Record found is blank.");
To have it in one line, this is what I did:
if any(([True if 'MICHAEL89' in username.upper() else False for username in USERNAMES])):
print('username exists in list')
I didn't test it time-wise though. I am not sure how fast/efficient it is.
I had the same problem earlier when I tried to edit an open source project from the internet .
Solved it by just Cleaning the solution and rebuilding it .
Hope this helps.
I wasn't able to change the source model like in the top answer (of @ob.), and I didn't want to register it globally like @Iggy. So I combined https://stackoverflow.com/a/2870420/237091 and @Iggy's https://stackoverflow.com/a/18152942/237091 to allow setting up the string enum converter on during the SerializeObject command itself:
Newtonsoft.Json.JsonConvert.SerializeObject(
objectToSerialize,
Newtonsoft.Json.Formatting.None,
new Newtonsoft.Json.JsonSerializerSettings()
{
Converters = new List<Newtonsoft.Json.JsonConverter> {
new Newtonsoft.Json.Converters.StringEnumConverter()
}
})
Old one but I would add my answer as per my findings:
var ancestralState = context.findAncestorStateOfType<ParentState>();
ancestralState.setState(() {
// here you can access public vars and update state.
...
});
You can use the Build Class to get the device information.
For example:
String myDeviceModel = android.os.Build.MODEL;
This acronym might help you to remember the ASP.NET life cycle stages which I wrote about in the below blog post.
R-SIL-VP-RU
- Request
- Start
- Initialization
- Load
- Validation
- Post back handling
- Rendering
- Unload
From my blog: Understand ASP.NET Page life cycle and remember stages in easy way
18 May 2014
The basic way, unfortunately, is to repeat yourself.
SELECT
CASE WHEN <condition 1> THEN <a1> WHEN <condition 2> THEN <a2> ELSE <a3> END,
CASE WHEN <condition 1> THEN <b1> WHEN <condition 2> THEN <b2> ELSE <b3> END
FROM
<table>
Fortunately, most RDBMS are clever enough to NOT have to evaluate the conditions multiple times. It's just redundant typing.
In MS SQL Server (2005+) you could possible use CROSS APPLY as an alternative to this. Though I have no idea how performant it is...
SELECT
*
FROM
<table>
CROSS APPLY
(
SELECT a1, b1 WHERE <condition 1>
UNION ALL
SELECT a2, b2 WHERE <condition 2>
UNION ALL
SELECT a3, b3 WHERE <condition 3>
)
AS case_proxy
The noticable downside here is that there is no ELSE equivalent and as all the conditions could all return values, they need to be framed such that only one can ever be true at a time.
EDIT
If Yuck's answer is changed to a UNION rather than JOIN approach, it becomes very similar to this. The main difference, however, being that this only scans the input data set once, rather than once per condition (100 times in your case).
EDIT
I've also noticed that you may mean that the values returned by the CASE statements are fixed. All records that match the same condition get the exact sames values in value1 and value2. This could be formed like this...
WITH
checked_data AS
(
SELECT
CASE WHEN <condition1> THEN 1
WHEN <condition2> THEN 2
WHEN <condition3> THEN 3
...
ELSE 100
END AS condition_id,
*
FROM
<table>
)
,
results (condition_id, value1, value2) AS
(
SELECT 1, a1, b1
UNION ALL
SELECT 2, a2, b2
UNION ALL
SELECT 3, a3, b3
UNION ALL
...
SELECT 100, a100, b100
)
SELECT
*
FROM
checked_data
INNER JOIN
results
ON results.condition_id = checked_data.condition_id
Include a few #ifndef name #define name #endif preprocessor that should solve your problem. The issue is it going from the header to the function then back to the header so it is redefining the class with all the preprocessor(#include) multiple times.
The problem with things like width:95%;
is that they don't look right in wide flexible layouts (because 5% can then be like 30 pixels).
The following solutions works very well for me (tested in Firefox, IE 9, Safari):
<table style="background-color: blue; width: 100%;" cellpadding="0" cellspacing="0">
<tr>
<td style="background-color: red; padding: 3px;">
<div style="margin-right: 3px;">
<div style="padding-right: 3px;">
<input type="text" style="width:100%;">
</div>
</div>
</td>
<td style="background-color: purple; padding: 3px;">
<div style="margin-right: 3px;">
<div style="padding-right: 3px;">
<input type="text" style="width:100%;">
</div>
</div>
</td>
<td style="background-color: green; padding: 3px;">
<div style="margin-right: 3px;">
<div style="padding-right: 3px;">
<input type="text" style="width:100%;">
</div>
</div>
</td>
</tr>
</table>
(added the colors to make it easier to notice the correct padding)
The trick is to wrap the input with two divs, the outer has a 3px margin (which makes it 3px smaller than the td), the inner has a 3px padding. This makes the input 6px smaller than the td, which is what you wanted to begin with.
I am not sure about the mechanics of this, but it works.
In this simple example, it also works with just a single div with right margin 6. However, in the case of my web application, only the above solution works.
<table style="background-color: blue; width: 100%;" cellpadding="0" cellspacing="0">
<tr>
<td style="background-color: red; padding: 3px;">
<div style="margin-right: 6px;">
<input type="text" style="width:100%;">
</div>
</td>
<td style="background-color: purple; padding: 3px;">
<div style="margin-right: 6px;">
<input type="text" style="width:100%;">
</div>
</td>
<td style="background-color: green; padding: 3px;">
<div style="margin-right: 6px;">
<input type="text" style="width:100%;">
</div>
</td>
</tr>
</table>
Select * from people p, address a where p.id = a.person_id and a.zip='97229';
Or you must TRY using JOIN
which is a more efficient and better way to do this as Gordon Linoff in the comments below also says that you need to learn this.
SELECT p.*, a.street, a.city FROM persons AS p
JOIN address AS a ON p.id = a.person_id
WHERE a.zip = '97299';
Here p.*
means it will show all the columns of PERSONS table.
For those who even yet have the problem, try enabling "Build project automatically" in the Java compiler settings and see if that makes a difference as it worked for me.
overthink suggested using the setup in the pom:
<project>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<configuration>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
... other stuff ...
</configuration>
</plugin>
</plgins>
</build>
...
First i thought this still won't attach the javadoc and sources (as i tried unsuccessfully with that -DdownloadSources option before).
But surprise - the .classpath file IS getting its sources and javadoc attached when using the POM variant!
Or for what seems like rampant overkill, but is actually simplistic ... Pretty much covers all of your cases, and no empty string or unary concerns.
In the case the first arg is '-v', then do your conditional ps -ef
, else in all other cases throw the usage.
#!/bin/sh
case $1 in
'-v') if [ "$1" = -v ]; then
echo "`ps -ef | grep -v '\['`"
else
echo "`ps -ef | grep '\[' | grep root`"
fi;;
*) echo "usage: $0 [-v]"
exit 1;; #It is good practice to throw a code, hence allowing $? check
esac
If one cares not where the '-v' arg is, then simply drop the case inside a loop. The would allow walking all the args and finding '-v' anywhere (provided it exists). This means command line argument order is not important. Be forewarned, as presented, the variable arg_match is set, thus it is merely a flag. It allows for multiple occurrences of the '-v' arg. One could ignore all other occurrences of '-v' easy enough.
#!/bin/sh
usage ()
{
echo "usage: $0 [-v]"
exit 1
}
unset arg_match
for arg in $*
do
case $arg in
'-v') if [ "$arg" = -v ]; then
echo "`ps -ef | grep -v '\['`"
else
echo "`ps -ef | grep '\[' | grep root`"
fi
arg_match=1;; # this is set, but could increment.
*) ;;
esac
done
if [ ! $arg_match ]
then
usage
fi
But, allow multiple occurrences of an argument is convenient to use in situations such as:
$ adduser -u:sam -s -f -u:bob -trace -verbose
We care not about the order of the arguments, and even allow multiple -u arguments. Yes, it is a simple matter to also allow:
$ adduser -u sam -s -f -u bob -trace -verbose
Not sure what isn't working in your case, but the following code will put a formula into cell A1 that will retrieve the value in the cell G2.
strProjectName = "Sheet1"
Cells(1, 1).Formula = "=" & strProjectName & "!" & Cells(2, 7).Address
The workbook and worksheet that strProjectName
references must exist at the time that this formula is placed. Excel will immediately try to evaluate the formula. You might be able to stop that from happening by turning off automatic recalculation until the workbook does exist.
Here's my solution: Simply get the count of your array, minus 1 (since they start in 0).
$lastkey = count($array) - 1;
foreach($array as $k=>$a){
if($k==$lastkey){
/*do something*/
}
}
You might need to allow different combinations of data in your intent filter to get it to work in different cases (http/
vs https/
, www.
vs no www.
, etc).
For example, I had to do the following for an app which would open when the user opened a link to Google Drive forms (www.docs.google.com/forms
)
Note that path prefix is optional.
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="http" />
<data android:scheme="https" />
<data android:host="www.docs.google.com" />
<data android:host="docs.google.com" />
<data android:pathPrefix="/forms" />
</intent-filter>
This is for Mac users:
first of all you have to clarify where the class file is... so for example, in 'Terminal' (A Mac Application) you would type:
cd
then wherever you file is e.g:
cd /Users/CollarBlast/Desktop/JavaFiles/
then you would hit enter. After that you would do the command. e.g:
cd /Users/CollarBlast/Desktop/JavaFiles/
(then i would press enter...)
Then i would type the command:
javap -c JavaTestClassFile.class
(then i would press enter again...)
and hopefully it should work!
Do it like this:
char s[256];
strcpy(s, "one two three");
char* token = strtok(s, " ");
while (token) {
printf("token: %s\n", token);
token = strtok(NULL, " ");
}
Note: strtok
modifies the string its tokenising, so it cannot be a const char*
.
Go to Product > Clean Build Folder
I would either:
ssh
from the command line and accept the public key (the host will be added to ~/.ssh/known_hosts
and everything should then work fine from Jsch) -OR-Configure JSch to not use "StrictHostKeyChecking" (this introduces insecurities and should only be used for testing purposes), using the following code:
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
Option #1 (adding the host to the ~/.ssh/known_hosts
file) has my preference.
The easiest way
import re
txt='this is a paragraph with<[1> in between</[1> and then there are cases ... where the<[99> number ranges from 1-100</[99>. and there are many other lines in the txt files with<[3> such tags </[3>'
out = re.sub("(<[^>]+>)", '', txt)
print out
Actually, the Sysinternals junction
command only works with directories (don't ask me why), so it can't hardlink files. I would go with cmd /c mklink
for soft links (I can't figure why it's not supported directly by PowerShell), or fsutil
for hardlinks.
If you need it to work on Windows XP, I do not know of anything other than Sysinternals junction
, so you might be limited to directories.
The second parameter of the callback function passed to each() will contain the actual DOM element and not a jQuery wrapper object. You can call the getAttribute() method of the element:
$('#category_sorting_form_save').click(function() {
var elements = $("#category_sorting_elements > div");
$.each(elements, function(key, value) {
console.info(key, ": ", value);
console.info("cat_id: ", value.getAttribute('cat_id'));
});
});
Or wrap the element in a jQuery object yourself:
$('#category_sorting_form_save').click(function() {
var elements = $("#category_sorting_elements > div");
$.each(elements, function(key, value) {
console.info(key, ": ", value);
console.info("cat_id: ", $(value).attr('cat_id'));
});
});
Or simply use $(this)
:
$('#category_sorting_form_save').click(function() {
var elements = $("#category_sorting_elements > div");
$.each(elements, function() {
console.info("cat_id: ", $(this).attr('cat_id'));
});
});
By this code for formating price in product list
echo Mage::helper('core')->currency($_product->getPrice());
combine two strings together in PHP?
$result = $data1 . ' ' . $data2;
val() should handle both cases
<option value="1">it's me</option>
$('select').val('1'); // selects "it's me"
$('select').val("it's me"); // also selects "it's me"
hash_map
was a common extension provided by many library implementations. That is exactly why it was renamed to unordered_map
when it was added to the C++ standard as part of TR1. map is generally implemented with a balanced binary tree like a red-black tree (implementations vary of course). hash_map
and unordered_map
are generally implemented with hash tables. Thus the order is not maintained. unordered_map
insert/delete/query will be O(1) (constant time) where map will be O(log n) where n is the number of items in the data structure. So unordered_map
is faster, and if you don't care about the order of the items should be preferred over map
. Sometimes you want to maintain order (ordered by the key) and for that map
would be the choice.
In my case there was a static variable which was not initialized. When I initialized it, the error was removed. I don't know the logic behind it but worked for me. I know its a little late but other people with similar problem might get some help.
Fixed by moving the view modifiers to onPostExecute so the fixed code is :
public class Soirees extends ListActivity {
private List<Message> messages;
private TextView tvSorties;
//private MyProgressDialog dialog;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.sorties);
tvSorties=(TextView)findViewById(R.id.TVTitle);
tvSorties.setText("Programme des soirées");
new ProgressTask(Soirees.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
List<Message> titles;
private ListActivity activity;
//private List<Message> messages;
public ProgressTask(ListActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
@Override
protected void onPostExecute(final Boolean success) {
List<Message> titles = new ArrayList<Message>(messages.size());
for (Message msg : messages){
titles.add(msg);
}
MessageListAdapter adapter = new MessageListAdapter(activity, titles);
activity.setListAdapter(adapter);
adapter.notifyDataSetChanged();
if (dialog.isShowing()) {
dialog.dismiss();
}
if (success) {
Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
}
}
protected Boolean doInBackground(final String... args) {
try{
BaseFeedParser parser = new BaseFeedParser();
messages = parser.parse();
return true;
} catch (Exception e){
Log.e("tag", "error", e);
return false;
}
}
}
}
@Vladimir, thx your code was very helpful.
At least in the current versions of PHPMailers, there's a function clearReplyTos() to empty the reply-to array.
$mail->ClearReplyTos();
$mail->addReplyTo([email protected], 'EXAMPLE');
Works 100%.
import java.text.DecimalFormat;
public class Formatting {
public static void main(String[] args) {
double value = 22.2323242434342;
// or value = Math.round(value*100) / 100.0;
System.out.println("this is before formatting: "+value);
DecimalFormat df = new DecimalFormat("####0.00");
System.out.println("Value: " + df.format(value));
}
}
Edit. As noted in the comments, this is no longer working with the latest Android Studio releases.
The latest Android studio seems to only reference to "Offline mode" via the keymap, but toggling this does not seem to change anything anymore.
In Android Studio open the settings and search for offline it will find the Gradle
category which contains Offline work. You can disable it there.
public string Sifre_Uret(int boy, int noalfa)
{
// 01.03.2016
// Genel amaçli sifre üretme fonksiyonu
//Fonskiyon 128 den büyük olmasina izin vermiyor.
if (boy > 128 ) { boy = 128; }
if (noalfa > 128) { noalfa = 128; }
if (noalfa > boy) { noalfa = boy; }
string passch = System.Web.Security.Membership.GeneratePassword(boy, noalfa);
//URL encoding ve Url Pass + json sorunu yaratabilecekler pass ediliyor.
//Microsoft Garanti etmiyor. Alfa Sayisallar Olabiliyorimis . !@#$%^&*()_-+=[{]};:<>|./?.
//https://msdn.microsoft.com/tr-tr/library/system.web.security.membership.generatepassword(v=vs.110).aspx
//URL ve Json ajax lar için filtreleme
passch = passch.Replace(":", "z");
passch = passch.Replace(";", "W");
passch = passch.Replace("'", "t");
passch = passch.Replace("\"", "r");
passch = passch.Replace("/", "+");
passch = passch.Replace("\\", "e");
passch = passch.Replace("?", "9");
passch = passch.Replace("&", "8");
passch = passch.Replace("#", "D");
passch = passch.Replace("%", "u");
passch = passch.Replace("=", "4");
passch = passch.Replace("~", "1");
passch = passch.Replace("[", "2");
passch = passch.Replace("]", "3");
passch = passch.Replace("{", "g");
passch = passch.Replace("}", "J");
//passch = passch.Replace("(", "6");
//passch = passch.Replace(")", "0");
//passch = passch.Replace("|", "p");
//passch = passch.Replace("@", "4");
//passch = passch.Replace("!", "u");
//passch = passch.Replace("$", "Z");
//passch = passch.Replace("*", "5");
//passch = passch.Replace("_", "a");
passch = passch.Replace(",", "V");
passch = passch.Replace(".", "N");
passch = passch.Replace("+", "w");
passch = passch.Replace("-", "7");
return passch;
}
You can either create a new Stage
, add your controls into it or if you require the POPUP as Dialog
box, then you may consider using DialogsFX or ControlsFX(Requires JavaFX8)
For creating a new Stage, you can use the following snippet
@Override
public void start(final Stage primaryStage) {
Button btn = new Button();
btn.setText("Open Dialog");
btn.setOnAction(
new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
final Stage dialog = new Stage();
dialog.initModality(Modality.APPLICATION_MODAL);
dialog.initOwner(primaryStage);
VBox dialogVbox = new VBox(20);
dialogVbox.getChildren().add(new Text("This is a Dialog"));
Scene dialogScene = new Scene(dialogVbox, 300, 200);
dialog.setScene(dialogScene);
dialog.show();
}
});
}
If you don't want it to be modal
(block other windows), use:
dialog.initModality(Modality.NONE);
This is the intended use case for Ray, which is a library for parallel and distributed Python. Under the hood, it serializes objects using the Apache Arrow data layout (which is a zero-copy format) and stores them in a shared-memory object store so they can be accessed by multiple processes without creating copies.
The code would look like the following.
import numpy as np
import ray
ray.init()
@ray.remote
def func(array, param):
# Do stuff.
return 1
array = np.ones(10**6)
# Store the array in the shared memory object store once
# so it is not copied multiple times.
array_id = ray.put(array)
result_ids = [func.remote(array_id, i) for i in range(4)]
output = ray.get(result_ids)
If you don't call ray.put
then the array will still be stored in shared memory, but that will be done once per invocation of func
, which is not what you want.
Note that this will work not only for arrays but also for objects that contain arrays, e.g., dictionaries mapping ints to arrays as below.
You can compare the performance of serialization in Ray versus pickle by running the following in IPython.
import numpy as np
import pickle
import ray
ray.init()
x = {i: np.ones(10**7) for i in range(20)}
# Time Ray.
%time x_id = ray.put(x) # 2.4s
%time new_x = ray.get(x_id) # 0.00073s
# Time pickle.
%time serialized = pickle.dumps(x) # 2.6s
%time deserialized = pickle.loads(serialized) # 1.9s
Serialization with Ray is only slightly faster than pickle, but deserialization is 1000x faster because of the use of shared memory (this number will of course depend on the object).
See the Ray documentation. You can read more about fast serialization using Ray and Arrow. Note I'm one of the Ray developers.
There is always the easy way.
import numpy as np
print(np.matrix(A))
I've just solved a problem related to this which may help other people.
Initially when loading up MSSMSE it had the server as PC_NAME\SQLEXPRESS
and when I tried to connect it gave me Error: 26 - Error Locating Server/Instance Specified
, so I went into SQL Server Configuration Manager to check if my SQL Server Browser
and SQL Server
services were running and set to automatic, only to find that instead of saying SQL Server (SQLEXPRESS)
it says SQL Server(MSSQLSERVER)
.
I then tried connecting to PC-NAME\MSSQLSERVER
and this time got SQL Network Interfaces, error: 25 - Connection string is not valid) (MicrosoftSQL Server, Error: 87) The parameter is incorrect
so I googled this error and found that somebody had suggested that instead of using PC-NAME\MSSQLSERVER
just use PC-NAME
as the Server Name at the server connection interface, and this seems to work.
There's a link here http://learningsqlserver.wordpress.com/2011/01/21/what-version-of-sql-server-do-i-have/ which explains that MSSQLSERVER is the default instance and can be connected to by using just your hostname.
I think this may have arisen because I've had SQL Server 2008 installed at some point in the past.
Suppose you have two forms, and you want to hide the property of one form via another:
form1 ob = new form1();
ob.Show(this);
this.Enabled= false;
and when you want to get focus back of form1 via form2 button then:
Form1 ob = new Form1();
ob.Visible = true;
this.Close();
A variation of @Anthony Faull's answer for those using LINQPad:
new Server(new ServerConnection(this.Connection.DataSource))
.Databases[this.Connection.Database]
.Tables["<table>", "dbo"]
?.Script(new ScriptingOptions {
SchemaQualify = true,
DriAll = true,
})
You'll need to reference 2 assemblies:
And add namespace references as mentioned in Anthony's snippet.
As in the multi-dimensional array an entry is another array, specify the index of that value to array_push:
array_push($md_array['recipe_type'], $newdata);
If you wanted to use the DB facade:
DB::table('table_name')->whereNotNull('sent_at')->get();
You can use dblink to create a view that is resolved in another database. This database may be on another server.
The server sends the following in its response header to set a cookie field.
Set-Cookie:
name=
value
If there is a cookie set, then the browser sends the following in its request header.
Cookie:
name=
value
See the HTTP Cookie article at Wikipedia for more information.
Above, you mean OR not AND. Example of AND: 110 & 011 == 010 which is neither of the things you're looking for.
For OR, just have 2 cases without the break on the 1st. Eg:
case 'a':
case 'A':
// do stuff
break;
onNewIntent()
is meant as entry point for singleTop activities which already run somewhere else in the stack and therefore can't call onCreate()
. From activities lifecycle point of view it's therefore needed to call onPause()
before onNewIntent()
. I suggest you to rewrite your activity to not use these listeners inside of onNewIntent()
. For example most of the time my onNewIntent()
methods simply looks like this:
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// getIntent() should always return the most recent
setIntent(intent);
}
With all setup logic happening in onResume()
by utilizing getIntent()
.
These are use in ruby on rails :-
<% %> :-
The <% %> tags are used to execute Ruby code that does not return anything, such as conditions, loops or blocks. Eg :-
<h1>Names of all the people</h1>
<% @people.each do |person| %>
Name: <%= person.name %><br>
<% end %>
<%= %> :-
use to display the content .
Name: <%= person.name %><br>
<% -%>:-
Rails extends ERB, so that you can suppress the newline simply by adding a trailing hyphen to tags in Rails templates
<%# %>:-
comment out the code
<%# WRONG %>
Hi, Mr. <% puts "Frodo" %>
You can Try this, After starting Service of elasticsearch Type below line in your browser.
localhost:9200
It will give Output Something like that,
{
"status" : 200,
"name" : "Hypnotia",
"cluster_name" : "elasticsearch",
"version" : {
"number" : "1.7.1",
"build_hash" : "b88f43fc40b0bcd7f173a1f9ee2e97816de80b19",
"build_timestamp" : "2015-07-29T09:54:16Z",
"build_snapshot" : false,
"lucene_version" : "4.10.4"
},
"tagline" : "You Know, for Search"
}
You need to give the WebClient object the credentials. Something like this...
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
Because you're encapsulating the product again. Try to convert it like so:
let body = JSON.stringify(product);
The Other Issue I have seen on this is when nesting arrays this tends to throw the warning, consider the following:
$data = [
"rs" => null
]
this above will work absolutely fine when used like:
$data["rs"] = 5;
But the below will throw a warning ::
$data = [
"rs" => [
"rs1" => null;
]
]
..
$data[rs][rs1] = 2; // this will throw the warning unless assigned to an array
I know this is an old question. The way I solved it - after failing by increasing the length or even changing to data type text - was creating an XLSX file and importing. It accurately detected the data type instead of setting all columns as varchar(50)
. Turns out nvarchar(255)
for that column would have done it too.
Chrome now has Copy as fetch in version 67:
Copy as fetch
Right-click a network request then select Copy > Copy As Fetch to copy the
fetch()
-equivalent code for that request to your clipboard.
https://developers.google.com/web/updates/2018/04/devtools#fetch
Sample output:
fetch("https://stackoverflow.com/posts/validate-body", {
credentials: "include",
headers: {},
referrer: "https://stackoverflow.com/",
referrerPolicy: "origin",
body:
"body=Chrome+now+has+_Copy+as+fetch_+in+version+67%3A%0A%0A%3E+Copy+as+fetch%0ARight-click+a+network+request+then+select+**Copy+%3E+Copy+As+Fetch**+to+copy+the+%60fetch()%60-equivalent+code+for+that+request+to+your+clipboard.%0A%0A&oldBody=&isQuestion=false",
method: "POST",
mode: "cors"
});
The difference is that Copy as cURL will also include all the request headers (such as Cookie and Accept) and is suitable for replaying the request outside of Chrome. The fetch()
code is suitable for replaying inside of the same browser.
In order to execute simple queries and return to my shell script, I think this works well:
$ sqlite3 example.db 'SELECT * FROM some_table;'
This is my edited version : you just need to add an extra argument "autoClose".
example :
$('input[name="fieldName"]').datepicker({ autoClose: true});
also you can specify a close callback if you want. :)
replace datepicker.js with this:
!function( $ ) {
// Picker object
var Datepicker = function(element, options , closeCallBack){
this.element = $(element);
this.format = DPGlobal.parseFormat(options.format||this.element.data('date-format')||'dd/mm/yyyy');
this.autoClose = options.autoClose||this.element.data('date-autoClose')|| true;
this.closeCallback = closeCallBack || function(){};
this.picker = $(DPGlobal.template)
.appendTo('body')
.on({
click: $.proxy(this.click, this)//,
//mousedown: $.proxy(this.mousedown, this)
});
this.isInput = this.element.is('input');
this.component = this.element.is('.date') ? this.element.find('.add-on') : false;
if (this.isInput) {
this.element.on({
focus: $.proxy(this.show, this),
//blur: $.proxy(this.hide, this),
keyup: $.proxy(this.update, this)
});
} else {
if (this.component){
this.component.on('click', $.proxy(this.show, this));
} else {
this.element.on('click', $.proxy(this.show, this));
}
}
this.minViewMode = options.minViewMode||this.element.data('date-minviewmode')||0;
if (typeof this.minViewMode === 'string') {
switch (this.minViewMode) {
case 'months':
this.minViewMode = 1;
break;
case 'years':
this.minViewMode = 2;
break;
default:
this.minViewMode = 0;
break;
}
}
this.viewMode = options.viewMode||this.element.data('date-viewmode')||0;
if (typeof this.viewMode === 'string') {
switch (this.viewMode) {
case 'months':
this.viewMode = 1;
break;
case 'years':
this.viewMode = 2;
break;
default:
this.viewMode = 0;
break;
}
}
this.startViewMode = this.viewMode;
this.weekStart = options.weekStart||this.element.data('date-weekstart')||0;
this.weekEnd = this.weekStart === 0 ? 6 : this.weekStart - 1;
this.onRender = options.onRender;
this.fillDow();
this.fillMonths();
this.update();
this.showMode();
};
Datepicker.prototype = {
constructor: Datepicker,
show: function(e) {
this.picker.show();
this.height = this.component ? this.component.outerHeight() : this.element.outerHeight();
this.place();
$(window).on('resize', $.proxy(this.place, this));
if (e ) {
e.stopPropagation();
e.preventDefault();
}
if (!this.isInput) {
}
var that = this;
$(document).on('mousedown', function(ev){
if ($(ev.target).closest('.datepicker').length == 0) {
that.hide();
}
});
this.element.trigger({
type: 'show',
date: this.date
});
},
hide: function(){
this.picker.hide();
$(window).off('resize', this.place);
this.viewMode = this.startViewMode;
this.showMode();
if (!this.isInput) {
$(document).off('mousedown', this.hide);
}
//this.set();
this.element.trigger({
type: 'hide',
date: this.date
});
},
set: function() {
var formated = DPGlobal.formatDate(this.date, this.format);
if (!this.isInput) {
if (this.component){
this.element.find('input').prop('value', formated);
}
this.element.data('date', formated);
} else {
this.element.prop('value', formated);
}
},
setValue: function(newDate) {
if (typeof newDate === 'string') {
this.date = DPGlobal.parseDate(newDate, this.format);
} else {
this.date = new Date(newDate);
}
this.set();
this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0);
this.fill();
},
place: function(){
var offset = this.component ? this.component.offset() : this.element.offset();
this.picker.css({
top: offset.top + this.height,
left: offset.left
});
},
update: function(newDate){
this.date = DPGlobal.parseDate(
typeof newDate === 'string' ? newDate : (this.isInput ? this.element.prop('value') : this.element.data('date')),
this.format
);
this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0);
this.fill();
},
fillDow: function(){
var dowCnt = this.weekStart;
var html = '<tr>';
while (dowCnt < this.weekStart + 7) {
html += '<th class="dow">'+DPGlobal.dates.daysMin[(dowCnt++)%7]+'</th>';
}
html += '</tr>';
this.picker.find('.datepicker-days thead').append(html);
},
fillMonths: function(){
var html = '';
var i = 0
while (i < 12) {
html += '<span class="month">'+DPGlobal.dates.monthsShort[i++]+'</span>';
}
this.picker.find('.datepicker-months td').append(html);
},
fill: function() {
var d = new Date(this.viewDate),
year = d.getFullYear(),
month = d.getMonth(),
currentDate = this.date.valueOf();
this.picker.find('.datepicker-days th:eq(1)')
.text(DPGlobal.dates.months[month]+' '+year);
var prevMonth = new Date(year, month-1, 28,0,0,0,0),
day = DPGlobal.getDaysInMonth(prevMonth.getFullYear(), prevMonth.getMonth());
prevMonth.setDate(day);
prevMonth.setDate(day - (prevMonth.getDay() - this.weekStart + 7)%7);
var nextMonth = new Date(prevMonth);
nextMonth.setDate(nextMonth.getDate() + 42);
nextMonth = nextMonth.valueOf();
var html = [];
var clsName,
prevY,
prevM;
while(prevMonth.valueOf() < nextMonth) {zs
if (prevMonth.getDay() === this.weekStart) {
html.push('<tr>');
}
clsName = this.onRender(prevMonth);
prevY = prevMonth.getFullYear();
prevM = prevMonth.getMonth();
if ((prevM < month && prevY === year) || prevY < year) {
clsName += ' old';
} else if ((prevM > month && prevY === year) || prevY > year) {
clsName += ' new';
}
if (prevMonth.valueOf() === currentDate) {
clsName += ' active';
}
html.push('<td class="day '+clsName+'">'+prevMonth.getDate() + '</td>');
if (prevMonth.getDay() === this.weekEnd) {
html.push('</tr>');
}
prevMonth.setDate(prevMonth.getDate()+1);
}
this.picker.find('.datepicker-days tbody').empty().append(html.join(''));
var currentYear = this.date.getFullYear();
var months = this.picker.find('.datepicker-months')
.find('th:eq(1)')
.text(year)
.end()
.find('span').removeClass('active');
if (currentYear === year) {
months.eq(this.date.getMonth()).addClass('active');
}
html = '';
year = parseInt(year/10, 10) * 10;
var yearCont = this.picker.find('.datepicker-years')
.find('th:eq(1)')
.text(year + '-' + (year + 9))
.end()
.find('td');
year -= 1;
for (var i = -1; i < 11; i++) {
html += '<span class="year'+(i === -1 || i === 10 ? ' old' : '')+(currentYear === year ? ' active' : '')+'">'+year+'</span>';
year += 1;
}
yearCont.html(html);
},
click: function(e) {
e.stopPropagation();
e.preventDefault();
var target = $(e.target).closest('span, td, th');
if (target.length === 1) {
switch(target[0].nodeName.toLowerCase()) {
case 'th':
switch(target[0].className) {
case 'switch':
this.showMode(1);
break;
case 'prev':
case 'next':
this.viewDate['set'+DPGlobal.modes[this.viewMode].navFnc].call(
this.viewDate,
this.viewDate['get'+DPGlobal.modes[this.viewMode].navFnc].call(this.viewDate) +
DPGlobal.modes[this.viewMode].navStep * (target[0].className === 'prev' ? -1 : 1)
);
this.fill();
this.set();
break;
}
break;
case 'span':
if (target.is('.month')) {
var month = target.parent().find('span').index(target);
this.viewDate.setMonth(month);
} else {
var year = parseInt(target.text(), 10)||0;
this.viewDate.setFullYear(year);
}
if (this.viewMode !== 0) {
this.date = new Date(this.viewDate);
this.element.trigger({
type: 'changeDate',
date: this.date,
viewMode: DPGlobal.modes[this.viewMode].clsName
});
}
this.showMode(-1);
this.fill();
this.set();
break;
case 'td':
if (target.is('.day') && !target.is('.disabled')){
var day = parseInt(target.text(), 10)||1;
var month = this.viewDate.getMonth();
if (target.is('.old')) {
month -= 1;
} else if (target.is('.new')) {
month += 1;
}
var year = this.viewDate.getFullYear();
this.date = new Date(year, month, day,0,0,0,0);
this.viewDate = new Date(year, month, Math.min(28, day),0,0,0,0);
this.fill();
this.set();
this.element.trigger({
type: 'changeDate',
date: this.date,
viewMode: DPGlobal.modes[this.viewMode].clsName
});
if(this.autoClose === true){
this.hide();
this.closeCallback();
}
}
break;
}
}
},
mousedown: function(e){
e.stopPropagation();
e.preventDefault();
},
showMode: function(dir) {
if (dir) {
this.viewMode = Math.max(this.minViewMode, Math.min(2, this.viewMode + dir));
}
this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show();
}
};
$.fn.datepicker = function ( option, val ) {
return this.each(function () {
var $this = $(this);
var datePicker = $this.data('datepicker');
var options = typeof option === 'object' && option;
if (!datePicker) {
if (typeof val === 'function')
$this.data('datepicker', (datePicker = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options),val)));
else{
$this.data('datepicker', (datePicker = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options))));
}
}
if (typeof option === 'string') datePicker[option](val);
});
};
$.fn.datepicker.defaults = {
onRender: function(date) {
return '';
}
};
$.fn.datepicker.Constructor = Datepicker;
var DPGlobal = {
modes: [
{
clsName: 'days',
navFnc: 'Month',
navStep: 1
},
{
clsName: 'months',
navFnc: 'FullYear',
navStep: 1
},
{
clsName: 'years',
navFnc: 'FullYear',
navStep: 10
}],
dates:{
days: ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche"],
daysShort: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"],
daysMin: ["D", "L", "Ma", "Me", "J", "V", "S", "D"],
months: ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"],
monthsShort: ["Jan", "Fév", "Mar", "Avr", "Mai", "Jui", "Jul", "Aou", "Sep", "Oct", "Nov", "Déc"],
today: "Aujourd'hui",
clear: "Effacer",
weekStart: 1,
format: "dd/mm/yyyy"
},
isLeapYear: function (year) {
return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0))
},
getDaysInMonth: function (year, month) {
return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]
},
parseFormat: function(format){
var separator = format.match(/[.\/\-\s].*?/),
parts = format.split(/\W+/);
if (!separator || !parts || parts.length === 0){
throw new Error("Invalid date format.");
}
return {separator: separator, parts: parts};
},
parseDate: function(date, format) {
var parts = date.split(format.separator),
date = new Date(),
val;
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
if (parts.length === format.parts.length) {
var year = date.getFullYear(), day = date.getDate(), month = date.getMonth();
for (var i=0, cnt = format.parts.length; i < cnt; i++) {
val = parseInt(parts[i], 10)||1;
switch(format.parts[i]) {
case 'dd':
case 'd':
day = val;
date.setDate(val);
break;
case 'mm':
case 'm':
month = val - 1;
date.setMonth(val - 1);
break;
case 'yy':
year = 2000 + val;
date.setFullYear(2000 + val);
break;
case 'yyyy':
year = val;
date.setFullYear(val);
break;
}
}
date = new Date(year, month, day, 0 ,0 ,0);
}
return date;
},
formatDate: function(date, format){
var val = {
d: date.getDate(),
m: date.getMonth() + 1,
yy: date.getFullYear().toString().substring(2),
yyyy: date.getFullYear()
};
val.dd = (val.d < 10 ? '0' : '') + val.d;
val.mm = (val.m < 10 ? '0' : '') + val.m;
var date = [];
for (var i=0, cnt = format.parts.length; i < cnt; i++) {
date.push(val[format.parts[i]]);
}
return date.join(format.separator);
},
headTemplate: '<thead>'+
'<tr>'+
'<th class="prev">‹</th>'+
'<th colspan="5" class="switch"></th>'+
'<th class="next">›</th>'+
'</tr>'+
'</thead>',
contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>'
};
DPGlobal.template = '<div class="datepicker dropdown-menu">'+
'<div class="datepicker-days">'+
'<table class=" table-condensed">'+
DPGlobal.headTemplate+
'<tbody></tbody>'+
'</table>'+
'</div>'+
'<div class="datepicker-months">'+
'<table class="table-condensed">'+
DPGlobal.headTemplate+
DPGlobal.contTemplate+
'</table>'+
'</div>'+
'<div class="datepicker-years">'+
'<table class="table-condensed">'+
DPGlobal.headTemplate+
DPGlobal.contTemplate+
'</table>'+
'</div>'+
'</div>';
}( window.jQuery );
When I run:
exec sp_readerrorlog @p1 = 0
,@p2 = 1
,@p3 = N'licensing'
I get:
SQL Server detected 2 sockets with 21 cores per socket and 21 logical processors per socket, 42 total logical processors; using 20 logical processors based on SQL Server licensing. This is an informational message; no user action is required.
also, SELECT @@VERSION shows:
Microsoft SQL Server 2014 (SP1-GDR) (KB4019091) - 12.0.4237.0 (X64) Jul 5 2017 22:03:42 Copyright (c) Microsoft Corporation Enterprise Edition (64-bit) on Windows NT 6.3 (Build 9600: ) (Hypervisor)
This is a VM
<script type="text/javascript">
jQuery(function () {
var container = jQuery("\#content");
jQuery(container)
.kendoGrid({
selectable: "single row",
dataSource: new kendo.data.DataSource({
transport: {
read: {
url: "@Url.Action("GetMsgDetails", "OutMessage")" + "?msgId=" + msgId,
dataType: "json",
},
},
batch: true,
}),
editable: "popup",
columns: [
{ field: "Id", title: "Id", width: 250, hidden: true },
{ field: "Data", title: "Message Body", width: 100 },
{ field: "mobile", title: "Mobile Number", width: 100 },
]
});
});
you can set the height and width of a view in a relative layout like this
ViewGroup.LayoutParams params = view.getLayoutParams();
params.height = 130;
view.setLayoutParams(params);
I made an extension function for Kotlin. Paste it where ever you like and import it while creating OkHttpClient
.
fun OkHttpClient.Builder.ignoreAllSSLErrors(): OkHttpClient.Builder {
val naiveTrustManager = object : X509TrustManager {
override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
override fun checkClientTrusted(certs: Array<X509Certificate>, authType: String) = Unit
override fun checkServerTrusted(certs: Array<X509Certificate>, authType: String) = Unit
}
val insecureSocketFactory = SSLContext.getInstance("TLSv1.2").apply {
val trustAllCerts = arrayOf<TrustManager>(naiveTrustManager)
init(null, trustAllCerts, SecureRandom())
}.socketFactory
sslSocketFactory(insecureSocketFactory, naiveTrustManager)
hostnameVerifier(HostnameVerifier { _, _ -> true })
return this
}
use it like this:
val okHttpClient = OkHttpClient.Builder().apply {
// ...
if (BuildConfig.DEBUG) //if it is a debug build ignore ssl errors
ignoreAllSSLErrors()
//...
}.build()
I am using as what John Rasch said:
Stream streamContent = taxformUpload.FileContent;
Well, you have [[
and ]]
to go to the start and end of file. This works in vi.
First Replace the MySQL dependency as given below
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
An error showing "Authentication plugin 'caching_sha2_password'" will appear. Run this command:
mysql -u root -p
ALTER USER 'username'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
IntelliJ just inserts them automagically; no shortcut required. If the class name is ambiguous, it'll show me the list of possibilities to choose from. It reads my mind....
install urllib3
!pip3 install urllib3
import urllib3
than install it
!pip3 install selenium
import selenium
Use powershell inside your bat file
PowerShell Remove-Item c:\scripts\* -include *.txt -exclude *test* -force -recurse
You can also exclude from removing some specific folder or file:
PowerShell Remove-Item C:/* -Exclude WINDOWS,autoexec.bat -force -recurse
string s = "9quali52ty3";
foreach(char c in s)
{
Console.WriteLine((int)c);
}
According to @Abhishek Singh's you need to understand the problem:
What is the line which gives exception ?? The reason for this is because the element to which you have referred is removed from the DOM structure
and you can not refer to it anymore (imagine what element's ID has changed).
Follow the code:
class TogglingPage {
@FindBy(...)
private WebElement btnTurnOff;
@FindBy(...)
private WebElement btnTurnOn;
TogglingPage turnOff() {
this.btnTurnOff.isDisplayed();
this.btnTurnOff.click(); // when clicked, button should swap into btnTurnOn
this.btnTurnOn.isDisplayed();
this.btnTurnOn.click(); // when clicked, button should swap into btnTurnOff
this.btnTurnOff.isDisplayed(); // throws an exception
return new TogglingPage();
}
}
Now, let us wonder why?
btnTurnOff
was found by a driver - okbtnTurnOff
was replaced by btnTurnOn
- okbtnTurnOn
was found by a driver. - okbtnTurnOn
was replaced by btnTurnOff
- okthis.btnTurnOff.isDisplayed();
on the element which does not exist anymore in Selenium sense - you can see it, it works perfectly, but it is a different instance of the same button. Possible fix:
TogglingPage turnOff() {
this.btnTurnOff.isDisplayed();
this.btnTurnOff.click();
TogglingPage newPage = new TogglingPage();
newPage.btnTurnOn.isDisplayed();
newPage.btnTurnOn.click();
TogglingPage newerPage = new TogglingPage();
newerPage.btnTurnOff.isDisplayed(); // ok
return newerPage;
}
I have gone through many links but this answer helped me alot:
$scope.redirectPage = function (data) {
$window.open(data, "popup", "width=1000,height=700,left=300,top=200");
};
** data will be absolute url which you are hitting.
Consider using System.Windows.Forms.Timer
instead of System.Threading.Timer
for a GUI application, for timers that are based on the Windows message queue instead of on dedicated threads or the thread pool.
In your scenario, for the purpose of periodic updates of UI, it seems particularly appropriate since you don't really have a background work or long calculation to perform. You just want to do periodic small tasks that have to happen on the UI thread anyway.
I do not think that you can do this easily. you should consider this answer here:
How can I display a pdf document into a Webview?
basically you'll be able to see a pdf if it is hosted online via google documents, but not if you have it in your device (you'll need a standalone reader for that)
I recommend using ECMAScript 6 spread operator, which will Bind trailing parameters to an array. With this solution you don't need to touch the arguments
object and your code will be simplified. The downside of this solution is that it does not work across most browsers, so instead you will have to use a JS compiler such as Babel. Under the hood Babel transforms arguments
into a Array with a for loop.
function sortArgs(...args) {
return args.sort();
}
If you can not use a ECMAScript 6, I recommend looking at some of the other answers such as @Jonathan Fingland
function sortArgs() {
var args = Array.prototype.slice.call(arguments);
return args.sort();
}
Code
spinner.setOnTouchListener(new View.OnTouchListener() {
@Override public boolean onTouch(View view, MotionEvent motionEvent) { isSpinnerTouch=true; return false; }});
holder.spinner_from.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int slot_position, long l) {
if(isSpinnerTouch)
{
Log.d("spinner_from", "spinner_from");
spinnerItemClickListener.onSpinnerItemClickListener(position, slot_position, AppConstant.FROM_SLOT_ONCLICK_CODE);
}
else {
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
fig = plt.figure()
ax = fig.add_subplot(111)
plt.xticks([0.4,0.14,0.2,0.2], fontsize = 50) # work on current fig
plt.show()
the x/yticks has the same properties as matplotlib.text
With little modification but almost similar approach to get the full file path of each sub folder
dataFolderPath = 'UCR_TS_Archive_2015/';
dirData = dir(dataFolderPath); %# Get the data for the current directory
dirIndex = [dirData.isdir]; %# Find the index for directories
fileList = {dirData(~dirIndex).name}'; %'# Get a list of the files
if ~isempty(fileList)
fileList = cellfun(@(x) fullfile(dataFolderPath,x),... %# Prepend path to files
fileList,'UniformOutput',false);
end
subDirs = {dirData(dirIndex).name}; %# Get a list of the subdirectories
validIndex = ~ismember(subDirs,{'.','..'}); %# Find index of subdirectories
%# that are not '.' or '..'
for iDir = find(validIndex) %# Loop over valid subdirectories
nextDir = fullfile(dataFolderPath,subDirs{iDir}); %# Get the subdirectory path
getAllFiles = dir(nextDir);
for k = 1:1:size(getAllFiles,1)
validFileIndex = ~ismember(getAllFiles(k,1).name,{'.','..'});
if(validFileIndex)
filePathComplete = fullfile(nextDir,getAllFiles(k,1).name);
fprintf('The Complete File Path: %s\n', filePathComplete);
end
end
end
Anyone who has set below property to
ScrollView:: android:fillViewport="true"
constraint layout: android:layout_height="wrap_content"
And it's still not working then make sure then you have not set the Inner scrollable layout (RecycleView) bottom constraint to bottom of the parent.
Add below lines of code:
android:nestedScrollingEnabled="false"
android:layout_height="wrap_content"
Make sure to remove below constraint:
app:layout_constraintBottom_toBottomOf="parent"
Full code
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/selectHubLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".ui.hubs.SelectHubFragment">
<include
android:id="@+id/include"
layout="@layout/signup_hub_selection_details"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv_HubSelection"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:nestedScrollingEnabled="false"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/include" />
</androidx.constraintlayout.widget.ConstraintLayout>
Braintree also has an open source PHP library that makes PHP integration pretty easy.
From the link above:
Several of these types can be modified using the keywords signed, unsigned, short, and long. When one of these type modifiers is used by itself, a data type of int is assumed
This means that you can assume the author is using ints.
<img>
is a replaced element; it has a display value of inline by default, but its default dimensions are defined by the embedded image's intrinsic values, like it were inline-block. You can set properties like border/border-radius, padding/margin, width, height, etc. on an image.
Replaced elements : They're elements whose contents are not affected by the current document's styles. The position of the replaced element can be affected using CSS, but not the contents of the replaced element itself.
Referenece : https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img
You can read the lines and replace all special characters safely this way.
Keep in mind that if you use \\W
you will not replace underscores.
Scanner scan = new Scanner(System.in);
while(scan.hasNextLine()){
System.out.println(scan.nextLine().replaceAll("[^a-zA-Z0-9]", ""));
}
Add white-space: nowrap;
:
.garage-title {
clear: both;
display: inline-block;
overflow: hidden;
white-space: nowrap;
}
file Protocol
Opens a file on a local or network drive.Syntax
Copy file:///sDrives[|sFile] Tokens
sDrives
Specifies the local or network drive.sFile
Optional. Specifies the file to open. If sFile is omitted and the account accessing the drive has permission to browse the directory, a list of accessible files and directories is displayed.Remarks
The file protocol and sDrives parameter can be omitted and substituted with just the command line representation of the drive letter and file location. For example, to browse the My Documents directory, the file protocol can be specified as file:///C|/My Documents/ or as C:\My Documents. In addition, a single '\' is equivalent to specifying the root directory on the primary local drive. On most computers, this is C:.
Available as of Microsoft Internet Explorer 3.0 or later.
Note Internet Explorer 6 Service Pack 1 (SP1) no longer allows browsing a local machine from the Internet zone. For instance, if an Internet site contains a link to a local file, Internet Explorer 6 SP1 displays a blank page when a user clicks on the link. Previous versions of Windows Internet Explorer followed the link to the local file.
Example
The following sample demonstrates four ways to use the File protocol.
Copy
//Specifying a drive and a file name. file:///C|/My Documents/ALetter.html //Specifying only a drive and a path to browse the directory. file:///C|/My Documents/ //Specifying a drive and a directory using the command line representation of the directory location. C:\My Documents\ //Specifying only the directory on the local primary drive. \My Documents\
As far as I have heared Google Chrome will have multithreaded javascript, so it is a "current implementations" problem.
To find the names of all files modified since your last commit:
git diff --name-only
Or (for a bit more information, including untracked files):
git status
To unpack a dictionary into keyword arguments, use **
. Also,, new-style formatting supports referring to attributes of objects and items of mappings:
'{0[latitude]} {0[longitude]}'.format(geopoint)
'The title is {0.title}s'.format(a) # the a from your first example
If the architecture and linker settings look good, check your h files. My issue was the same error, but I had restructured the h files and I removed an extern statement. Other m files were using that variable, causing the linker error.
I would avoid now using /// <reference path='moo.ts'/>
but for external libraries where the definition file is not included into the package.
The reference path
solves errors in the editor, but it does not really means the file needs to be imported. Therefore if you are using a gulp workflow or JSPM, those might try to compile separately each file instead of tsc -out
to one file.
From Typescript 1.5
Just prefix what you want to export at the file level (root scope)
aLib.ts
{
export class AClass(){} // exported i.e. will be available for import
export valueZero = 0; // will be available for import
}
You can also add later in the end of the file what you want to export
{
class AClass(){} // not exported yet
valueZero = 0; // not exported yet
valueOne = 1; // not exported (and will not in this example)
export {AClass, valueZero} // pick the one you want to export
}
Or even mix both together
{
class AClass(){} // not exported yet
export valueZero = 0; // will be available for import
export {AClass} // add AClass to the export list
}
For the import you have 2 options, first you pick again what you want (one by one)
anotherFile.ts
{
import {AClass} from "./aLib.ts"; // you import only AClass
var test = new AClass();
}
Or the whole exports
{
import * as lib from "./aLib.ts"; // you import all the exported values within a "lib" object
var test = new lib.AClass();
}
Note regarding the exports: exporting twice the same value will raise an error { export valueZero = 0; export {valueZero}; // valueZero is already exported… }
Use a margin to space around an element.
.box {
margin: top right bottom left;
}
.box {
margin: 10px 5px 10px 5px;
}
This adds space outside of the element. So background colours, borders etc will not be included.
If you want to add spacing within an element use padding instead. It can be called in the same way as above.
Ok I found out the answer myself. Much like npm cache clean
, Yarn also has its own
yarn cache clean
This is the problem:
while(str.charAt(i)==ch)
That will keep going until it falls off the end... when i
is the same as the length of the string, it will be asking for a character beyond the end of the string. You probably want:
while (i < str.length() && str.charAt(i) == ch)
You also need to set count
to 0 at the start of each iteration of the bigger loop - the count resets, after all - and change
count = count + i;
to either:
count++;
... or get rid of count
or i
. They're always going to have the same value, after all. Personally I'd just use one variable, declared and initialized inside the loop. That's a general style point, in fact - it's cleaner to declare local variables when they're needed, rather than declaring them all at the top of the method.
However, then your program will loop forever, as this doesn't do anything useful:
str.substring(count);
Strings are immutable in Java - substring
returns a new string. I think you want:
str = str.substring(count);
Note that this will still output "a2b2a2" for "aabbaa". Is that okay?
WHERE filters before data is grouped, and HAVING filters after data is grouped. This is an important distinction; rows that are eliminated by a WHERE clause will not be included in the group. This could change the calculated values which, in turn(=as a result) could affect which groups are filtered based on the use of those values in the HAVING clause.
And continues,
HAVING is so similar to WHERE that most DBMSs treat them as the same thing if no GROUP BY is specified. Nevertheless, you should make that distinction yourself. Use HAVING only in conjunction with GROUP BY clauses. Use WHERE for standard row-level filtering.
Excerpt From: Forta, Ben. “Sams Teach Yourself SQL in 10 Minutes (5th Edition) (Sams Teach Yourself...).”.
The simplest way I can suggest is using regex on JS
as:
//Only use [0] if you are sure that the string matches the pattern
//Otherwise, verify if 'match' returns something
"/Date(1512488018202)/".match(/\d+/)[0]
On Ubuntu (doc)
sudo systemctl status mongod
If running
? mongod.service - MongoDB Database Server
Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
Active: active (running) since Wed 2020-10-14 14:13:40 UTC; 3s ago
Docs: https://docs.mongodb.org/manual
Main PID: 1604 (mongod)
Memory: 210.8M
CGroup: /system.slice/mongod.service
+-1604 /usr/bin/mongod --config /etc/mongod.conf
If not running
? mongod.service - MongoDB Database Server
Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
Active: inactive (dead)
Docs: https://docs.mongodb.org/manual
To start mongodb
sudo systemctl start mongod
I use this code
$variable = array();
if( count( $variable ) == 0 )
{
echo "Array is Empty";
}
else
{
echo "Array is not Empty";
}
But note that if the array has a large number of keys, this code will spend much time counting them, as compared to the other answers here.
append
adds an element to a list, and extend
concatenates the first list with another list (or another iterable, not necessarily a list.)
>>> li = ['a', 'b', 'mpilgrim', 'z', 'example']
>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li.append("new")
>>> li
['a', 'b', 'mpilgrim', 'z', 'example', 'new']
>>> li.append(["new", 2])
>>> li
['a', 'b', 'mpilgrim', 'z', 'example', 'new', ['new', 2]]
>>> li.insert(2, "new")
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', ['new', 2]]
>>> li.extend(["two", "elements"])
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', ['new', 2], 'two', 'elements']
Download the latest CMake Mac binary distribution here: https://cmake.org/download/ (current latest is: https://cmake.org/files/v3.17/cmake-3.17.1-Darwin-x86_64.dmg)
Double click the downloaded .dmg file to install it. In the window that pops up, drag the CMake icon into the Application folder.
Add this line to your .bashrc file: PATH="/Applications/CMake.app/Contents/bin":"$PATH"
Reload your .bashrc file: source ~/.bashrc
Verify the latest cmake version is installed: cmake --version
You can launch the CMake GUI by clicking on LaunchPad and typing cmake. Click on the CMake icon that appears.
This exception happened when I forgot to close the connections
@T0xicCode's answer is correct, but I thought I would expand on the details since it actually took me about 20 hours to finally get a working solution implemented.
If you're looking to run Nginx in its own container and use it as a reverse proxy to load balance multiple applications on the same server instance then the steps you need to follow are as such:
Link Your Containers
When you docker run
your containers, typically by inputting a shell script into User Data
, you can declare links to any other running containers. This means that you need to start your containers up in order and only the latter containers can link to the former ones. Like so:
#!/bin/bash
sudo docker run -p 3000:3000 --name API mydockerhub/api
sudo docker run -p 3001:3001 --link API:API --name App mydockerhub/app
sudo docker run -p 80:80 -p 443:443 --link API:API --link App:App --name Nginx mydockerhub/nginx
So in this example, the API
container isn't linked to any others, but the
App
container is linked to API
and Nginx
is linked to both API
and App
.
The result of this is changes to the env
vars and the /etc/hosts
files that reside within the API
and App
containers. The results look like so:
/etc/hosts
Running cat /etc/hosts
within your Nginx
container will produce the following:
172.17.0.5 0fd9a40ab5ec
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.3 App
172.17.0.2 API
ENV Vars
Running env
within your Nginx
container will produce the following:
API_PORT=tcp://172.17.0.2:3000
API_PORT_3000_TCP_PROTO=tcp
API_PORT_3000_TCP_PORT=3000
API_PORT_3000_TCP_ADDR=172.17.0.2
APP_PORT=tcp://172.17.0.3:3001
APP_PORT_3001_TCP_PROTO=tcp
APP_PORT_3001_TCP_PORT=3001
APP_PORT_3001_TCP_ADDR=172.17.0.3
I've truncated many of the actual vars, but the above are the key values you need to proxy traffic to your containers.
To obtain a shell to run the above commands within a running container, use the following:
sudo docker exec -i -t Nginx bash
You can see that you now have both /etc/hosts
file entries and env
vars that contain the local IP address for any of the containers that were linked. So far as I can tell, this is all that happens when you run containers with link options declared. But you can now use this information to configure nginx
within your Nginx
container.
Configuring Nginx
This is where it gets a little tricky, and there's a couple of options. You can choose to configure your sites to point to an entry in the /etc/hosts
file that docker
created, or you can utilize the ENV
vars and run a string replacement (I used sed
) on your nginx.conf
and any other conf files that may be in your /etc/nginx/sites-enabled
folder to insert the IP values.
OPTION A: Configure Nginx Using ENV Vars
This is the option that I went with because I couldn't get the
/etc/hosts
file option to work. I'll be trying Option B soon enough and update this post with any findings.
The key difference between this option and using the /etc/hosts
file option is how you write your Dockerfile
to use a shell script as the CMD
argument, which in turn handles the string replacement to copy the IP values from ENV
to your conf file(s).
Here's the set of configuration files I ended up with:
Dockerfile
FROM ubuntu:14.04
MAINTAINER Your Name <[email protected]>
RUN apt-get update && apt-get install -y nano htop git nginx
ADD nginx.conf /etc/nginx/nginx.conf
ADD api.myapp.conf /etc/nginx/sites-enabled/api.myapp.conf
ADD app.myapp.conf /etc/nginx/sites-enabled/app.myapp.conf
ADD Nginx-Startup.sh /etc/nginx/Nginx-Startup.sh
EXPOSE 80 443
CMD ["/bin/bash","/etc/nginx/Nginx-Startup.sh"]
nginx.conf
daemon off;
user www-data;
pid /var/run/nginx.pid;
worker_processes 1;
events {
worker_connections 1024;
}
http {
# Basic Settings
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 33;
types_hash_max_size 2048;
server_tokens off;
server_names_hash_bucket_size 64;
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Logging Settings
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
# Gzip Settings
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 3;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types text/plain text/xml text/css application/x-javascript application/json;
gzip_disable "MSIE [1-6]\.(?!.*SV1)";
# Virtual Host Configs
include /etc/nginx/sites-enabled/*;
# Error Page Config
#error_page 403 404 500 502 /srv/Splash;
}
NOTE: It's important to include
daemon off;
in yournginx.conf
file to ensure that your container doesn't exit immediately after launching.
api.myapp.conf
upstream api_upstream{
server APP_IP:3000;
}
server {
listen 80;
server_name api.myapp.com;
return 301 https://api.myapp.com/$request_uri;
}
server {
listen 443;
server_name api.myapp.com;
location / {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
proxy_pass http://api_upstream;
}
}
Nginx-Startup.sh
#!/bin/bash
sed -i 's/APP_IP/'"$API_PORT_3000_TCP_ADDR"'/g' /etc/nginx/sites-enabled/api.myapp.com
sed -i 's/APP_IP/'"$APP_PORT_3001_TCP_ADDR"'/g' /etc/nginx/sites-enabled/app.myapp.com
service nginx start
I'll leave it up to you to do your homework about most of the contents of nginx.conf
and api.myapp.conf
.
The magic happens in Nginx-Startup.sh
where we use sed
to do string replacement on the APP_IP
placeholder that we've written into the upstream
block of our api.myapp.conf
and app.myapp.conf
files.
This ask.ubuntu.com question explains it very nicely: Find and replace text within a file using commands
GOTCHA On OSX,
sed
handles options differently, the-i
flag specifically. On Ubuntu, the-i
flag will handle the replacement 'in place'; it will open the file, change the text, and then 'save over' the same file. On OSX, the-i
flag requires the file extension you'd like the resulting file to have. If you're working with a file that has no extension you must input '' as the value for the-i
flag.GOTCHA To use ENV vars within the regex that
sed
uses to find the string you want to replace you need to wrap the var within double-quotes. So the correct, albeit wonky-looking, syntax is as above.
So docker has launched our container and triggered the Nginx-Startup.sh
script to run, which has used sed
to change the value APP_IP
to the corresponding ENV
variable we provided in the sed
command. We now have conf files within our /etc/nginx/sites-enabled
directory that have the IP addresses from the ENV
vars that docker set when starting up the container. Within your api.myapp.conf
file you'll see the upstream
block has changed to this:
upstream api_upstream{
server 172.0.0.2:3000;
}
The IP address you see may be different, but I've noticed that it's usually 172.0.0.x
.
You should now have everything routing appropriately.
GOTCHA You cannot restart/rerun any containers once you've run the initial instance launch. Docker provides each container with a new IP upon launch and does not seem to re-use any that its used before. So
api.myapp.com
will get 172.0.0.2 the first time, but then get 172.0.0.4 the next time. ButNginx
will have already set the first IP into its conf files, or in its/etc/hosts
file, so it won't be able to determine the new IP forapi.myapp.com
. The solution to this is likely to useCoreOS
and itsetcd
service which, in my limited understanding, acts like a sharedENV
for all machines registered into the sameCoreOS
cluster. This is the next toy I'm going to play with setting up.
OPTION B: Use /etc/hosts
File Entries
This should be the quicker, easier way of doing this, but I couldn't get it to work. Ostensibly you just input the value of the /etc/hosts
entry into your api.myapp.conf
and app.myapp.conf
files, but I couldn't get this method to work.
UPDATE: See @Wes Tod's answer for instructions on how to make this method work.
Here's the attempt that I made in api.myapp.conf
:
upstream api_upstream{
server API:3000;
}
Considering that there's an entry in my /etc/hosts
file like so: 172.0.0.2 API
I figured it would just pull in the value, but it doesn't seem to be.
I also had a couple of ancillary issues with my Elastic Load Balancer
sourcing from all AZ's so that may have been the issue when I tried this route. Instead I had to learn how to handle replacing strings in Linux, so that was fun. I'll give this a try in a while and see how it goes.
I came here with similar error:
System.InvalidOperationException: 'The entity type 'MyType' requires a primary key to be defined.'
After reading answer by hvd, realized I had simply forgotten to make my key property 'public'. This..
namespace MyApp.Models.Schedule
{
public class MyType
{
[Key]
int Id { get; set; }
// ...
Should be this..
namespace MyApp.Models.Schedule
{
public class MyType
{
[Key]
public int Id { get; set; } // must be public!
// ...
Now I use org.apache.commons.lang3.CharEncoding.UTF_8
constant from commons-lang.
This will get what you want in plain JS.
var el = document.getElementById('*spaM4');
text = (el.innerText || el.textContent);
I was totally lost on why my Gridview.Databind()
would not refresh.
My issue, I discovered, was my gridview was inside a UpdatePanel. To get my GridView to FINALLY refresh was this:
gvServerConfiguration.Databind()
uppServerConfiguration.Update()
uppServerConfiguration is the id associated with my UpdatePanel in my asp.net code.
Hope this helps someone.
As far as I understand, you have more than one form tag in your web page that causes the problem. Make sure you have only one server-side form tag for each page.
Use YouTube Android Player API.
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.andreaskonstantakos.vfy.MainActivity">
<com.google.android.youtube.player.YouTubePlayerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="visible"
android:layout_centerHorizontal="true"
android:id="@+id/youtube_player"
android:layout_alignParentTop="true" />
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="195dp"
android:visibility="visible"
android:id="@+id/button" />
</RelativeLayout>
MainActivity.java:
package com.example.andreaskonstantakos.vfy;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
public class MainActivity extends YouTubeBaseActivity {
YouTubePlayerView youTubePlayerView;
Button button;
YouTubePlayer.OnInitializedListener onInitializedListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);
button = (Button) findViewById(R.id.button);
onInitializedListener = new YouTubePlayer.OnInitializedListener(){
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.loadVideo("Hce74cEAAaE");
youTubePlayer.play();
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
};
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
youTubePlayerView.initialize(PlayerConfig.API_KEY,onInitializedListener);
}
});
}
}
and the PlayerConfig.java class:
package com.example.andreaskonstantakos.vfy;
/**
* Created by Andreas Konstantakos on 13/4/2017.
*/
public class PlayerConfig {
PlayerConfig(){}
public static final String API_KEY =
"xxxxx";
}
Replace the "Hce74cEAAaE" with your video ID from https://www.youtube.com/watch?v=Hce74cEAAaE. Get your API_KEY from Console.developers.google.com and also replace it on the PlayerConfig.API_KEY. For any further information you can follow the following tutorial step by step: https://www.youtube.com/watch?v=3LiubyYpEUk
This worked for me in Laravel 5.8
return \Redirect::to('https://bla.com/?yken=KuQxIVTNRctA69VAL6lYMRo0');
Or instead of / you can use
use Redirect;
Exporting without default
means it's a "named export". You can have multiple named exports in a single file. So if you do this,
class Template {}
class AnotherTemplate {}
export { Template, AnotherTemplate }
then you have to import these exports using their exact names. So to use these components in another file you'd have to do,
import {Template, AnotherTemplate} from './components/templates'
Alternatively if you export as the default
export like this,
export default class Template {}
Then in another file you import the default export without using the {}
, like this,
import Template from './components/templates'
There can only be one default export per file. In React it's a convention to export one component from a file, and to export it is as the default export.
You're free to rename the default export as you import it,
import TheTemplate from './components/templates'
And you can import default and named exports at the same time,
import Template,{AnotherTemplate} from './components/templates'
Do you want to insert one dictionary into the other, as one of its elements, or do you want to reference the values of one dictionary from the keys of another?
Previous answers have already covered the first case, where you are creating a dictionary within another dictionary.
To re-reference the values of one dictionary into another, you can use dict.update
:
>>> d1 = {1: [1]}
>>> d2 = {2: [2]}
>>> d1.update(d2)
>>> d1
{1: [1], 2: [2]}
A change to a value that's present in both dictionaries will be visible in both:
>>> d1[2].append('appended')
>>> d1
{1: [1], 2: [2, 'appended']}
>>> d2
{2: [2, 'appended']}
This is the same as copying the value over or making a new dictionary with it, i.e.
>>> d3 = {1: d1[1]}
>>> d3[1].append('appended from d3')
>>> d1[1]
[1, 'appended from d3']
You can also set up a mime type for application/JavaScript to run as PHP, .NET, Java, or whatever language you're using. I've done this for dynamic CSS files in the past.
Because HTTP is stateless, in order to associate a request to any other request, you need a way to store user data between HTTP requests.
Cookies or URL parameters ( for ex. like http://example.com/myPage?asd=lol&boo=no ) are both suitable ways to transport data between 2 or more request. However they are not good in case you don't want that data to be readable/editable on client side.
The solution is to store that data server side, give it an "id", and let the client only know (and pass back at every http request) that id. There you go, sessions implemented. Or you can use the client as a convenient remote storage, but you would encrypt the data and keep the secret server-side.
Of course there are other aspects to consider, like you don't want people to hijack other's sessions, you want sessions to not last forever but to expire, and so on.
In your specific example, the user id (could be username or another unique ID in your user database) is stored in the session data, server-side, after successful identification. Then for every HTTP request you get from the client, the session id (given by the client) will point you to the correct session data (stored by the server) that contains the authenticated user id - that way your code will know what user it is talking to.
This solution works perfectly for bottom bar based fragment navigation when you want to close the app when back pressed in primary fragment.
On the other hand when you are opening the secondary fragment (fragment in fragment) which is defined as "DetailedPizza" in my code it will return the previous state of primary fragment. Cheers !
Inside activities on back pressed put this:
Fragment home = getSupportFragmentManager().findFragmentByTag("DetailedPizza");
if (home instanceof FragmentDetailedPizza && home.isVisible()) {
if (getFragmentManager().getBackStackEntryCount() != 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
} else {
//Primary fragment
moveTaskToBack(true);
}
And launch the other fragment like this:
Fragment someFragment = new FragmentDetailedPizza();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.container_body, someFragment, "DetailedPizza");
transaction.addToBackStack("DetailedPizza");
transaction.commit();
11. R (or another dependency) is out of date and you don't want to update it.
Warning this is not exactly best practice.
DESCRIPTION
file.Remove the offending line with your text editor e.g.
Depends: R (>= 3.1.1)
Install from local (i.e. from the parent directory of DESCRIPTION
) e.g.
install.packages("foo", type="source", repos=NULL)
This exception is thrown if the underlying method(method called using Reflection) throws an exception.
So if the method, that has been invoked by reflection API, throws an exception (as for example runtime exception), the reflection API will wrap the exception into an InvocationTargetException.
As the saying goes, a picture is worth a thousand words. Here is how I visualize it:
Here is how we get to that picture:
Create a name myfile.txt
in the file system that points to a new inode (which contains the metadata for the file and points to the blocks of data that contain its contents, i.e. the text "Hello, World!":
$ echo 'Hello, World!' > myfile.txt
Create a hard link my-hard-link
to the file myfile.txt
, which means "create a file that should point to the same inode that myfile.txt
points to":
$ ln myfile.txt my-hard-link
Create a soft link my-soft-link
to the file myfile.txt
, which means "create a file that should point to the file myfile.txt
":
$ ln -s myfile.txt my-soft-link
Look what will now happen if myfile.txt
is deleted (or moved): my-hard-link
still points to the same contents, and is thus unaffected, whereas my-soft-link
now points to nothing. Other answers discuss the pros/cons of each.
Try
import sys
fn_name = sys._getframe().f_code.co_name
further reference https://www.oreilly.com/library/view/python-cookbook/0596001673/ch14s08.html
object.runtimeType
returns the type of object
For example:
print("HELLO".runtimeType); //prints String
var x=0.0;
print(x.runtimeType); //prints double
It is matter of performance and memory usage, compile and keep the complied pattern if you need to use it a lot. A typical usage of regex is to validated user input (format), and also format output data for users, in these classes, saving the complied pattern, seems quite logical as they usually called a lot.
Below is a sample validator, which is really called a lot :)
public class AmountValidator {
//Accept 123 - 123,456 - 123,345.34
private static final String AMOUNT_REGEX="\\d{1,3}(,\\d{3})*(\\.\\d{1,4})?|\\.\\d{1,4}";
//Compile and save the pattern
private static final Pattern AMOUNT_PATTERN = Pattern.compile(AMOUNT_REGEX);
public boolean validate(String amount){
if (!AMOUNT_PATTERN.matcher(amount).matches()) {
return false;
}
return true;
}
}
As mentioned by @Alan Moore, if you have reusable regex in your code, (before a loop for example), you must compile and save pattern for reuse.
You've already listed the most notable solutions for embedding Chromium (CEF, Chrome Frame, Awesomium). There aren't any more projects that matter.
There is still the Berkelium project (see Berkelium Sharp and Berkelium Managed), but it emebeds an old version of Chromium.
CEF is your best bet - it's fully open source and frequently updated. It's the only option that allows you to embed the latest version of Chromium. Now that Per Lundberg is actively working on porting CEF 3 to CefSharp, this is the best option for the future. There is also Xilium.CefGlue, but this one provides a low level API for CEF, it binds to the C API of CEF. CefSharp on the other hand binds to the C++ API of CEF.
Adobe is not the only major player using CEF, see other notable applications using CEF on the CEF wikipedia page.
Updating Chrome Frame is pointless since the project has been retired.
The other methods don't remove multiple extensions. Some also have problems with filenames that don't have extensions. This snippet deals with both instances and works in both Python 2 and 3. It grabs the basename from the path, splits the value on dots, and returns the first one which is the initial part of the filename.
import os
def get_filename_without_extension(file_path):
file_basename = os.path.basename(file_path)
filename_without_extension = file_basename.split('.')[0]
return filename_without_extension
Here's a set of examples to run:
example_paths = [
"FileName",
"./FileName",
"../../FileName",
"FileName.txt",
"./FileName.txt.zip.asc",
"/path/to/some/FileName",
"/path/to/some/FileName.txt",
"/path/to/some/FileName.txt.zip.asc"
]
for example_path in example_paths:
print(get_filename_without_extension(example_path))
In every case, the value printed is:
FileName
The issue here is that JSON, as a format, is generally parsed in full and then handled in-memory, which for such a large amount of data is clearly problematic.
The solution to this is to work with the data as a stream - reading part of the file, working with it, and then repeating.
The best option appears to be using something like ijson - a module that will work with JSON as a stream, rather than as a block file.
Edit: Also worth a look - kashif's comment about json-streamer
and Henrik Heino's comment about bigjson
.
It depends on what you're trying to do.
You currently have it set up as a normalized database, which is fine, and the way you are doing it is appropriate.
However, there are other ways of doing it.
You could have a posts collection that has imbedded comments for each post with references to the users that you can iteratively query to get. You could store the user's name with the comments, you could store them all in one document.
The thing with NoSQL is it's designed for flexible schemas and very fast reading and writing. In a typical Big Data farm the database is the biggest bottleneck, you have fewer database engines than you do application and front end servers...they're more expensive but more powerful, also hard drive space is very cheap comparatively. Normalization comes from the concept of trying to save space, but it comes with a cost at making your databases perform complicated Joins and verifying the integrity of relationships, performing cascading operations. All of which saves the developers some headaches if they designed the database properly.
With NoSQL, if you accept that redundancy and storage space aren't issues because of their cost (both in processor time required to do updates and hard drive costs to store extra data), denormalizing isn't an issue (for embedded arrays that become hundreds of thousands of items it can be a performance issue, but most of the time that's not a problem). Additionally you'll have several application and front end servers for every database cluster. Have them do the heavy lifting of the joins and let the database servers stick to reading and writing.
TL;DR: What you're doing is fine, and there are other ways of doing it. Check out the mongodb documentation's data model patterns for some great examples. http://docs.mongodb.org/manual/data-modeling/
if you need to remove the first leter of string
string.slice(1, 0)
and for remove last letter
string.slice(0, -1)
You haven't properly cased your onchange
prop in the input
. It needs to be onChange
in JSX.
<input
type="text"
value={this.props.searchString}
ref="searchStringInput"
onchange={this.handleChange} <--[should be onChange]
/>
The topic of passing a value
prop to an <input>
, and then somehow changing the value passed in response to user interaction using an onChange
handler is pretty well-considered in the docs.
They refer to such inputs as Controlled Components, and refer to inputs that instead let the DOM natively handle the input's value and subsequent changes from the user as Uncontrolled Components.
Whenever you set the value
prop of an input
to some variable, you have a Controlled Component. This means you must change the value of the variable by some programmatic means or else the input will always hold that value and will never change, even when you type -- the native behaviour of the input, to update its value on typing, is overridden by React here.
So, you're correctly taking that variable from state, and have a handler to update the state all set up fine. The problem was because you have onchange
and not the correct onChange
the handler was never being called and so the value
was never being updated when you type into the input. When you do use onChange
the handler is called, the value
is updated when you type, and you see your changes.
Join / concat & Split functions on ArrayList:
To Join /concat all elements of arraylist with comma (",") to String.
List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");
String allIds = TextUtils.join(",", ids);
Log.i("Result", allIds);
To split all elements of String to arraylist with comma (",").
String allIds = "1,2,3,4";
String[] allIdsArray = TextUtils.split(allIds, ",");
ArrayList<String> idsList = new ArrayList<String>(Arrays.asList(allIdsArray));
for(String element : idsList){
Log.i("Result", element);
}
Done
if you just want to temporarily disable the link but leave the href there to enable later (which is what I wanted to do) I found that all browsers use the first href. Hence I was able to do:
<a class="ea-link" href="javascript:void(0)" href="/export/">Export</a>
For those that run into this and end up on this answer, as I did, where they got this error during uninstall orupgrade and Ubuntu keeps failing to uninstall the previous because the service doesn't exist this one line will get you past that and allow the uninstall or upgrade to continue.
sudo touch /lib/systemd/system/mongod.service
use now() in any cell. then use that cell as a "dummy" parameter in a function. when now() changes every minute the formula recalculates. example: someFunction(a1,b1,c1) * (cell with now() / cell with now())
With Esc and Command + 1 you can navigate between project view and editor area - back and forward, in this way you can select the folder/location you need
With Control +Option + N you can trigger New file menu and select whatever you need, class, interface, file, etc. This works in editor as well in project view and it relates to the current selected location
// please consider that this is working with standard key mapping
This solution is using javascript to open a new window when a user clicks on your custom share button.
HTML:
<a href="#" onclick="share_fb('http://urlhere.com/test/55d7258b61707022e3050000');return false;" rel="nofollow" share_url="http://urlhere.com/test/55d7258b61707022e3050000" target="_blank">
//using fontawesome
<i class="uk-icon-facebook uk-float-left"></i>
Share
</a>
and in your javascript file. note window.open params are (url, dialogue title, width, height)
function share_fb(url) {
window.open('https://www.facebook.com/sharer/sharer.php?u='+url,'facebook-share-dialog',"width=626, height=436")
}
there one more option that allows to get "select" size with joins, and table size as option too
-- 1
EXPLAIN PLAN
FOR
SELECT
Scheme.Table_name.table_column1 AS "column1",
Scheme.Table_name.table_column2 AS "column2",
Scheme.Table_name.table_column3 AS "column3",
FROM Scheme.Table_name
WHERE ;
SELECT * FROM TABLE (DBMS_XPLAN.display);
This concerns Java versions 7 and earlier.
To quote a good answer to the same question:
If you want it back as a string later, you can call getPath(). Indeed, if you really wanted to mimic Path.Combine, you could just write something like:
public static String combine (String path1, String path2) {
File file1 = new File(path1);
File file2 = new File(file1, path2);
return file2.getPath();
}
Maybe this way:
def myTrunc(theNumber, theDigits):
myDigits = 10 ** theDigits
return (int(theNumber * myDigits) / myDigits)
Add the s
modifier to your regex to cause .
to match newlines:
$string =~ /(START)(.+?)(END)/s;
This worked for me, the key is you need a separate thread to analyze the socket state with polling. doing it in the same thread as the socket fails detection.
//open or receive a server socket - TODO your code here
socket = new Socket(....);
//enable the keep alive so we can detect closure
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
//create a thread that checks every 5 seconds if the socket is still connected. TODO add your thread starting code
void MonitorSocketsForClosureWorker() {
DateTime nextCheckTime = DateTime.Now.AddSeconds(5);
while (!exitSystem) {
if (nextCheckTime < DateTime.Now) {
try {
if (socket!=null) {
if(socket.Poll(5000, SelectMode.SelectRead) && socket.Available == 0) {
//socket not connected, close it if it's still running
socket.Close();
socket = null;
} else {
//socket still connected
}
}
} catch {
socket.Close();
} finally {
nextCheckTime = DateTime.Now.AddSeconds(5);
}
}
Thread.Sleep(1000);
}
}
The other answer is very complete, but here is a rule of thumb:
call
is blocking:
call('notepad.exe')
print('hello') # only executed when notepad is closed
Popen
is non-blocking:
Popen('notepad.exe')
print('hello') # immediately executed
You should add namespace if you are not using it:
System.Windows.Forms.MessageBox.Show("Some text", "Some title",
System.Windows.Forms.MessageBoxButtons.OK,
System.Windows.Forms.MessageBoxIcon.Error);
Alternatively, you can add at the begining of your file:
using System.Windows.Forms
and then use (as stated in previous answers):
MessageBox.Show("Some text", "Some title",
MessageBoxButtons.OK, MessageBoxIcon.Error);
One reason: the literal 0
has a bad tendency to acquire the type int
, e.g. in perfect argument forwarding or more in general as argument with templated type.
Another reason: readability and clarity of code.
I think, answers to this question are too old... currently some desktop and mobile browsers support HTML Templates for doing this.
I've built a little example:
Tested OK in Chrome 61.0, Opera 48.0, Opera Neon 1.0, Android Browser 6.0, Chrome Mobile 61.0 and Adblocker Browser 54.0
Tested KO in Safari 10.1, Firefox 56.0, Edge 38.14 and IE 11
More compatibility info in canisue.com
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML Template Example</title>
<link rel="stylesheet" href="styles.css">
<link rel="import" href="autoload-template.html">
</head>
<body>
<div class="template-container">1</div>
<div class="template-container">2</div>
<div class="template-container">3</div>
<div class="template-container">4</div>
<div class="template-container">5</div>
</body>
</html>
autoload-template.html
<span id="template-content">
Template Hello World!
</span>
<script>
var me = document.currentScript.ownerDocument;
var post = me.querySelector( '#template-content' );
var container = document.querySelectorAll( '.template-container' );
//alert( container.length );
for(i=0; i<container.length ; i++) {
container[i].appendChild( post.cloneNode( true ) );
}
</script>
styles.css
#template-content {
color: red;
}
.template-container {
background-color: yellow;
color: blue;
}
Your can get more examples in this HTML5 Rocks post
If you use the Logcat display inside the 'debug' perspective in Eclipse the lines are colour-coded. It's pretty easy to find what made your app crash because it's usually in red.
The Java (or Dalvik) virtual machine should never crash, but if your program throws an exception and does not catch it the VM will terminate your program, which is the 'crash' you are seeing.
use 'any'
dict = {}
if any(dict) :
# true
# dictionary is not empty
else :
# false
# dictionary is empty
One common case of shaping a single TCP connection can actually be assembled from dual pairs of socat
and cpipe
in UNIX fashion like this:
socat TCP-LISTEN:5555,reuseaddr,reuseport,fork SYSTEM:'cpipe -ngr -b 1 -s 10 | socat - "TCP:localhost:5000" | cpipe -ngr -b 1 -s 300'
This simulates a connection with bandwidth of approximately 300kB/s from your service at :5000
and to at approximately 10kB/s and listens on :5555
for incoming connections. Caveat: Note that this per-connection, so each individual TCP connection gets this amount.
Explanation:
The outer (left) socat
listens with the given options on :5555
as a forking server. The first cpipe
command in the SYSTEM:...
option then throttles data that went into socket :5555 (and comes out of the first, outer socat
) to at most 10kByte/s. That data is then forwarding using another socat
which connects to localhost:5000
(where the service you want to slow down should be listening). Data from localhost:5000
is then put into the right cpipe
command, which (with the given values) throttles it to about 300kB/s.
The option -ngr
to cpipe
is important. It causes cpipe to read non-greedily from its input file-descriptor. Otherwise, you might get stuck with data in the buffers not being forwarded and waiting for a reply.
Using the more common buffer
tool instead of cpipe
is likely possible as well.
(Credits: This is based on the "double-tee" recipe by Christophe Loor from the socat
documentation)