This solved it for me:
cordova platform update [email protected]
You can use Raphaël—JavaScript Library and achieve it easily. It will work in IE also.
You must detach your entity from session before modifying its ID fields
During the preflight request, you should see the following two headers: Access-Control-Request-Method and Access-Control-Request-Headers. These request headers are asking the server for permissions to make the actual request. Your preflight response needs to acknowledge these headers in order for the actual request to work.
For example, suppose the browser makes a request with the following headers:
Origin: http://yourdomain.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-Custom-Header
Your server should then respond with the following headers:
Access-Control-Allow-Origin: http://yourdomain.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: X-Custom-Header
Pay special attention to the Access-Control-Allow-Headers response header. The value of this header should be the same headers in the Access-Control-Request-Headers request header, and it can not be '*'.
Once you send this response to the preflight request, the browser will make the actual request. You can learn more about CORS here: http://www.html5rocks.com/en/tutorials/cors/
SIMPLE ANSWER:
onclick="functionName(ID.value);
Where ID is the ID of the input field.
desired o/p: Enabling feature XYZ......Done
you can use below command
$a = "Enabling feature XYZ"
Write-output "$a......Done"
you have to add variable and statement inside quotes. hope this is helpful :)
Thanks Techiegal
I use a few methods depending. In the same stylesheet i use: @media (max-width: 450px), or for separate make sure you have the link in the header correctly. I had a look at your fixmeup and you have a confusing array of links to css. It acts as you say also on HTC desire S.
Actually, you should use the translate directive for such stuff instead.
<h1 translate="{{pageTitle}}"></h1>
The directive takes care of asynchronous execution and is also clever enough to unwatch translation ids on the scope if the translation has no dynamic values.
However, if there's no way around and you really have to use $translate
service in the controller, you should wrap the call in a $translateChangeSuccess
event using $rootScope
in combination with $translate.instant()
like this:
.controller('foo', function ($rootScope, $scope, $translate) {
$rootScope.$on('$translateChangeSuccess', function () {
$scope.pageTitle = $translate.instant('PAGE.TITLE');
});
})
So why $rootScope
and not $scope
? The reason for that is, that in angular-translate's events are $emit
ed on $rootScope
rather than $broadcast
ed on $scope
because we don't need to broadcast through the entire scope hierarchy.
Why $translate.instant()
and not just async $translate()
? When $translateChangeSuccess
event is fired, it is sure that the needed translation data is there and no asynchronous execution is happening (for example asynchronous loader execution), therefore we can just use $translate.instant()
which is synchronous and just assumes that translations are available.
Since version 2.8.0 there is also $translate.onReady()
, which returns a promise that is resolved as soon as translations are ready. See the changelog.
Okay, per http://www.oracle.com/technology/tech/globalization/htdocs/nls_lang%20faq.htm:
NLS_LANG cannot be changed by ALTER SESSION, NLS_LANGUAGE and NLS_TERRITORY can. However NLS_LANGUAGE and /or NLS_TERRITORY cannot be set as "standalone" parameters in the environment or registry on the client.
Evidently the "right" solution is, before logging into Oracle at all, setting the following environment variable:
export NLS_LANG=AMERICAN_AMERICA.UTF8
Oracle gets a big fat F for usability.
I made a PDO function which returns all the column names in an simple array.
public function getColumnNames($table){
$sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = :table";
try {
$core = Core::getInstance();
$stmt = $core->dbh->prepare($sql);
$stmt->bindValue(':table', $table, PDO::PARAM_STR);
$stmt->execute();
$output = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$output[] = $row['COLUMN_NAME'];
}
return $output;
}
catch(PDOException $pe) {
trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
}
}
The output will be an array:
Array (
[0] => id
[1] => name
[2] => email
[3] => shoe_size
[4] => likes
... )
Sorry for the necro but I like my function ;)
P.S. I have not included the class Core but you can use your own class.. D.S.
you should try with figaspect. It works for me. From the docs:
Create a figure with specified aspect ratio. If arg is a number, use that aspect ratio. > If arg is an array, figaspect will determine the width and height for a figure that would fit array preserving aspect ratio. The figure width, height in inches are returned. Be sure to create an axes with equal with and height, eg
Example usage:
# make a figure twice as tall as it is wide
w, h = figaspect(2.)
fig = Figure(figsize=(w,h))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
ax.imshow(A, **kwargs)
# make a figure with the proper aspect for an array
A = rand(5,3)
w, h = figaspect(A)
fig = Figure(figsize=(w,h))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
ax.imshow(A, **kwargs)
Edit: I am not sure of what you are looking for. The above code changes the canvas (the plot size). If you want to change the size of the matplotlib window, of the figure, then use:
In [68]: f = figure(figsize=(5,1))
this does produce a window of 5x1 (wxh).
I got this error today and ended up here after googling. None of the existing answers seem relevant to my situation. The only thing I needed to do was to import a model from my __init__.py
file in the top level of an app. I had to move my imports into the functions using the model.
Django seems to have some weird code that can fail like this in so many different scenarios!
next()
can read the input only till the space. It can't read two words separated by a space. Also, next()
places the cursor in the same line after reading the input.
nextLine()
reads input including space between the words (that is, it reads till the end of line \n
). Once the input is read, nextLine()
positions the cursor in the next line.
For reading the entire line you can use nextLine()
.
Not answering OPs question directly, but for the people finding this question in search of clarity on what's the difference between allow,deny
and deny,allow
:
Read the comma as a "but".
allow but deny
: whitelist with exceptions.deny but allow
: blacklist with exceptions.allow only one country access, but exclude proxies within this country
OP needed a whitelist with exceptions, therefore allow,deny
instead of deny,allow
Prior to Internet Explorer 8 there were no support for Media queries. But depending on your case you can try to use conditional comments to target only Internet Explorer 8 and lower. You just have to use a proper CSS files architecture.
You can use:
MYSTRING="abc123"
MYLENGTH=$(printf "%s" "$MYSTRING" | wc -c)
wc -c
or wc --bytes
for byte counts = Unicode characters are counted with 2, 3 or more bytes.wc -m
or wc --chars
for character counts = Unicode characters are counted single until they use more bytes.I'm not sure if this will still be useful to people, but with ES6 I have a way to do it that I find clean and useful.
class MyClass {
constructor ( arg1, arg2, arg3 )
myFunction1 () {...}
myFunction2 () {...}
myFunction3 () {...}
}
module.exports = ( arg1, arg2, arg3 ) => { return new MyClass( arg1,arg2,arg3 ) }
And then you get your expected behaviour.
var MyClass = require('/MyClass.js')( arg1, arg2, arg3 )
You can disable pager for commands that don't recognize --no-pager
flag.
git config --global pager.<command> false
I disable for log aliases and set specific quantity to return.
git config --global pager.log false
I had a similar problem. I was working on a project where I did not control the web.xml configuration file, so I could not use the changes suggested about altering the version. Of course the project was not using JSF so this was especially annoying for me.
I found that there is a really simple fix. Go to Preferences > Maven > Java EE Itegration and uncheck the "JSF Configurator" box.
I did this in a fresh workspace before importing the project again, but it may work equally as well on an existing project ... not sure.
The most portable solution is just to read the file in chunks, and then write the data out to the socket, in a loop (and likewise, the other way around when receiving the file). You allocate a buffer, read
into that buffer, and write
from that buffer into your socket (you could also use send
and recv
, which are socket-specific ways of writing and reading data). The outline would look something like this:
while (1) {
// Read data into buffer. We may not have enough to fill up buffer, so we
// store how many bytes were actually read in bytes_read.
int bytes_read = read(input_file, buffer, sizeof(buffer));
if (bytes_read == 0) // We're done reading from the file
break;
if (bytes_read < 0) {
// handle errors
}
// You need a loop for the write, because not all of the data may be written
// in one call; write will return how many bytes were written. p keeps
// track of where in the buffer we are, while we decrement bytes_read
// to keep track of how many bytes are left to write.
void *p = buffer;
while (bytes_read > 0) {
int bytes_written = write(output_socket, p, bytes_read);
if (bytes_written <= 0) {
// handle errors
}
bytes_read -= bytes_written;
p += bytes_written;
}
}
Make sure to read the documentation for read
and write
carefully, especially when handling errors. Some of the error codes mean that you should just try again, for instance just looping again with a continue
statement, while others mean something is broken and you need to stop.
For sending the file to a socket, there is a system call, sendfile
that does just what you want. It tells the kernel to send a file from one file descriptor to another, and then the kernel can take care of the rest. There is a caveat that the source file descriptor must support mmap
(as in, be an actual file, not a socket), and the destination must be a socket (so you can't use it to copy files, or send data directly from one socket to another); it is designed to support the usage you describe, of sending a file to a socket. It doesn't help with receiving the file, however; you would need to do the loop yourself for that. I cannot tell you why there is a sendfile
call but no analogous recvfile
.
Beware that sendfile
is Linux specific; it is not portable to other systems. Other systems frequently have their own version of sendfile
, but the exact interface may vary (FreeBSD, Mac OS X, Solaris).
In Linux 2.6.17, the splice
system call was introduced, and as of 2.6.23 is used internally to implement sendfile
. splice
is a more general purpose API than sendfile
. For a good description of splice
and tee
, see the rather good explanation from Linus himself. He points out how using splice
is basically just like the loop above, using read
and write
, except that the buffer is in the kernel, so the data doesn't have to transferred between the kernel and user space, or may not even ever pass through the CPU (known as "zero-copy I/O").
try any of the following,
background-size: contain;
background-size: cover;
background-size: 100%;
.container{
background-size: 100%;
}
The simplest and clean way to do that (actually svn 1.9, released 2015) is using:
svn info --show-item revision [--no-newline] [SVNURL/SVNPATH]
The output is the number of the last revision (joungest) for the SVNURL,
or the number of the current revision of the working copy of SVNPATH.
The --no-newline
is optional, instructs svn
not to emit a cosmetic newline (\n
) after the value, if you need minimal output (only the revision number).
See: https://subversion.apache.org/docs/release-notes/1.9.html#svn-info-item
the query() method can do that very intuitively. Express your condition in a string to be evaluated like the following example :
df = df.query("columnNameA <= @x or columnNameB == @y")
with x and y are declared variables which you can refer to with @
In case you are in control of the Server that sends the content of the iframe you can set the setting for X-Frame-Options
in your webserver.
To send the X-Frame-Options header for all pages, add this to your site's configuration:
Header always append X-Frame-Options SAMEORIGIN
To configure nginx to send the X-Frame-Options header, add this either to your http, server or location configuration:
add_header X-Frame-Options SAMEORIGIN;
This header option is optional, so if the option is not set at all, you will give the option to configure this to the next instance (e.g. the visitors browser or a proxy)
source: https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options
len(repr(float(x)/3))
However I must say that this isn't as reliable as you think.
Floats are entered/displayed as decimal numbers, but your computer (in fact, your standard C library) stores them as binary. You get some side effects from this transition:
>>> print len(repr(0.1))
19
>>> print repr(0.1)
0.10000000000000001
The explanation on why this happens is in this chapter of the python tutorial.
A solution would be to use a type that specifically tracks decimal numbers, like python's decimal.Decimal
:
>>> print len(str(decimal.Decimal('0.1')))
3
I've had the same problem.
Use CSS to hide is not the best solution, because sometimes you want users without JS can see the div.. The cleanest solution is to hide the div with JQuery. But the div is visible about 0.5 seconde, which is problematic if the div is on the top of the page.
In these cases, I use an intermediate solution, without JQuery. This one works and is immediate :
<script>document.write('<style>.js_hidden { display: none; }</style>');</script>
<div class="js_hidden">This div will be hidden for JS users, and visible for non JS users.</div>
Of course, you can still add all the effects you want on the div, JQuery toggle() for example. And you will get the best behaviour possible (imho) :
I dont think youre returning json object from server. just a string.
you need the dataType of the return object to be json
My version of this is an adaptation of Arvo's work, with a little more added on to ensure two other cases.
1) If we have all 0s, we should return the digit 0.
2) If we have a blank, we should still return a blank character.
CASE
WHEN PATINDEX('%[^0]%', str_col + '.') > LEN(str_col) THEN RIGHT(str_col, 1)
ELSE SUBSTRING(str_col, PATINDEX('%[^0]%', str_col + '.'), LEN(str_col))
END
$(document).ready(function() {
var referrer = document.referrer;
if(referrer.equals("Setting.jsp")){
function goBack() {
window.history.go();
}
}
if(referrer.equals("http://localhost:8080/Ads/Terms.jsp")){
window.history.forward();
function noBack() {
window.history.forward();
}
}
});
using this you can avoid load previous page load
Based on the answers by @James and @Jyotirmoy Bhattacharya I came up with this solution:
zx <- replicate (5, rnorm(50))
zx_means <- (colMeans(zx, na.rm = TRUE))
boxplot(zx, horizontal = FALSE, outline = FALSE)
points(zx_means, pch = 22, col = "darkgrey", lwd = 7)
(See this post for more details)
If you would like to add points to horizontal box plots, please see this post.
[cell setSelectionStyle:UITableViewCellSelectionStyleGray];
Make sure you have used the above line to use the selection effect
Here's my version of that nice CSS solution JS Fiddle example posted above.
HTML
<div id="donate">
<label class="blue"><input type="radio" name="toggle"><span>$20</span></label>
<label class="green"><input type="radio" name="toggle"><span>$50</span></label>
<label class="yellow"><input type="radio" name="toggle"><span>$100</span></label>
<label class="pink"><input type="radio" name="toggle"><span>$500</span></label>
<label class="purple"><input type="radio" name="toggle"><span>$1000</span></label>
</div>
CSS
body {
font-family:sans-serif;
}
#donate {
margin:4px;
float:left;
}
#donate label {
float:left;
width:170px;
margin:4px;
background-color:#EFEFEF;
border-radius:4px;
border:1px solid #D0D0D0;
overflow:auto;
}
#donate label span {
text-align:center;
font-size: 32px;
padding:13px 0px;
display:block;
}
#donate label input {
position:absolute;
top:-20px;
}
#donate input:checked + span {
background-color:#404040;
color:#F7F7F7;
}
#donate .yellow {
background-color:#FFCC00;
color:#333;
}
#donate .blue {
background-color:#00BFFF;
color:#333;
}
#donate .pink {
background-color:#FF99FF;
color:#333;
}
#donate .green {
background-color:#A3D900;
color:#333;
}
#donate .purple {
background-color:#B399FF;
color:#333;
}
Styled with coloured buttons :)
Enabling delayed variable expansion solves you problem, the script produces "hi":
setlocal EnableDelayedExpansion
set var1=A
set var2=B
set AB=hi
set newvar=!%var1%%var2%!
echo %newvar%
Thanks @thefourtheye, your code greatly helped. I created a generic function from your solution using the version 4.5.0 of Lodash.
function groupBy(dataToGroupOn, fieldNameToGroupOn, fieldNameForGroupName, fieldNameForChildren) {
var result = _.chain(dataToGroupOn)
.groupBy(fieldNameToGroupOn)
.toPairs()
.map(function (currentItem) {
return _.zipObject([fieldNameForGroupName, fieldNameForChildren], currentItem);
})
.value();
return result;
}
To use it:
var result = groupBy(data, 'color', 'colorId', 'users');
Here is the updated fiddler;
nodeName
is the attribute you are looking for. For example:
var elt = document.getElementById('foo');
console.log(elt.nodeName);
Note that nodeName
returns the element name capitalized and without the angle brackets, which means that if you want to check if an element is an <div>
element you could do it as follows:
elt.nodeName == "DIV"
While this would not give you the expected results:
elt.nodeName == "<div>"
Along with jerjer answer(top), sometimes in your parent window and child window are not both external or both internal you will see a problem of opener undefined, and you cannot access parent page properties, see window.opener is undefined on Internet Explorer
If your application is 32 bit, and you want to deploy in a 64 bit machine, You need to set 'Enable 32 Bit Applications' property to 'True' in the application pool - advanced settings.
My comprehensive solution to disable/override all console.*
functions is here.
Of course, please make sure you are including it after checking necessary context. For example, only including in production release, it's not bombing any other crucial components etc.
Quoting it here:
"use strict";_x000D_
(() => {_x000D_
var console = (window.console = window.console || {});_x000D_
[_x000D_
"assert", "clear", "count", "debug", "dir", "dirxml",_x000D_
"error", "exception", "group", "groupCollapsed", "groupEnd",_x000D_
"info", "log", "markTimeline", "profile", "profileEnd", "table",_x000D_
"time", "timeEnd", "timeStamp", "trace", "warn"_x000D_
].forEach(method => {_x000D_
console[method] = () => {};_x000D_
});_x000D_
console.log("This message shouldn't be visible in console log");_x000D_
})();
_x000D_
This is a simple way to call notification by using default vibrate and sound from system.
private void sendNotification(String message, String tick, String title, boolean sound, boolean vibrate, int iconID) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Notification notification = new Notification();
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
if (sound) {
notification.defaults |= Notification.DEFAULT_SOUND;
}
if (vibrate) {
notification.defaults |= Notification.DEFAULT_VIBRATE;
}
notificationBuilder.setDefaults(notification.defaults);
notificationBuilder.setSmallIcon(iconID)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setTicker(tick)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
Add vibrate permission if you are going to use it:
<uses-permission android:name="android.permission.VIBRATE"/>
Good luck,'.
Suppose you want to print the SQL query of the following statements.
$user = User::find(5);
You just need to do as follows:
DB::enableQueryLog();//enable query logging
$user = User::find(5);
print_r(DB::getQueryLog());//print sql query
This will print the last executed query in Laravel.
The variable $_POST
is automatically populated.
Try var_dump($_POST);
to see the contents.
You can access individual values like this: echo $_POST["name"];
This, of course, assumes your form is using the typical form encoding (i.e. enctype=”multipart/form-data”
If your post data is in another format (e.g. JSON or XML, you can do something like this:
$post = file_get_contents('php://input');
and $post
will contain the raw data.
Assuming you're using the standard $_POST
variable, you can test if a checkbox is checked like this:
if(isset($_POST['myCheckbox']) && $_POST['myCheckbox'] == 'Yes')
{
...
}
If you have an array of checkboxes (e.g.
<form action="myscript.php" method="post">
<input type="checkbox" name="myCheckbox[]" value="A" />val1<br />
<input type="checkbox" name="myCheckbox[]" value="B" />val2<br />
<input type="checkbox" name="myCheckbox[]" value="C" />val3<br />
<input type="checkbox" name="myCheckbox[]" value="D" />val4<br />
<input type="checkbox" name="myCheckbox[]" value="E" />val5
<input type="submit" name="Submit" value="Submit" />
</form>
Using [ ]
in the checkbox name indicates that the selected values will be accessed by PHP script as an array. In this case $_POST['myCheckbox']
won't return a single string but will return an array consisting of all the values of the checkboxes that were checked.
For instance, if I checked all the boxes, $_POST['myCheckbox']
would be an array consisting of: {A, B, C, D, E}
. Here's an example of how to retrieve the array of values and display them:
$myboxes = $_POST['myCheckbox'];
if(empty($myboxes))
{
echo("You didn't select any boxes.");
}
else
{
$i = count($myboxes);
echo("You selected $i box(es): <br>");
for($j = 0; $j < $i; $j++)
{
echo $myboxes[$j] . "<br>";
}
}
Using self.class.blah
is NOT the same as using ClassName.blah
when it comes to inheritance.
class Truck
def self.default_make
"mac"
end
def make1
self.class.default_make
end
def make2
Truck.default_make
end
end
class BigTruck < Truck
def self.default_make
"bigmac"
end
end
ruby-1.9.3-p0 :021 > b=BigTruck.new
=> #<BigTruck:0x0000000307f348>
ruby-1.9.3-p0 :022 > b.make1
=> "bigmac"
ruby-1.9.3-p0 :023 > b.make2
=> "mac"
To follow up the answer above, for a .war
artifact, I found I had to apply the equivalent configuration to maven-war-plugin
, rather than maven-jar-plugin
:
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.1</version>
<configuration>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest>
</archive>
</configuration>
</plugin>
This added the version information to MANIFEST.MF
in the project's .jar
(included in WEB-INF/lib
of the .war
)
Building on RobertoNovelo's answer:
import * as fs from 'fs';
is currently the simplest way to do it.
It was tested with a Node.js project (Node.js v10.15.3), with esm, allowing to use import
.
To answer the questions directly:
Will
collect()
behave the same way if called on a dataframe?
Yes, spark.DataFrame.collect
is functionally the same as spark.RDD.collect
. They serve the same purpose on these different objects.
What about the
select()
method?
There is no such thing as spark.RDD.select
, so it cannot be the same as spark.DataFrame.select
.
Does it also work the same way as
collect()
if called on a dataframe?
The only thing that is similar between select
and collect
is that they are both functions on a DataFrame. They have absolutely zero overlap in functionality.
Here's my own description: collect
is the opposite of sc.parallelize
. select
is the same as the SELECT
in any SQL statement.
If you are still having trouble understanding what collect
actually does (for either RDD or DataFrame), then you need to look up some articles about what spark is doing behind the scenes. e.g.:
It has been asked in the past, apparently it costs a lot to mobile browsers, so it's been disabled.
Check this comment by @PaulIrish:
Fixed-backgrounds have huge repaint cost and decimate scrolling performance, which is, I believe, why it was disabled.
you can see workarounds to this in this posts:
any
is something specific to TypeScript is explained quite well by alex's answer.
Object
refers to the JavaScript object
type. Commonly used as {}
or sometimes new Object
. Most things in javascript are compatible with the object data type as they inherit from it. But any
is TypeScript specific and compatible with everything in both directions (not inheritance based). e.g. :
var foo:Object;
var bar:any;
var num:number;
foo = num; // Not an error
num = foo; // ERROR
// Any is compatible both ways
bar = num;
num = bar;
Click on the src/main/java
folder and right click and create the xml file. If you create the application.xml
file in a subpackage other than /
, it will not work.
Know your structure is look like this
package/
| subpackage/
| Abc.java
| Test.java
/application.xml
The best approach I've found so far is to set a background view of the cell and clear background of cell subviews. Of course, this looks nice on tables with indexed style only, no matter with or without accessories.
Here is a sample where cell's background is panted yellow:
UIView* backgroundView = [ [ [ UIView alloc ] initWithFrame:CGRectZero ] autorelease ];
backgroundView.backgroundColor = [ UIColor yellowColor ];
cell.backgroundView = backgroundView;
for ( UIView* view in cell.contentView.subviews )
{
view.backgroundColor = [ UIColor clearColor ];
}
It is from an external js file and it is the only file linked to the page.
OK.
When I double click this file I get the following error
Sounds like you're double-clicking/running a .js file, which will attempt to run the script outside the browser, like a command line script. And that would explain this error:
Windows Script Host Error: 'window' is not defined Code: 800A1391
... not an error you'll see in a browser. And of course, the browser is what supplies the window
object.
ADDENDUM: As a course of action, I'd suggest opening the relevant HTML file and taking a peek at the console. If you don't see anything there, it's likely your window.onload
definition is simply being hit after the browser fires the window.onload
event.
A POST request can include a query string, however normally it doesn't - a standard HTML form with a POST action will not normally include a query string for example.
This is exactly how it worked for me. For some reason the above code failed.
This one runs a check every 3 minutes for any files in there and auto moves it to the destination folder. If you need to be prompted for conflicts then change the /y to /-y
:backup
move /y "D:\Dropbox\Dropbox\Camera Uploads\*.*" "D:\Archive\Camera Uploads\"
timeout 360
goto backup
You can use the dir step, example:
dir("folder") {
sh "pwd"
}
The folder
can be relative or absolute path.
Use DateTime.Today
property. It will return date component of DateTime.Now
. It is equivalent of DateTime.Now.Date
.
How to Use TempTable in Stored Procedure?
Here are the steps:
CREATE TEMP TABLE
-- CREATE TEMP TABLE
Create Table #MyTempTable (
EmployeeID int
);
INSERT TEMP SELECT DATA INTO TEMP TABLE
-- INSERT COMMON DATA
Insert Into #MyTempTable
Select EmployeeID from [EmployeeMaster] Where EmployeeID between 1 and 100
SELECT TEMP TABLE (You can now use this select query)
Select EmployeeID from #MyTempTable
FINAL STEP DROP THE TABLE
Drop Table #MyTempTable
I hope this will help. Simple and Clear :)
It may be worth considering if having your menu without any associated scope is the right way to go. Its not really the angular way.
But, if it is the way you need to go, then you can do it by adding the functions to $rootScope and then within those functions using $broadcast to send events. your controller then uses $on to listen for those events.
Another thing to consider if you do end up having your menu without a scope is that if you have multiple routes, then all of your controllers will have to have their own upate and get functions. (this is assuming you have multiple controllers)
I set the PYTHONPATH
to '.'
and that solved it for me.
export PYTHONPATH='.'
For a one-liner you could as easily do:
PYTHONPATH='.' your_python_script
These commands are expected to be run in a terminal
.htaccess is a hidden file, so you must set all files as visible in your ftp.
I suggest you return your permalink structure to default ( ?p=ID ) so you ensure that .htaccess is the problem.
After that, you could simply set "month and name" structure again, and see if it works.
PS: Have you upgraded to 3.1? I've seen some people with plugin issues in this case.
Note: Disregard this answer, as I must have misunderstood the question.
select *
from Table
where len(ColName) mod 2 = 1
The exact syntax depends on what flavor of SQL you're using.
You could start by using git merge --no-commit
, and then edit the merge however you like i.e. by unstaging config.xml
or any other file, then commit. I suspect you'd want to automate it further after that using hooks, but I think it'd be worth going through manually at least once.
I don't know if this is still actual for you, but I still leave my comment so maybe it will help somebody else. I had same issue, and the solution proposed by @dighan on bountysource.com/issues/ solved it for me.
So here is the code that solved my problem:
var media = document.getElementById("YourVideo");
const playPromise = media.play();
if (playPromise !== null){
playPromise.catch(() => { media.play(); })
}
It still throws an error into console, but at least the video is playing :)
This is best answered here Question 211383
These days, any self-respecting person should be using the stated "micro-clearfix" approach of clearing floats.
It's not too hard. Firstly, take a look at FileReader Interface.
So, when the form is submitted, catch the submission process and
var file = document.getElementById('fileBox').files[0]; //Files[0] = 1st file
var reader = new FileReader();
reader.readAsText(file, 'UTF-8');
reader.onload = shipOff;
//reader.onloadstart = ...
//reader.onprogress = ... <-- Allows you to update a progress bar.
//reader.onabort = ...
//reader.onerror = ...
//reader.onloadend = ...
function shipOff(event) {
var result = event.target.result;
var fileName = document.getElementById('fileBox').files[0].name; //Should be 'picture.jpg'
$.post('/myscript.php', { data: result, name: fileName }, continueSubmission);
}
Then, on the server side (i.e. myscript.php):
$data = $_POST['data'];
$fileName = $_POST['name'];
$serverFile = time().$fileName;
$fp = fopen('/uploads/'.$serverFile,'w'); //Prepends timestamp to prevent overwriting
fwrite($fp, $data);
fclose($fp);
$returnData = array( "serverFile" => $serverFile );
echo json_encode($returnData);
Or something like it. I may be mistaken (and if I am, please, correct me), but this should store the file as something like 1287916771myPicture.jpg
in /uploads/
on your server, and respond with a JSON variable (to a continueSubmission()
function) containing the fileName on the server.
Check out fwrite()
and jQuery.post()
.
On the above page it details how to use readAsBinaryString()
, readAsDataUrl()
, and readAsArrayBuffer()
for your other needs (e.g. images, videos, etc).
Add the following dependency to your pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.2</version>
</dependency>
Was facing same issue. In my case it was non-compatible GIT versions across multiple users who are accessing(pull/push) same project.
have just updated GIT version and updated the path on Android studio settings and its working fine for me.
Edit -
Git for Windows (1.9.5) having some problem, updating the same may helps.
The interface
keyword indicates that you are declaring a traditional interface class in Java.
The @interface
keyword is used to declare a new annotation type.
See docs.oracle tutorial on annotations for a description of the syntax.
See the JLS if you really want to get into the details of what @interface
means.
Try this. This should work:
<div data-role="page" id="page" style="background-image: url('#URL'); background-attachment: fixed; background-repeat: no-repeat; background-size: 100% 100%;"
data-theme="a">
TO get pretty timing differences, then
// d1, d2 are dates
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");
A checklist for doing such a thing:
func_name = function() {...}
Better still, use frameworks which handles it like in Prototype. You have Ajax.updater
.
because you are just learning I suggest you practice converting a SELECT joins to UPDATE or DELETE joins. First I suggest you generate a SELECT statement joining these two tables:
SELECT *
FROM tempDataView a
INNER JOIN tempData b
ON a.Name = b.Name
Then note that we have two table aliases a
and b
. Using these aliases you can easily generate UPDATE statement to update either table a or b. For table a you have an answer provided by JW. If you want to update b
, the statement will be:
UPDATE b
SET b.marks = a.marks
FROM tempDataView a
INNER JOIN tempData b
ON a.Name = b.Name
Now, to convert the statement to a DELETE statement use the same approach. The statement below will delete from a
only (leaving b intact) for those records that match by name:
DELETE a
FROM tempDataView a
INNER JOIN tempData b
ON a.Name = b.Name
You can use the SQL Fiddle created by JW as a playground
for utf8 str:
function unicodeStrDigits($str) {
$arr = array();
$sub = '';
for ($i = 0; $i < strlen($str); $i++) {
if (is_numeric($str[$i])) {
$sub .= $str[$i];
continue;
} else {
if ($sub) {
array_push($arr, $sub);
$sub = '';
}
}
}
if ($sub) {
array_push($arr, $sub);
}
return $arr;
}
When you want to run an executable file from the Command prompt, (cmd.exe), or a batch file, it will:
%PATH%
environment variable for the executable file.If the file isn't found in either of those options you will need to either:
%PATH%
by apending it, (recommended only with extreme caution).You can see which locations are specified in %PATH%
from the Command prompt, Echo %Path%
.
Because of your reported error we can assume that Mobile.exe
is not in the current directory or in a location specified within the %Path%
variable, so you need to use 1.
, 2.
or 3.
.
Examples for 1.
C:\directory_path_without_spaces\My-App\Mobile.exe
or:
"C:\directory path with spaces\My-App\Mobile.exe"
Alternatively you may try:
Start C:\directory_path_without_spaces\My-App\Mobile.exe
or
Start "" "C:\directory path with spaces\My-App\Mobile.exe"
Where ""
is an empty title, (you can optionally add a string between those doublequotes).
Examples for 2.
CD /D C:\directory_path_without_spaces\My-App
Mobile.exe
or
CD /D "C:\directory path with spaces\My-App"
Mobile.exe
You could also use the /D
option with Start
to change the working directory for the executable to be run by the start command
Start /D C:\directory_path_without_spaces\My-App Mobile.exe
or
Start "" /D "C:\directory path with spaces\My-App" Mobile.exe
The m2e plugin uses it's own distribution of Maven, packaged with the plugin.
In order to use Maven from command line, you need to have it installed as a standalone application. Here is an instruction explaining how to do it in Windows
Once Maven is properly installed (i.e. be sure that MAVEN_HOME
, JAVA_HOME
and PATH
variables are set correctly): you must run mvn eclipse:eclipse
from the directory containing the pom.xml
.
Getting Java to properly notify you of encoding errors is tricky. You must use the most verbose and, alas, the least used of the four alternate contructors for each of InputStreamReader
and OutputStreamWriter
to receive a proper exception on an encoding glitch.
For file I/O, always make sure to always use as the second argument to both OutputStreamWriter
and InputStreamReader
the fancy encoder argument:
Charset.forName("UTF-8").newEncoder()
There are other even fancier possibilities, but none of the three simpler possibilities work for exception handing. These do:
OutputStreamWriter char_output = new OutputStreamWriter(
new FileOutputStream("some_output.utf8"),
Charset.forName("UTF-8").newEncoder()
);
InputStreamReader char_input = new InputStreamReader(
new FileInputStream("some_input.utf8"),
Charset.forName("UTF-8").newDecoder()
);
As for running with
$ java -Dfile.encoding=utf8 SomeTrulyRemarkablyLongcLassNameGoeShere
The problem is that that will not use the full encoder argument form for the character streams, and so you will again miss encoding problems.
Here’s a longer example, this one managing a process instead of a file, where we promote two different input bytes streams and one output byte stream all to UTF-8 character streams with full exception handling:
// this runs a perl script with UTF-8 STD{IN,OUT,ERR} streams
Process
slave_process = Runtime.getRuntime().exec("perl -CS script args");
// fetch his stdin byte stream...
OutputStream
__bytes_into_his_stdin = slave_process.getOutputStream();
// and make a character stream with exceptions on encoding errors
OutputStreamWriter
chars_into_his_stdin = new OutputStreamWriter(
__bytes_into_his_stdin,
/* DO NOT OMIT! */ Charset.forName("UTF-8").newEncoder()
);
// fetch his stdout byte stream...
InputStream
__bytes_from_his_stdout = slave_process.getInputStream();
// and make a character stream with exceptions on encoding errors
InputStreamReader
chars_from_his_stdout = new InputStreamReader(
__bytes_from_his_stdout,
/* DO NOT OMIT! */ Charset.forName("UTF-8").newDecoder()
);
// fetch his stderr byte stream...
InputStream
__bytes_from_his_stderr = slave_process.getErrorStream();
// and make a character stream with exceptions on encoding errors
InputStreamReader
chars_from_his_stderr = new InputStreamReader(
__bytes_from_his_stderr,
/* DO NOT OMIT! */ Charset.forName("UTF-8").newDecoder()
);
Now you have three character streams that all raise exception on encoding errors, respectively called chars_into_his_stdin
, chars_from_his_stdout
, and chars_from_his_stderr
.
This is only slightly more complicated that what you need for your problem, whose solution I gave in the first half of this answer. The key point is this is the only way to detect encoding errors.
Just don’t get me started about PrintStream
s eating exceptions.
This worked for me:
string Connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
+ HttpContext.Current.Server.MapPath("\\myPath\\myFile.db")
+ ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\"";
I'm querying an XLSX file so don't worry about any of the other stuff in the connection string but the Data Source.
So my answer is:
HttpContext.Current.Server.MapPath("\\myPath\\myFile.db")
You can probably use timers : http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx
Timers can provide you a precision up to 1 millisecond. Depending on the tick interval an event will be generated. Do your stuff inside the tick event.
Extract the hour, look for a leading space, if found replace with a zero;
set hr=%time:~0,2%
if "%hr:~0,1%" equ " " set hr=0%hr:~1,1%
echo Archive_%date:~-4,4%%date:~-10,2%%date:~-7,2%_%hr%%time:~3,2%%time:~6,2%.zip
If you are using SQL*Plus try the following...
set long 8000
select ...
my best solution :
WHERE
COALESCE(char_length(fieldValue), 0) = 0
COALESCE returns the first non-null expr in the expression list().
if the fieldValue is null or empty string then: we will return the second element then 0.
so 0 is equal to 0 then this fieldValue is a null or empty string.
in python for exemple:
def coalesce(fieldValue):
if fieldValue in (null,''):
return 0
good luck
According to the documentation, timestamp
is a synonym for rowversion
- it's automatically generated and guaranteed1 to be unique. datetime
isn't - it's just a data type which handles dates and times, and can be client-specified on insert etc.
1 Assuming you use it properly, of course. See comments.
You have a couple options, you could setTimeout()
or setInterval()
. Here's a great article that elaborates on how to use them.
The magic is that they're built in to JavaScript, you can use them with any library.
My case was a database corruption after a minor upgrade in mysql basically 5.0.x to 5.1.x with the DB in myisam. The same lines on query: MySQL server has gone away Error reading result set's header
After repairing & optimizing it with mysqlcheck, it returned to normal, without the need to change the socket timeout.
The value 3172978990 is greater than 2147483647 – the maximum value for INT
– hence the error. MySQL integer types and their ranges are listed here.
Also note that the (10)
in INT(10)
does not define the "size" of an integer. It specifies the display width of the column. This information is advisory only.
To fix the error, change your datatype to VARCHAR
. Phone and Fax numbers should be stored as strings. See this discussion.
make DESTDIR=./new/customized/path install
This quick command worked for me for opencv release 3.2.0 installation on Ubuntu 16. DESTDIR path can be relative as well as absolute.
Such redirection can also be useful in case user does not have admin privileges as long as DESTDIR location has right access for the user. e.g /home//
I'd use datediff
, and not care about format conversions:
SELECT *
FROM mytable
WHERE DATEDIFF(MONTH, my_date_column, GETDATE()) <= 3
ES6 allows a construct where a function argument is specified with a "..." notation such as
function testArgs (...args) {
// Where you can test picking the first element
console.log(args[0]);
}
There is a way this can be done, but it needs to be planned carefully. Take for example the following QBASIC program:
1 A = 1; B = 10;
10 print "A = ",A;
20 IF (A < B) THEN A = A + 1; GOTO 10
30 PRINT "That's the end."
Then create your JavaScript to initialize all variables first, followed by making an initial function call to start the ball rolling (we execute this initial function call at the end), and set up functions for every set of lines that you know will be executed in the one unit.
Follow this with the initial function call...
var a, b;
function fa(){
a = 1;
b = 10;
fb();
}
function fb(){
document.write("a = "+ a + "<br>");
fc();
}
function fc(){
if(a<b){
a++;
fb();
return;
}
else
{
document.write("That's the end.<br>");
}
}
fa();
The result in this instance is:
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
a = 7
a = 8
a = 9
a = 10
That's the end.
Redrawing image with background and fill color
extension UIImage {
func withBackground(color: UIColor, fill fillColor: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, true, scale)
guard let ctx = UIGraphicsGetCurrentContext(), let image = cgImage else { return self }
defer { UIGraphicsEndImageContext() }
ctx.concatenate(CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: size.height))
let rect = CGRect(origin: .zero, size: size)
// draw background
ctx.setFillColor(color.cgColor)
ctx.fill(rect)
// draw image with fill color
ctx.clip(to: rect, mask: image)
ctx.setFillColor(fillColor.cgColor)
ctx.fill(rect)
return UIGraphicsGetImageFromCurrentImageContext() ?? self
}
}
Add the below to the build.gradle
project module:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Let's think a little different, You can use static parameters:
class global {
static $foo = "bar";
}
And you can use and modify it every where you like, like:
function func() {
echo global::$foo;
}
As Arnaud suggested in a comment to the original post, you should put this in your html header:
<meta http-equiv="X-UA-Compatible" content="IE=edge">
I don't want any cred for this. I just want to make it more visible for anyone else that come here.
Try a simple SQL Server restart first before doing anything drastic. Might fix it. It did for me
Ultimately, what you're trying to do with the EXTRA blank lines between each one is a little confusing :)
I think what you really want to do is use Get-ItemProperty. You'll get errors when values are missing, but you can suppress them with -ErrorAction 0
or just leave them as reminders. Because the Registry provider returns extra properties, you'll want to stick in a Select-Object that uses the same properties as the Get-Properties.
Then if you want each property on a line with a blank line between, use Format-List (otherwise, use Format-Table to get one per line).
gci -path hklm:\software\microsoft\windows\currentversion\uninstall |
gp -Name DisplayName, InstallDate |
select DisplayName, InstallDate |
fl | out-file addrem.txt
Try this:
num = input("Please input your number: ")
num = float("%0.2f" % (num))
print(num)
I believe this is a lot simpler. For 1 decimal place use %0.1f
. For 2 decimal places use %0.2f
and so on.
Or, if you want to reduce it all to 2 lines:
num = float("%0.2f" % (float(input("Please input your number: "))))
print(num)
There is a better, and simpler, solution than the one given by John Vinyard. Use NullLocator
:
import matplotlib.pyplot as plt
plt.plot(range(10))
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.show()
plt.savefig('plot')
Hope that helps.
The <Leader>
key is mapped to \ by default. So if you have a map of <Leader>t
, you can execute it by default with \+t. For more detail or re-assigning it using the mapleader
variable, see
:help leader
To define a mapping which uses the "mapleader" variable, the special string "<Leader>" can be used. It is replaced with the string value of "mapleader". If "mapleader" is not set or empty, a backslash is used instead. Example: :map <Leader>A oanother line <Esc> Works like: :map \A oanother line <Esc> But after: :let mapleader = "," It works like: :map ,A oanother line <Esc> Note that the value of "mapleader" is used at the moment the mapping is defined. Changing "mapleader" after that has no effect for already defined mappings.
If you need to actually replace the td you are selecting from the DOM, then you need to first go to the parentNode, then replace the contents replace the innerHTML with a new html string representing what you want. The trick is converting the first-table-cell to a string so you can then use it in a string replace method.
I added a fiddle example: http://jsfiddle.net/vzUF4/
<table><tr><td id="first-table-cell">0</td><td>END</td></tr></table>
<script>
var firstTableCell = document.getElementById('first-table-cell');
var tableRow = firstTableCell.parentNode;
// Create a separate node used to convert node into string.
var renderingNode = document.createElement('tr');
renderingNode.appendChild(firstTableCell.cloneNode(true));
// Do a simple string replace on the html
var stringVersionOfFirstTableCell = renderingNode.innerHTML;
tableRow.innerHTML = tableRow.innerHTML.replace(stringVersionOfFirstTableCell,
'<td>0</td><td>1</td>');
</script>
A lot of the complexity here is that you are mixing DOM methods with string methods.
If DOM methods work for your application, it would be much bette to use those.
You can also do this with pure DOM methods (document.createElement, removeChild, appendChild), but it takes more lines of code and your question explicitly said you wanted to use a string.
Assuming you're using jQuery..
var input = '19 51 2.108997\n20 47 2.1089';
var lines = input.split('\n');
var output = '';
$.each(lines, function(key, line) {
var parts = line.split(' ');
output += '<span>' + parts[0] + ' ' + parts[1] + '</span><span>' + parts[2] + '</span>\n';
});
$(output).appendTo('body');
From Object Explorer in SQL Server Management Studio, find your database and expand the node (click on the + sign beside your database). The first item from that expanded tree is Database Diagrams. Right-click on that and you'll see various tasks including creating a new database diagram. If you've never created one before, it'll ask if you want to install the components for creating diagrams. Click yes then proceed.
Do note that PostgreSQL 9.0 (today in beta testing) will have a simple way to do that:
test=> GRANT SELECT ON ALL TABLES IN SCHEMA public TO joeuser;
Another way is call super() with the required argument as a first statement in derived class constructor.
public class Sup {
public Sup(String s) { ...}
}
public class Sub extends Sup {
public Sub() { super("hello"); .. }
}
There is a similar call, isUserAMonkey()
, that returns true if the MonkeyRunner tool is being used. The SDK explanation is just as curious as this one.
public static boolean isUserAMonkey(){}
Returns
true
if the user interface is currently being messed with by a monkey.
Here is the source.
I expect that this was added in anticipation of a new SDK tool named something with a goat and will actually be functional to test for the presence of that tool.
Also see a similar question, Strange function in ActivityManager: isUserAMonkey. What does this mean, what is its use?.
window.alert = null;
alert('test'); // fail
delete window.alert; // true
alert('test'); // win
window
is an instance of DOMWindow
, and by setting something to window.alert
, the correct implementation is being "shadowed", i.e. when accessing alert
it is first looking for it on the window
object. Usually this is not found, and it then goes up the prototype chain to find the native implementation. However, when manually adding the alert
property to window
it finds it straight away and does not need to go up the prototype chain. Using delete window.alert
you can remove the window own property and again expose the prototype implementation of alert
. This may help explain:
window.hasOwnProperty('alert'); // false
window.alert = null;
window.hasOwnProperty('alert'); // true
delete window.alert;
window.hasOwnProperty('alert'); // false
I needed one line version for short array:
($array = [1, 2, 3, 4])[mt_rand(0, count($array) - 1)]
or if array is fixed:
[1, 2, 3, 4][mt_rand(0, 3]
Use the below:
var regEx = new RegExp(pattern1+'|'+pattern2, 'gi');
str.match(regEx);
External hive table has advantages that it does not remove files when we drop tables,we can set row formats with different settings , like serde....delimited
On my remote machine, I had TensorFlow
installed via pip
and when I was importing it in ipython
the import was successful. Despite of that I still got the No module named tensorflow
error when I was running my scripts. The issue here was that I was running my scripts with sudo
, so the python
and tensorflow
paths were not visible to the root. When I ran my scripts without sudo
, everything worked.
You can very easily iterate over dictionaries, too:
for team, scores in NL_East.iteritems():
runs_scored = float(scores[0])
runs_allowed = float(scores[1])
win_percentage = round((runs_scored**2)/((runs_scored**2)+(runs_allowed**2))*1000)
print '%s: %.1f%%' % (team, win_percentage)
In SSMS 2012, you'll have to use:
To enable single-user mode, in SQL instance properties, DO NOT go to "Advance" tag, there is already a "Startup Parameters" tag.
Try this:-
printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
getch();
getch()
is used to get a character from console but does not echo to the screen.
This question is the first link for a Spring Boot search, therefore, would be great to put here the solution recommended in the official documentation. Spring Boot has its own convenience bean RestTemplateBuilder:
@Bean
public RestTemplate restTemplate(
RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder
.setConnectTimeout(Duration.ofSeconds(500))
.setReadTimeout(Duration.ofSeconds(500))
.build();
}
Manual creation of RestTemplate instances is a potentially troublesome approach because other auto-configured beans are not being injected in manually created instances.
Edit 09/2016: In Python 3 and up use urllib.request instead of urllib2
Actually the simplest way is:
import urllib2 # the lib that handles the url stuff
data = urllib2.urlopen(target_url) # it's a file like object and works just like a file
for line in data: # files are iterable
print line
You don't even need "readlines", as Will suggested. You could even shorten it to: *
import urllib2
for line in urllib2.urlopen(target_url):
print line
But remember in Python, readability matters.
However, this is the simplest way but not the safe way because most of the time with network programming, you don't know if the amount of data to expect will be respected. So you'd generally better read a fixed and reasonable amount of data, something you know to be enough for the data you expect but will prevent your script from been flooded:
import urllib2
data = urllib2.urlopen("http://www.google.com").read(20000) # read only 20 000 chars
data = data.split("\n") # then split it into lines
for line in data:
print line
* Second example in Python 3:
import urllib.request # the lib that handles the url stuff
for line in urllib.request.urlopen(target_url):
print(line.decode('utf-8')) #utf-8 or iso8859-1 or whatever the page encoding scheme is
simply use:
PorterDuff.Mode mode = PorterDuff.Mode.SRC_IN;
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
mode = PorterDuff.Mode.MULTIPLY;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
progressBar.setProgressTintList(ColorStateList.valueOf(Color.RED));
progressBar.setProgressBackgroundTintList(ColorStateList.valueOf(Color.RED));
} else {
Drawable progressDrawable;
progressDrawable = (progressBar.isIndeterminate() ? progressBar.getIndeterminateDrawable() : progressBar.getProgressDrawable()).mutate();
progressDrawable.setColorFilter(context.getResources().getColor(Color.RED), mode);
progressBar.setProgressDrawable(progressDrawable);
}
That does the trick:
ls -R1 $PWD | while read l; do case $l in *:) d=${l%:};; "") d=;; *) echo "$d/$l";; esac; done | grep -i ".txt"
But it does that by "sinning" with the parsing of ls
, though, which is considered bad form by the GNU and Ghostscript communities.
Documentation for crypto: http://nodejs.org/api/crypto.html
const crypto = require('crypto')
const text = 'I love cupcakes'
const key = 'abcdeg'
crypto.createHmac('sha1', key)
.update(text)
.digest('hex')
CAST(timestamp_expression AS DATE)
For example, The query is : SELECT CAST(SYSTIMESTAMP AS DATE) FROM dual;
You can disable FK and CHECK constraints only in SQL 2005+. See ALTER TABLE
ALTER TABLE foo NOCHECK CONSTRAINT ALL
or
ALTER TABLE foo NOCHECK CONSTRAINT CK_foo_column
Primary keys and unique constraints can not be disabled, but this should be OK if I've understood you correctly.
Thanks to Neevek his answer worked for me but it doesn't lock the vertical scrolling when user has started scrolling the horizontal view(ViewPager) in horizontal direction and then without lifting the finger scroll vertically it starts to scroll the underlying container view(ScrollView). I fixed it by making a slight change in Neevak's code:
private float xDistance, yDistance, lastX, lastY;
int lastEvent=-1;
boolean isLastEventIntercepted=false;
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
xDistance = yDistance = 0f;
lastX = ev.getX();
lastY = ev.getY();
break;
case MotionEvent.ACTION_MOVE:
final float curX = ev.getX();
final float curY = ev.getY();
xDistance += Math.abs(curX - lastX);
yDistance += Math.abs(curY - lastY);
lastX = curX;
lastY = curY;
if(isLastEventIntercepted && lastEvent== MotionEvent.ACTION_MOVE){
return false;
}
if(xDistance > yDistance )
{
isLastEventIntercepted=true;
lastEvent = MotionEvent.ACTION_MOVE;
return false;
}
}
lastEvent=ev.getAction();
isLastEventIntercepted=false;
return super.onInterceptTouchEvent(ev);
}
In my case, I was mistaken the function parameters, which are:
context.drawImage(image, left, top);
context.drawImage(image, left, top, width, height);
If you expect them to be
context.drawImage(image, width, height);
you will place the image just outside the canvas with the same effects as described in the question.
here is a UITextfield (and other similar fields) category that i made that will make the textfield avoid the keyboard, you should be able to drop this in your view controller as is and it should work. It moves the entire screen up so the current textfield is above the keyboard with animations
#import "UIView+avoidKeyboard.h"
#import "AppDelegate.h"
@implementation UIView (avoidKeyboard)
- (void) becomeFirstResponder {
if(self.isFirstResponder)
return;
[super becomeFirstResponder];
if ([self isKindOfClass:[UISearchBar class]] ||
[self isKindOfClass:[UITextField class]] ||
[self isKindOfClass:[UITextView class]])
{
AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
CGRect screenBounds = appDelegate.window.frame;
CGFloat keyboardHeight;
CGFloat keyboardY;
CGFloat viewsLowestY;
CGPoint origin = [self.superview convertPoint:self.frame.origin toView:appDelegate.window]; //get this views origin in terms of the main screens bounds
if(UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation])){ //the window.frame doesnt take its orientation into account so if its sideways we must use the x value of the origin instead of the y
keyboardHeight = 216;
keyboardY = screenBounds.size.height - keyboardHeight; //find the keyboards y coord relative to how much the main window has moved up
viewsLowestY = origin.y + self.frame.size.height; //find the lowest point of this view
}
else {
keyboardHeight = 162;
keyboardY = screenBounds.size.width - keyboardHeight;
viewsLowestY = origin.x + self.frame.size.height;
}
CGFloat difference = viewsLowestY - keyboardY + 20; //find if this view overlaps with the keyboard with some padding
if (difference > 0){ //move screen up if there is an overlap
[UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
CGRect frame = appDelegate.window.frame;
if(UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation])){
frame.origin.y -= difference;
}
else {
frame.origin.x -= difference;
}
appDelegate.window.frame = frame;
}
completion:nil];
}
}
}
//look at appDelegate to see when the keyboard is hidden
@end
In your appDelegate add this function
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHides:) name:UIKeyboardWillHideNotification object:nil]; //add in didFinishLaunchingWithOptions
...
- (void)keyboardHides:(NSNotification *)notification
{
[UIView animateWithDuration:0.3 animations:^{
[window setFrame: CGRectMake(0, 0, window.frame.size.width, window.frame.size.height)];
} completion:nil];
}
According to this MSDN entry, the limit is 1 million rows. You could be running in compatibility mode, which would limit you to the old standard of 65k. Does your excel say compatibility mode in the title? If so, you can save the file as a new style file under the "save as" menu, or change your default to always use the 2007 file standard.
Previous answer didn't work for me.
But this worked perfectly. Convert Data URI to File then append to FormData
In the plyr
package there is a function rbind.fill
that will merge data.frames and introduce NA
for empty cells:
library(plyr)
combined <- rbind.fill(mtcars[c("mpg", "wt")], mtcars[c("wt", "cyl")])
combined[25:40, ]
mpg wt cyl
25 19.2 3.845 NA
26 27.3 1.935 NA
27 26.0 2.140 NA
28 30.4 1.513 NA
29 15.8 3.170 NA
30 19.7 2.770 NA
31 15.0 3.570 NA
32 21.4 2.780 NA
33 NA 2.620 6
34 NA 2.875 6
35 NA 2.320 4
Try this (It is for Indian mobile number validation):
if (!phoneNumber.matches("^[6-9]\\d{9}$")) {
return false;
} else {
return true;
}
You need to use js get better height for body div
<html><body>
<div id="head" style="height:50px; width=100%; font-size:50px;">This is head</div>
<div id="body" style="height:700px; font-size:100px; white-space:pre-wrap; overflow:scroll;">
This is body
T
h
i
s
i
s
b
o
d
y
</div>
</body></html>
Use the row number to differentiate between duplicate records. Keep the first row number for an EmpID/EmpSSN and delete the rest:
DELETE FROM Employee a
WHERE ROW_NUMBER() <> ( SELECT MIN( ROW_NUMBER() )
FROM Employee b
WHERE a.EmpID = b.EmpID
AND a.EmpSSN = b.EmpSSN )
You may directly write into your css file like this :
.content {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
left:50%;_x000D_
transform: translate(-50%,-50%);_x000D_
}
_x000D_
<div class = "content" >_x000D_
_x000D_
<p> some text </p>_x000D_
</div>
_x000D_
If you're just looking for a more concise syntax you can put the for loop on one line:
array = ['a', 'b']
for value in array: print(value)
Just separate additional statements with a semicolon.
array = ['a', 'b']
for value in array: print(value); print('hello')
This may not conform to your local style guide, but it could make sense to do it like this when you're playing around in the console.
There is a better solution to this answer that is more Angular based.
Save your string in a variable in the .ts file
MyStrings = ["one","two","three"]
In the html file use *ngFor.
<div class="one" *ngFor="let string of MyStrings; let i = index">
<div class="two">{{string}}</div>
</div>
if you want to dynamically insert the div element, just push more strings into the MyStrings array
myFunction(nextString){
this.MyString.push(nextString)
}
this way every time you click the button containing the myFunction(nextString) you effectively add another class="two" div which acts the same way as inserting it into the DOM with pure javascript.
To your secondary question
var elem1 = $('#elem1'),
elem2 = $('#elem2'),
elem3 = $('#elem3');
You can use the variable as the replacement of selector.
elem1.css({'display':'none'}); //will work
In the below case selector is already stored in a variable.
$(elem1,elem2,elem3).css({'display':'none'}); // will not work
i wouldn't do it this way
I'd use name arrays in the form elements
so i'd get the layout
$_POST['field'][0]['name'] = 'value';
$_POST['field'][0]['price'] = 'value';
$_POST['field'][1]['name'] = 'value';
$_POST['field'][1]['price'] = 'value';
then you could do an array slice to get the amount you need
I use to do the compact way
grep -5 string file
That is the equivalent of
grep -A 5 -B 5 string file
Or maybe and that is prob it
<img src="path" onclick="this.src='path'">
_x000D_
dynamic version
ALTER PROCEDURE [dbo].[ReseedTableIdentityCol](@p_table varchar(max))-- RETURNS int
AS
BEGIN
-- Declare the return variable here
DECLARE @sqlCommand nvarchar(1000)
DECLARE @maxVal INT
set @sqlCommand = 'SELECT @maxVal = ISNULL(max(ID),0)+1 from '+@p_table
EXECUTE sp_executesql @sqlCommand, N'@maxVal int OUTPUT',@maxVal=@maxVal OUTPUT
DBCC CHECKIDENT(@p_table, RESEED, @maxVal)
END
exec dbo.ReseedTableIdentityCol @p_table='Junk'
For all databases query sys.sysprocesses
SELECT * FROM sys.sysprocesses WHERE open_tran = 1
For the current database use:
DBCC OPENTRAN
Using CentOS7, logs are available using the command journalctl -u docker
. Answering distinctly, because @sabin's answer might be accurate for older versions of CentOS but was not true for me.
systemd has its own logging system called the journal. The logs for the docker daemon can be viewed using journalctl -u docker
Microsoft Network Monitor (http://www.microsoft.com/downloads/details.aspx?FamilyID=983b941d-06cb-4658-b7f6-3088333d062f)
In case someone google for this, the solutions above didn't work for me so i ended using "pure" javascript
document.getElementById("The id of the element").value = "The value"
And that would set the value and make the current value selected in the combo box. Tested in firefox.
it was easier than keep googling a solution for jQuery
MAC OSX
For yesterday's date:
date -v-1d +%F
where 1d defines current day minus 1 day. Similarly,
date -v-1w +%F - for previous week date
date -v-1m +%F - for previous month date
IF YOU HAVE GNU DATE,
date --date="1 day ago"
More info: https://www.cyberciti.biz/tips/linux-unix-get-yesterdays-tomorrows-date.html
I suggest wrapping your call to requestAnimationFrame
in a setTimeout
:
const fps = 25;
function animate() {
// perform some animation task here
setTimeout(() => {
requestAnimationFrame(animate);
}, 1000 / fps);
}
animate();
You need to call requestAnimationFrame
from within setTimeout
, rather than the other way around, because requestAnimationFrame
schedules your function to run right before the next repaint, and if you delay your update further using setTimeout
you will have missed that time window. However, doing the reverse is sound, since you’re simply waiting a period of time before making the request.
The angular way is shown in the angular docs :)
https://docs.angularjs.org/api/ng/directive/ngReadonly
Here is the example they use:
<body>
Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
<input type="text" ng-readonly="checked" value="I'm Angular"/>
</body>
Basically the angular way is to create a model object that will hold whether or not the input should be readonly and then set that model object accordingly. The beauty of angular is that most of the time you don't need to do any dom manipulation. You just have angular render the view they way your model is set (let angular do the dom manipulation for you and keep your code clean).
So basically in your case you would want to do something like below or check out this working example.
<button ng-click="isInput1ReadOnly = !isInput1ReadOnly">Click Me</button>
<input type="text" ng-readonly="isInput1ReadOnly" value="Angular Rules!"/>
The closest thing C does to "computing p" in a way that's directly visible to applications is acos(-1)
or similar. This is almost always done with polynomial/rational approximations for the function being computed (either in C, or by the FPU microcode).
However, an interesting issue is that computing the trigonometric functions (sin
, cos
, and tan
) requires reduction of their argument modulo 2p. Since 2p is not a diadic rational (and not even rational), it cannot be represented in any floating point type, and thus using any approximation of the value will result in catastrophic error accumulation for large arguments (e.g. if x
is 1e12
, and 2*M_PI
differs from 2p by e, then fmod(x,2*M_PI)
differs from the correct value of 2p by up to 1e12*e/p times the correct value of x
mod 2p. That is to say, it's completely meaningless.
A correct implementation of C's standard math library simply has a gigantic very-high-precision representation of p hard coded in its source to deal with the issue of correct argument reduction (and uses some fancy tricks to make it not-quite-so-gigantic). This is how most/all C versions of the sin
/cos
/tan
functions work. However, certain implementations (like glibc) are known to use assembly implementations on some cpus (like x86) and don't perform correct argument reduction, leading to completely nonsensical outputs. (Incidentally, the incorrect asm usually runs about the same speed as the correct C code for small arguments.)
I have also used a non-generic version, using the new
keyword:
public interface IMetadata
{
Type DataType { get; }
object Data { get; }
}
public interface IMetadata<TData> : IMetadata
{
new TData Data { get; }
}
Explicit interface implementation is used to allow both Data
members:
public class Metadata<TData> : IMetadata<TData>
{
public Metadata(TData data)
{
Data = data;
}
public Type DataType
{
get { return typeof(TData); }
}
object IMetadata.Data
{
get { return Data; }
}
public TData Data { get; private set; }
}
You could derive a version targeting value types:
public interface IValueTypeMetadata : IMetadata
{
}
public interface IValueTypeMetadata<TData> : IMetadata<TData>, IValueTypeMetadata where TData : struct
{
}
public class ValueTypeMetadata<TData> : Metadata<TData>, IValueTypeMetadata<TData> where TData : struct
{
public ValueTypeMetadata(TData data) : base(data)
{}
}
This can be extended to any kind of generic constraints.
First off, your code is a bit off. aes()
is an argument in ggplot()
, you don't use ggplot(...)
+ aes(...) + layers
Second, from the help file ?geom_bar
:
By default, geom_bar uses stat="count" which makes the height of the bar proportion to the number of cases in each group (or if the weight aethetic is supplied, the sum of the weights). If you want the heights of the bars to represent values in the data, use stat="identity" and map a variable to the y aesthetic.
You want the second case, where the height of the bar is equal to the conversion_rate
So what you want is...
data_country <- data.frame(country = c("China", "Germany", "UK", "US"),
conversion_rate = c(0.001331558,0.062428188, 0.052612025, 0.037800687))
ggplot(data_country, aes(x=country,y = conversion_rate)) +geom_bar(stat = "identity")
Result:
Your flex items have
flex: 0 0 200px; /* <aside> */
flex: 1 0 auto; /* <article> */
That means:
The <aside>
will start at 200px
wide.
Then it won't grow nor shrink.
The <article>
will start at the width given by the content.
Then, if there is available space, it will grow to cover it.
Otherwise it won't shrink.
To prevent horizontal overflow, you can:
flex-basis: 0
and then let them grow with a positive flex-grow
.flex-shrink
to let them shrink if there isn't enough space.To prevent vertical overflow, you can
min-height
instead of height
to allow the flex items grow more if necessaryoverflow
different than visible on the flex itemsoverflow
different than visible on the flex containerFor example,
main, aside, article {
margin: 10px;
border: solid 1px #000;
border-bottom: 0;
min-height: 50px; /* min-height instead of height */
}
main {
display: flex;
}
aside {
flex: 0 1 200px; /* Positive flex-shrink */
}
article {
flex: 1 1 auto; /* Positive flex-shrink */
}
_x000D_
<main>
<aside>x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x </aside>
<article>don't let flex item overflow container.... y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y </article>
</main>
_x000D_
Try this. I've use the Large Object Binary (LOB) format for storing generated PDF documents, some of which were 10+ MB in size, in a database and it worked wonderfully.
You can also try adding the Motumedia PPA to your apt sources and update your ffmpeg packages.
you can remove an App from the store or "Unpublish" by clicking a tiny label bellow your app's title, right side of the "PUBLISHED" green status label.
Works even if your app was live (published) for long time, mine was.
Regards.
If your question was "why doesn't this cmd script fragment work?" then the answer is that for /f
iterates over lines. The delims
split lines into fields, but you're only capturing the first field in %%P
. There is no way to capture an arbitrary number of fields with a for /f
loop.
The solution depends on the PHP version you are using. At least there are 2 solutions:
As @JosepAlsina said before the best and also shortest solution is to use array_column
as following:
$catIds = array_column($objects, 'id');
Notice:
For iterating an array
containing \stdClass
es as used in the question it is only possible with PHP versions >= 7.0
. But when using an array
containing array
s you can do the same since PHP >= 5.5
.
@Greg said in older PHP versions it is possible to do following:
$catIds = array_map(create_function('$o', 'return $o->id;'), $objects);
But beware: In newer PHP versions >= 5.3.0
it is better to use Closure
s, like followed:
$catIds = array_map(function($o) { return $o->id; }, $objects);
First solution creates a new function and puts it into your RAM. The garbage collector does not delete the already created and already called function instance out of memory for some reason. And that regardless of the fact, that the created function instance can never be called again, because we have no pointer for it. And the next time when this code is called, the same function will be created again. This behavior slowly fills your memory...
Both examples with memory output to compare them:
while (true)
{
$objects = array_map(create_function('$o', 'return $o->id;'), $objects);
echo memory_get_usage() . "\n";
sleep(1);
}
// the output
4235616
4236600
4237560
4238520
...
while (true)
{
$objects = array_map(function($o) { return $o->id; }, $objects);
echo memory_get_usage() . "\n";
sleep(1);
}
// the output
4235136
4235168
4235168
4235168
...
Memory leak?! Is Garbage Collector doing right when using 'create_function' within 'array_map'?
The basic difference is, like you stated, generating GUI events from the BackgroundWorker
. If the thread does not need to update the display or generate events for the main GUI thread, then it can be a simple thread.
Use git shortlog just like this
git shortlog -sn
Or create an alias (for ZSH based terminal)
# show contributors by commits
alias gcall="git shortlog -sn"
Declaration, generally, refers to the introduction of a new name in the program. For example, you can declare a new function by describing it's "signature":
void xyz();
or declare an incomplete type:
class klass;
struct ztruct;
and last but not least, to declare an object:
int x;
It is described, in the C++ standard, at §3.1/1 as:
A declaration (Clause 7) may introduce one or more names into a translation unit or redeclare names introduced by previous declarations.
A definition is a definition of a previously declared name (or it can be both definition and declaration). For example:
int x;
void xyz() {...}
class klass {...};
struct ztruct {...};
enum { x, y, z };
Specifically the C++ standard defines it, at §3.1/1, as:
A declaration is a definition unless it declares a function without specifying the function’s body (8.4), it contains the extern specifier (7.1.1) or a linkage-specification25 (7.5) and neither an initializer nor a function- body, it declares a static data member in a class definition (9.2, 9.4), it is a class name declaration (9.1), it is an opaque-enum-declaration (7.2), it is a template-parameter (14.1), it is a parameter-declaration (8.3.5) in a function declarator that is not the declarator of a function-definition, or it is a typedef declaration (7.1.3), an alias-declaration (7.1.3), a using-declaration (7.3.3), a static_assert-declaration (Clause 7), an attribute- declaration (Clause 7), an empty-declaration (Clause 7), or a using-directive (7.3.4).
Initialization refers to the "assignment" of a value, at construction time. For a generic object of type T
, it's often in the form:
T x = i;
but in C++ it can be:
T x(i);
or even:
T x {i};
with C++11.
So does it mean definition equals declaration plus initialization?
It depends. On what you are talking about. If you are talking about an object, for example:
int x;
This is a definition without initialization. The following, instead, is a definition with initialization:
int x = 0;
In certain context, it doesn't make sense to talk about "initialization", "definition" and "declaration". If you are talking about a function, for example, initialization does not mean much.
So, the answer is no: definition does not automatically mean declaration plus initialization.
You can use c++ boost::property_tree::ptree for parsing json data. here is the example for your json data. this would be more easy if you shift name inside each child nodes
#include <iostream>
#include <string>
#include <tuple>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
int main () {
namespace pt = boost::property_tree;
pt::ptree loadPtreeRoot;
pt::read_json("example.json", loadPtreeRoot);
std::vector<std::tuple<std::string, std::string, std::string>> people;
pt::ptree temp ;
pt::ptree tage ;
pt::ptree tprofession ;
std::string age ;
std::string profession ;
//Get first child
temp = loadPtreeRoot.get_child("Anna");
tage = temp.get_child("age");
tprofession = temp.get_child("profession");
age = tage.get_value<std::string>();
profession = tprofession.get_value<std::string>();
std::cout << "age: " << age << "\n" << "profession :" << profession << "\n" ;
//push tuple to vector
people.push_back(std::make_tuple("Anna", age, profession));
//Get Second child
temp = loadPtreeRoot.get_child("Ben");
tage = temp.get_child("age");
tprofession = temp.get_child("profession");
age = tage.get_value<std::string>();
profession = tprofession.get_value<std::string>();
std::cout << "age: " << age << "\n" << "profession :" << profession << "\n" ;
//push tuple to vector
people.push_back(std::make_tuple("Ben", age, profession));
for (const auto& tmppeople: people) {
std::cout << "Child[" << std::get<0>(tmppeople) << "] = " << " age : "
<< std::get<1>(tmppeople) << "\n profession : " << std::get<2>(tmppeople) << "\n";
}
}
When I started using json, I was confused and unable to figure it out for some time, but finally I got what I wanted
Here is the simple solution
import json
m = {'id': 2, 'name': 'hussain'}
n = json.dumps(m)
o = json.loads(n)
print(o['id'], o['name'])
The algorithm std::replace
works per element on a given sequence (so it replaces elements with different elements, and can not replace it with nothing). But there is no empty character. If you want to remove elements from a sequence, the following elements have to be moved, and std::replace
doesn't work like this.
You can try to use std::remove
(together with std::erase
) to achieve this.
str.erase(std::remove(str.begin(), str.end(), 'a'), str.end());
Float has 32 bit (4 bytes) with 8 places accuracy. Double has 64 bit (8 bytes) with 16 places accuracy.
If you need better accuracy, use Double instead of Float.
In this line:
for name, email, lastname in unpaidMembers.items():
unpaidMembers.items()
must have only two values per iteration.
Here is a small example to illustrate the problem:
This will work:
for alpha, beta, delta in [("first", "second", "third")]:
print("alpha:", alpha, "beta:", beta, "delta:", delta)
This will fail, and is what your code does:
for alpha, beta, delta in [("first", "second")]:
print("alpha:", alpha, "beta:", beta, "delta:", delta)
In this last example, what value in the list is assigned to delta
? Nothing, There aren't enough values, and that is the problem.
bool contains = pricePublicList.Any(p => p.Size == 200);
jminix is an embedded web based JMX console. Not sure if it's maintained any longer, but still.
Answer by @Ben proved to be useful for me. But I needed to check the product version as it was the main increment happening in my software and followed semantic versioning.
myFileVersionInfo.ProductVersion
This method met my expectations
Update: Instead of explicitly mentioning dll path in program (as needed in production version), we can get product version using Assembly.
Assembly assembly = Assembly.GetExecutingAssembly();
FileVersionInfo fileVersionInfo =FileVersionInfo.GetVersionInfo(assembly.Location);
string ProdVersion= fileVersionInfo.ProductVersion;
#!/bin/bash
msg1=${1} #First Parameter
msg2=${2} #Second Parameter
concatString=$msg1"$msg2" #Concatenated String
concatString2="$msg1$msg2"
echo $concatString
echo $concatString2
Using INDEX
and MATCH
for binning. Easier to maintain if we have more bins.
=INDEX({"Text 1","Text 2","Text 3"},MATCH(A2,{0,5,21,100}))
It sounds like you want a StackPanel
where the final element uses up all the remaining space. But why not use a DockPanel
? Decorate the other elements in the DockPanel
with DockPanel.Dock="Top"
, and then your help control can fill the remaining space.
XAML:
<DockPanel Width="200" Height="200" Background="PowderBlue">
<TextBlock DockPanel.Dock="Top">Something</TextBlock>
<TextBlock DockPanel.Dock="Top">Something else</TextBlock>
<DockPanel
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Height="Auto"
Margin="10">
<GroupBox
DockPanel.Dock="Right"
Header="Help"
Width="100"
Background="Beige"
VerticalAlignment="Stretch"
VerticalContentAlignment="Stretch"
Height="Auto">
<TextBlock Text="This is the help that is available on the news screen."
TextWrapping="Wrap" />
</GroupBox>
<StackPanel DockPanel.Dock="Left" Margin="10"
Width="Auto" HorizontalAlignment="Stretch">
<TextBlock Text="Here is the news that should wrap around."
TextWrapping="Wrap"/>
</StackPanel>
</DockPanel>
</DockPanel>
If you are on a platform without DockPanel
available (e.g. WindowsStore), you can create the same effect with a grid. Here's the above example accomplished using grids instead:
<Grid Width="200" Height="200" Background="PowderBlue">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0">
<TextBlock>Something</TextBlock>
<TextBlock>Something else</TextBlock>
</StackPanel>
<Grid Height="Auto" Grid.Row="1" Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<GroupBox
Width="100"
Height="Auto"
Grid.Column="1"
Background="Beige"
Header="Help">
<TextBlock Text="This is the help that is available on the news screen."
TextWrapping="Wrap"/>
</GroupBox>
<StackPanel Width="Auto" Margin="10" DockPanel.Dock="Left">
<TextBlock Text="Here is the news that should wrap around."
TextWrapping="Wrap"/>
</StackPanel>
</Grid>
</Grid>
Using an ECMAScript Edition 6 (ES6/ES2015) string template:
let d = new Date();
let formatted = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;
If you need to change the delimiters:
const delimiter = '/';
let formatted = [d.getFullYear(), d.getMonth() + 1, d.getDate()].join(delimiter);
It is simple, as a java, Android also supporting singleton. -
Singleton is a part of Gang of Four design pattern and it is categorized under creational design patterns.
-> Static member : This contains the instance of the singleton class.
-> Private constructor : This will prevent anybody else to instantiate the Singleton class.
-> Static public method : This provides the global point of access to the Singleton object and returns the instance to the client calling class.
use getInstance() of Singleton class
public class Logger{
private static Logger objLogger;
private Logger(){
//ToDo here
}
public static Logger getInstance()
{
if (objLogger == null)
{
objLogger = new Logger();
}
return objLogger;
}
}
while use singleton -
Logger.getInstance();
The 2 highest upvoted answers are correct. As of today, the only thing I needed to change (from default settings) was to enable generation using dot instead of the built-in generator.
Some important notes:
html/inherits.html
or (from the website navigation) classes => class hierarchy => "Go to the textual class hierarchy".T
.
foo
inherits from T
and the T
template type parameter has a default, such default will be assumed. If there is a type bar
which inherits from foo<U>
where U
is different than the default, bar
will have a foo<U>
parent. foo<>
and bar<U>
will not have a common parent.variant
instantiation will be displayed to inherit from variant<Ts...>
.<...>
string in their name representing type and non-type parameters which did not have defaults.as @fabrizio-valencia said use lower case. in windows if you export mysql database (phpmyadmin) the tables name will converted to lower case and this lead to all sort of problems. see Are table names in MySQL case sensitive?
For Google Places Autocomplete V3, the best solution for this is two API requests.
Here is the fiddle
The reason why none of the other answers sufficed is because they either used jquery to mimic events (hacky) or used either Geocoder or Google Places Search box which does not always match autocomplete results. Instead, what we will do is is uses Google's Autocomplete Service as detailed here with only javascript (no jquery)
Below is detailed the most cross browser compatible solution using native Google APIs to generate the autocomplete box and then rerun the query to select the first option.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places&language=en"></script>
Javascript
// For convenience, although if you are supporting IE8 and below
// bind() is not supported
var $ = document.querySelector.bind(document);
function autoCallback(predictions, status) {
// *Callback from async google places call
if (status != google.maps.places.PlacesServiceStatus.OK) {
// show that this address is an error
pacInput.className = 'error';
return;
}
// Show a successful return
pacInput.className = 'success';
pacInput.value = predictions[0].description;
}
function queryAutocomplete(input) {
// *Uses Google's autocomplete service to select an address
var service = new google.maps.places.AutocompleteService();
service.getPlacePredictions({
input: input,
componentRestrictions: {
country: 'us'
}
}, autoCallback);
}
function handleTabbingOnInput(evt) {
// *Handles Tab event on delivery-location input
if (evt.target.id == "pac-input") {
// Remove active class
evt.target.className = '';
// Check if a tab was pressed
if (evt.which == 9 || evt.keyCode == 9) {
queryAutocomplete(evt.target.value);
}
}
}
// ***** Initializations ***** //
// initialize pac search field //
var pacInput = $('#pac-input');
pacInput.focus();
// Initialize Autocomplete
var options = {
componentRestrictions: {
country: 'us'
}
};
var autocomplete = new google.maps.places.Autocomplete(pacInput, options);
// ***** End Initializations ***** //
// ***** Event Listeners ***** //
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var result = autocomplete.getPlace();
if (typeof result.address_components == 'undefined') {
queryAutocomplete(result.name);
} else {
// returns native functionality and place object
console.log(result.address_components);
}
});
// Tabbing Event Listener
if (document.addEventListener) {
document.addEventListener('keydown', handleTabbingOnInput, false);
} else if (document.attachEvent) { // IE8 and below
document.attachEvent("onsubmit", handleTabbingOnInput);
}
// search form listener
var standardForm = $('#search-shop-form');
if (standardForm.addEventListener) {
standardForm.addEventListener("submit", preventStandardForm, false);
} else if (standardForm.attachEvent) { // IE8 and below
standardForm.attachEvent("onsubmit", preventStandardForm);
}
// ***** End Event Listeners ***** //
HTML
<form id="search-shop-form" class="search-form" name="searchShopForm" action="/impl_custom/index/search/" method="post">
<label for="pac-input">Delivery Location</label>
<input id="pac-input" type="text" placeholder="Los Angeles, Manhattan, Houston" autocomplete="off" />
<button class="search-btn btn-success" type="submit">Search</button>
</form>
The only gripe is that the native implementation returns a different data structure although the information is the same. Adjust accordingly.
git rm --fileName
git ls-files
to make sure that the file is removed or untracked
git commit -m "UntrackChanges"
git push
You can see a detailed description here.
ini_set('display_errors', 1);
// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
// Report all PHP errors (see changelog)
error_reporting(E_ALL);
// Report all PHP errors
error_reporting(-1);
// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
Changelog
5.4.0 E_STRICT became part of E_ALL
5.3.0 E_DEPRECATED and E_USER_DEPRECATED introduced.
5.2.0 E_RECOVERABLE_ERROR introduced.
5.0.0 E_STRICT introduced (not part of E_ALL).
They are lists because you type them as lists in the dictionary:
bikes = {
# Bike designed for children"
"Trike": ["Trike", 20, 100],
# Bike designed for everyone"
"Kruzer": ["Kruzer", 50, 165]
}
You should use the bike-class instead:
bikes = {
# Bike designed for children"
"Trike": Bike("Trike", 20, 100),
# Bike designed for everyone"
"Kruzer": Bike("Kruzer", 50, 165)
}
This will allow you to get the cost of the bikes with bike.cost as you were trying to.
for bike in bikes.values():
profit = bike.cost * margin
print(bike.name + " : " + str(profit))
This will now print:
Kruzer : 33.0
Trike : 20.0
java android
in my case
I want to change from
~/propic/........png
anything after /propic/ doesn't matter what before it
........png
finally, I found the code in Class StringUtils
this is the code
public static String substringAfter(final String str, final String separator) {
if (isEmpty(str)) {
return str;
}
if (separator == null) {
return "";
}
final int pos = str.indexOf(separator);
if (pos == 0) {
return str;
}
return str.substring(pos + separator.length());
}
Here is the code of ReadDoc/docx.java: This will read a dox/docx file and print its content to the console. you can customize it your way.
import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
public class ReadDocFile
{
public static void main(String[] args)
{
File file = null;
WordExtractor extractor = null;
try
{
file = new File("c:\\New.doc");
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
HWPFDocument document = new HWPFDocument(fis);
extractor = new WordExtractor(document);
String[] fileData = extractor.getParagraphText();
for (int i = 0; i < fileData.length; i++)
{
if (fileData[i] != null)
System.out.println(fileData[i]);
}
}
catch (Exception exep)
{
exep.printStackTrace();
}
}
}
I solved using a "manual" deserialization. I'll explain in code
public ActionResult MyMethod([System.Web.Http.FromBody] MyModel model)
{
if (module.Fields == null && !string.IsNullOrEmpty(Request.Form["fields"]))
{
model.Fields = JsonConvert.DeserializeObject<MyFieldModel[]>(Request.Form["fields"]);
}
//... more code
}
Using bash regular expressions:
re="http://([^/]+)/"
if [[ $name =~ $re ]]; then echo ${BASH_REMATCH[1]}; fi
Edit - OP asked for explanation of syntax. Regular expression syntax is a large topic which I can't explain in full here, but I will attempt to explain enough to understand the example.
re="http://([^/]+)/"
This is the regular expression stored in a bash variable, re
- i.e. what you want your input string to match, and hopefully extract a substring. Breaking it down:
http://
is just a string - the input string must contain this substring for the regular expression to match[]
Normally square brackets are used say "match any character within the brackets". So c[ao]t
would match both "cat" and "cot". The ^
character within the []
modifies this to say "match any character except those within the square brackets. So in this case [^/]
will match any character apart from "/".+
to the end of it says "match 1 or more of the preceding sub-expression". So [^/]+
matches 1 or more of the set of all characters, excluding "/".()
parentheses around a subexpression says that you want to save whatever matched that subexpression for later processing. If the language you are using supports this, it will provide some mechanism to retrieve these submatches. For bash, it is the BASH_REMATCH array.Next, we have to test the input string against the regular expression to see if it matches. We can use a bash conditional to do that:
if [[ $name =~ $re ]]; then
echo ${BASH_REMATCH[1]}
fi
In bash, the [[ ]]
specify an extended conditional test, and may contain the =~
bash regular expression operator. In this case we test whether the input string $name
matches the regular expression $re
. If it does match, then due to the construction of the regular expression, we are guaranteed that we will have a submatch (from the parentheses ()
), and we can access it using the BASH_REMATCH array:
${BASH_REMATCH[0]}
will be the entire string matched by the regular expression, i.e. "http://www.google.com/".()
within a regular expression - The BASH_REMATCH
elements will correspond to these in order. So in this case ${BASH_REMATCH[1]}
will contain "www.google.com", which I think is the string you want.Note that the contents of the BASH_REMATCH array only apply to the last time the regular expression =~
operator was used. So if you go on to do more regular expression matches, you must save the contents you need from this array each time.
This may seem like a lengthy description, but I have really glossed over several of the intricacies of regular expressions. They can be quite powerful, and I believe with decent performance, but the regular expression syntax is complex. Also regular expression implementations vary, so different languages will support different features and may have subtle differences in syntax. In particular escaping of characters within a regular expression can be a thorny issue, especially when those characters would have an otherwise different meaning in the given language.
Note that instead of setting the $re
variable on a separate line and referring to this variable in the condition, you can put the regular expression directly into the condition. However in bash 3.2, the rules were changed regarding whether quotes around such literal regular expressions are required or not. Putting the regular expression in a separate variable is a straightforward way around this, so that the condition works as expected in all bash versions that support the =~
match operator.
swift4 (tested)
let alertController = UIAlertController(title: "Select Photo", message: "Select atleast one photo", preferredStyle: .actionSheet)
let action1 = UIAlertAction(title: "From Photo", style: .default) { (action) in
print("Default is pressed.....")
}
let action2 = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
print("Cancel is pressed......")
}
let action3 = UIAlertAction(title: "Click new", style: .default) { (action) in
print("Destructive is pressed....")
}
alertController.addAction(action1)
alertController.addAction(action2)
alertController.addAction(action3)
self.present(alertController, animated: true, completion: nil)
}
I generally prefer hyphens with lower case, but one thing not yet mentioned is that sometimes it's nice to have the file name exactly match the name of a single module or instantiable function contained within.
For example, I have a revealing module declared with var knockoutUtilityModule = function() {...}
within its own file named knockoutUtilityModule.js, although objectively I prefer knockout-utility-module.js.
Similarly, since I'm using a bundling mechanism to combine scripts, I've taken to defining instantiable functions (templated view models etc) each in their own file, C# style, for maintainability. For example, ProductDescriptorViewModel lives on its own inside ProductDescriptorViewModel.js (I use upper case for instantiable functions).
None of the above answers worked for me. I did notice that resizing my window did cause a redraw. So this did it for me:
$(window).trigger('resize');
Get a shell of your running container and change the root pass.
docker exec -it <MyContainer> bash
root@MyContainer:/# passwd
Enter new UNIX password:
Retype new UNIX password:
Just multiply the number by 100, round, and divide the resulting number by 100.
This was the reason why I was getting it:
I had an ASP:ListBox. Initially it was hidden. At client side I would populate it via AJAX with options. The user chose one option. Then when clicking the Submit button, the Server would get all funny about the ListBox, since it did not remember it having any options.
So what I did is to make sure I clear all the list options before submitting the form back to the server. That way the server did not complain since the list went to the client empty and it came back empty.
Sorted!!!
Performance-wise bash outperforms python in the process startup time.
Here are some measurements from my core i7 laptop running Linux Mint:
Starting process Startup time
empty /bin/sh script 1.7 ms
empty /bin/bash script 2.8 ms
empty python script 11.1 ms
python script with a few libs* 110 ms
*Python loaded libs are: os, os.path, json, time, requests, threading, subprocess
This shows a huge difference however bash execution time degrades quickly if it has to do anything sensible since it usually must call external processes.
If you care about performance use bash only for:
Install the extension "Code Runner". Check if you can compile your program with csc
(ex.: csc hello.cs
). The command csc
is shipped with Mono. Then add this to your VS Code user settings:
"code-runner.executorMap": {
"csharp": "echo '# calling mono\n' && cd $dir && csc /nologo $fileName && mono $dir$fileNameWithoutExt.exe",
// "csharp": "echo '# calling dotnet run\n' && dotnet run"
}
Open your C# file and use the execution key of Code Runner.
Edit: also added dotnet run
, so you can choose how you want to execute your program: with Mono, or with dotnet. If you choose dotnet, then first create the project (dotnet new console
, dotnet restore
).
Instead of
css=#container
use
css=div.container:nth-of-type(1),css=div.container:nth-of-type(2)
You can't do it if v1 is null, but you can check with an operator.
v2 = v1 ?? 0;
Applying same filter in HTML with multiple columns, just example:
variable = (array | filter : {Lookup1Id : subject.Lookup1Id, Lookup2Id : subject.Lookup2Id} : true)
Here is a pure PHP class to perform backups on MySQL databases not using mysqldump or mysql commands: Backing up MySQL databases with pure PHP
It's better if you create a class that has all the query methods, inclusively, in a different package, so instead of typing all the process in every class, you just call the method from that class.
For Linux Mint, this problem is actually referenced in the Docker website:
Note: The
lsb_release -cs
sub-command below returns the name of your Ubuntu distribution, such asxenial
. Sometimes, in a distribution like Linux Mint, you might have to change$(lsb_release -cs)
to your parent Ubuntu distribution. For example, if you are using Linux Mint Rafaela, you could use trusty.amd64:
$ sudo add-apt-repository \
"deb [arch=amd64]
https://download.docker.com/linux/ubuntu \
$(lsb_release -cs) \
stable"
The lsb_release -cs
command gives a repository for which Docker has no prepared package - you must change it to xenial.
The correct command for Linux Mint 18 which is based on Ubuntu 16.04 Xenial is
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
xenial \
stable"
You should probably re-write the script to return a value rather than output it. Instead of:
a=$( script.sh ) # Now a is a string, either "success" or "Failed"
case "$a" in
success) echo script succeeded;;
Failed) echo script failed;;
esac
you would be able to do:
if script.sh > /dev/null; then
echo script succeeded
else
echo script failed
fi
It is much simpler for other programs to work with you script if they do not have to parse the output. This is a simple change to make. Just exit 0
instead of printing success
, and exit 1
instead of printing Failed
. Of course, you can also print those values as well as exiting with a reasonable return value, so that wrapper scripts have flexibility in how they work with the script.
In your TS Definition file, e.g. typings.d.ts`, you can add this line:
declare module "*.json" {
const value: any;
export default value;
}
Then add this in your typescript(.ts) file:-
import * as data from './colors.json';
const word = (<any>data).name;
Check it out -
<input type="button" id="btnclick" value="click" />
var intervalA;
var intervalB;
$(document).ready(function () {
$('#btnclick').click(function () {
blinkFont();
setTimeout(function () {
clearInterval(intervalA);
clearInterval(intervalB);
}, 5000);
});
});
function blinkFont() {
document.getElementById("blink").style.color = "red"
document.getElementById("blink").style.background = "black"
intervalA = setTimeout("blinkFont()", 500);
}
function setblinkFont() {
document.getElementById("blink").style.color = "black"
document.getElementById("blink").style.background = "red"
intervalB = setTimeout("blinkFont()", 500);
}
</script>
<div id="blink" class="live-chat">
<span>This is blinking text and background</span>
</div>
Ruby(1.9+)
#!/usr/bin/env ruby
Dir["*"].each do |file|
h=Hash.new(0)
open(file).each do |row|
row.chomp.split("\t").each do |w|
h[ w ] += 1
end
end
h.sort{|a,b| b[1]<=>a[1] }.each{|x,y| print "#{x}:#{y}\n" }
end
Be aware that there is an additional setting in jQuery UI v1.10. There is an appendTo setting that has been added, to address the ASP.NET workaround you're using to re-add the element to the form.
Try:
$("#dialog").dialog({
autoOpen: false,
height: 280,
width: 440,
modal: true,
**appendTo**:"form"
});
You can iterate through the <li>
s in the <ul>
and stop when you find the right one.
function getIndex(li) {
var lis = li.parentNode.getElementsByTagName('li');
for (var i = 0, len = lis.length; i < len; i++) {
if (li === lis[i]) {
return i;
}
}
}
This can now be done without expression trees and extension methods in a type safe manner with the new C# feature nameof()
like this:
Attribute.IsDefined(typeof(YourClass).GetProperty(nameof(YourClass.Id)), typeof(IsIdentity));
nameof() was introduced in C# 6