In TypeScript, you can do:
private getImage(imagePath): ng.IPromise<any> {
var defer = this.q.defer<any>();
var img = new Image();
img.src = imagePath;
img.addEventListener('load',()=>{
defer.resolve(img);
});
return defer.promise;
}
Use the above function to getimage object. Then the following to add to pdf file:
pdf.addImage(getImage(url), 'png', x, y, imagewidth, imageheight);
In plain JavaScript, the function looks like this:
function (imagePath) {
var defer = this.q.defer();
var img = new Image();
img.src = imagePath;
img.addEventListener('load', function () {
defer.resolve(img);
});
return defer.promise;
};
First, you should install "platformio-ide-terminal": Open "Preferences ?," >> Click "+ Install" >> In "Search packages" type "platformio-ide-terminal" >> Click "Install".
And answering exactly the question. If you have previously installed, just use:
ctrl-`
or Option+Command+T (??T)node -v
will show you the current version.npm -v
will show you the current version.brew link --overwrite --dry-run node
will force the link and overwrite all conflicting files.brew install node
do a fresh installation.brew update
brew upgrade node
brew link --overwrite node
or
brew link node
I always liked going after it directly:
SELECT
DB_NAME( dbid ) AS DatabaseName,
CAST( ( SUM( size ) * 8 ) / ( 1024.0 * 1024.0 ) AS decimal( 10, 2 ) ) AS DbSizeGb
FROM
sys.sysaltfiles
GROUP BY
DB_NAME( dbid )
In such case you will need to parse zip local header entries. Each file, stored in zip file, has preceding Local File Header entry, which (normally) contains enough information for decompression, Generally, you can make simple parsing of such entries in stream, select needed file, copy header + compressed file data to other file, and call unzip on that part (if you don't want to deal with the whole Zip decompression code or library).
This works for spanish operation system.
Script accepts two parameters:
script.bat listofurls.txt output.txt
@echo off
setlocal enabledelayedexpansion
set OUTPUT_FILE=%2
>nul copy nul %OUTPUT_FILE%
for /f %%i in (%1) do (
set SERVER_ADDRESS=No se pudo resolver el host
for /f "tokens=1,2,3,4,5" %%v in ('ping -a -n 1 %%i ^&^& echo SERVER_IS_UP')
do (
if %%v==Haciendo set SERVER_ADDRESS=%%z
if %%v==Respuesta set SERVER_ADDRESS=%%x
if %%v==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
)
echo %%i [!SERVER_ADDRESS::=!] is !SERVER_STATE! >>%OUTPUT_FILE%
echo %%i [!SERVER_ADDRESS::=!] is !SERVER_STATE!
)
I had the same problem, This is what I did: I have a SPA with multiple views in the same page (without ajax), so this is the code of the module:
var app = angular.module('otisApp', ['chieffancypants.loadingBar', 'ngRoute']);
app.config(['$routeProvider', function($routeProvider){
$routeProvider.when('/:page', {
templateUrl: function(page){return page.page + '.html';},
controller:'otisCtrl'
})
.otherwise({redirectTo:'/otis'});
}]);
I have only one controller for all views, but, the problem is the same as the question, the controller always refresh data, in order to avoid this behavior I did what people suggest above and I created a service for that purpose, then pass it to the controller as follows:
app.factory('otisService', function($http){
var service = {
answers:[],
...
}
return service;
});
app.controller('otisCtrl', ['$scope', '$window', 'otisService', '$routeParams',
function($scope, $window, otisService, $routeParams){
$scope.message = "Hello from page: " + $routeParams.page;
$scope.update = function(answer){
otisService.answers.push(answers);
};
...
}]);
Now I can call the update function from any of my views, pass values and update my model, I haven't no needed to use html5 apis for persistence data (this is in my case, maybe in other cases would be necessary to use html5 apis like localstorage and other stuff).
This can also be achieved with jsp:include. Chad Darby explains well here in this video https://www.youtube.com/watch?v=EWbYj0qoNHo
Got the same problem but didn't found a good solution yet for detecting it automatically . Now im using PsPad (www.pspad.com) for that ;) Works fine
As documentation says:
Raised when the part of a "multipart/form-data" request identified by its name cannot be found.
This may be because the request is not a multipart/form-data either because the part is not present in the request, or because the web application is not configured correctly for processing multipart requests -- e.g. no MultipartResolver.
grep -r -e string directory
-r
is for recursive; -e
is optional but its argument specifies the regex to search for. Interestingly, POSIX grep
is not required to support -r
(or -R
), but I'm practically certain that System V in practice they (almost) all do. Some versions of grep
did, sogrep
support -R
as well as (or conceivably instead of) -r
; AFAICT, it means the same thing.
The reason for methods in interfaces being by default public and abstract seems quite logical and obvious to me.
A method in an interface it is by default abstract to force the implementing class to provide an implementation and is public by default so the implementing class has access to do so.
Adding those modifiers in your code is redundant and useless and can only lead to the conclusion that you lack knowledge and/or understanding of Java fundamentals.
in your build.gradle add the following to the end of the android node
android {
....
....
sourceSets {
main.java.srcDirs += 'src/main/<YOUR DIRECTORY>'
}
}
Try using the data
option of the $.ajax
function. More info here.
$('#btnSaveComments').click(function () {
var comments = $('#txtComments').val();
var selectedId = $('#hdnSelectedId').val();
$.ajax({
url: '<%: Url.Action("SaveComments")%>',
data: { 'id' : selectedId, 'comments' : comments },
type: "post",
cache: false,
success: function (savingStatus) {
$("#hdnOrigComments").val($('#txtComments').val());
$('#lblCommentsNotification').text(savingStatus);
},
error: function (xhr, ajaxOptions, thrownError) {
$('#lblCommentsNotification').text("Error encountered while saving the comments.");
}
});
});
I tried this on the command.it is working for me.
if "$(OutDir)"=="bin\Debug\" goto Visual
:TFSBuild
goto exit
:Visual
xcopy /y "$(TargetPath)$(TargetName).dll" "$(ProjectDir)..\Demo"
xcopy /y "$(TargetDir)$(TargetName).pdb" "$(ProjectDir)..\Demo"
goto exit
:exit
For programming languages like Java, the alternate data structure used by most programmers to represent pair like data-structures are two array, and data is accessed via the same index
example: http://www-igm.univ-mlv.fr/~lecroq/string/node8.html#SECTION0080
This isn't ideal as the data should be bound together, but also turn out to be pretty cheap. Also, if your use case demands storing co-ordinates then its better to build your own data structure.
I've something like this in my library
public class Pair<First,Second>{.. }
You should be checking if the user has granted permission of external storage by using:
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Log.v(TAG,"Permission is granted");
//File write logic here
return true;
}
If not, you need to ask the user to grant your app a permission:
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
Of course these are for marshmallow devices only so you need to check if your app is running on Marshmallow:
if (Build.VERSION.SDK_INT >= 23) {
//do your check here
}
Be also sure that your activity implements OnRequestPermissionResult
The entire permission looks like this:
public boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG,"Permission is granted");
return true;
} else {
Log.v(TAG,"Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG,"Permission is granted");
return true;
}
}
Permission result callback:
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
//resume tasks needing this permission
}
}
Use six
:
from six.moves.urllib.parse import quote
six
will simplify compatibility problems between Python 2 and Python 3, such as different import paths.
sed --expression='s/\r\n/\n/g'
Since the question mentions sed, this is the most straight forward way to use sed to achieve this. What the expression says is replace all carriage-return and line-feed with just line-feed only. That is what you need when you go from Windows to Unix. I verified it works.
Try float
property. Here's an example: http://jsfiddle.net/mLmHR/
I am not very familiar with CMake and could not use Mondkin's solution directly.
Here is what I came up with in my CMakeLists.txt using the latest version of CLion (1.2.4) and MinGW on Windows (I guess you will just need to replace all: g++ mytest.cpp -o bin/mytest by make if you are not using the same setup):
cmake_minimum_required(VERSION 3.3)
project(mytest)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
add_custom_target(mytest ALL COMMAND mingw32-make WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
And the custom Makefile is like this (it is located at the root of my project and generates the executable in a bin directory):
all:
g++ mytest.cpp -o bin/mytest
I am able to build the executable and errors in the log window are clickable.
Hints in the IDE are quite limited through, which is a big limitation compared to pure CMake projects...
Found an article titled "MYSQL WITH NOLOCK"
https://web.archive.org/web/20100814144042/http://sqldba.org/articles/22-mysql-with-nolock.aspx
in MS SQL Server you would do the following:
SELECT * FROM TABLE_NAME WITH (nolock)
and the MYSQL equivalent is
SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;
SELECT * FROM TABLE_NAME ;
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ;
EDIT
Michael Mior suggested the following (from the comments)
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;
SELECT * FROM TABLE_NAME ;
COMMIT ;
Try to not use setInterval
.
You can resend request to server after successful response with timeout.
jQuery:
sendRequest(); //call function
function sendRequest(){
$.ajax({
url: "test.php",
success:
function(result){
$('#links').text(result); //insert text of test.php into your div
setTimeout(function(){
sendRequest(); //this will send request again and again;
}, 5000);
}
});
}
If you cancel and see that run
sp_who2 'active'
(Activity Monitor won't be available on old sql server 2000 FYI )
Spot the SPID you wish to kill e.g. 81
Kill 81
Run the sp_who2 'active'
again and you will probably notice it is sleeping ... rolling back
To get the STATUS run again the KILL
Kill 81
Then you will get a message like this
SPID 81: transaction rollback in progress. Estimated rollback completion: 63%. Estimated time remaining: 992 seconds.
I'm using Conda on Windows and this answer did not work for me. But I can suggest another solution:
rename enviroment folder (old_name
to new_name
)
open shell and activate env with custom folder:
conda.bat activate "C:\Users\USER_NAME\Miniconda3\envs\new_name"
now you can use this enviroment, but it's not on the enviroment list. Update\install\remove any package to fix it. For example, update numpy:
conda update numpy
after applying any action to package, the environment will show in env list. To check this, type:
conda env list
If its in a landscape then you will be needing more width and less height! That's just what all websites have.
Lets go with a basic first then the rest!
The basic CSS:
By CSS you can do this,
#body {
width: 100%;
height: 100%;
}
Here you are using a div with id
body, as:
<body>
<div id="body>
all the text would go here!
</div>
</body>
Then you can have a web page with 100%
height and width.
What if he tries to resize the window?
The issues pops up, what if he tries to resize the window? Then all the elements inside #body
would try to mess up the UI. For that you can write this:
#body {
height: 100%;
width: 100%;
}
And just add min-height
max-height
min-width
and max-width
.
This way, the page element would stay at the place they were at the page load.
Using JavaScript:
Using JavaScript, you can control the UI, use jQuery as:
$('#body').css('min-height', '100%');
And all other remaining CSS properties, and JS will take care of the User Interface when the user is trying to resize the window.
How to not add scroll to the web page:
If you are not trying to add a scroll, then you can use this JS
$('#body').css('min-height', screen.height); // or anyother like window.height
This way, the document will get a new height whenever the user would load the page.
Second option is better, because when users would have different screen resolutions they would want a CSS or Style sheet created for their own screen. Not for others!
Tip: So try using JS to find current Screen size and edit the page! :)
This method orderBy
does not change the input array,
you have to assign the result to your array :
var chars = this.state.characters;
chars = _.orderBy(chars, ['name'],['asc']); // Use Lodash to sort array by 'name'
this.setState({characters: chars})
It all depends on the type of classification problem you are dealing with. There are three main categories
In the first case, binary cross-entropy should be used and targets should be encoded as one-hot vectors.
In the second case, categorical cross-entropy should be used and targets should be encoded as one-hot vectors.
In the last case, binary cross-entropy should be used and targets should be encoded as one-hot vectors. Each output neuron (or unit) is considered as a separate random binary variable, and the loss for the entire vector of outputs is the product of the loss of single binary variables. Therefore it is the product of binary cross-entropy for each single output unit.
The binary cross-entropy is defined as
and categorical cross-entropy is defined as
where c
is the index running over the number of classes C
.
First of all, the provided long code:
<xsl:choose>
<xsl:when test="OU_NAME='OU_ADDR1'"> --comparing two elements coming from XML
<!--remove if adrees already contain operating unit name <xsl:value-of select="OU_NAME"/> <fo:block/>-->
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="OU_NAME"/>
<fo:block/>
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
</xsl:otherwise>
</xsl:choose>
is equivalent to this, much shorter code:
<xsl:if test="not(OU_NAME='OU_ADDR1)'">
<xsl:value-of select="OU_NAME"/>
</xsl:if>
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
Now, to your question:
how to compare two elements coming from xml as string
In Xpath 1.0 strings can be compared only for equality (or inequality), using the operator =
and the function not()
together with the operator =
.
$str1 = $str2
evaluates to true()
exactly when the string $str1
is equal to the string $str2
.
not($str1 = $str2)
evaluates to true()
exactly when the string $str1
is not equal to the string $str2
.
There is also the !=
operator. It generally should be avoided because it has anomalous behavior whenever one of its operands is a node-set.
Now, the rules for comparing two element nodes are similar:
$el1 = $el2
evaluates to true()
exactly when the string value of $el1
is equal to the string value of $el2
.
not($el1 = $el2)
evaluates to true()
exactly when the string value of $el1
is not equal to the string value of $el2
.
However, if one of the operands of =
is a node-set, then
$ns = $str
evaluates to true()
exactly when there is at least one node in the node-set $ns1
, whose string value is equal to the string $str
$ns1 = $ns2
evaluates to true()
exactly when there is at least one node in the node-set $ns1
, whose string value is equal to the string value of some node from $ns2
Therefore, the expression:
OU_NAME='OU_ADDR1'
evaluates to true()
only when there is at least one element child of the current node that is named OU_NAME
and whose string value is the string 'OU_ADDR1'.
This is obviously not what you want!
Most probably you want:
OU_NAME=OU_ADDR1
This expression evaluates to true
exactly there is at least one OU_NAME
child of the current node and one OU_ADDR1
child of the current node with the same string value.
Finally, in XPath 2.0, strings can be compared also using the value comparison operators lt
, le
, eq
, gt
, ge
and the inherited from XPath 1.0 general comparison operator =
.
Trying to evaluate a value comparison operator when one or both of its arguments is a sequence of more than one item results in error.
It's convenient to define a macro for get current timestamp
class Constant {
struct Time {
let now = { round(NSDate().timeIntervalSince1970) } // seconds
}
}
Then you can use let timestamp = Constant.Time.now()
A solution avoiding CASE WHEN
is to use COALESCE
.
SELECT
t1.Col2 AS t1Col2,
t2.Col2 AS t2Col2,
COALESCE(NULLIF(t1.Col2, t2.Col2),NULLIF(t2.Col2, t1.Col2)) as NULL_IF_SAME
FROM @t1 AS t1
JOIN @t2 AS t2 ON t1.ColID = t2.ColID
NULL_IF_SAME
column will give NULL
for all rows where t1.col2 = t2.col2
(including NULL
).
Though this is not more readable than CASE WHEN
expression, it is ANSI SQL.
Just for the sake of fun, if one wants to have boolean bit values of 0 and 1 (though it is not very readable, hence not recommended), one can use (which works for all datatypes):
1/ISNULL(LEN(COALESCE(NULLIF(t1.Col2, t2.Col2),NULLIF(t2.Col2, t1.Col2)))+2,1) as BOOL_BIT_SAME.
Now if you have one of the numeric data types and want bits, in the above LEN
function converts to string first which may be problematic,so instead this should work:
1/(CAST(ISNULL(ABS(COALESCE(NULLIF(t1.Col2, t2.Col2),NULLIF(t2.Col2, t1.Col2)))+1,0)as bit)+1) as FAST_BOOL_BIT_SAME_NUMERIC
Above will work for Integers without CAST
.
NOTE: also in SQLServer 2012, we have IIF
function.
The difference is in view-port wire-frame rendering and double-sided polygon rendering, which is very common in professional CAD/3D software but not in games.
The difference is almost 10x-13x faster in single-fixed rendering pipeline (now very obsolete but some CAD software using it) rendering double sided polygons and wireframes:
Thats how entry level Quadro beats high-end GeForce. At least in the single-fixed pipeline using legacy calls like glLightModel(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE). The trick is done with driver optimization (does not matter if its single-fixed pipeline Direct3D or OpenGL). And its true that on some GeForce cards some firmware/hardware hacking can unlock the features.
If double sided is implemented using shader code, the GeForce has to render the polygon twice giving the Quadro only 2x the speed difference (it's less in real-world). The wireframe rendering remains much much slower on GeForce even if implemented in a modern way.
Todays GeForce cards can render millions of polygons per second, drawing lines with faded polygons can result in 100x speed difference eliminating the Quadro benefit.
Quadro equivalent GTX cards have usually better clock speeds giving 2%-10% better performance in games.
So to sum up:
The Quadro rules the single-fixed legacy now obsolete rendering pipeline (which CAD uses), but by implementing modern rendering methods this can be significantly reduced (virtually no speed gain in Maya's Viewport 2.0, it uses GLSL effects - very similar to game engine).
Other reasons to get Quadro are double precision float computations for science, better warranty and display's support for professionals.
That's about it, price-vise the Quadros or FirePros are artificially overpriced.
To deploy your application to prod environment add
"build": "vue-cli-service build --mode prod"
in your scripts in package.json file.
Open your main.js and add
Vue.config.productionTip = false;
right after your imports. Then open your cli in the project folder and run this command
npm run build
This will make a dist folder in your project directory you may upload that dist folder in your host and your website will be live
I found an easier way to do it without the need of extra methods that arrange a queue.
JS
$.ajax({
type: 'POST',
url: 'ajax1.php',
data:{
id: 1,
cb:'method1'//declaration of callback method of ajax1.php
},
success: function(data){
//catching up values
var data = JSON.parse(data);
var cb=data[0].cb;//here whe catching up the callback 'method1'
eval(cb+"(JSON.stringify(data));");//here we calling method1 and pass all data
}
});
$.ajax({
type: 'POST',
url: 'ajax2.php',
data:{
id: 2,
cb:'method2'//declaration of callback method of ajax2.php
},
success: function(data){
//catching up values
var data = JSON.parse(data);
var cb=data[0].cb;//here whe catching up the callback 'method2'
eval(cb+"(JSON.stringify(data));");//here we calling method2 and pass all data
}
});
//the callback methods
function method1(data){
//here we have our data from ajax1.php
alert("method1 called with data="+data);
//doing stuff we would only do in method1
//..
}
function method2(data){
//here we have our data from ajax2.php
alert("method2 called with data="+data);
//doing stuff we would only do in method2
//..
}
PHP (ajax1.php)
<?php
//catch up callbackmethod
$cb=$_POST['cb'];//is 'method1'
$json[] = array(
"cb" => $cb,
"value" => "ajax1"
);
//encoding array in JSON format
echo json_encode($json);
?>
PHP (ajax2.php)
<?php
//catch up callbackmethod
$cb=$_POST['cb'];//is 'method2'
$json[] = array(
"cb" => $cb,
"value" => "ajax2"
);
//encoding array in JSON format
echo json_encode($json);
?>
You may use the Range.Find method:
http://msdn.microsoft.com/en-us/library/office/ff839746.aspx
This will get you the first cell which contains the search string. By repeating this with setting the "After" argument to the next cell you will get all other occurrences until you are back at the first occurrence.
This will likely be much faster.
Another way using template reference variable and ViewChild, as proposed by Frelseren:
import { ViewChild } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<div>
<input type="file" #fileInput/>
</div>
`
})
export class AppComponent {
@ViewChild("fileInput") fileInputVariable: any;
randomMethod() {
const files = this.fileInputVariable.nativeElement.files;
console.log(files);
}
}
Result for Windows Command Prompt
In my case, 8080 is the port I want to kill
And 18264 is the PID listening on port 8080
So the task you have to kill is the PID for that particular port
C:\Users\Niroshan>netstat -ano|findstr "PID :8080"
Proto Local Address Foreign Address State PID
TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING 18264
taskkill /PID 18264 /f
you can do this:
<div class="picture1"> </div>
and put this into your css file:
div.picture1 {
width:100px; /*width of your image*/
height:100px; /*height of your image*/
background-image:url('yourimage.file');
margin:0; /* If you want no margin */
padding:0; /*if your want to padding */
}
otherwise, just use them as plain
Yes there is retainAll
check out this
Set<Type> intersection = new HashSet<Type>(s1);
intersection.retainAll(s2);
Images can be placed in place of radio buttons by using label and span elements.
<div class="customize-radio">
<label>Favourite Smiley</label>
<br>
<label for="hahaha">
<input type="radio" name="smiley" id="hahaha">
<span class="haha-img"></span>
HAHAHA
</label>
<label for="kiss">
<input type="radio" name="smiley" id="kiss">
<span class="kiss-img"></span>
Kiss
</label>
<label for="tongueOut">
<input type="radio" name="smiley" id="tongueOut">
<span class="tongueout-img"></span>
TongueOut
</label>
</div>
Radio button should be hidden,
.customize-radio label > input[type = 'radio'] {
visibility: hidden;
position: absolute;
}
Image can be given in the span tag,
.customize-radio label > input[type = 'radio'] ~ span{
cursor: pointer;
width: 27px;
height: 24px;
display: inline-block;
background-size: 27px 24px;
background-repeat: no-repeat;
}
.haha-img {
background-image: url('hahabefore.png');
}
.kiss-img{
background-image: url('kissbefore.png');
}
.tongueout-img{
background-image: url('tongueoutbefore.png');
}
To change the image on click of radio button, add checked state to the input tag,
.customize-radio label > input[type = 'radio']:checked ~ span.haha-img{
background-image: url('haha.png');
}
.customize-radio label > input[type = 'radio']:checked ~ span.kiss-img{
background-image: url('kiss.png');
}
.customize-radio label > input[type = 'radio']:checked ~ span.tongueout-img{
background-image: url('tongueout.png');
}
If you have any queries, Refer to the following link, As I have taken solution from the below blog, http://frontendsupport.blogspot.com/2018/06/cool-radio-buttons-with-images.html
Here is example:
You have a.bat:
@echo off
if exist b.bat goto RUNB
goto END
:RUNB
b.bat
:END
and b.bat called conditionally from a.bat:
@echo off
echo "This is b.bat"
You can also use the excellent URI.js library by Rodney Rehm. Here's how:-
var qs = URI('www.mysite.com/default.aspx?dest=aboutus.aspx').query(true); // == { dest : 'aboutus.aspx' }
alert(qs.dest); // == aboutus.aspx
And to parse the query string of current page:-
var $_GET = URI(document.URL).query(true); // ala PHP
alert($_GET['dest']); // == aboutus.aspx
Nobody did point the subtle difference in the semantics of the functions name()
and local-name()
.
name(someNode)
returns the full
name of the node, and that includes
the prefix and colon in case the node
is an element or an attribute.local-name(someNode)
returns only
the local name of the node, and that
doesn't include the prefix and colon
in case the node is an element or an
attribute.Therefore, in situations where a name may belong to two different namespaces, one must use the name()
function in order for these names to be still distinguished.
And, BTW, it is possible to specify both functions without any argument:
name()
is an abbreviation for name(.)
local-name()
is an abbreviation for local-name(.)
Finally, do remember that not only elements and attributes have names, these two functions can also be used on PIs and on these they are identical).
Converting SecretKeySpec to String and vice-versa:
you can use getEncoded()
method in SecretKeySpec
which will give byteArray
, from that you can use encodeToString()
to get string
value of SecretKeySpec
in Base64
object.
While converting SecretKeySpec
to String
: use decode()
in Base64
will give byteArray
, from that you can create instance for SecretKeySpec
with the params as the byteArray
to reproduce your SecretKeySpec
.
String mAesKey_string;
SecretKeySpec mAesKey= new SecretKeySpec(secretKey.getEncoded(), "AES");
//SecretKeySpec to String
byte[] byteaes=mAesKey.getEncoded();
mAesKey_string=Base64.encodeToString(byteaes,Base64.NO_WRAP);
//String to SecretKeySpec
byte[] aesByte = Base64.decode(mAesKey_string, Base64.NO_WRAP);
mAesKey= new SecretKeySpec(aesByte, "AES");
the correct syntax is -
with t1
as
(select * from tab1
where conditions...
),
t2
as
(select * from tab2
where conditions...
(you can access columns of t1 here as well)
)
select * from t1, t2
where t1.col1=t2.col2;
You cannot declare global variables in SQLServer.
If you're using Management Studio you can use SQLCMD mode like @Lanorkin pointed out.
Otherwise you can use CONTEXT_INFO
to store a single variable that is visible during a session and connection, but it'll disappear after that.
Only truly global would be to create a global temp table (named ##yourTableName), and store your variables there, but that will also disappear when all connection are closed.
Here's a quick way to preview a large table without having it run too wide:
Display function:
# display large dataframes in an html iframe
def ldf_display(df, lines=500):
txt = ("<iframe " +
"srcdoc='" + df.head(lines).to_html() + "' " +
"width=1000 height=500>" +
"</iframe>")
return IPython.display.HTML(txt)
Now just run this in any cell:
ldf_display(large_dataframe)
This will convert the dataframe to html then display it in an iframe. The advantage is that you can control the output size and have easily accessible scroll bars.
Worked for my purposes, maybe it will help someone else.
Shouldn't the @Html.EditorFor()
make use of the Attributes you put in your model?
[DefaultValue(false)]
public bool TestAccount { get; set; }
If code elegance ranks higher than the performance hit of regex, then
'1234567'.match(/^(.*)(.{3})/).slice(1).join(',')
=> "1234,567"
There's a lot of room to further modify the regex to be more precise.
If join()
doesn't work then you might need to use map
with a closure, at which point the other answers here may be less bytes and line noise.
A short version would be:
echo sh(script: 'ls -al', returnStdout: true).result
The standard best practice for REST APIs is to have a hyphen, not camelcase or underscores.
This comes from Mark Masse's "REST API Design Rulebook" from Oreilly.
In addition, note that Stack Overflow itself uses hyphens in the URL: .../hyphen-underscore-or-camelcase-as-word-delimiter-in-uris
As does WordPress: http://inventwithpython.com/blog/2012/03/18/how-much-math-do-i-need-to-know-to-program-not-that-much-actually
static inner class: can declare static & non static members but can only access static members of its parents class.
non static inner class: can declare only non static members but can access static and non static member of its parent class.
You can also match case insensitive regexs and make it more readable by using the Pattern.CASE_INSENSITIVE constant like:
Pattern mypattern = Pattern.compile(MYREGEX, Pattern.CASE_INSENSITIVE);
Matcher mymatcher= mypattern.matcher(mystring);
For Java 8 you can use the following command line to get the heap space utilization in kB:
jstat -gc <PID> | tail -n 1 | awk '{split($0,a," "); sum=a[3]+a[4]+a[6]+a[8]; print sum}'
The command basically sums up:
You may also want to include the metaspace and the compressed class space utilization. In this case you have to add a[10] and a[12] to the awk sum.
I recently had to migrate from MySQL to JavaDB for a project that our team is working on. I found a Java library written by Apache called DdlUtils that made this pretty easy. It provides an API that lets you do the following:
The tools that we ended up with weren't completely automated, but they worked pretty well. Even if your application is not in Java, it shouldn't be too difficult to whip up a few small tools to do a one-time migration. I think I was able to pull of our migration with less than 150 lines of code.
There's a messy workaround at http://www.ozgrid.com/Excel/autocomplete-validation.htm that basically works like this:
Tools - Options > Edit
;For 1D array, numpy.correlate
is faster than scipy.signal.correlate
, under different sizes, I see a consistent 5x peformance gain using numpy.correlate
. When two arrays are of similar size (the bright line connecting the diagonal), the performance difference is even more outstanding (50x +).
# a simple benchmark
res = []
for x in range(1, 1000):
list_x = []
for y in range(1, 1000):
# generate different sizes of series to compare
l1 = np.random.choice(range(1, 100), size=x)
l2 = np.random.choice(range(1, 100), size=y)
time_start = datetime.now()
np.correlate(a=l1, v=l2)
t_np = datetime.now() - time_start
time_start = datetime.now()
scipy.signal.correlate(in1=l1, in2=l2)
t_scipy = datetime.now() - time_start
list_x.append(t_scipy / t_np)
res.append(list_x)
plt.imshow(np.matrix(res))
As default, scipy.signal.correlate calculates a few extra numbers by padding and that might explained the performance difference.
>> l1 = [1,2,3,2,1,2,3]
>> l2 = [1,2,3]
>> print(numpy.correlate(a=l1, v=l2))
>> print(scipy.signal.correlate(in1=l1, in2=l2))
[14 14 10 10 14]
[ 3 8 14 14 10 10 14 8 3] # the first 3 is [0,0,1]dot[1,2,3]
Using management studio the procedure can be done as follows
You'll need to specify the WITH REPLACE option to overwrite the existing adventure_second database with a backup taken from a different database.
Click option menu and tick Overwrite the existing database(With replace)
This pattern does a thread-safe lazy-initialization of the instance without explicit synchronization!
public class MySingleton {
private static class Loader {
static final MySingleton INSTANCE = new MySingleton();
}
private MySingleton () {}
public static MySingleton getInstance() {
return Loader.INSTANCE;
}
}
It works because it uses the class loader to do all the synchronization for you for free: The class MySingleton.Loader
is first accessed inside the getInstance()
method, so the Loader
class loads when getInstance()
is called for the first time. Further, the class loader guarantees that all static initialization is complete before you get access to the class - that's what gives you thread-safety.
It's like magic.
It's actually very similar to the enum pattern of Jhurtado, but I find the enum pattern an abuse of the enum concept (although it does work)
Use off()
method after click event is triggered to disable element for the further click.
$('#clickElement').off('click');
If you are using 5.6 php,
sudo apt-get install php5.6-curl
You have to download and add the SQLite JDBC driver to your classpath.
You can download from here https://bitbucket.org/xerial/sqlite-jdbc/downloads
If you use Gradle, you will only have to add the SQLite dependency:
dependencies {
compile 'org.xerial:sqlite-jdbc:3.8.11.2'
}
Next thing you have to do is to initialize the driver:
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException eString) {
System.err.println("Could not init JDBC driver - driver not found");
}
The easilest way is
import java.util.*;
public class Stdio4 {
public static void main(String[] args) {
int a=0;
int arr[] = new int[3];
Scanner scan = new Scanner(System.in);
for(int i=0;i<3;i++)
{
a = scan.nextInt(); //Takes input from separate lines
arr[i]=a;
}
for(int i=0;i<3;i++)
{
System.out.println(arr[i]); //outputs in separate lines also
}
}
}
You can do either…
$qb->where('e.fecha BETWEEN :monday AND :sunday')
->setParameter('monday', $monday->format('Y-m-d'))
->setParameter('sunday', $sunday->format('Y-m-d'));
or…
$qb->where('e.fecha > :monday')
->andWhere('e.fecha < :sunday')
->setParameter('monday', $monday->format('Y-m-d'))
->setParameter('sunday', $sunday->format('Y-m-d'));
You can also use the hmisc package that will give you the following percentiles:
0.05, 0.1, 0.25, 0.5, 0.75, 0.9 , 0.95
Just use the describe(table_ages)
I think this is very nice and short
<img src="imagenotfound.gif" alt="Image not found" onerror="this.src='imagefound.gif';" />
But, be careful. The user's browser will be stuck in an endless loop if the onerror image itself generates an error.
EDIT
To avoid endless loop, remove the onerror
from it at once.
<img src="imagenotfound.gif" alt="Image not found" onerror="this.onerror=null;this.src='imagefound.gif';" />
By calling this.onerror=null
it will remove the onerror then try to get the alternate image.
NEW I would like to add a jQuery way, if this can help anyone.
<script>
$(document).ready(function()
{
$(".backup_picture").on("error", function(){
$(this).attr('src', './images/nopicture.png');
});
});
</script>
<img class='backup_picture' src='./images/nonexistent_image_file.png' />
You simply need to add class='backup_picture' to any img tag that you want a backup picture to load if it tries to show a bad image.
I know this is an old question, but I wanted to add something to the answers already here in hopes of helping someone else.
You can script the ftp
command with the -s:filename
option. The syntax is just a list of commands to pass to the ftp
shell, each terminated by a newline. This page has a nice reference to the commands that can be performed with ftp
.
Using the normal ftp
doesn't work very well when you need to have an entire directory tree copied to or from a ftp site. So you could use something like these to handle those situations.
These scripts works with the Windows ftp
command and allows for uploading and downloading of entire directories from a single command. This makes it pretty self reliant when using on different systems.
Basically what they do is map out the directory structure to be up/downloaded, dump corresponding ftp
commands to a file, then execute those commands when the mapping has finished.
ftpupload.bat
@echo off
SET FTPADDRESS=%1
SET FTPUSERNAME=%2
SET FTPPASSWORD=%3
SET LOCALDIR=%~f4
SET REMOTEDIR=%5
if "%FTPADDRESS%" == "" goto FTP_UPLOAD_USAGE
if "%FTPUSERNAME%" == "" goto FTP_UPLOAD_USAGE
if "%FTPPASSWORD%" == "" goto FTP_UPLOAD_USAGE
if "%LOCALDIR%" == "" goto FTP_UPLOAD_USAGE
if "%REMOTEDIR%" == "" goto FTP_UPLOAD_USAGE
:TEMP_NAME
set TMPFILE=%TMP%\%RANDOM%_ftpupload.tmp
if exist "%TMPFILE%" goto TEMP_NAME
SET INITIALDIR=%CD%
echo user %FTPUSERNAME% %FTPPASSWORD% > %TMPFILE%
echo bin >> %TMPFILE%
echo lcd %LOCALDIR% >> %TMPFILE%
cd %LOCALDIR%
setlocal EnableDelayedExpansion
echo mkdir !REMOTEDIR! >> !TMPFILE!
echo cd %REMOTEDIR% >> !TMPFILE!
echo mput * >> !TMPFILE!
for /d /r %%d in (*) do (
set CURRENT_DIRECTORY=%%d
set RELATIVE_DIRECTORY=!CURRENT_DIRECTORY:%LOCALDIR%=!
echo mkdir "!REMOTEDIR!/!RELATIVE_DIRECTORY:~1!" >> !TMPFILE!
echo cd "!REMOTEDIR!/!RELATIVE_DIRECTORY:~1!" >> !TMPFILE!
echo mput "!RELATIVE_DIRECTORY:~1!\*" >> !TMPFILE!
)
echo quit >> !TMPFILE!
endlocal EnableDelayedExpansion
ftp -n -i "-s:%TMPFILE%" %FTPADDRESS%
del %TMPFILE%
cd %INITIALDIR%
goto FTP_UPLOAD_EXIT
:FTP_UPLOAD_USAGE
echo Usage: ftpupload [address] [username] [password] [local directory] [remote directory]
echo.
:FTP_UPLOAD_EXIT
set INITIALDIR=
set FTPADDRESS=
set FTPUSERNAME=
set FTPPASSWORD=
set LOCALDIR=
set REMOTEDIR=
set TMPFILE=
set CURRENT_DIRECTORY=
set RELATIVE_DIRECTORY=
@echo on
ftpget.bat
@echo off
SET FTPADDRESS=%1
SET FTPUSERNAME=%2
SET FTPPASSWORD=%3
SET LOCALDIR=%~f4
SET REMOTEDIR=%5
SET REMOTEFILE=%6
if "%FTPADDRESS%" == "" goto FTP_UPLOAD_USAGE
if "%FTPUSERNAME%" == "" goto FTP_UPLOAD_USAGE
if "%FTPPASSWORD%" == "" goto FTP_UPLOAD_USAGE
if "%LOCALDIR%" == "" goto FTP_UPLOAD_USAGE
if not defined REMOTEDIR goto FTP_UPLOAD_USAGE
if not defined REMOTEFILE goto FTP_UPLOAD_USAGE
:TEMP_NAME
set TMPFILE=%TMP%\%RANDOM%_ftpupload.tmp
if exist "%TMPFILE%" goto TEMP_NAME
echo user %FTPUSERNAME% %FTPPASSWORD% > %TMPFILE%
echo bin >> %TMPFILE%
echo lcd %LOCALDIR% >> %TMPFILE%
echo cd "%REMOTEDIR%" >> %TMPFILE%
echo mget "%REMOTEFILE%" >> %TMPFILE%
echo quit >> %TMPFILE%
ftp -n -i "-s:%TMPFILE%" %FTPADDRESS%
del %TMPFILE%
goto FTP_UPLOAD_EXIT
:FTP_UPLOAD_USAGE
echo Usage: ftpget [address] [username] [password] [local directory] [remote directory] [remote file pattern]
echo.
:FTP_UPLOAD_EXIT
set FTPADDRESS=
set FTPUSERNAME=
set FTPPASSWORD=
set LOCALDIR=
set REMOTEFILE=
set REMOTEDIR=
set TMPFILE=
set CURRENT_DIRECTORY=
set RELATIVE_DIRECTORY=
@echo on
To get the details about the error I had to add ASPNETCORE_ENVIRONMENT
environment variable for the corresponding Application Pool system.applicationHost/applicationPools
.
Note: the web application in my case was ASP.NET Core 2
web application hosted on IIS 10
. It can be done via Configuration Editor
in IIS Manager
(see Editing Collections with Configuration Editor to figure out where to find this editor in IIS Manager
).
To answer your question as I understand it: Why use C#? (You say you're already sold on F#.)
First off. It's not just "functional versus OO". It's "Functional+OO versus OO". C#'s functional features are pretty rudimentary. F#'s are not. Meanwhile, F# does almost all of C#'s OO features. For the most part, F# ends up as a superset of C#'s functionality.
However, there are a few cases where F# might not be the best choice:
Interop. There are plenty of libraries that just aren't going to be too comfortable from F#. Maybe they exploit certain C# OO things that F# doesn't do the same, or perhaps they rely on internals of the C# compiler. For example, Expression. While you can easily turn an F# quotation into an Expression, the result is not always exactly what C# would create. Certain libraries have a problem with this.
Yes, interop is a pretty big net and can result in a bit of friction with some libraries.
I consider interop to also include if you have a large existing codebase. It might not make sense to just start writing parts in F#.
Design tools. F# doesn't have any. Does not mean it couldn't have any, but just right now you can't whip up a WinForms app with F# codebehind. Even where it is supported, like in ASPX pages, you don't currently get IntelliSense. So, you need to carefully consider where your boundaries will be for generated code. On a really tiny project that almost exclusively uses the various designers, it might not be worth it to use F# for the "glue" or logic. On larger projects, this might become less of an issue.
This isn't an intrinsic problem. Unlike the Rex M's answer, I don't see anything intrinsic about C# or F# that make them better to do a UI with lots of mutable fields. Maybe he was referring to the extra overhead of having to write "mutable" and using <- instead of =.
Also depends on the library/designer used. We love using ASP.NET MVC with F# for all the controllers, then a C# web project to get the ASPX designers. We mix the actual ASPX "code inline" between C# and F#, depending on what we need on that page. (IntelliSense versus F# types.)
Other tools. They might just be expecting C# only and not know how to deal with F# projects or compiled code. Also, F#'s libraries don't ship as part of .NET, so you have a bit extra to ship around.
But the number one issue? People. If none of your developers want to learn F#, or worse, have severe difficulty comprehending certain aspects, then you're probably toast. (Although, I'd argue you're toast anyways in that case.) Oh, and if management says no, that might be an issue.
I wrote about this a while ago: Why NOT F#?
Since wdiff
accepts args specifying the string at the beginning and end of both insertions and deletions, you can use ANSI color sequences as those strings:
wdiff -n -w $'\033[30;41m' -x $'\033[0m' -y $'\033[30;42m' -z $'\033[0m' file1 file2
For example, this is the output of comparing two CSV files:
Example from https://www.gnu.org/software/wdiff/manual/html_node/wdiff-Examples.html
In my case the program (elinks) returned lines that looked empty, but in fact had special terminal characters, color control codes and backspace, so grep
options presented in other answers did not work for me. So I wrote this small script in Node.js. I called the file tight
, but that's just a random name.
#!/usr/bin/env node
function visible(a) {
var R = ''
for (var i = 0; i < a.length; i++) {
if (a[i] == '\b') { R -= 1; continue; }
if (a[i] == '\u001b') {
while (a[i] != 'm' && i < a.length) i++
if (a[i] == undefined) break
}
else R += a[i]
}
return R
}
function empty(a) {
a = visible(a)
for (var i = 0; i < a.length; i++) {
if (a[i] != ' ') return false
}
return true
}
var readline = require('readline')
var rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false })
rl.on('line', function(line) {
if (!empty(line)) console.log(line)
})
An INNER JOIN
can return data from the columns from both tables, and can duplicate values of records on either side have more than one match. A LEFT SEMI JOIN
can only return columns from the left-hand table, and yields one of each record from the left-hand table where there is one or more matches in the right-hand table (regardless of the number of matches). It's equivalent to (in standard SQL):
SELECT name
FROM table_1 a
WHERE EXISTS(
SELECT * FROM table_2 b WHERE (a.name=b.name))
If there are multiple matching rows in the right-hand column, an INNER JOIN
will return one row for each match on the right table, while a LEFT SEMI JOIN
only returns the rows from the left table, regardless of the number of matching rows on the right side. That's why you're seeing a different number of rows in your result.
I am trying to get the names within table_1 that only appear in table_2.
Then a LEFT SEMI JOIN
is the appropriate query to use.
You can use this:
DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss");
You can't make window.open
modal and I strongly recommend you not to go that way.
Instead you can use something like jQuery UI's dialog widget.
UPDATE:
You can use load()
method:
$("#dialog").load("resource.php").dialog({options});
This way it would be faster but the markup will merge into your main document so any submit will be applied on the main window.
And you can use an IFRAME:
$("#dialog").append($("<iframe></iframe>").attr("src", "resource.php")).dialog({options});
This is slower, but will submit independently.
There's no difference, ==
is a synonym for =
(for the C/C++ people, I assume). See here, for example.
You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.
The proper way to initialize a multidimensional array in C or C++ is
int arr[2][5] = {{1,8,12,20,25}, {5,9,13,24,26}};
You can use this same trick to initialize even higher-dimensional arrays if you want.
Also, be careful in your initial code - you were trying to use 1-indexed offsets into the array to initialize it. This didn't compile, but if it did it would cause problems because C arrays are 0-indexed!
mongodb://localhost:27017/yourDatabase
mongodb://yourComputerName:27017/yourDatabase
mongodb://Gabriel-Laptop:27017/shop
To find your computer/laptop name write in the search bar View your PC name
and the name near Device name
is the name you are looking for.
Note: I read somewhere that using localhost
keyword in Windows OS for MongoDB is not recommended (most probably here).
/**
* Does something interesting
*
* @param Place $where Where something interesting takes place
* @param integer $repeat How many times something interesting should happen
*
* @throws Some_Exception_Class If something interesting cannot happen
* @author Monkey Coder <[email protected]>
* @return Status
*/
/**
* Short description for class
*
* Long description for class (if any)...
*
* @copyright 2006 Zend Technologies
* @license http://www.zend.com/license/3_0.txt PHP License 3.0
* @version Release: @package_version@
* @link http://dev.zend.com/package/PackageName
* @since Class available since Release 1.2.0
*/
<?php
/**
* Short description for file
*
* Long description for file (if any)...
*
* PHP version 5.6
*
* LICENSE: This source file is subject to version 3.01 of the PHP license
* that is available through the world-wide-web at the following URI:
* http://www.php.net/license/3_01.txt. If you did not receive a copy of
* the PHP License and are unable to obtain it through the web, please
* send a note to [email protected] so we can mail you a copy immediately.
*
* @category CategoryName
* @package PackageName
* @author Original Author <[email protected]>
* @author Another Author <[email protected]>
* @copyright 1997-2005 The PHP Group
* @license http://www.php.net/license/3_01.txt PHP License 3.01
* @version SVN: $Id$
* @link http://pear.php.net/package/PackageName
* @see NetOther, Net_Sample::Net_Sample()
* @since File available since Release 1.2.0
* @deprecated File deprecated in Release 2.0.0
*/
/**
* This is a "Docblock Comment," also known as a "docblock." The class'
* docblock, below, contains a complete description of how to write these.
*/
require_once 'PEAR.php';
// {{{ constants
/**
* Methods return this if they succeed
*/
define('NET_SAMPLE_OK', 1);
// }}}
// {{{ GLOBALS
/**
* The number of objects created
* @global int $GLOBALS['_NET_SAMPLE_Count']
*/
$GLOBALS['_NET_SAMPLE_Count'] = 0;
// }}}
// {{{ Net_Sample
/**
* An example of how to write code to PEAR's standards
*
* Docblock comments start with "/**" at the top. Notice how the "/"
* lines up with the normal indenting and the asterisks on subsequent rows
* are in line with the first asterisk. The last line of comment text
* should be immediately followed on the next line by the closing asterisk
* and slash and then the item you are commenting on should be on the next
* line below that. Don't add extra lines. Please put a blank line
* between paragraphs as well as between the end of the description and
* the start of the @tags. Wrap comments before 80 columns in order to
* ease readability for a wide variety of users.
*
* Docblocks can only be used for programming constructs which allow them
* (classes, properties, methods, defines, includes, globals). See the
* phpDocumentor documentation for more information.
* http://phpdoc.org/tutorial_phpDocumentor.howto.pkg.html
*
* The Javadoc Style Guide is an excellent resource for figuring out
* how to say what needs to be said in docblock comments. Much of what is
* written here is a summary of what is found there, though there are some
* cases where what's said here overrides what is said there.
* http://java.sun.com/j2se/javadoc/writingdoccomments/index.html#styleguide
*
* The first line of any docblock is the summary. Make them one short
* sentence, without a period at the end. Summaries for classes, properties
* and constants should omit the subject and simply state the object,
* because they are describing things rather than actions or behaviors.
*
* Below are the tags commonly used for classes. @category through @version
* are required. The remainder should only be used when necessary.
* Please use them in the order they appear here. phpDocumentor has
* several other tags available, feel free to use them.
*
* @category CategoryName
* @package PackageName
* @author Original Author <[email protected]>
* @author Another Author <[email protected]>
* @copyright 1997-2005 The PHP Group
* @license http://www.php.net/license/3_01.txt PHP License 3.01
* @version Release: @package_version@
* @link http://pear.php.net/package/PackageName
* @see NetOther, Net_Sample::Net_Sample()
* @since Class available since Release 1.2.0
* @deprecated Class deprecated in Release 2.0.0
*/
class Net_Sample
{
// {{{ properties
/**
* The status of foo's universe
* Potential values are 'good', 'fair', 'poor' and 'unknown'.
* @var string $foo
*/
public $foo = 'unknown';
/**
* The status of life
* Note that names of private properties or methods must be
* preceeded by an underscore.
* @var bool $_good
*/
private $_good = true;
// }}}
// {{{ setFoo()
/**
* Registers the status of foo's universe
*
* Summaries for methods should use 3rd person declarative rather
* than 2nd person imperative, beginning with a verb phrase.
*
* Summaries should add description beyond the method's name. The
* best method names are "self-documenting", meaning they tell you
* basically what the method does. If the summary merely repeats
* the method name in sentence form, it is not providing more
* information.
*
* Summary Examples:
* + Sets the label (preferred)
* + Set the label (avoid)
* + This method sets the label (avoid)
*
* Below are the tags commonly used for methods. A @param tag is
* required for each parameter the method has. The @return
* and @access tags are mandatory. The @throws tag is required if
* the method uses exceptions. @static is required if the method can
* be called statically. The remainder should only be used when
* necessary. Please use them in the order they appear here.
* phpDocumentor has several other tags available, feel free to use
* them.
*
* The @param tag contains the data type, then the parameter's
* name, followed by a description. By convention, the first noun in
* the description is the data type of the parameter. Articles like
* "a", "an", and "the" can precede the noun. The descriptions
* should start with a phrase. If further description is necessary,
* follow with sentences. Having two spaces between the name and the
* description aids readability.
*
* When writing a phrase, do not capitalize and do not end with a
* period:
* + the string to be tested
*
* When writing a phrase followed by a sentence, do not capitalize the
* phrase, but end it with a period to distinguish it from the start
* of the next sentence:
* + the string to be tested. Must use UTF-8 encoding.
*
* Return tags should contain the data type then a description of
* the data returned. The data type can be any of PHP's data types
* (int, float, bool, string, array, object, resource, mixed)
* and should contain the type primarily returned. For example, if
* a method returns an object when things work correctly but false
* when an error happens, say 'object' rather than 'mixed.' Use
* 'void' if nothing is returned.
*
* Here's an example of how to format examples:
* <code>
* require_once 'Net/Sample.php';
*
* $s = new Net_Sample();
* if (PEAR::isError($s)) {
* echo $s->getMessage() . "\n";
* }
* </code>
*
* Here is an example for non-php example or sample:
* <samp>
* pear install net_sample
* </samp>
*
* @param string $arg1 the string to quote
* @param int $arg2 an integer of how many problems happened.
* Indent to the description's starting point
* for long ones.
*
* @return int the integer of the set mode used. FALSE if foo
* foo could not be set.
* @throws exceptionclass [description]
*
* @access public
* @static
* @see Net_Sample::$foo, Net_Other::someMethod()
* @since Method available since Release 1.2.0
* @deprecated Method deprecated in Release 2.0.0
*/
function setFoo($arg1, $arg2 = 0)
{
/*
* This is a "Block Comment." The format is the same as
* Docblock Comments except there is only one asterisk at the
* top. phpDocumentor doesn't parse these.
*/
if ($arg1 == 'good' || $arg1 == 'fair') {
$this->foo = $arg1;
return 1;
} elseif ($arg1 == 'poor' && $arg2 > 1) {
$this->foo = 'poor';
return 2;
} else {
return false;
}
}
// }}}
}
// }}}
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* c-hanging-comment-ender-p: nil
* End:
*/
?>
Source: PEAR Docblock Comment standards
Update from 2014, from Bootstrap docs:
Grids and full-width layouts Folks looking to create fully fluid layouts (meaning your site stretches the entire width of the viewport) must wrap their grid content in a containing element with padding: 0 15px; to offset the margin: 0 -15px; used on .rows.
If you have a low # of commits and you don't care if these are combined into one mega-commit, this works well and isn't as scary as doing git rebase
:
unstage the files (replace 1 with # of commits)
git reset --soft HEAD~1
create a new branch
git checkout -b NewBranchName
add the changes
git add -A
make a commit
git commit -m "Whatever"
select CONVERT(NVARCHAR, SYSDATETIME(), 106) AS [DD-MON-YYYY]
or else
select REPLACE(CONVERT(NVARCHAR,GETDATE(), 106), ' ', '-')
both works fine
I don't like the passwords that Membership.GeneratePassword() creates, as they're too ugly and have too many special characters.
This code generates a 10 digit not-too-ugly password.
string password = Guid.NewGuid().ToString("N").ToLower()
.Replace("1", "").Replace("o", "").Replace("0","")
.Substring(0,10);
Sure, I could use a Regex to do all the replaces but this is more readable and maintainable IMO.
I'm using rather specified charset (ISO-8859-2) because not every mail system (for example: http://10minutemail.com) can read UTF-8 mails. If you need this:
function utf8_to_latin2($str)
{
return iconv ( 'utf-8', 'ISO-8859-2' , $str );
}
function my_mail($to,$s,$text,$form, $reply)
{
mail($to,utf8_to_latin2($s),utf8_to_latin2($text),
"From: $form\r\n".
"Reply-To: $reply\r\n".
"X-Mailer: PHP/" . phpversion());
}
I have made another mailer function, because apple device could not read well the previous version.
function utf8mail($to,$s,$body,$from_name="x",$from_a = "[email protected]", $reply="[email protected]")
{
$s= "=?utf-8?b?".base64_encode($s)."?=";
$headers = "MIME-Version: 1.0\r\n";
$headers.= "From: =?utf-8?b?".base64_encode($from_name)."?= <".$from_a.">\r\n";
$headers.= "Content-Type: text/plain;charset=utf-8\r\n";
$headers.= "Reply-To: $reply\r\n";
$headers.= "X-Mailer: PHP/" . phpversion();
mail($to, $s, $body, $headers);
}
I would use something like this:
String.format("%tF %<tT.%<tL", dateTime);
Variable dateTime
could be any date and/or time value, see JavaDoc for Formatter
.
MySQL uses CONCAT() to concatenate strings
SELECT * FROM tableOne
LEFT JOIN tableTwo
ON tableTwo.query = CONCAT('category_id=', tableOne.category_id)
I actually used the answer from How do I run a node.js app as a background service? combined with what dwrz said above. In my case, I was creating a Discord bot that needed to be able to run when I was not around.
With this service in place, I initially got the same error that the initial poster did, which brought me here. I was missing the #!/usr/bin/env node
at the top of my executed node.js script.
Since then, no problems, although I intend to see what else can be extended to the service itself.
JPA doesn't provide any specification on mapping annotations to select fetch strategy. In general, related entities can be fetched in any one of the ways given below
So SELECT
and JOIN
are two extremes and SUBSELECT
falls in between. One can choose suitable strategy based on her/his domain model.
By default SELECT
is used by both JPA/EclipseLink and Hibernate. This can be overridden by using:
@Fetch(FetchMode.JOIN)
@Fetch(FetchMode.SUBSELECT)
in Hibernate. It also allows to set SELECT
mode explicitly using @Fetch(FetchMode.SELECT)
which can be tuned by using batch size e.g. @BatchSize(size=10)
.
Corresponding annotations in EclipseLink are:
@JoinFetch
@BatchFetch
The physical database size doesn't matter. The number of records don't matter.
In my experience the biggest problem that you are going to run in to is not size, but the number of queries you can handle at a time. Most likely you are going to have to move to a master/slave configuration so that the read queries can run against the slaves and the write queries run against the master. However if you are not ready for this yet, you can always tweak your indexes for the queries you are running to speed up the response times. Also there is a lot of tweaking you can do to the network stack and kernel in Linux that will help.
I have had mine get up to 10GB, with only a moderate number of connections and it handled the requests just fine.
I would focus first on your indexes, then have a server admin look at your OS, and if all that doesn't help it might be time to implement a master/slave configuration.
According to the release-notes, Java 11 removed the Java EE modules:
java.xml.bind (JAXB) - REMOVED
See JEP 320 for more info.
You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0</version>
</dependency>
Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.3</version>
<scope>runtime</scope>
</dependency>
Use latest release of Eclipse Implementation of JAXB 3.0.0:
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>3.0.0</version>
<scope>runtime</scope>
</dependency>
Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*
, so update import statements:
javax.xml.bind -> jakarta.xml.bind
Did some testing with the following script, on both PS 2 and PS 4 and had the same result. I hope this helps people.
$PSVersionTable.PSVersion
function PSscript {
$PSscript = Get-Item $MyInvocation.ScriptName
Return $PSscript
}
""
$PSscript = PSscript
$PSscript.FullName
$PSscript.Name
$PSscript.BaseName
$PSscript.Extension
$PSscript.DirectoryName
""
$PSscript = Get-Item $MyInvocation.InvocationName
$PSscript.FullName
$PSscript.Name
$PSscript.BaseName
$PSscript.Extension
$PSscript.DirectoryName
Results -
Major Minor Build Revision
----- ----- ----- --------
4 0 -1 -1
C:\PSscripts\Untitled1.ps1
Untitled1.ps1
Untitled1
.ps1
C:\PSscripts
C:\PSscripts\Untitled1.ps1
Untitled1.ps1
Untitled1
.ps1
C:\PSscripts
Try this...hopefully it will offer you a solution:
function sortlist_name()
{
var lb = document.getElementById('mylist');
arrTexts = new Array();
newTexts = new Array();
txt = new Array();
newArray =new Array();
for(i=0; i<lb.length; i++)
{
arrTexts[i] = lb.options[i].text;
}
for(i=0;i<arrTexts.length; i++)
{
str = arrTexts[i].split(" -> ");
newTexts[i] = str[1]+' -> '+str[0];
}
newTexts.sort();
for(i=0;i<newTexts.length; i++)
{
txt = newTexts[i].split(' -> ');
newArray[i] = txt[1]+' -> '+txt[0];
}
for(i=0; i<lb.length; i++)
{
lb.options[i].text = newArray[i];
lb.options[i].value = newArray[i];
}
}
/***********revrse by name******/
function sortreverse_name()
{
var lb = document.getElementById('mylist');
arrTexts = new Array();
newTexts = new Array();
txt = new Array();
newArray =new Array();
for(i=0; i<lb.length; i++)
{
arrTexts[i] = lb.options[i].text;
}
for(i=0;i<arrTexts.length; i++)
{
str = arrTexts[i].split(" -> ");
newTexts[i] = str[1]+' -> '+str[0];
}
newTexts.reverse();
for(i=0;i<newTexts.length; i++)
{
txt = newTexts[i].split(' -> ');
newArray[i] = txt[1]+' -> '+txt[0];
}
for(i=0; i<lb.length; i++)
{
lb.options[i].text = newArray[i];
lb.options[i].value = newArray[i];
}
}
function sortlist_id() {
var lb = document.getElementById('mylist');
arrTexts = new Array();
for(i=0; i<lb.length; i++) {
arrTexts[i] = lb.options[i].text;
}
arrTexts.sort();
for(i=0; i<lb.length; i++) {
lb.options[i].text = arrTexts[i];
lb.options[i].value = arrTexts[i];
}
}
/***********revrse by id******/
function sortreverse_id() {
var lb = document.getElementById('mylist');
arrTexts = new Array();
for(i=0; i<lb.length; i++) {
arrTexts[i] = lb.options[i].text;
}
arrTexts.reverse();
for(i=0; i<lb.length; i++) {
lb.options[i].text = arrTexts[i];
lb.options[i].value = arrTexts[i];
}
}
</script>
ID<a href="javascript:sortlist_id()"> ▲ </a> <a href="javascript:sortreverse_id()">▼</a> | Name<a href="javascript:sortlist_name()"> ▲ </a> <a href="javascript:sortreverse_name()">▼</a><br/>
<select name=mylist id=mylist size=8 style='width:150px'>
<option value="bill">4 -> Bill</option>
<option value="carl">5 -> Carl</option>
<option value="Anton">1 -> Anton</option>
<option value="mike">2 -> Mike</option>
<option value="peter">3 -> Peter</option>
</select>
<br>
You can change the URL with:
window.history.pushState({}, document.title, window.location.pathname);
this way, you can overwrite the URL without the search parameter, I use it to clean the URL after take the GET parameters.
The difference between link
and controller
comes into play when you want to nest directives in your DOM and expose API functions from the parent directive to the nested ones.
From the docs:
Best Practice: use controller when you want to expose an API to other directives. Otherwise use link.
Say you want to have two directives my-form
and my-text-input
and you want my-text-input
directive to appear only inside my-form
and nowhere else.
In that case, you will say while defining the directive my-text-input
that it requires a controller from the parent
DOM element using the require argument, like this: require: '^myForm'
. Now the controller from the parent element will be injected
into the link
function as the fourth argument, following $scope, element, attributes
. You can call functions on that controller and communicate with the parent directive.
Moreover, if such a controller is not found, an error will be raised.
There is no real need to use the link
function if one is defining the controller
since the $scope
is available on the controller
. Moreover, while defining both link
and controller
, one does need to be careful about the order of invocation of the two (controller
is executed before).
However, in keeping with the Angular way, most DOM manipulation and 2-way binding using $watchers
is usually done in the link
function while the API for children and $scope
manipulation is done in the controller
. This is not a hard and fast rule, but doing so will make the code more modular and help in separation of concerns (controller will maintain the directive
state and link
function will maintain the DOM
+ outside bindings).
Here's a little php function I wrote that uses the regex directly from MSFT's suggested javascript sniffing code from this article: http://msdn.microsoft.com/en-us/library/ms537509(v=vs.85).aspx
/**
* Returns the version of Internet Explorer or false
*/
function isIE(){
$isIE = preg_match("/MSIE ([0-9]{1,}[\.0-9]{0,})/",$_SERVER['HTTP_USER_AGENT'],$version);
if($isIE){
return $version[1];
}
return $isIE;
}
String res =" Application " res=res.trim();
o/p: Application
Note: White space ,blank space are trim or removed
You can define a DB class as below. Also, as andrewf suggested, use a context manager for cursor access.I'd define it as a member function. This way it keeps the connection open across multiple transactions from the app code and saves unnecessary reconnections to the server.
import pyodbc
class MS_DB():
""" Collection of helper methods to query the MS SQL Server database.
"""
def __init__(self, username, password, host, port=1433, initial_db='dev_db'):
self.username = username
self._password = password
self.host = host
self.port = str(port)
self.db = initial_db
conn_str = 'DRIVER=DRIVER=ODBC Driver 13 for SQL Server;SERVER='+ \
self.host + ';PORT='+ self.port +';DATABASE='+ \
self.db +';UID='+ self.username +';PWD='+ \
self._password +';'
print('Connected to DB:', conn_str)
self._connection = pyodbc.connect(conn_str)
pyodbc.pooling = False
def __repr__(self):
return f"MS-SQLServer('{self.username}', <password hidden>, '{self.host}', '{self.port}', '{self.db}')"
def __str__(self):
return f"MS-SQLServer Module for STP on {self.host}"
def __del__(self):
self._connection.close()
print("Connection closed.")
@contextmanager
def cursor(self, commit: bool = False):
"""
A context manager style of using a DB cursor for database operations.
This function should be used for any database queries or operations that
need to be done.
:param commit:
A boolean value that says whether to commit any database changes to the database. Defaults to False.
:type commit: bool
"""
cursor = self._connection.cursor()
try:
yield cursor
except pyodbc.DatabaseError as err:
print("DatabaseError {} ".format(err))
cursor.rollback()
raise err
else:
if commit:
cursor.commit()
finally:
cursor.close()
ms_db = MS_DB(username='my_user', password='my_secret', host='hostname')
with ms_db.cursor() as cursor:
cursor.execute("SELECT @@version;")
print(cur.fetchall())
Actually you can do with VS Code the following:
I ran into the exact same problem on Ubuntu 12.04, because I installed matplotlib (within a virtualenv) using
pip install matplotlib
To make long story short, my advice is: don't try to install matplotlib using pip or by hand; let a real package manager (e.g. apt-get / synaptic) install it and all its dependencies for you.
Unfortunately, matplotlib's backends (alternative methods for actually rendering your plots) have all sorts of dependencies that pip will not deal with. Even worse, it fails silently; that is, pip install matplotlib
appears to install matplotlib successfully. But when you try to use it (e.g. pyplot.show()
), no plot window will appear. I tried all the different backends that people on the web suggest (Qt4Agg, GTK, etc.), and they all failed (i.e. when I tried to import matplotlib.pyplot, I get ImportError
because it's trying to import some dependency that's missing). I then researched how to install those dependencies, but it just made me want to give up using pip (within virtualenv) as a viable installation solution for any package that has non-Python package dependencies.
The whole experience sent me crawling back to apt-get / synaptic (i.e. the Ubuntu package manager) to install software like matplotlib. That worked perfectly. Of course, that means you can only install into your system directories, no virtualenv goodness, and you are stuck with the versions that Ubuntu distributes, which may be way behind the current version...
Make sure the .ico file isn't corrupted as well. I got the same error which went away when I tried a different .ico file.
Use ?
:
<form action="?" method="post">
It will send the user back to the same page.
I used jQuery .scroll() function to track the event of the toolbar scroll value using scrollTop. I then used a conditional to determine if it was greater than the value on what I wanted to replace. In the below example it was "Results". If the value was true then the results-label added a class 'fixedSimilarLabel' and the new styles were then taken into account.
$('.toolbar').scroll(function (e) {
//console.info(e.currentTarget.scrollTop);
if (e.currentTarget.scrollTop >= 130) {
$('.results-label').addClass('fixedSimilarLabel');
}
else {
$('.results-label').removeClass('fixedSimilarLabel');
}
});
You can now toggle column selection mode, which changes mouse gestures and arrow keys, via:
"editor.action.toggleColumnSelection"
Note: There is a "Column Selection" panel in the status bar after activation, which you can press to disable it again.
Since React eventually boils down to plain old JavaScript, you can really place it anywhere! For instance, you could place it on a componentDidMount()
in a React class.
For you edit, you may want to try something like this:
class Component extends React.Component {
constructor(props) {
super(props);
this.onAddBucket = this.onAddBucket.bind(this);
}
componentWillMount() {
this.setState({
buckets: {},
})
}
componentDidMount() {
this.onAddBucket();
}
onAddBucket() {
let self = this;
let getToken = localStorage.getItem('myToken');
var apiBaseUrl = "...";
let input = {
"name" : this.state.fields["bucket_name"]
}
axios.defaults.headers.common['Authorization'] = getToken;
axios.post(apiBaseUrl+'...',input)
.then(function (response) {
if (response.data.status == 200) {
this.setState({
buckets: this.state.buckets.concat(response.data.buckets),
});
} else {
alert(response.data.message);
}
})
.catch(function (error) {
console.log(error);
});
}
render() {
return (
{this.state.bucket}
);
}
}
You copied using Cells.
If so, no need to PasteSpecial since you are copying data at exactly the same format.
Here's your code with some fixes.
Dim x As Workbook, y As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Set x = Workbooks.Open("path to copying book")
Set y = Workbooks.Open("path to pasting book")
Set ws1 = x.Sheets("Sheet you want to copy from")
Set ws2 = y.Sheets("Sheet you want to copy to")
ws1.Cells.Copy ws2.cells
y.Close True
x.Close False
If however you really want to paste special, use a dynamic Range("Address") to copy from.
Like this:
ws1.Range("Address").Copy: ws2.Range("A1").PasteSpecial xlPasteValues
y.Close True
x.Close False
Take note of the :
colon after the .Copy
which is a Statement Separating
character.
Using Object.PasteSpecial
requires to be executed in a new line.
Hope this gets you going.
As an updated answer from 2020. --user , -u option is Username or UID (format: <name|uid>[:<group|gid>]).
Then, it works for me like this,
docker exec -it -u root:root container /bin/bash
Reference: https://docs.docker.com/engine/reference/commandline/exec/
One of the following:
find *.txt -exec awk 'END {print $0 "," FILENAME}' {} \;
find *.txt -exec sh -c 'echo "$(tail -n 1 "$1"),$1"' _ {} \;
find *.txt -exec sh -c 'echo "$(sed -n "\$p" "$1"),$1"' _ {} \;
If you are using Visual Studio, you can also left-click on the project in Solution Explorer and change the Windows Authentication property to Enabled in the Properties window.
Use:
Dim n As String = MsgBox("Do you really want to exit?", MsgBoxStyle.YesNo, "Confirmation Dialog Box")
If n = vbYes Then
MsgBox("Current Form is closed....")
Me.Close() 'Current Form Closed
Yogi_Cottex.Show() 'Form Name.show()
End If
If you want to write the history to a file:
import readline
readline.write_history_file('python_history.txt')
The help function gives:
Help on built-in function write_history_file in module readline:
write_history_file(...)
write_history_file([filename]) -> None
Save a readline history file.
The default filename is ~/.history.
Mathew's answer works for the terminal python shell, but it didn't work for IDLE shell in my case because many versions of python existed before I replaced them all with Python2.7.7. How I solved the problem with IDLE.
cd /Applications/Python\ 2.7/IDLE.app/Contents/Resources/
sudo nano idlemain.py
, enter password if required.os.chdir(os.path.expanduser('~/Documents'))
this line, I added sys.path.append("/Users/admin/Downloads....")
NOTE: replace contents of the quotes with the directory where python module to be addedSince your problem is to downscale your image, there is no point in talking about interpolation -which is about creating pixel-. The issue here is downsampling.
To downsample an image, we need to turn each square of p * p pixels in the original image into a single pixel in the destination image.
For performances reasons Browsers do a very simple downsampling : to build the smaller image, they will just pick ONE pixel in the source and use its value for the destination. which 'forgets' some details and adds noise.
Yet there's an exception to that : since the 2X image downsampling is very simple to compute (average 4 pixels to make one) and is used for retina/HiDPI pixels, this case is handled properly -the Browser does make use of 4 pixels to make one-.
BUT... if you use several time a 2X downsampling, you'll face the issue that the successive rounding errors will add too much noise.
What's worse, you won't always resize by a power of two, and resizing to the nearest power + a last resizing is very noisy.
What you seek is a pixel-perfect downsampling, that is : a re-sampling of the image that will take all input pixels into account -whatever the scale-.
To do that we must compute, for each input pixel, its contribution to one, two, or four destination pixels depending wether the scaled projection of the input pixels is right inside a destination pixels, overlaps an X border, an Y border, or both.
( A scheme would be nice here, but i don't have one. )
Here's an example of canvas scale vs my pixel perfect scale on a 1/3 scale of a zombat.
Notice that the picture might get scaled in your Browser, and is .jpegized by S.O..
Yet we see that there's much less noise especially in the grass behind the wombat, and the branches on its right. The noise in the fur makes it more contrasted, but it looks like he's got white hairs -unlike source picture-.
Right image is less catchy but definitively nicer.
Here's the code to do the pixel perfect downscaling :
fiddle result :
http://jsfiddle.net/gamealchemist/r6aVp/embedded/result/
fiddle itself : http://jsfiddle.net/gamealchemist/r6aVp/
// scales the image by (float) scale < 1
// returns a canvas containing the scaled image.
function downScaleImage(img, scale) {
var imgCV = document.createElement('canvas');
imgCV.width = img.width;
imgCV.height = img.height;
var imgCtx = imgCV.getContext('2d');
imgCtx.drawImage(img, 0, 0);
return downScaleCanvas(imgCV, scale);
}
// scales the canvas by (float) scale < 1
// returns a new canvas containing the scaled image.
function downScaleCanvas(cv, scale) {
if (!(scale < 1) || !(scale > 0)) throw ('scale must be a positive number <1 ');
var sqScale = scale * scale; // square scale = area of source pixel within target
var sw = cv.width; // source image width
var sh = cv.height; // source image height
var tw = Math.floor(sw * scale); // target image width
var th = Math.floor(sh * scale); // target image height
var sx = 0, sy = 0, sIndex = 0; // source x,y, index within source array
var tx = 0, ty = 0, yIndex = 0, tIndex = 0; // target x,y, x,y index within target array
var tX = 0, tY = 0; // rounded tx, ty
var w = 0, nw = 0, wx = 0, nwx = 0, wy = 0, nwy = 0; // weight / next weight x / y
// weight is weight of current source point within target.
// next weight is weight of current source point within next target's point.
var crossX = false; // does scaled px cross its current px right border ?
var crossY = false; // does scaled px cross its current px bottom border ?
var sBuffer = cv.getContext('2d').
getImageData(0, 0, sw, sh).data; // source buffer 8 bit rgba
var tBuffer = new Float32Array(3 * tw * th); // target buffer Float32 rgb
var sR = 0, sG = 0, sB = 0; // source's current point r,g,b
/* untested !
var sA = 0; //source alpha */
for (sy = 0; sy < sh; sy++) {
ty = sy * scale; // y src position within target
tY = 0 | ty; // rounded : target pixel's y
yIndex = 3 * tY * tw; // line index within target array
crossY = (tY != (0 | ty + scale));
if (crossY) { // if pixel is crossing botton target pixel
wy = (tY + 1 - ty); // weight of point within target pixel
nwy = (ty + scale - tY - 1); // ... within y+1 target pixel
}
for (sx = 0; sx < sw; sx++, sIndex += 4) {
tx = sx * scale; // x src position within target
tX = 0 | tx; // rounded : target pixel's x
tIndex = yIndex + tX * 3; // target pixel index within target array
crossX = (tX != (0 | tx + scale));
if (crossX) { // if pixel is crossing target pixel's right
wx = (tX + 1 - tx); // weight of point within target pixel
nwx = (tx + scale - tX - 1); // ... within x+1 target pixel
}
sR = sBuffer[sIndex ]; // retrieving r,g,b for curr src px.
sG = sBuffer[sIndex + 1];
sB = sBuffer[sIndex + 2];
/* !! untested : handling alpha !!
sA = sBuffer[sIndex + 3];
if (!sA) continue;
if (sA != 0xFF) {
sR = (sR * sA) >> 8; // or use /256 instead ??
sG = (sG * sA) >> 8;
sB = (sB * sA) >> 8;
}
*/
if (!crossX && !crossY) { // pixel does not cross
// just add components weighted by squared scale.
tBuffer[tIndex ] += sR * sqScale;
tBuffer[tIndex + 1] += sG * sqScale;
tBuffer[tIndex + 2] += sB * sqScale;
} else if (crossX && !crossY) { // cross on X only
w = wx * scale;
// add weighted component for current px
tBuffer[tIndex ] += sR * w;
tBuffer[tIndex + 1] += sG * w;
tBuffer[tIndex + 2] += sB * w;
// add weighted component for next (tX+1) px
nw = nwx * scale
tBuffer[tIndex + 3] += sR * nw;
tBuffer[tIndex + 4] += sG * nw;
tBuffer[tIndex + 5] += sB * nw;
} else if (crossY && !crossX) { // cross on Y only
w = wy * scale;
// add weighted component for current px
tBuffer[tIndex ] += sR * w;
tBuffer[tIndex + 1] += sG * w;
tBuffer[tIndex + 2] += sB * w;
// add weighted component for next (tY+1) px
nw = nwy * scale
tBuffer[tIndex + 3 * tw ] += sR * nw;
tBuffer[tIndex + 3 * tw + 1] += sG * nw;
tBuffer[tIndex + 3 * tw + 2] += sB * nw;
} else { // crosses both x and y : four target points involved
// add weighted component for current px
w = wx * wy;
tBuffer[tIndex ] += sR * w;
tBuffer[tIndex + 1] += sG * w;
tBuffer[tIndex + 2] += sB * w;
// for tX + 1; tY px
nw = nwx * wy;
tBuffer[tIndex + 3] += sR * nw;
tBuffer[tIndex + 4] += sG * nw;
tBuffer[tIndex + 5] += sB * nw;
// for tX ; tY + 1 px
nw = wx * nwy;
tBuffer[tIndex + 3 * tw ] += sR * nw;
tBuffer[tIndex + 3 * tw + 1] += sG * nw;
tBuffer[tIndex + 3 * tw + 2] += sB * nw;
// for tX + 1 ; tY +1 px
nw = nwx * nwy;
tBuffer[tIndex + 3 * tw + 3] += sR * nw;
tBuffer[tIndex + 3 * tw + 4] += sG * nw;
tBuffer[tIndex + 3 * tw + 5] += sB * nw;
}
} // end for sx
} // end for sy
// create result canvas
var resCV = document.createElement('canvas');
resCV.width = tw;
resCV.height = th;
var resCtx = resCV.getContext('2d');
var imgRes = resCtx.getImageData(0, 0, tw, th);
var tByteBuffer = imgRes.data;
// convert float32 array into a UInt8Clamped Array
var pxIndex = 0; //
for (sIndex = 0, tIndex = 0; pxIndex < tw * th; sIndex += 3, tIndex += 4, pxIndex++) {
tByteBuffer[tIndex] = Math.ceil(tBuffer[sIndex]);
tByteBuffer[tIndex + 1] = Math.ceil(tBuffer[sIndex + 1]);
tByteBuffer[tIndex + 2] = Math.ceil(tBuffer[sIndex + 2]);
tByteBuffer[tIndex + 3] = 255;
}
// writing result to canvas.
resCtx.putImageData(imgRes, 0, 0);
return resCV;
}
It is quite memory greedy, since a float buffer is required to store the intermediate values of the destination image (-> if we count the result canvas, we use 6 times the source image's memory in this algorithm).
It is also quite expensive, since each source pixel is used whatever the destination size, and we have to pay for the getImageData / putImageDate, quite slow also.
But there's no way to be faster than process each source value in this case, and situation is not that bad : For my 740 * 556 image of a wombat, processing takes between 30 and 40 ms.
Try below structure for applying two color border,
<div class="white">
<div class="grey">
</div>
</div>
.white
{
border: 2px solid white;
}
.grey
{
border: 1px solid grey;
}
Remember, you can only add a cookie for the current domain.
If you want to add a cookie for your Google account, do
browser.get('http://google.com')
for cookie in cookies:
browser.add_cookie(cookie)
You can use getBoudingClientRect()
of the relative
parent.
document.addEventListener("mousemove", (e) => {
let xCoord = e.clientX - e.target.getBoundingClientRect().left + e.offsetX
let yCoord = e.clientY - e.target.getBoundingClientRect().top + e.offsetY
console.log("xCoord", xCoord, "yCoord", yCoord)
})
img And You can use this kode
class Nokta:
def __init__(self,x,y):
self.x=x
self.y=y
class Dogru:
def __init__(self,a,b):
self.a=a
self.b=b
def Kesisim(self,Dogru_b):
x1= self.a.x
x2=self.b.x
x3=Dogru_b.a.x
x4=Dogru_b.b.x
y1= self.a.y
y2=self.b.y
y3=Dogru_b.a.y
y4=Dogru_b.b.y
#Notlardaki denklemleri kullandim
pay1=((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3))
pay2=((x2-x1) * (y1 - y3) - (y2 - y1) * (x1 - x3))
payda=((y4 - y3) *(x2-x1)-(x4 - x3)*(y2 - y1))
if pay1==0 and pay2==0 and payda==0:
print("DOGRULAR BIRBIRINE ÇAKISIKTIR")
elif payda==0:
print("DOGRULAR BIRBIRNE PARALELDIR")
else:
ua=pay1/payda if payda else 0
ub=pay2/payda if payda else 0
#x ve y buldum
x=x1+ua*(x2-x1)
y=y1+ua*(y2-y1)
print("DOGRULAR {},{} NOKTASINDA KESISTI".format(x,y))
The Reason
You are not opening the page through a server, like Apache, so when the browser tries to obtain the resource it thinks it is from a separate domain, which is not allowed. Though some browsers do allow it.
The Solution
Run inetmgr and host your page locally and browse as http://localhost:portnumber/PageName.html or through a web server like Apache, nginx, node etc.
Alternatively use a different browser No error was shown when directly opening the page using Firefox and Safari. It comes only for Chrome and IE(xx).
If you are using code editors like Brackets, Sublime or Notepad++, those apps handle this error automatically.
Addition to Alex' answer:
$(function() {
$('input[type="submit"]').prop('disabled', true);
$('#check').on('input', function(e) {
if(this.value.length === 6) {
$('input[type="submit"]').prop('disabled', false);
} else {
$('input[type="submit"]').prop('disabled', true);
}
});
});
<input type="text" maxlength="6" id="check" data-minlength="6" /><br />
<input type="submit" value="send" />
But: You should always remember to validate the user input on the server side again. The user could modify the local HTML or disable JavaScript.
If you want the key and value when iterating, you can use a for...of loop with Object.entries.
const myObj = {a: 1, b: 2}
for (let [key, value] of Object.entries(myObj)) {
console.log(`key=${key} value=${value}`)
}
// output:
// key=a value=1
// key=b value=2
You need to check your config file if it has correct values such as systempath and artifact Id.
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>C:\Users\Akshay\Downloads\ojdbc6.jar</systemPath>
</dependency>
You can place your json to js file and save it to global variable. It is not asynchronous, but it can help.
Make sure to run pip3 for python3.7.
pip3 freeze >> yourfile.txt
Before executing the above command make sure you have created a virtual environment.
python3:
pip3 install virtualenv
python3 -m venv <myenvname>
python2:
pip install virtualenv
virtualenv <myenvname>
After that put your source code in the directory. If you run the python file now, probably it won't launch if you are using non-native modules. You can install those modules by running pip3 install <module>
or pip install <module>
.
This will not affect you entire module list except the environment you are in.
Now you can execute the command at the top and now you have a requirements file which contains only the modules you installed in the virtual environment. Now you can run the command at the top.
I advise everyone to use environments as it makes things easier when it comes to stuff like this.
This happens when you have 1 name for the Java class on hard disk and another name of Java class in the code!!
For example, I renamed my MainActivity
class to MainnActivity
only (!) in the code. I got this error immediately.
There is also a visual indicator in the Project tab of Android Studio - a class inside a class, like you have nested classed, but with an error indicator.
The solution is to simply rename class name in the Project tab (SHIFT
+ F6
) to match the name in the Java code.
SELECT COUNT(*)
FROM table_emp
WHERE YEAR(ARR_DATE) = '2012'
GROUP BY MONTH(ARR_DATE)
For changing default font family of the TextViews, override textViewStyle in your app theme.
For using custom font in fontFamily, use font resources which is in support library.
The feature was added in Android 26 but backported to older versions via supportlib.
https://developer.android.com/guide/topics/resources/font-resource.html https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html#using-support-lib
with a little typescript
import { useState, useEffect } from 'react';
interface WindowDimentions {
width: number;
height: number;
}
function getWindowDimensions(): WindowDimentions {
const { innerWidth: width, innerHeight: height } = window;
return {
width,
height
};
}
export default function useWindowDimensions(): WindowDimentions {
const [windowDimensions, setWindowDimensions] = useState<WindowDimentions>(
getWindowDimensions()
);
useEffect(() => {
function handleResize(): void {
setWindowDimensions(getWindowDimensions());
}
window.addEventListener('resize', handleResize);
return (): void => window.removeEventListener('resize', handleResize);
}, []);
return windowDimensions;
}
_x000D_
You can use the -as operator. If casting succeed you get back a number:
$numberAsString -as [int]
Convert.ToString(value, CultureInfo.InvariantCulture);
A way that I know of:
$product->getResource()->getAttribute($attribute_code)
->getFrontend()->getValue($product)
Simply make a div to be the direct child of body (with the class name bg for example), encompassing all other elements in the body, and add this to the CSS file:
.bg {
background-image: url('_images/home.jpg');//Put your appropriate image URL here
background-size: 100% 100%; //You need to put 100% twice here to stretch width and height
}
Refer to this link: https://www.w3schools.com/css/css_rwd_images.asp Scroll down to the part that says:
- If the background-size property is set to "100% 100%", the background image will stretch to cover the entire content area
There it shows the 'img_flowers.jpg' stretching to the size of the screen or browser regardless of how you resize it.
In my case the problem occurred due to closing my PC while visual studio were remain open, so in result csproj.user file saved empty. Thankfully i have already backup, so i just copied all xml from csproj.user and paste in my affected project csproj.user file ,so it worked perfectly.
This file just contain building device info and some more.
Also it may cause some warnigs in logs like a Cglib2AopProxy Unable to proxy method. And many other reasons for this are described here Why always have single implementaion interfaces in service and dao layers?
Python syntax does permit more than one statement on a line, separated by semicolon (;). However, limiting each line to one statement makes it easier for a human to follow a program's logic when reading through it.
So, another way of solving this issue, is to understand why the lint message is there and not put more than one statement on a line.
Yes, you may find it easier to write multiple statements per line, however, Pylint is for every other reader of your code not just you.
Putting the above together, you can make an alias
alias your_cmd=". your_cmd"
if you don't want to write the leading "." each time you want to source your script to the shell environment, or if you simply don't want to remember that must be done for the script to work correctly.
All hover is doing behind the scenes is binding to the mouseover and mouseout property. I would bind and unbind your functions from those events individually.
For example, say you have the following html:
<a href="#" class="myLink">Link</a>
then your jQuery would be:
$(document).ready(function() {
function mouseOver()
{
$(this).css('color', 'red');
}
function mouseOut()
{
$(this).css('color', 'blue');
}
// either of these might work
$('.myLink').hover(mouseOver, mouseOut);
$('.myLink').mouseover(mouseOver).mouseout(mouseOut);
// otherwise use this
$('.myLink').bind('mouseover', mouseOver).bind('mouseout', mouseOut);
// then to unbind
$('.myLink').click(function(e) {
e.preventDefault();
$('.myLink').unbind('mouseover', mouseOver).unbind('mouseout', mouseOut);
});
});
Here is a function generalizing previous approaches, creating a grid of images in PIL:
from PIL import Image
import numpy as np
def pil_grid(images, max_horiz=np.iinfo(int).max):
n_images = len(images)
n_horiz = min(n_images, max_horiz)
h_sizes, v_sizes = [0] * n_horiz, [0] * (n_images // n_horiz)
for i, im in enumerate(images):
h, v = i % n_horiz, i // n_horiz
h_sizes[h] = max(h_sizes[h], im.size[0])
v_sizes[v] = max(v_sizes[v], im.size[1])
h_sizes, v_sizes = np.cumsum([0] + h_sizes), np.cumsum([0] + v_sizes)
im_grid = Image.new('RGB', (h_sizes[-1], v_sizes[-1]), color='white')
for i, im in enumerate(images):
im_grid.paste(im, (h_sizes[i % n_horiz], v_sizes[i // n_horiz]))
return im_grid
It will shrink each row and columns of the grid to the minimum. You can have only a row by using pil_grid(images), or only a column by using pil_grid(images, 1).
One benefit of using PIL over numpy-array based solutions is that you can deal with images structured differently (like grayscale or palette-based images).
Example outputs
def dummy(w, h):
"Produces a dummy PIL image of given dimensions"
from PIL import ImageDraw
im = Image.new('RGB', (w, h), color=tuple((np.random.rand(3) * 255).astype(np.uint8)))
draw = ImageDraw.Draw(im)
points = [(i, j) for i in (0, im.size[0]) for j in (0, im.size[1])]
for i in range(len(points) - 1):
for j in range(i+1, len(points)):
draw.line(points[i] + points[j], fill='black', width=2)
return im
dummy_images = [dummy(20 + np.random.randint(30), 20 + np.random.randint(30)) for _ in range(10)]
pil_grid(dummy_images)
:
pil_grid(dummy_images, 3)
:
pil_grid(dummy_images, 1)
:
I think the most efficient way is to preallocate and then emplace elements:
template <typename T>
std::vector<T> VectorFromSet(const std::set<T>& from)
{
std::vector<T> to;
to.reserve(from.size());
for (auto const& value : from)
to.emplace_back(value);
return to;
}
That way we will only invoke copy constructor for every element as opposed to calling default constructor first and then copy assignment operator for other solutions listed above. More clarifications below.
back_inserter may be used but it will invoke push_back() on the vector (https://en.cppreference.com/w/cpp/iterator/back_insert_iterator). emplace_back() is more efficient because it avoids creating a temporary when using push_back(). It is not a problem with trivially constructed types but will be a performance implication for non-trivially constructed types (e.g. std::string).
We need to avoid constructing a vector with the size argument which causes all elements default constructed (for nothing). Like with solution using std::copy(), for instance.
And, finally, vector::assign() method or the constructor taking the iterator range are not good options because they will invoke std::distance() (to know number of elements) on set iterators. This will cause unwanted additional iteration through the all set elements because the set is Binary Search Tree data structure and it does not implement random access iterators.
Hope that helps.
Remove if
from if @item.rigged ? "Yes" : "No"
Ternary operator has form condition ? if_true : if_false
I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between
BEGIN
SELECT MONTH(CURDATE()) INTO @curmonth;
SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
SELECT DAY(@checkweekday) INTO @checkday;
SET @daycount = 0;
SET @workdays = 0;
WHILE(@daycount < @totaldays) DO
IF (WEEKDAY(@checkweekday) < 5) THEN
SET @workdays = @workdays+1;
END IF;
SET @daycount = @daycount+1;
SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
END WHILE;
END
Just for others:
If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query
delimiter ;;
drop procedure if exists test2;;
create procedure test2()
begin
select ‘Hello World’;
end
;;
Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.
The first_day function you need is: How to get first day of every corresponding month in mysql?
Showing the Procedure is working Simply add the following line below END WHILE and above END
SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;
Then use the following code in the SQL Query Window.
call test2 /* or whatever you changed the name of the stored procedure to */
NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).
<%!
private void myFunc(String Bits, javax.servlet.jsp.JspWriter myOut)
{
try{ myOut.println("<div>"+Bits+"</div>"); }
catch(Exception eek) { }
}
%>
...
<%
myFunc("more difficult than it should be",out);
%>
Try this, it worked for me!
Not to be too basic, but this:
>>> char1 = ['a''b''c''d''e''f''g''h''i''j''k''l'
'm''n''o''p''q''r''s''t''u''v''w''x''y''z']
is very different than this:
>>> char2 = ['a','b','c','d','e','f','g','h','i','j','k','l',
'm','n','o','p','q','r','s','t','u','v','w','x','y','z']
The first, without commas and what you have in your question, is a one element list with a 26 element string. The second is a 26 element list each a single character in length.
If you print each:
>>> print char1, len(char1), len(char1[0])
['abcdefghijklmnopqrstuvwxyz'] 1 26
>>> print char2, len(char2), len(char2[0])
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q','r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] 26 1
It becomes apparent that it takes an additional step to turn the individual characters of char1
into an iterable.
If you have the sequence of characters 'a' through 'z' and/or 'A' through 'Z', you can easily return the number of the character with list comprehension:
>>> [ord(x)%32 for x in char2]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
For the type of data structure you have, you need to access the string first:
>>> [ord(x)%32 for x in char1[0]]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
So if your code listing is the same as in your question, that may be your issue.
A reasonable alternative is: [ord(x.lower())-96 for x in char1[0]]
You can see that your characters=['a''b''c'...]
, without the commas, is just the same as typing all the characters in a string in a list like this ['abc...']
.
So now try:
>>> import string
>>> [ord(x.lower())-96 for x in string.letters]
[1,2,...26, 1,2,3...26] # my ellipses
>>> char3=[string.letters] # one string as element[0]
>>> [ord(x)%32 for x in char3[0]]
>>> [ord(x)%32 for x in [string.letters][0]]
As others have already noted, pre-increment is usually faster than post-increment for user-defined types. To understand why this is so, look at the typical code pattern to implement both operators:
Foo& operator++()
{
some_member.increase();
return *this;
}
Foo operator++(int dummy_parameter_indicating_postfix)
{
Foo copy(*this);
++(*this);
return copy;
}
As you can see, the prefix version simply modifies the object and returns it by reference.
The postfix version, on the other hand, must make a copy before the actual increment is performed, and then that copy is copied back to the caller by value. It is obvious from the source code that the postfix version must do more work, because it includes a call to the prefix version: ++(*this);
For built-in types, it does not make any difference as long as you discard the value, i.e. as long as you do not embed ++i
or i++
in a larger expression such as a = ++i
or b = i++
.
This is a slightly enhanced version of previous answers.
CancellationToken
for the original task, and when timeout occurs, you get TimeoutException
instead of OperationCanceledException
.async Task<TResult> CancelAfterAsync<TResult>(
Func<CancellationToken, Task<TResult>> startTask,
TimeSpan timeout, CancellationToken cancellationToken)
{
using (var timeoutCancellation = new CancellationTokenSource())
using (var combinedCancellation = CancellationTokenSource
.CreateLinkedTokenSource(cancellationToken, timeoutCancellation.Token))
{
var originalTask = startTask(combinedCancellation.Token);
var delayTask = Task.Delay(timeout, timeoutCancellation.Token);
var completedTask = await Task.WhenAny(originalTask, delayTask);
// Cancel timeout to stop either task:
// - Either the original task completed, so we need to cancel the delay task.
// - Or the timeout expired, so we need to cancel the original task.
// Canceling will not affect a task, that is already completed.
timeoutCancellation.Cancel();
if (completedTask == originalTask)
{
// original task completed
return await originalTask;
}
else
{
// timeout
throw new TimeoutException();
}
}
}
InnerCallAsync
may take a long time to complete. CallAsync
wraps it with a timeout.
async Task<int> CallAsync(CancellationToken cancellationToken)
{
var timeout = TimeSpan.FromMinutes(1);
int result = await CancelAfterAsync(ct => InnerCallAsync(ct), timeout,
cancellationToken);
return result;
}
async Task<int> InnerCallAsync(CancellationToken cancellationToken)
{
return 42;
}
Contents of table cell, variable height, could be more than 60px;
<div style="position: absolute; bottom: 0px;">
Notice
</div>
If you combine both Ben and ausadmin's solutions, you end up with a very MVVM friendly solution:
<TextBox Text="{Binding Txt1, Mode=TwoWay, UpdateSourceTrigger=Explicit}">
<TextBox.InputBindings>
<KeyBinding Gesture="Enter"
Command="{Binding UpdateTextBoxBindingOnEnterCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type TextBox}}}" />
</TextBox.InputBindings>
</TextBox>
...which means you are passing the TextBox
itself as the parameter to the Command
.
This leads to your Command
looking like this (if you're using a DelegateCommand
-style implementation in your VM):
public bool CanExecuteUpdateTextBoxBindingOnEnterCommand(object parameter)
{
return true;
}
public void ExecuteUpdateTextBoxBindingOnEnterCommand(object parameter)
{
TextBox tBox = parameter as TextBox;
if (tBox != null)
{
DependencyProperty prop = TextBox.TextProperty;
BindingExpression binding = BindingOperations.GetBindingExpression(tBox, prop);
if (binding != null)
binding.UpdateSource();
}
}
This Command
implementation can be used for any TextBox
and best of all no code in the code-behind though you may want to put this in it's own class so there are no dependencies on System.Windows.Controls
in your VM. It depends on how strict your code guidelines are.
WiX is the way to go for new installers. If WiX alone is too complicated or not flexible enough on the GUI side consider using SharpSetup - it allows you to create installer GUI in WinForms of WPF and has other nice features like translations, autoupdater, built-in prerequisites, improved autocompletion in VS and more.
(Disclaimer: I am the author of SharpSetup.)
Try this. It's very easy:
driver.getPageSource().contains("text to search");
This really worked for me in Selenium WebDriver.
No, that's not possible. The port is not part of the hostname, so it has no meaning in the hosts
-file.
Download and run the following script to recursively convert soft tabs to hard tabs in plain text files.
Place and execute the script from inside the folder which contains the plain text files.
#!/bin/bash
find . -type f -and -not -path './.git/*' -exec grep -Iq . {} \; -and -print | while read -r file; do {
echo "Converting... "$file"";
data=$(unexpand --first-only -t 4 "$file");
rm "$file";
echo "$data" > "$file";
}; done;
You can use FractionallySizedBox
Sometimes decoratedBox doesn't cover the full-screen size. We can fix it by wrapping it with FractionallySizedBox Widget. In this widget we give widthfactor and heightfactor.
The widthfactor
shows the [FractionallySizedBox]widget should take _____ percentage of the app's width.
The heightfactor
shows the [FractionallySizedBox]widget should take _____ percentage of the app's height.
Example : heightfactor = 0.3 means 30% of app's height. widthfactor = 0.4 means 40% of app's width.
Hence, for full screen set heightfactor = 1.0 and widthfactor = 1.0
Tip
: FractionallySizedBox goes well with the stack
widget. So that you can easily add buttons, avatars, texts over your background image in the stack widget whereas in rows and columns you cannot do that.
For more info check out this project's repository github repository link for this project
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: Stack(
children: <Widget>[
Container(
child: FractionallySizedBox(
heightFactor: 1.0,
widthFactor: 1.0,
//for full screen set heightFactor: 1.0,widthFactor: 1.0,
child: DecoratedBox(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("images/1.jpg"),
fit: BoxFit.fill,
),
),
),
),
),
],
),
),
),
);
}
}
There is a new way to do this.
Android Studio 2.2 has APK Analyzer it will give lot of info about apk, checkout it here :- http://android-developers.blogspot.in/2016/05/android-studio-22-preview-new-ui.html
You could modify a PDF renderer such as xpdf or evince to render into a graphics image on your server, and then deliver the image to the user. This is how Google's quick view of PDF files works, they render it locally, then deliver images to the user. No downloaded PDF file, and the source is pretty well obscured. :)
In this sample, I created a JavaScript progress bar (with percentage display), you can control it and hide it with JavaScript.
In this sample, the progress bar advances every 100ms. You can see it in JSFiddle
var elapsedTime = 0;
var interval = setInterval(function() {
timer()
}, 100);
function progressbar(percent) {
document.getElementById("prgsbarcolor").style.width = percent + '%';
document.getElementById("prgsbartext").innerHTML = percent + '%';
}
function timer() {
if (elapsedTime > 100) {
document.getElementById("prgsbartext").style.color = "#FFF";
document.getElementById("prgsbartext").innerHTML = "Completed.";
if (elapsedTime >= 107) {
clearInterval(interval);
history.go(-1);
}
} else {
progressbar(elapsedTime);
}
elapsedTime++;
}
Here's another way to do it in VBA.
Function ConvertToArray(ByVal value As String)
value = StrConv(value, vbUnicode)
ConvertToArray = Split(Left(value, Len(value) - 1), vbNullChar)
End Function
Sub example()
Dim originalString As String
originalString = "hi there"
Dim myArray() As String
myArray = ConvertToArray(originalString)
End Sub
You can use:
a.delete(a[0])
a.delete_at 0
Both can work
try a generalized linear model with a gaussian family
y = np.array([-6, -5, -10, -5, -8, -3, -6, -8, -8])
X = np.array([
[-4.95, -4.55, -10.96, -1.08, -6.52, -0.81, -7.01, -4.46, -11.54],
[-5.87, -4.52, -11.64, -3.36, -7.45, -2.36, -7.33, -7.65, -10.03],
[-0.76, -0.71, -0.98, 0.75, -0.86, -0.50, -0.33, -0.94, -1.03],
[14.73, 13.74, 15.49, 24.72, 16.59, 22.44, 13.93, 11.40, 18.18],
[4.02, 4.47, 4.18, 4.96, 4.29, 4.81, 4.32, 4.43, 4.28],
[0.20, 0.16, 0.19, 0.16, 0.10, 0.15, 0.21, 0.16, 0.21],
[0.45, 0.50, 0.53, 0.60, 0.48, 0.53, 0.50, 0.49, 0.55],
])
X=zip(*reversed(X))
df=pd.DataFrame({'X':X,'y':y})
columns=7
for i in range(0,columns):
df['X'+str(i)]=df.apply(lambda row: row['X'][i],axis=1)
df=df.drop('X',axis=1)
print(df)
#model_formula='y ~ X0+X1+X2+X3+X4+X5+X6'
model_formula='y ~ X0'
model_family = sm.families.Gaussian()
model_fit = glm(formula = model_formula,
data = df,
family = model_family).fit()
print(model_fit.summary())
# Extract coefficients from the fitted model wells_fit
#print(model_fit.params)
intercept, slope = model_fit.params
# Print coefficients
print('Intercept =', intercept)
print('Slope =', slope)
# Extract and print confidence intervals
print(model_fit.conf_int())
df2=pd.DataFrame()
df2['X0']=np.linspace(0.50,0.70,50)
df3=pd.DataFrame()
df3['X1']=np.linspace(0.20,0.60,50)
prediction0=model_fit.predict(df2)
#prediction1=model_fit.predict(df3)
plt.plot(df2['X0'],prediction0,label='X0')
plt.ylabel("y")
plt.xlabel("X0")
plt.show()
Since Java 8 this kind of code compiles as expected and the type parameter gets inferred by the compiler.
public Person(String name) {
this(name, Collections.emptyList()); // Inferred to List<String> in Java 8
}
public Person(String name, List<String> nicknames) {
this.name = name;
this.nicknames = nicknames;
}
The new thing in Java 8 is that the target type of an expression will be used to infer type parameters of its sub-expressions. Before Java 8 only direct assignments and arguments to methods where used for type parameter inference.
In this case the parameter type of the constructor will be the target type for Collections.emptyList()
, and the return value type will get chosen to match the parameter type.
This mechanism was added in Java 8 mainly to be able to compile lambda expressions, but it improves type inferences generally.
Java is getting closer to proper Hindley–Milner type inference with every release!
Eclipse artifact searching depends on repository's index file. It seems you did not download the index file.
Go to Window -> Prefrences -> Maven and check "Download repository index updates on start". Restart Eclipse and then look at the progress view. An index file should be downloading.
After downloading completely, artifact searching will be ready to use.
UPDATE You also need to rebuild your Maven repository index in 'maven repository view'.
In this view , open 'Global Repositories', right-click 'central', check 'Full Index Enable', and then, click 'Rebuild Index' in the same menu.
A 66M index file will be downloaded.
As it was already mentioned in previous answers, your matrix cannot be inverted, because its determinant is 0.
But if you still want to get inverse matrix, you can use np.linalg.pinv
, which leverages SVD to approximate initial matrix.
The add
method that takes a String
and a Person
is calling a different add
method that takes a Position
. The one that takes Position
is inherited from the ArrayList
class.
Since your class Staff
extends ArrayList<Position>
, it automatically has the add(Position)
method. The new add(String, Person)
method is one that was written particularly for the Staff class.
For the things that you are suggesting you can just change the levels using the levels
:
levels(iris$Species)[3] <- 'new'
You should define the function textcolor before. Because textcolor is not a standard function in C.
void textcolor(unsigned short color) {
HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hcon,color);
}
No, [^\x20-\x7E]
is not ASCII.
This is real ASCII:
[^\x00-\x7F]
Otherwise, it will trim out newlines and other special characters that are part of the ASCII table!
Maybe you want set -e
:
www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:
This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.
Found this one:
[x for (i,x) in enumerate(my_list) if my_list[i] == "two"]
Will print:
["two"]
Any class which extends Exception
class will be a user defined Checked exception class where as any class which extends RuntimeException
will be Unchecked exception class.
as mentioned in User defined exception are checked or unchecked exceptions
So, not throwing the checked exception(be it user-defined or built-in exception) gives compile time error.
Checked exception are the exceptions that are checked at compile time.
Unchecked exception are the exceptions that are not checked at compiled time
If you are using startActivityForResult()
in your previous activities, just override OnActivityResult()
and call the finish();
method inside it in all activities.. This will do the job...
You can make this in three steps:
CREATE TABLE test2 AS
SELECT PersId
FROM pers p
WHERE (
chefID IS NOT NULL
OR gehalt < (
SELECT MAX (
gehalt * 1.05
)
FROM pers MA
WHERE MA.chefID = p.chefID
)
)
...
UPDATE pers P
SET P.gehalt = P.gehalt * 1.05
WHERE PersId
IN (
SELECT PersId
FROM test2
)
DROP TABLE test2;
or
UPDATE Pers P, (
SELECT PersId
FROM pers p
WHERE (
chefID IS NOT NULL
OR gehalt < (
SELECT MAX (
gehalt * 1.05
)
FROM pers MA
WHERE MA.chefID = p.chefID
)
)
) t
SET P.gehalt = P.gehalt * 1.05
WHERE p.PersId = t.PersId
Use FirstOrDefault or a foreach loop as already mentioned. Manually fetching an enumerator and calling Current should be avoided. foreach will dispose your enumerator for you if it implements IDisposable. When calling MoveNext and Current you have to dispose it manually (if aplicable).
Just like @Dampes8N said:
$result = mysql_query($sql,$conecction);
$fp = fopen('file.csv', 'w');
while($row = mysql_fetch_assoc($result)){
fputcsv($fp, $row);
}
fclose($fp);
Hope this helps.
Following query will give you the exact table names of the database having field name like '%myName'.
SELECT distinct(TABLE_NAME)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%myName%'
If you want to list all the files currently being tracked under the branch master
, you could use this command:
git ls-tree -r master --name-only
If you want a list of files that ever existed (i.e. including deleted files):
git log --pretty=format: --name-only --diff-filter=A | sort - | sed '/^$/d'
You can also use EXIT_SUCCESS
instead of return 0;
. The macro EXIT_SUCCESS
is actually defined as zero, but makes your program more readable.
Adding a solution here for a different problem, but one that manifests with the same error... Take care when constructing json on the fly (as api responses or whatever) to escape literal double quotes in your string members. You may be consuming your own malformed json.
Your regex ^[0-9]
matches anything beginning with a digit, including strings like "1A". To avoid a partial match, append a $
to the end:
^[0-9]*$
This accepts any number of digits, including none. To accept one or more digits, change the *
to +
. To accept exactly one digit, just remove the *
.
UPDATE: You mixed up the arguments to IsMatch
. The pattern should be the second argument, not the first:
if (!System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$"))
CAUTION: In JavaScript, \d
is equivalent to [0-9]
, but in .NET, \d
by default matches any Unicode decimal digit, including exotic fare like ? (Myanmar 2) and ? (N'Ko 9). Unless your app is prepared to deal with these characters, stick with [0-9]
(or supply the RegexOptions.ECMAScript flag).
Just use ` character to separate command on multiline
Programmatically: Run time
You can do programmatically using setTypeface():
textView.setTypeface(null, Typeface.NORMAL); // for Normal Text
textView.setTypeface(null, Typeface.BOLD); // for Bold only
textView.setTypeface(null, Typeface.ITALIC); // for Italic
textView.setTypeface(null, Typeface.BOLD_ITALIC); // for Bold and Italic
XML: Design Time
You can set in XML as well:
android:textStyle="normal"
android:textStyle="normal|bold"
android:textStyle="normal|italic"
android:textStyle="bold"
android:textStyle="bold|italic"
Hope this will help
Summved
A more efficient method, that uses integer math rather than strings/varchars, that will result in an int type rather than a string type is:
SELECT YYYYMM = (YEAR(GETDATE()) * 100) + MONTH(GETDATE())
Adds two zeros to the right side of the year and then adds the month to the added two zeros.
This is what I've been using. Haven't seen any issues.
destroy: function(){
this.remove();
this.unbind();
}
For a new path to be added to PATH environment variable in MacOS just create a new file under /etc/paths.d
directory and add write path to be set in the file. Restart the terminal. You can check with echo $PATH
at the prompt to confirm if the path was added to the environment variable.
For example: to add a new path /usr/local/sbin
to the PATH
variable:
cd /etc/paths.d
sudo vi newfile
Add the path to the newfile
and save it.
Restart the terminal and type echo $PATH
to confirm
You can also use translate(). If the third argument is too short, the corresponding characters from the second argument are deleted. Unlike regexp_replace() you don't need to worry about special characters. Source code.
With set of static imports, Guava solution can be very compact one-liner:
toString(getResource("foo.txt"), UTF_8);
The following imports are required:
import static com.google.common.io.Resources.getResource
import static com.google.common.io.Resources.toString
import static java.nio.charset.StandardCharsets.UTF_8
Video Tutorial: Accessing the Camera with HTML5 & appMobi API will be helpful for you.
Also, you may try the getUserMedia
method (supported by Opera 12)
Also look at log4net, which makes logging to 1 or more event stores — whether it's the console, the Windows event log, a text file, a network pipe, a SQL database, etc. — pretty trivial. You can even filter stuff in its configuration, for instance, so that only log records of a particular severity (say ERROR or FATAL) from a single component or assembly are directed to a particular event store.
You can try : Yolk
For install yolk, try:
easy_install yolk
Yolk is a Python tool for obtaining information about installed Python packages and querying packages avilable on PyPI (Python Package Index).
You can see which packages are active, non-active or in development mode and show you which have newer versions available by querying PyPI.
I depends heavily on which number formats you aim to support, and how strict you want to enforce number grouping, use of whitespace and other separators etc....
Take a look at this similar question to get some ideas.
Then there is E.164 which is a numbering standard recommendation from ITU-T
Maybe you might try the web to send the file with proper Content-Type header and with the header like this:
Content-Disposition: inline; filename="xxx.xxx"
Here is a discussion about these headers: How to force files to open in browser instead of download (pdf)?
Or just search on google for content-disposition.
LogisticRegression
is not for regression but classification !
The Y
variable must be the classification class,
(for example 0
or 1
)
And not a continuous
variable,
that would be a regression problem.
You need to print
to get that output.
You should do
>>> x = "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
>>> x # this is the value, returned by the join() function
'I\nwould\nexpect\nmultiple\nlines'
>>> print x # this prints your string (the type of output you want)
I
would
expect
multiple
lines
msiexec.exe /x "{588A9A11-1E20-4B91-8817-2D36ACBBBF9F}" /q
I use the jQuery clueTip plugin for this.
Put this code in your .htaccess file
RewriteEngine On
ErrorDocument 404 /404.php
where 404.php
is the file name
and placed at root. You can put full path
over here.
The facade is another Request class, access it with the full path:
$input = \Request::all();
From laravel 5 you can also access it through the request()
function:
$input = request()->all();
You don't have to use Tomcat installation as a server location. It is much easier just to copy the files in the ROOT folder.
Eclipse forgets to copy the default apps (ROOT, examples, etc.) when it creates a Tomcat folder inside the Eclipse workspace. Go to
C:\apache-tomcat-7.0.8\webapps
, R-click on the ROOT folder and copy it. Then go to your Eclipse workspace, go to the.metadata
folder, and search for "wtpwebapps". You should find something likeyour-eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
(or../tmp1/wtpwebapps
if you already had another server registered in Eclipse). Go to thewtpwebapps
folder, R-click, and paste ROOT (say "yes" if asked if you want to merge/replace folders/files). Then reloadhttp://localhost/
to see the Tomcat welcome page.
Source: HTTP Status 404 error in tomcat
Here is an updated answer for iOS7+. It uses NSURLSession, the new hotness. Disclaimer, this is untested and was written in a text field:
- (void)post {
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://example.com/dontposthere"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
// Uncomment the following two lines if you're using JSON like I imagine many people are (the person who is asking specified plain text)
// [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
// [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:@"POST"];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}];
[postDataTask resume];
}
-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)( NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler {
completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
}
Or better yet, use AFNetworking 2.0+. Usually I would subclass AFHTTPSessionManager, but I'm putting this all in one method to have a concise example.
- (void)post {
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@"https://example.com"]];
// Many people will probably want [AFJSONRequestSerializer serializer];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
// Many people will probably want [AFJSONResponseSerializer serializer];
manager.responseSerializer = [AFHTTPRequestSerializer serializer];
manager.securityPolicy.allowInvalidCertificates = NO; // Some servers require this to be YES, but default is NO.
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"username" password:@"password"];
[[manager POST:@"dontposthere" parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"darn it");
}] resume];
}
If you are using the JSON response serializer, the responseObject will be object from the JSON response (often NSDictionary or NSArray).
1. First should understand the error meaning
Error not enough values to unpack (expected 3, got 2)
means:
a 2 part tuple, but assign to 3 values
and I have written demo code to show for you:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Function: Showing how to understand ValueError 'not enough values to unpack (expected 3, got 2)'
# Author: Crifan Li
# Update: 20191212
def notEnoughUnpack():
"""Showing how to understand python error `not enough values to unpack (expected 3, got 2)`"""
# a dict, which single key's value is two part tuple
valueIsTwoPartTupleDict = {
"name1": ("lastname1", "email1"),
"name2": ("lastname2", "email2"),
}
# Test case 1: got value from key
gotLastname, gotEmail = valueIsTwoPartTupleDict["name1"] # OK
print("gotLastname=%s, gotEmail=%s" % (gotLastname, gotEmail))
# gotLastname, gotEmail, gotOtherSomeValue = valueIsTwoPartTupleDict["name1"] # -> ValueError not enough values to unpack (expected 3, got 2)
# Test case 2: got from dict.items()
for eachKey, eachValues in valueIsTwoPartTupleDict.items():
print("eachKey=%s, eachValues=%s" % (eachKey, eachValues))
# same as following:
# Background knowledge: each of dict.items() return (key, values)
# here above eachValues is a tuple of two parts
for eachKey, (eachValuePart1, eachValuePart2) in valueIsTwoPartTupleDict.items():
print("eachKey=%s, eachValuePart1=%s, eachValuePart2=%s" % (eachKey, eachValuePart1, eachValuePart2))
# but following:
for eachKey, (eachValuePart1, eachValuePart2, eachValuePart3) in valueIsTwoPartTupleDict.items(): # will -> ValueError not enough values to unpack (expected 3, got 2)
pass
if __name__ == "__main__":
notEnoughUnpack()
using VSCode
debug effect:
2. For your code
for name, email, lastname in unpaidMembers.items():
but error
ValueError: not enough values to unpack (expected 3, got 2)
means each item(a tuple value) in unpaidMembers
, only have 1 parts:email
, which corresponding above code
unpaidMembers[name] = email
so should change code to:
for name, email in unpaidMembers.items():
to avoid error.
But obviously you expect extra lastname
, so should change your above code to
unpaidMembers[name] = (email, lastname)
and better change to better syntax:
for name, (email, lastname) in unpaidMembers.items():
then everything is OK and clear.
Here's a solution that keeps things within a dplyr pipe chain. You sort the data in advance, and then using mutate_at to convert to a factor. I've modified the data slightly to show how this solution can be applied generally, given data that can be sensibly sorted:
# the data
temp <- data.frame(type=rep(c("T", "F", "P"), 4),
size=rep(c("50%", "100%", "200%", "150%"), each=3), # cannot sort this
size_num = rep(c(.5, 1, 2, 1.5), each=3), # can sort this
amount=c(48.4, 48.1, 46.8,
25.9, 26.0, 24.9,
20.8, 21.5, 16.5,
21.1, 21.4, 20.1))
temp %>%
arrange(size_num) %>% # sort
mutate_at(vars(size), funs(factor(., levels=unique(.)))) %>% # convert to factor
ggplot() +
geom_bar(aes(x = type, y=amount, fill=type),
position="dodge", stat="identity") +
facet_grid(~ size)
You can apply this solution to arrange the bars within facets, too, though you can only choose a single, preferred order:
temp %>%
arrange(size_num) %>%
mutate_at(vars(size), funs(factor(., levels=unique(.)))) %>%
arrange(desc(amount)) %>%
mutate_at(vars(type), funs(factor(., levels=unique(.)))) %>%
ggplot() +
geom_bar(aes(x = type, y=amount, fill=type),
position="dodge", stat="identity") +
facet_grid(~ size)
ggplot() +
geom_bar(aes(x = type, y=amount, fill=type),
position="dodge", stat="identity") +
facet_grid(~ size)
We have lot of answers to this question. This answer may be helpful in some scenarios If you want to ignore the null values you can use the NOT_NULL in class level. as below
@JsonInclude(Include.NON_NULL)
class Foo
{
String bar;
}
Some times you may need to ignore the empty values such as you may have initialized the arrayList but there is no elements in that list.In that time using NOT_EMPTY annotation to ignore those empty value fields
@JsonInclude(Include.NON_EMPTY)
class Foo
{
String bar;
}