[ $(echo $variable_to_test | sed s/\n// | sed s/\ //) == "" ] && echo "String is empty"
Stripping all newlines and spaces from the string will cause a blank one to be reduced to nothing which can be tested and acted upon
Short version which you can pass to kill command:
lsof -i:80 -t
Better late than never, I suppose. I was motivated to develop this specifically because my Fedora scripts weren't working on the Mac. The problem is dependencies and Bash. Macs don't have them, or if they do, they are often somewhere else (another path). Dependency path manipulation in a cross-platform Bash script is a headache at best and a security risk at worst - so it's best to avoid their use, if possible.
The function get_realpath() below is simple, Bash-centric, and no dependencies are required. I uses only the Bash builtins echo and cd. It is also fairly secure, as everything gets tested at each stage of the way and it returns error conditions.
If you don't want to follow symlinks, then put set -P at the front of the script, but otherwise cd should resolve the symlinks by default. It's been tested with file arguments that are {absolute | relative | symlink | local} and it returns the absolute path to the file. So far we've not had any problems with it.
function get_realpath() {
if [[ -f "$1" ]]
then
# file *must* exist
if cd "$(echo "${1%/*}")" &>/dev/null
then
# file *may* not be local
# exception is ./file.ext
# try 'cd .; cd -;' *works!*
local tmppwd="$PWD"
cd - &>/dev/null
else
# file *must* be local
local tmppwd="$PWD"
fi
else
# file *cannot* exist
return 1 # failure
fi
# reassemble realpath
echo "$tmppwd"/"${1##*/}"
return 0 # success
}
You can combine this with other functions get_dirname, get_filename, get_stemname and validate_path. These can be found at our GitHub repository as realpath-lib (full disclosure - this is our product but we offer it free to the community without any restrictions). It also could serve as a instructional tool - it's well documented.
We've tried our best to apply so-called 'modern Bash' practices, but Bash is a big subject and I'm certain there will always be room for improvement. It requires Bash 4+ but could be made to work with older versions if they are still around.
If you want install python libs and their dependencies offline, finish following these steps on a machine with the same os, network connected, and python installed:
1) Create a requirements.txt
file with similar content (Note - these are the libraries you wish to download):
Flask==0.12
requests>=2.7.0
scikit-learn==0.19.1
numpy==1.14.3
pandas==0.22.0
One option for creating the requirements file is to use pip freeze > requirements.txt
. This will list all libraries in your environment. Then you can go in to requirements.txt
and remove un-needed ones.
2) Execute command mkdir wheelhouse && pip download -r requirements.txt -d wheelhouse
to download libs and their dependencies to directory wheelhouse
3) Copy requirements.txt into wheelhouse
directory
4) Archive wheelhouse into wheelhouse.tar.gz
with tar -zcf wheelhouse.tar.gz wheelhouse
Then upload wheelhouse.tar.gz
to your target machine:
1) Execute tar -zxf wheelhouse.tar.gz
to extract the files
2) Execute pip install -r wheelhouse/requirements.txt --no-index --find-links wheelhouse
to install the libs and their dependencies
Yet another example...
from __future__ import print_function #Only for Python2
with open('file1.txt') as f1, open('file2.txt') as f2, open('outfile.txt', 'w') as outfile:
for line1, line2 in zip(f1, f2):
if line1 == line2:
print(line1, end='', file=outfile)
And if you want to eliminate common blank lines, just change the if statement to:
if line1.strip() and line1 == line2:
.strip()
removes all leading and trailing whitespace, so if that's all that's on a line, it will become an empty string ""
, which is considered false.
According to this documentation, the find method will search down through the tree of elements until it finds the element in the selector parameters. So $(parentSelector).find(childSelector)
is the fastest and most efficient way to do this.
DIV
elements can get focus if set the tabindex
attribute. Here is the working example.
#focus-example > .extra {_x000D_
display: none;_x000D_
}_x000D_
#focus-example:focus > .extra {_x000D_
display: block;_x000D_
}
_x000D_
<div id="focus-example" tabindex="0">_x000D_
<div>Focus me!</div>_x000D_
<div class="extra">Hooray!</div>_x000D_
</div>
_x000D_
For more information about focus
and blur
, you can check out this article.
Update:
And here is another example using focus
to create a menu
.
#toggleMenu:focus {_x000D_
outline: none;_x000D_
}_x000D_
button:focus + .menu {_x000D_
display: block;_x000D_
}_x000D_
.menu {_x000D_
display: none;_x000D_
}_x000D_
.menu:focus {_x000D_
display: none;_x000D_
}
_x000D_
<div id="toggleMenu" tabindex="0">_x000D_
<button type="button">Menu</button>_x000D_
<ul class="menu" tabindex="1">_x000D_
<li>Home</li>_x000D_
<li>About Me</li>_x000D_
<li>Contacts</li>_x000D_
</ul>_x000D_
</div>
_x000D_
So my answer ended up being a solution that allows me to use the _this variable pointing to the original object. I create a new instance of a "Square" however I hated the way the "Square" generated it's size. I thought it should follow my specific needs. However in order to do so I needed the square to have an updated "GetSize" function with the internals of that function calling other functions already existing in the square such as this.height, this.GetVolume(). But in order to do so I needed to do this without any crazy hacks. So here is my solution.
Some other Object initializer or helper function.
this.viewer = new Autodesk.Viewing.Private.GuiViewer3D(
this.viewerContainer)
var viewer = this.viewer;
viewer.updateToolbarButtons = this.updateToolbarButtons(viewer);
Function in the other object.
updateToolbarButtons = function(viewer) {
var _viewer = viewer;
return function(width, height){
blah blah black sheep I can refer to this.anything();
}
};
The cause of your problem is simple. So many people will run into the same problem, Because I did too and it took me hour to figure out. Just in case, someone else stumbles, The problem is in your query, your select statement is calling $dbname
instead of table name. So its not found whereby returning false
which is boolean
. Good luck.
You can use lambda in Java 8
public static void main(String[] args) {
tentimes(inputPrm - > System.out.println(inputPrm));
//tentimes(System.out::println); // You can also replace lambda with static method reference
}
public static void tentimes(Consumer myFunction) {
for (int i = 0; i < 10; i++)
myFunction.accept("hello");
}
For further info about Java Lambdas and FunctionalInterfaces
Keydown is pressing the key without releasing it, Keypress is a complete press-and-release cycle.
Put another way, KeyDown + KeyUp = Keypress
A piece of code is easier for people who have such problem. I share my code and you can use it directly. Please note that OpenCV store pixels as BGR.
cv::Mat vImage_;
if(src_)
{
cv::Vec3f vec_;
for(int i = 0; i < vHeight_; i++)
for(int j = 0; j < vWidth_; j++)
{
vec_ = cv::Vec3f((*src_)[0]/255.0, (*src_)[1]/255.0, (*src_)[2]/255.0);//Please note that OpenCV store pixels as BGR.
vImage_.at<cv::Vec3f>(vHeight_-1-i, j) = vec_;
++src_;
}
}
if(! vImage_.data ) // Check for invalid input
printf("failed to read image by OpenCV.");
else
{
cv::namedWindow( windowName_, CV_WINDOW_AUTOSIZE);
cv::imshow( windowName_, vImage_); // Show the image.
}
This is another example of how to use keySet(), get(), values() and entrySet() functions to obtain Keys and Values in a Map:
Map<Integer, String> testKeyset = new HashMap<Integer, String>();
testKeyset.put(1, "first");
testKeyset.put(2, "second");
testKeyset.put(3, "third");
testKeyset.put(4, "fourth");
// Print a single value relevant to a specified Key. (uses keySet())
for(int mapKey: testKeyset.keySet())
System.out.println(testKeyset.get(mapKey));
// Print all values regardless of the key.
for(String mapVal: testKeyset.values())
System.out.println(mapVal.trim());
// Displays the Map in Key-Value pairs (e.g: [1=first, 2=second, 3=third, 4=fourth])
System.out.println(testKeyset.entrySet());
This is a cute class I use (in cases I want to catch event on a View, if it is a ViewGroup, I use the second implementation):
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
public class SwipeDetector implements View.OnTouchListener{
private int min_distance = 100;
private float downX, downY, upX, upY;
private View v;
private onSwipeEvent swipeEventListener;
public SwipeDetector(View v){
this.v=v;
v.setOnTouchListener(this);
}
public void setOnSwipeListener(onSwipeEvent listener)
{
try{
swipeEventListener=listener;
}
catch(ClassCastException e)
{
Log.e("ClassCastException","please pass SwipeDetector.onSwipeEvent Interface instance",e);
}
}
public void onRightToLeftSwipe(){
if(swipeEventListener!=null)
swipeEventListener.SwipeEventDetected(v,SwipeTypeEnum.RIGHT_TO_LEFT);
else
Log.e("SwipeDetector error","please pass SwipeDetector.onSwipeEvent Interface instance");
}
public void onLeftToRightSwipe(){
if(swipeEventListener!=null)
swipeEventListener.SwipeEventDetected(v,SwipeTypeEnum.LEFT_TO_RIGHT);
else
Log.e("SwipeDetector error","please pass SwipeDetector.onSwipeEvent Interface instance");
}
public void onTopToBottomSwipe(){
if(swipeEventListener!=null)
swipeEventListener.SwipeEventDetected(v,SwipeTypeEnum.TOP_TO_BOTTOM);
else
Log.e("SwipeDetector error","please pass SwipeDetector.onSwipeEvent Interface instance");
}
public void onBottomToTopSwipe(){
if(swipeEventListener!=null)
swipeEventListener.SwipeEventDetected(v,SwipeTypeEnum.BOTTOM_TO_TOP);
else
Log.e("SwipeDetector error","please pass SwipeDetector.onSwipeEvent Interface instance");
}
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN: {
downX = event.getX();
downY = event.getY();
return true;
}
case MotionEvent.ACTION_UP: {
upX = event.getX();
upY = event.getY();
float deltaX = downX - upX;
float deltaY = downY - upY;
//HORIZONTAL SCROLL
if(Math.abs(deltaX) > Math.abs(deltaY))
{
if(Math.abs(deltaX) > min_distance){
// left or right
if(deltaX < 0)
{
this.onLeftToRightSwipe();
return true;
}
if(deltaX > 0) {
this.onRightToLeftSwipe();
return true;
}
}
else {
//not long enough swipe...
return false;
}
}
//VERTICAL SCROLL
else
{
if(Math.abs(deltaY) > min_distance){
// top or down
if(deltaY < 0)
{ this.onTopToBottomSwipe();
return true;
}
if(deltaY > 0)
{ this.onBottomToTopSwipe();
return true;
}
}
else {
//not long enough swipe...
return false;
}
}
return true;
}
}
return false;
}
public interface onSwipeEvent
{
public void SwipeEventDetected(View v, SwipeTypeEnum SwipeType);
}
public SwipeDetector setMinDistanceInPixels(int min_distance)
{
this.min_distance=min_distance;
return this;
}
public enum SwipeTypeEnum
{
RIGHT_TO_LEFT,LEFT_TO_RIGHT,TOP_TO_BOTTOM,BOTTOM_TO_TOP
}
}
and this is a use example:
filters_container=(RelativeLayout)root.findViewById(R.id.filters_container);
new SwipeDetector(filters_container).setOnSwipeListener(new SwipeDetector.onSwipeEvent() {
@Override
public void SwipeEventDetected(View v, SwipeDetector.SwipeTypeEnum swipeType) {
if(swipeType==SwipeDetector.SwipeTypeEnum.LEFT_TO_RIGHT)
getActivity().onBackPressed();
}
});
In some cases you would like to detect the swipe gestures on a container and pass down the touch Events to the childs so in that case you can create a Custom View group, lets say RelativeLayout and override onInterceptTouchEvent , and there you can detect the swipe event without blocking the pass of Touch Event to your child views,for Example:
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.RelativeLayout;
public class SwipeDetectRelativeLayout extends RelativeLayout {
private float x1,x2;
static final int MIN_DISTANCE=150;
private onSwipeEventDetected mSwipeDetectedListener;
public SwipeDetectRelativeLayout(Context context) {
super(context);
}
public SwipeDetectRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SwipeDetectRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch(ev.getAction())
{
case MotionEvent.ACTION_DOWN:
x1 = ev.getX();
break;
case MotionEvent.ACTION_UP:
x2 = ev.getX();
float deltaX = x2 - x1;
if (Math.abs(deltaX) > MIN_DISTANCE)
{
//swiping right to left
if(deltaX<0)
{
if(mSwipeDetectedListener!=null)
mSwipeDetectedListener.swipeEventDetected();
}
}
break;
}
return super.onInterceptTouchEvent(ev);
}
public interface onSwipeEventDetected
{
public void swipeEventDetected();
}
public void registerToSwipeEvents(onSwipeEventDetected listener)
{
this.mSwipeDetectedListener=listener;
}
}
This will return pure class name even when using namespace:
echo substr(strrchr(__CLASS__, "\\"), 1);
Another way by using ajax method:
View:
@Html.TextBox("txtValue", null, new { placeholder = "Input value" })
<input type="button" value="Start" id="btnStart" />
<script>
$(function () {
$('#btnStart').unbind('click');
$('#btnStart').on('click', function () {
$.ajax({
url: "/yourControllerName/yourMethod",
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: JSON.stringify({
txtValue: $("#txtValue").val()
}),
async: false
});
});
});
</script>
Controller:
[HttpPost]
public EmptyResult YourMethod(string txtValue)
{
// do what you want with txtValue
...
}
record = int(input("Enter the student record need to add :"))
stud_data={}
for i in range(0,record):
Name = input("Enter the student name :").split()
Age = input("Enter the {} age :".format(Name))
Grade = input("Enter the {} grade :".format(Name)).split()
Nam_key = Name[0]
Age_value = Age[0]
Grade_value = Grade[0]
stud_data[Nam_key] = {Age_value,Grade_value}
print(stud_data)
I might be a bit late to answer this but this will be useful for new people looking for this answer.
The answers above are good, but to have a perfect video background you have to check at the aspect ratio as the video might cut or the canvas around get deformed when resizing the screen or using it on different screen sizes.
I got into this issue not long ago and I found the solution using media queries.
Here is a tutorial that I wrote on how to create a Fullscreen Video Background with only CSS
I will add the code here as well:
HTML:
<div class="videoBgWrapper">
<video loop muted autoplay poster="img/videoframe.jpg" class="videoBg">
<source src="videosfolder/video.webm" type="video/webm">
<source src="videosfolder/video.mp4" type="video/mp4">
<source src="videosfolder/video.ogv" type="video/ogg">
</video>
</div>
CSS:
.videoBgWrapper {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
overflow: hidden;
z-index: -100;
}
.videoBg{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
@media (min-aspect-ratio: 16/9) {
.videoBg{
width: 100%;
height: auto;
}
}
@media (max-aspect-ratio: 16/9) {
.videoBg {
width: auto;
height: 100%;
}
}
I hope you find it useful.
Eclipse > Source > Generate Getters and Setters
For those who want to just copy and paste the fastest implementation of shift, there is a benchmark and conclusion(see the end). In addition, I introduce fill_value parameter and fix some bugs.
import numpy as np
import timeit
# enhanced from IronManMark20 version
def shift1(arr, num, fill_value=np.nan):
arr = np.roll(arr,num)
if num < 0:
arr[num:] = fill_value
elif num > 0:
arr[:num] = fill_value
return arr
# use np.roll and np.put by IronManMark20
def shift2(arr,num):
arr=np.roll(arr,num)
if num<0:
np.put(arr,range(len(arr)+num,len(arr)),np.nan)
elif num > 0:
np.put(arr,range(num),np.nan)
return arr
# use np.pad and slice by me.
def shift3(arr, num, fill_value=np.nan):
l = len(arr)
if num < 0:
arr = np.pad(arr, (0, abs(num)), mode='constant', constant_values=(fill_value,))[:-num]
elif num > 0:
arr = np.pad(arr, (num, 0), mode='constant', constant_values=(fill_value,))[:-num]
return arr
# use np.concatenate and np.full by chrisaycock
def shift4(arr, num, fill_value=np.nan):
if num >= 0:
return np.concatenate((np.full(num, fill_value), arr[:-num]))
else:
return np.concatenate((arr[-num:], np.full(-num, fill_value)))
# preallocate empty array and assign slice by chrisaycock
def shift5(arr, num, fill_value=np.nan):
result = np.empty_like(arr)
if num > 0:
result[:num] = fill_value
result[num:] = arr[:-num]
elif num < 0:
result[num:] = fill_value
result[:num] = arr[-num:]
else:
result[:] = arr
return result
arr = np.arange(2000).astype(float)
def benchmark_shift1():
shift1(arr, 3)
def benchmark_shift2():
shift2(arr, 3)
def benchmark_shift3():
shift3(arr, 3)
def benchmark_shift4():
shift4(arr, 3)
def benchmark_shift5():
shift5(arr, 3)
benchmark_set = ['benchmark_shift1', 'benchmark_shift2', 'benchmark_shift3', 'benchmark_shift4', 'benchmark_shift5']
for x in benchmark_set:
number = 10000
t = timeit.timeit('%s()' % x, 'from __main__ import %s' % x, number=number)
print '%s time: %f' % (x, t)
benchmark result:
benchmark_shift1 time: 0.265238
benchmark_shift2 time: 0.285175
benchmark_shift3 time: 0.473890
benchmark_shift4 time: 0.099049
benchmark_shift5 time: 0.052836
shift5 is winner! It's OP's third solution.
If you are using Bootstrap 3.3.x then use this code (you need to add class name carousel-fade to your carousel).
.carousel-fade .carousel-inner .item {
-webkit-transition-property: opacity;
transition-property: opacity;
}
.carousel-fade .carousel-inner .item,
.carousel-fade .carousel-inner .active.left,
.carousel-fade .carousel-inner .active.right {
opacity: 0;
}
.carousel-fade .carousel-inner .active,
.carousel-fade .carousel-inner .next.left,
.carousel-fade .carousel-inner .prev.right {
opacity: 1;
}
.carousel-fade .carousel-inner .next,
.carousel-fade .carousel-inner .prev,
.carousel-fade .carousel-inner .active.left,
.carousel-fade .carousel-inner .active.right {
left: 0;
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
.carousel-fade .carousel-control {
z-index: 2;
}
[[UIApplication sharedApplication].windows.lastObject addSubview:myView];
I ended up here and my issue was that I was querying for
{$not: {email: /@domain.com/}}
instead of
{email: {$not: /@domain.com/}}
Static variable in a header file:
say 'common.h'
has
static int zzz;
This variable 'zzz'
has internal linkage (This same variable can not be accessed in other translation units). Each translation unit which includes 'common.h'
has it's own unique object of name 'zzz'
.
Static variable in a class:
Static variable in a class is not a part of the subobject of the class. There is only one copy of a static data member shared by all the objects of the class.
$9.4.2/6 - "Static data members of a class in namespace scope have external linkage (3.5).A local class shall not have static data members."
So let's say 'myclass.h'
has
struct myclass{
static int zzz; // this is only a declaration
};
and myclass.cpp
has
#include "myclass.h"
int myclass::zzz = 0 // this is a definition,
// should be done once and only once
and "hisclass.cpp"
has
#include "myclass.h"
void f(){myclass::zzz = 2;} // myclass::zzz is always the same in any
// translation unit
and "ourclass.cpp"
has
#include "myclass.h"
void g(){myclass::zzz = 2;} // myclass::zzz is always the same in any
// translation unit
So, class static members are not limited to only 2 translation units. They need to be defined only once in any one of the translation units.
Note: usage of 'static' to declare file scope variable is deprecated and unnamed namespace is a superior alternate
Obviously '12/01/2012 13:16:32.000' doesn't match 'DD-MON-YYYY hh24:mi' format.
Update:
You need 'MM/DD/YYYY hh24:mi:ss.ff' format and to use TO_TIMESTAMP instead of TO_DATE cause dates don't hold millis in oracle.
When you reference Range like that it's called an unqualified reference because you don't specifically say which sheet the range is on. Unqualified references are handled by the "_Global" object that determines which object you're referring to and that depends on where your code is.
If you're in a standard module, unqualified Range will refer to Activesheet. If you're in a sheet's class module, unqualified Range will refer to that sheet.
inputTemplateContent is a variable that contains a reference to a range, probably a named range. If you look at the RefersTo property of that named range, it likely points to a sheet other than the Activesheet at the time the code executes.
The best way to fix this is to avoid unqualified Range references by specifying the sheet. Like
With ThisWorkbook.Worksheets("Template")
.Range(inputTemplateHeader).Value = NO_ENTRY
.Range(inputTemplateContent).Value = NO_ENTRY
End With
Adjust the workbook and worksheet references to fit your particular situation.
If indeed the goal is to see if a string contains the actual space character (as described in the title), as opposed to any other sort of whitespace characters, you can use:
string s = "Hello There";
bool fHasSpace = s.Contains(" ");
If you're looking for ways to detect whitespace, there's several great options below.
You don't need a generate bock if you want all the bits of temp
assigned in the same always block.
parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
always @(posedge sysclk) begin
for (integer c=0; c<ROWBITS; c=c+1) begin: test
temp[c] <= 1'b0;
end
end
Alternatively, if your simulator supports IEEE 1800 (SytemVerilog), then
parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
always @(posedge sysclk) begin
temp <= '0; // fill with 0
end
end
I did this in MonoTouch in the following method, I'm sure a pure Obj-C based approach wouldn't be too different. I used this inside a class which had changing URLs at times which is why I just didn't put it in a if/elseif statement.
NSString *myUrls = @"fb://profile/100000369031300|http://www.facebook.com/ytn3rd";
NSArray *urls = [myUrls componentsSeparatedByString:@"|"];
for (NSString *url in urls){
NSURL *nsurl = [NSURL URLWithString:url];
if ([[UIApplication sharedApplication] canOpenURL:nsurl]){
[[UIApplication sharedApplication] openURL:nsurl];
break;
}
}
The break is not always called before your app changes to Safari/Facebook. I assume your program will halt there and call it when you come back to it.
The bitfield approach has other advantages in the embedded arena. You can define a struct that maps directly onto the bits in a particular hardware register.
struct HwRegister {
unsigned int errorFlag:1; // one-bit flag field
unsigned int Mode:3; // three-bit mode field
unsigned int StatusCode:4; // four-bit status code
};
struct HwRegister CR3342_AReg;
You need to be aware of the bit packing order - I think it's MSB first, but this may be implementation-dependent. Also, verify how your compiler handlers fields crossing byte boundaries.
You can then read, write, test the individual values as before.
Accessing package variables in a Script Component (of a Data Flow Task) is not the same as accessing package variables in a Script Task. For a Script Component, you first need to open the Script Transformation Editor (right-click on the component and select "Edit..."). In the Custom Properties section of the Script tab, you can enter (or select) the properties you want to make available to the script, either on a read-only or read-write basis: Then, within the script itself, the variables will be available as strongly-typed properties of the Variables object:
// Modify as necessary
public override void PreExecute()
{
base.PreExecute();
string thePath = Variables.FilePath;
// Do something ...
}
public override void PostExecute()
{
base.PostExecute();
string theNewValue = "";
// Do something to figure out the new value...
Variables.FilePath = theNewValue;
}
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
string thePath = Variables.FilePath;
// Do whatever needs doing here ...
}
One important caveat: if you need to write to a package variable, you can only do so in the PostExecute() method.
Regarding the code snippet:
IDTSVariables100 varCollection = null;
this.VariableDispenser.LockForRead("User::FilePath");
string XlsFile;
XlsFile = varCollection["User::FilePath"].Value.ToString();
varCollection
is initialized to null and never set to a valid value. Thus, any attempt to dereference it will fail.
If running on Windows try running R or R Studio as administrator to avoid Windows OS file system constraints.
It works great for both known and unknown height elements. Make sure to set the outer div to height: 100%;
and reset the default margin
on body
. See the browser support tables.
html, body {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
height: 100%;_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
}_x000D_
.header, .footer {_x000D_
background: silver;_x000D_
}_x000D_
.content {_x000D_
flex: 1;_x000D_
overflow: auto;_x000D_
background: pink;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="header">Header</div>_x000D_
<div class="content">_x000D_
<div style="height:1000px;">Content</div>_x000D_
</div>_x000D_
<div class="footer">Footer</div>_x000D_
</div>
_x000D_
For both known and unknown height elements. It also works in legacy browsers including IE8.
html, body {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
display: table;_x000D_
}_x000D_
.header, .content, .footer {_x000D_
display: table-row;_x000D_
}_x000D_
.header, .footer {_x000D_
background: silver;_x000D_
}_x000D_
.inner {_x000D_
display: table-cell;_x000D_
}_x000D_
.content .inner {_x000D_
height: 100%;_x000D_
position: relative;_x000D_
background: pink;_x000D_
}_x000D_
.scrollable {_x000D_
position: absolute;_x000D_
left: 0; right: 0;_x000D_
top: 0; bottom: 0;_x000D_
overflow: auto;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="header">_x000D_
<div class="inner">Header</div>_x000D_
</div>_x000D_
<div class="content">_x000D_
<div class="inner">_x000D_
<div class="scrollable">_x000D_
<div style="height:1000px;">Content</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="footer">_x000D_
<div class="inner">Footer</div>_x000D_
</div>_x000D_
</div>
_x000D_
calc()
If header and footer are fixed height, you can use CSS calc()
.
html, body {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
height: 100%;_x000D_
}_x000D_
.header, .footer {_x000D_
height: 50px;_x000D_
background: silver;_x000D_
}_x000D_
.content {_x000D_
height: calc(100% - 100px);_x000D_
overflow: auto;_x000D_
background: pink;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="header">Header</div>_x000D_
<div class="content">_x000D_
<div style="height:1000px;">Content</div>_x000D_
</div>_x000D_
<div class="footer">Footer</div>_x000D_
</div>
_x000D_
If the header and footer are known height, and they are also percentage you can just do the simple math making them together of 100% height.
html, body {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
height: 100%;_x000D_
}_x000D_
.header, .footer {_x000D_
height: 10%;_x000D_
background: silver;_x000D_
}_x000D_
.content {_x000D_
height: 80%;_x000D_
overflow: auto;_x000D_
background: pink;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="header">Header</div>_x000D_
<div class="content">_x000D_
<div style="height:1000px;">Content</div>_x000D_
</div>_x000D_
<div class="footer">Footer</div>_x000D_
</div>
_x000D_
In my situation this helped:
Before proceeding to execute these commands close all VS Code instances.
clean cache with
npm cache clean --force
install the latest version of npm globally as admin:
npm install -g npm@latest --force
clean cache with
npm cache clean --force
Try to install your component once again.
I hope this works for others, if not you may also try temporarily disabling antivirus software before trying again.
Use json_decode to transform your JSON into a PHP array. Example:
$json = '{"a":"b"}';
$array = json_decode($json, true);
echo $array['a']; // b
Configure The "php.ini" File
First, ensure that PHP is configured to allow file uploads. In your "php.ini" file, search for the file_uploads directive, and set it to On:
file_uploads = On
Create The HTML Form
Next, create an HTML form that allow users to choose the image file they want to upload:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
Some rules to follow for the HTML form above: Make sure that the form uses method="post" The form also needs the following attribute: enctype="multipart/form-data". It specifies which content-type to use when submitting the form Without the requirements above, the file upload will not work. Other things to notice: The type="file" attribute of the tag shows the input field as a file-select control, with a "Browse" button next to the input control The form above sends data to a file called "upload.php", which we will create next.
Create The Upload File PHP Script
The "upload.php" file contains the code for uploading a file:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
You will need have to download InternetExplorer driver executable on your system, download it from the source (http://code.google.com/p/selenium/downloads/list) after download unzip it and put on the place of somewhere in your computer. In my example, I will place it to D:\iexploredriver.exe
Then you have write below code in your eclipse main class
System.setProperty("webdriver.ie.driver", "D:/iexploredriver.exe");
WebDriver driver = new InternetExplorerDriver();
set intersection
and dict comprehension
can be used here
# the dictionary
d = {1:2, 3:4, 5:6, 7:8}
# the subset of keys I'm interested in
l = (1,5)
>>>{key:d[key] for key in set(l) & set(d)}
{1: 2, 5: 6}
Another approach would be to use a list comprehension with a condition checking for lengths. Below is a demonstration:
# input list of strings that we want to prepend zeros
In [71]: list_of_str = ["101010", "10101010", "11110", "0000"]
# prepend zeros to make each string to length 8, if length of string is less than 8
In [83]: ["0"*(8-len(s)) + s if len(s) < desired_len else s for s in list_of_str]
Out[83]: ['00101010', '10101010', '00011110', '00000000']
I faced the same problem of brew command not found while installing Homebrew on mac BigSur with M1 processor.
I - Install XCode if it is not installed yet.
II - Select terminal.app in Finder.
III - RMB click on Terminal and select "Get Info"
IV - Select Open using Rosetta checkbox.
V - Close any open Terminal windows.
VI - Open a new Terminal window and install Hobebrew:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
VII - Test Homebrew installation.
IIX - Uncheck Open using Rosetta checkbox.
catch (WhateverException e) {
throw e;
}
will simply rethrow the exception you've caught (obviously the surrounding method has to permit this via its signature etc.). The exception will maintain the original stack trace.
The formula that you have is fine. But, after entering it, you need to hit Control + Shift + Enter in order to apply it to the range of values. Specifically:
Select the range of values in the destination sheet.
Enter into the formula panel your desired formula, e.g. =Sheet2!A1:F1
Hit Control + Shift + Enter to apply the formula to the range.
Triggering change events on arbitrary elements creates dependencies between components which are hard to reason about. It's better to stick with React's one-way data flow.
There is no simple snippet to trigger React's change event. The logic is implemented in ChangeEventPlugin.js and there are different code branches for different input types and browsers. Moreover, the implementation details vary across versions of React.
I have built react-trigger-change that does the thing, but it is intended to be used for testing, not as a production dependency:
let node;
ReactDOM.render(
<input
onChange={() => console.log('changed')}
ref={(input) => { node = input; }}
/>,
mountNode
);
reactTriggerChange(node); // 'changed' is logged
Scala evolved out of a pure functional language known as Funnel and represents a clean-room implementation of almost all Java's syntax, differing only where a clear improvement could be made or where it would compromise the functional nature of the language. Such differences include singleton objects instead of static methods, and type inference.
Much of this was based on Martin Odersky's prior work with the Pizza language. The OO/FP integration goes far beyond mere closures and has led to the language being described as post-functional.
Despite this, it's the closest to Java in many ways. Mainly due to a combination of OO support and static typing, but also due to a explicit goal in the language design that it should integrate very tightly with Java.
Groovy explicitly tackles two of Java's biggest criticisms by
It's perhaps syntactically closest to Java, not offering some of the richer functional constructs that Clojure and Scala provide, but still offering a definite evolutionary improvement - especially for writing script-syle programs.
Groovy has the strongest commercial backing of the three languages, mostly via springsource.
Clojure is a functional language in the LISP family, it's also dynamically typed.
Features such as STM support give it some of the best out-of-the-box concurrency support, whereas Scala requires a 3rd-party library such as Akka to duplicate this.
Syntactically, it's also the furthest of the three languages from typical Java code.
I also have to disclose that I'm most acquainted with Scala :)
SELECT group,subGroup,COUNT(*) FROM tablename GROUP BY group,subgroup
I don't believe this is possible - there is no ability to set the timezone on a Date object after it is created.
And in a way this makes sense - conceptually (if perhaps not in implementation); per http://en.wikipedia.org/wiki/Unix_timestamp (emphasis mine):
Unix time, or POSIX time, is a system for describing instants in time, defined as the number of seconds elapsed since midnight Coordinated Universal Time (UTC) of Thursday, January 1, 1970.
Once you've constructed one it will represent a certain point in "real" time. The time zone is only relevant when you want to convert that abstract time point into a human-readable string.
Thus it makes sense you would only be able to change the actual time the Date represents in the constructor. Sadly it seems that there is no way to pass in an explicit timezone - and the constructor you are calling (arguably correctly) translates your "local" time variables into GMT when it stores them canonically - so there is no way to use the int, int, int
constructor for GMT times.
On the plus side, it's trivial to just use the constructor that takes a String instead. You don't even have to convert the numeric month into a String (on Firefox at least), so I was hoping a naive implementation would work. However, after trying it out it works successfully in Firefox, Chrome, and Opera but fails in Konqueror ("Invalid Date") , Safari ("Invalid Date") and IE ("NaN"). I suppose you'd just have a lookup array to convert the month to a string, like so:
var months = [ '', 'January', 'February', ..., 'December'];
function createGMTDate(xiYear, xiMonth, xiDate) {
return new Date(months[xiMonth] + ' ' + xiDate + ', ' + xiYear + ' 00:00:00 GMT');
}
I found a faster way of embedding:
Based off your code, i created this Fiddle
You need to use
var cb = document.getElementsByName('field206451')[0];
var label = document.getElementsByName('label206451')[0];
if you want to use name attributes then you have to take the index since it is a list of items, not just a single one. Everything else worked good.
You can only do this with an abstract class, not with an interface.
Declare Rectangle
as an abstract class
instead of an interface
and declare the methods that must be implemented by the sub-class as public abstract
. Then class Tile
extends class Rectangle
and must implement the abstract methods from Rectangle
.
Simply use the .rules('add')
method immediately after creating the element...
var filenumber = 1;
$("#AddFile").click(function () { //User clicks button #AddFile
// create the new input element
$('<li><input type="file" name="FileUpload' + filenumber + '" id="FileUpload' + filenumber + '" /> <a href="#" class="RemoveFileUpload">Remove</a></li>').prependTo("#FileUploader");
// declare the rule on this newly created input field
$('#FileUpload' + filenumber).rules('add', {
required: true, // <- with this you would not need 'required' attribute on input
accept: "image/jpeg, image/pjpeg"
});
filenumber++; // increment counter for next time
return false;
});
You'll still need to use .validate()
to initialize the plugin within a DOM ready handler.
You'll still need to declare rules for your static elements using .validate()
. Whatever input elements that are part of the form when the page loads... declare their rules within .validate()
.
You don't need to use .each()
, when you're only targeting ONE element with the jQuery selector attached to .rules()
.
You don't need the required
attribute on your input element when you're declaring the required
rule using .validate()
or .rules('add')
. For whatever reason, if you still want the HTML5 attribute, at least use a proper format like required="required"
.
Working DEMO: http://jsfiddle.net/8dAU8/5/
You can get clean and clear solutions by building the appropriate predicates as helper functions. In other words, use the Python set-builder notation the same way you would write the answer with regular mathematics set-notation.
The whole idea behind set comprehensions is to let us write and reason in code the same way we do mathematics by hand.
With an appropriate predicate in hand, problem 1 simplifies to:
low_primes = {x for x in range(1, 100) if is_prime(x)}
And problem 2 simplifies to:
low_prime_pairs = {(x, x+2) for x in range(1,100,2) if is_prime(x) and is_prime(x+2)}
Note how this code is a direct translation of the problem specification, "A Prime Pair is a pair of consecutive odd numbers that are both prime."
P.S. I'm trying to give you the correct problem solving technique without actually giving away the answer to the homework problem.
First time scroll when entering in recycler view first time then use
linearLayoutManager.scrollToPositionWithOffset(messageHashMap.size()-1
put in minus for scroll down for scroll up put in positive value);
if the view is very big in height then scrolltoposition particular offset is used for the top of view then you use
int overallXScroldl =chatMessageBinding.rvChat.computeVerticalScrollOffset();
chatMessageBinding.rvChat.smoothScrollBy(0, Math.abs(overallXScroldl));
STATIC_ROOT
linestatic
folder in different directory. For suppose the directory is: project\static
Now update: STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'project/static/')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Whatever you do the main point is STATICFILES_DIRS
and STATIC_ROOT
should not contain same directory.
I know it's been a long time but hope the new buddies can get help from it
This error can also be caused by nested <form>
tag in the master page which is not allowed.
<form id="someid"></form>
This will likely be the cause if you have picked up a template and copying the code from somewhere as it.
You have to break the nesting of <form>
tag. The following should become
<form method="" name="form1">
<form method="" name="form2>
</form>
</form>
should become
<form method="" name="form1">
</form>
<form method="" name="form2>
</form>
I think this should work, irrespective of how often and when you run it ...
date -d "yesterday 13:00" '+%Y-%m-%d'
this is to further clarify JD Isaaks answer ...
The problem you run into often is that you are using php to output html from many different php sources, and those sources are often, for whatever reason, outputting via different ways.
Sometimes you have literal html content that you want to directly output to the browser; other times the output is being dynamically created (server-side).
The dynamic content is always(?) going to be a string. Now you have to combine this stringified dynamic html with any literal, direct-to-display html ... into one meaningful html node structure.
This usually forces the developer to wrap all that direct-to-display content into a string (as JD Isaak was discussing) so that it can be properly delivered/inserted in conjunction with the dynamic html ... even though you don't really want it wrapped.
But by using ob_## methods you can avoid that string-wrapping mess. The literal content is, instead, output to the buffer. Then in one easy step the entire contents of the buffer (all your literal html), is concatenated into your dynamic-html string.
(My example shows literal html being output to the buffer, which is then added to a html-string ... look also at JD Isaaks example to see string-wrapping-of-html).
<?php // parent.php
//---------------------------------
$lvs_html = "" ;
$lvs_html .= "<div>html</div>" ;
$lvs_html .= gf_component_assembler__without_ob( ) ;
$lvs_html .= "<div>more html</div>" ;
$lvs_html .= "----<br/>" ;
$lvs_html .= "<div>html</div>" ;
$lvs_html .= gf_component_assembler__with_ob( ) ;
$lvs_html .= "<div>more html</div>" ;
echo $lvs_html ;
// 02 - component contents
// html
// 01 - component header
// 03 - component footer
// more html
// ----
// html
// 01 - component header
// 02 - component contents
// 03 - component footer
// more html
//---------------------------------
function gf_component_assembler__without_ob( )
{
$lvs_html = "<div>01 - component header</div>" ; // <table ><tr>" ;
include( "component_contents.php" ) ;
$lvs_html .= "<div>03 - component footer</div>" ; // </tr></table>" ;
return $lvs_html ;
} ;
//---------------------------------
function gf_component_assembler__with_ob( )
{
$lvs_html = "<div>01 - component header</div>" ; // <table ><tr>" ;
ob_start();
include( "component_contents.php" ) ;
$lvs_html .= ob_get_clean();
$lvs_html .= "<div>03 - component footer</div>" ; // </tr></table>" ;
return $lvs_html ;
} ;
//---------------------------------
?>
<!-- component_contents.php -->
<div>
02 - component contents
</div>
springframework library Check whether the given String is empty.
f(StringUtils.isEmpty(str)) {
//.... String is blank or null
}
Use the DateTime.ToUniversalTime
method.
The function add() returns the old date, but changes the original date :)
startdate = "20.03.2014";
var new_date = moment(startdate, "DD.MM.YYYY");
new_date.add(5, 'days');
alert(new_date);
In Python3 iteritems()
is no longer supported
Use .items
for field, possible_values in fields.items():
print(field, possible_values)
Empty
refers to a variable being at its default value. So if you check if a cell with a value of 0 = Empty
then it would return true.
IsEmpty
refers to no value being initialized.
In a nutshell, if you want to see if a cell is empty (as in nothing exists in its value) then use IsEmpty
. If you want to see if something is currently in its default value then use Empty
.
Perhaps you don't have to include the single quotes:
curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/&fileName=1.doc"
Update: Reading curl's manual, you could actually separate both fields with two --data:
curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/" --data "fileName=1.doc"
You could also try --data-binary:
curl --request POST 'http://localhost/Service' --data-binary "path=/xyz/pqr/test/" --data-binary "fileName=1.doc"
And --data-urlencode:
curl --request POST 'http://localhost/Service' --data-urlencode "path=/xyz/pqr/test/" --data-urlencode "fileName=1.doc"
If the message is:
The library com.google.android.gms:play-services-measurement-base is being requested by various other libraries at [[15.0.4,15.0.4]], but resolves to 15.0.2. Disable the plugin and check your dependencies tree using ./gradlew :app:dependencies.
Change the version of all the play services libraries you are using to the one you need (15.0.2 in this case) could solve the problem.
In my case, I've changed:
implementation 'com.google.android.gms:play-services-base:+' -> implementation 'com.google.android.gms:play-services-base:15.0.2'
implementation 'com.google.android.gms:play-services-location:+' -> implementation 'com.google.android.gms:play-services-location:15.0.2'
implementation 'com.google.android.gms:play-services-maps:+' -> implementation 'com.google.android.gms:play-services-maps:15.0.2'
implementation 'com.google.android.gms:play-services-auth:+' -> implementation 'com.google.android.gms:play-services-auth:15.0.2'
implementation 'com.google.android.gms:play-services-places:+' -> implementation 'com.google.android.gms:play-services-places:15.0.2'
If double quotes do not solve the issue then try e.g.
dir /X ~1 c:\
to get a list of alternative file or directory names. Example output:
11/09/2014 12:54 AM 8,065 DEFAUL~1.XML Default Desktop Policy.xml
06/12/2014 03:49 PM <DIR> PROGRA~1 Program Files
10/12/2014 12:46 AM <DIR> PROGRA~2 Program Files (x86)
Now use the short 8 character file or folder name in the 5th column, e.g. PROGRA~1 or DEFAUL~1.XML, in your commands. For instance:
set JAVA_HOME=c:\PROGRA~1\Java\jdk1.6.0_45
In both cases it first calculates value, but in post-increment it holds old value and after calculating returns it
++a
a++
No, You cannot publish on Github pages. Try Heroku or something like that. You can only deploy static sites on github pages. You can't deploy a server on github pages.
It is just not a valid Java syntax. You can do
names = new String[] {"Ankit","Bohra","Xyz"};
Maven working terminology having phases and goals.
Phase:Maven phase is a set of action which is associated with 2 or 3 goals
exmaple:- if you run mvn clean
this is the phase will execute the goal mvn clean:clean
Goal:Maven goal bounded with the phase
for reference http://books.sonatype.com/mvnref-book/reference/lifecycle-sect-structure.html
There is a difference between $(this)
and event.target
, and quite a significant one. While this
(or event.currentTarget
, see below) always refers to the DOM element the listener was attached to, event.target
is the actual DOM element that was clicked. Remember that due to event bubbling, if you have
<div class="outer">
<div class="inner"></div>
</div>
and attach click listener to the outer div
$('.outer').click( handler );
then the handler
will be invoked when you click inside the outer div as well as the inner one (unless you have other code that handles the event on the inner div and stops propagation).
In this example, when you click inside the inner div, then in the handler
:
this
refers to the .outer
DOM element (because that's the object to which the handler was attached)event.currentTarget
also refers to the .outer
element (because that's the current target element handling the event)event.target
refers to the .inner
element (this gives you the element where the event originated)The jQuery wrapper $(this)
only wraps the DOM element in a jQuery object so you can call jQuery functions on it. You can do the same with $(event.target)
.
Also note that if you rebind the context of this
(e.g. if you use Backbone it's done automatically), it will point to something else. You can always get the actual DOM element from event.currentTarget
.
I also encuntered the same in S4. I've tested the app in Galaxy Grand , HTC , Sony Experia but got only in s4. You can ignore it as its not related to your app.
I have faced issue like my main page index.jsp contains the below line but eventhough rendering was not proper in IE. Found the issue and I have added the code in all the files which I included in index.jsp. Hurray! it worked.
So You need to add below code in all the files which you include into the page otherwise it wont work.
<!doctype html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
</head>
if you want to draw circle on button then this code might be use full. else if you want to draw a circle on other control just change the name of control and also event. like here event button is called. if you want to draw this circle in group box call the Groupbox event. regards
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.button1.Location = new Point(108, 12);
// this.Paint += new PaintEventHandler(Form1_Paint);
this.button1.Paint += new PaintEventHandler(button1_Paint);
}
void button1_Paint(object sender, PaintEventArgs e)
{
Graphics g = this.button1.CreateGraphics();
Pen pen = new Pen(Color.Red);
g.DrawEllipse(pen, 10, 10, 20, 20);
}
}
There is an alternative - you can provide a member of type XmlSerializerNamespaces in the type to be serialized. Decorate it with the XmlNamespaceDeclarations attribute. Add the namespace prefixes and URIs to that member. Then, any serialization that does not explicitly provide an XmlSerializerNamespaces will use the namespace prefix+URI pairs you have put into your type.
Example code, suppose this is your type:
[XmlRoot(Namespace = "urn:mycompany.2009")]
public class Person {
[XmlAttribute]
public bool Known;
[XmlElement]
public string Name;
[XmlNamespaceDeclarations]
public XmlSerializerNamespaces xmlns;
}
You can do this:
var p = new Person
{
Name = "Charley",
Known = false,
xmlns = new XmlSerializerNamespaces()
}
p.xmlns.Add("",""); // default namespace is emoty
p.xmlns.Add("c", "urn:mycompany.2009");
And that will mean that any serialization of that instance that does not specify its own set of prefix+URI pairs will use the "p" prefix for the "urn:mycompany.2009" namespace. It will also omit the xsi and xsd namespaces.
The difference here is that you are adding the XmlSerializerNamespaces to the type itself, rather than employing it explicitly on a call to XmlSerializer.Serialize(). This means that if an instance of your type is serialized by code you do not own (for example in a webservices stack), and that code does not explicitly provide a XmlSerializerNamespaces, that serializer will use the namespaces provided in the instance.
I know this question is old but the accepted answer does not work anymore and since this is the fist link on google search i'll tell how i solved this problem.
for eclipse using ubuntu:
go to Window->Preferences->Ant->Runtime->Select Ant_Home_Entries and click on add external jars then find in file explorer where your jdk is (default is in /usr/lib/jvm/) and in the lib folder of your jdk you will find the tool.jar. select this one and click apply.
try to build your project and things should work!
note: i hadn't used ant for a long time but needed it for ycsb couchbase workload generator (http://www.couchbase.com/wiki/display/couchbase/Load+Generator+Setup) if anyone is/was stuck on this.
// to check if the given string contain alphabets
function isPangram(sentence){
let lowerCased = sentence.toLowerCase();
let letters = "abcdefghijklmnopqrstuvwxyz";
// traditional for loop can also be used
for (let char of letters){
if (!lowerCased.includes(char)) return false;
}
return true;
}
First you should check how many commits you have:
git log
There are two status:
One is that there are only two commits:
For example:
commit A
commit B
(In this case, you can't use git rebase to do) you need to do following.
$ git reset --soft HEAD^1
$ git commit --amend
Another is that there are more than two commits; you want to merge commit C and D.
For example:
commit A
commit B
commit C
commit D
(under this condition, you can use git rebase)
git rebase -i B
And than use "squash" to do. The rest thins is very easy. If you still don't know, please read http://zerodie.github.io/blog/2012/01/19/git-rebase-i/
On top of the answers already given, to open a new tab the javascript command window.open()
can be used.
For example:
# Opens a new tab
self.driver.execute_script("window.open()")
# Switch to the newly opened tab
self.driver.switch_to.window(self.driver.window_handles[1])
# Navigate to new URL in new tab
self.driver.get("https://google.com")
# Run other commands in the new tab here
You're then able to close the original tab as follows
# Switch to original tab
self.driver.switch_to.window(self.driver.window_handles[0])
# Close original tab
self.driver.close()
# Switch back to newly opened tab, which is now in position 0
self.driver.switch_to.window(self.driver.window_handles[0])
Or close the newly opened tab
# Close current tab
self.driver.close()
# Switch back to original tab
self.driver.switch_to.window(self.driver.window_handles[0])
Hope this helps.
How about exporting the variable, but only inside the subshell?:
(export FOO=bar && somecommand someargs | somecommand2)
Keith has a point, to unconditionally execute the commands, do this:
(export FOO=bar; somecommand someargs | somecommand2)
This is the solution I came up with:
import time
from threading import Thread
from threading import Lock
def myfunc(i, mutex):
mutex.acquire(1)
time.sleep(1)
print "Thread: %d" %i
mutex.release()
mutex = Lock()
for i in range(0,10):
t = Thread(target=myfunc, args=(i,mutex))
t.start()
print "main loop %d" %i
Output:
main loop 0
main loop 1
main loop 2
main loop 3
main loop 4
main loop 5
main loop 6
main loop 7
main loop 8
main loop 9
Thread: 0
Thread: 1
Thread: 2
Thread: 3
Thread: 4
Thread: 5
Thread: 6
Thread: 7
Thread: 8
Thread: 9
Updating your Git configuration file directly (if you do not want to memorize fancy commands):
Open your .git/config
file in your favorite text editor. It will be in the folder that you cloned or in the repository that you performed git init
in. Go into that repository. .git
is a hidden folder, and pressing Ctrl + H should show the hidden folder, (ls -a
in terminal).
Below is a sample of the .git/config
file. Copy and paste these lines and be sure to update those lines with your Git information.
[user]
name = Tux
email = [email protected]
username = happy_feet
[remote "origin"]
url = https://github.com/happy_feet/my_code.git
fetch = +refs/heads/*:refs/remotes/origin/*
Change the URL part with the following format for SSH:
url = [email protected]:happy_feet/my_code.git
(The above formats do not change with various Git remote servers like GitHub or Bitbucket. It's the same if you are using Git for version control):
Note: The SSH way of connecting to a remote Git repository will require you to add your public SSH key to your Git remote server (like GitHub or Bitbucket. Search the settings page for SSH keys).
To know how to generate your SSH keys, refer to: Creating SSH keys
From the description and from the reference to the search box in the Ubuntu site, I gather that you actually want an arrowhead character pointing to the right. There are no Unicode characters designed to be used as arrowheads, but some of them may visually resemble an arrowhead.
In particular, if you draw your idea of the character at Shapecatcher.com, you will find many suggestions, such as “>” RIGHT-POINTING ANGLE BRACKET' (U+232A) and “?” MEDIUM RIGHT-POINTING ANGLE BRACKET ORNAMENT (U+276D).
Such characters generally have limited support in fonts, so you would need to carefully write a longish font-family
list or to use a downloadable font. See my Guide to using special characters in HTML.
Especially if the intended use is as a symbol in a search box, as the reference to the Ubuntu page suggests, it is questionable whether you should use a character at all. It’s not really an element of text here; rather, a graphic symbol that accompanies text but isn’t a part of it. So why take all the trouble with using a character (safely), when it isn’t really a character?
Java's Calendar representation is not the best, they are working on it for Java 8. I would advise you to use Joda Time or another similar library.
Here is a quick example using LocalDate from the Joda Time library:
LocalDate localDate = new LocalDate(year, month, day);
Date date = localDate.toDate();
Here you can follow a quick start tutorial.
This code works:
$(".ui-button-text").live(
'hover',
function (ev) {
if (ev.type == 'mouseover') {
$(this).addClass("ui-state-hover");
}
if (ev.type == 'mouseout') {
$(this).removeClass("ui-state-hover");
}
});
If you want to read space separated string, and immediately split the string into an array, you can do this:
var arr = readLine()!.characters.split(" ").map(String.init)
eg.
print("What is your full name?")
var arr = readLine()!.characters.split(" ").map(String.init)
var firstName = ""
var middleName = ""
var lastName = ""
if arr.count > 0 {
firstName = arr[0]
}
if arr.count > 2 {
middleName = arr[1]
lastName = arr[2]
} else if arr.count > 1 {
lastName = arr[1]
}
print("First Name: \(firstName)")
print("Middle Name: \(middleName)")
print("Last Name: \(lastName)")
Why not use a generator instead?
private IEnumerable<string> ReadLogLines(string logPath) {
using(StreamReader reader = File.OpenText(logPath)) {
string line = "";
while((line = reader.ReadLine()) != null) {
yield return line;
}
}
}
Then you can use it like you would use the list:
var logFile = ReadLogLines(LOG_PATH);
foreach(var s in logFile) {
// Do whatever you need
}
Of course, if you need to have a List<string>
, then you will need to keep the entire file contents in memory. There's really no way around that.
Generally speaking, you should not put anything into META-INF yourself. Instead, you should rely upon whatever you use to package up your JAR. This is one of the areas where I think Ant really excels: specifying JAR file manifest attributes. It's very easy to say something like:
<jar ...>
<manifest>
<attribute name="Main-Class" value="MyApplication"/>
</manifest>
</jar>
At least, I think that's easy... :-)
The point is that META-INF should be considered an internal Java meta directory. Don't mess with it! Any files you want to include with your JAR should be placed in some other sub-directory or at the root of the JAR itself.
While @coolscitist's answer worked for me, there is also a way that does not clutter your kernel environment with the complete jupyter package+deps. It is described in the ipython docs and is (I suspect) only necessary if you run the notebook server in a non-base environment.
conda activate name_of_your_kernel_env
conda install ipykernel
python -m ipykernel install --prefix=/home/your_username/.conda/envs/name_of_your_jupyter_server_env --name 'name_of_your_kernel_env'
You can check if it works using
conda activate name_of_your_jupyter_server_env
jupyter kernelspec list
Identify all the fields that could be related to your search and then use a query like:
SELECT * FROM clients
WHERE field1 LIKE '%Mary%'
OR field2 LIKE '%Mary%'
OR field3 LIKE '%Mary%'
OR field4 LIKE '%Mary%'
....
(do that for each field you want to check)
Using LIKE '%Mary%'
instead of = 'Mary'
will look for the fields that contains someCaracters + 'Mary' + someCaracters.
Yes Jython does this, but it may or may not be what you want
I have several projects in a solution. For some of the projects, I previously added the references manually. When I used NuGet to update the WebAPI package, those references were not updated automatically.
I found out that I can either manually update those reference so they point to the v5 DLL inside the Packages folder of my solution or do the following.
string strData = "This is much easier"
int intDelimiterIndx = strData.IndexOf("is");
int intDelimiterLength = "is".Length;
str1 = strData.Substring(0, intDelimiterIndx);
str2 = strData.Substring(intDelimiterIndx + intDelimiterLength, strData.Length - (intDelimiterIndx + intDelimiterLength));
I know I am quite late to post this, but I share similar experience when I learned the ropes of IAP model.
In-app purchase is one of the most comprehensive workflow in iOS implemented by Storekit framework. The entire documentation is quite clear if you patience to read it, but is somewhat advanced in nature of technicality.
To summarize:
1 - Request the products - use SKProductRequest & SKProductRequestDelegate classes to issue request for Product IDs and receive them back from your own itunesconnect store.
These SKProducts should be used to populate your store UI which the user can use to buy a specific product.
2 - Issue payment request - use SKPayment & SKPaymentQueue to add payment to the transaction queue.
3 - Monitor transaction queue for status update - use SKPaymentTransactionObserver Protocol's updatedTransactions method to monitor status:
SKPaymentTransactionStatePurchasing - don't do anything
SKPaymentTransactionStatePurchased - unlock product, finish the transaction
SKPaymentTransactionStateFailed - show error, finish the transaction
SKPaymentTransactionStateRestored - unlock product, finish the transaction
4 - Restore button flow - use SKPaymentQueue's restoreCompletedTransactions to accomplish this - step 3 will take care of the rest, along with SKPaymentTransactionObserver's following methods:
paymentQueueRestoreCompletedTransactionsFinished
restoreCompletedTransactionsFailedWithError
Here is a step by step tutorial (authored by me as a result of my own attempts to understand it) that explains it. At the end it also provides code sample that you can directly use.
Here is another one I created to explain certain things that only text could describe in better manner.
Method 1 : Using jQuery Ajax Get call (partial page update).
Suitable for when you need to retrieve jSon data from database.
Controller's Action Method
[HttpGet]
public ActionResult Foo(string id)
{
var person = Something.GetPersonByID(id);
return Json(person, JsonRequestBehavior.AllowGet);
}
Jquery GET
function getPerson(id) {
$.ajax({
url: '@Url.Action("Foo", "SomeController")',
type: 'GET',
dataType: 'json',
// we set cache: false because GET requests are often cached by browsers
// IE is particularly aggressive in that respect
cache: false,
data: { id: id },
success: function(person) {
$('#FirstName').val(person.FirstName);
$('#LastName').val(person.LastName);
}
});
}
Person class
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Method 2 : Using jQuery Ajax Post call (partial page update).
Suitable for when you need to do partial page post data into database.
Post method is also same like above just replace [HttpPost]
on Action method and type as post
for jquery method.
For more information check Posting JSON Data to MVC Controllers Here
Method 3 : As a Form post scenario (full page update).
Suitable for when you need to save or update data into database.
View
@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{
@Html.TextBoxFor(model => m.Text)
<input type="submit" value="Save" />
}
Action Method
[HttpPost]
public ActionResult SaveData(FormCollection form)
{
// Get movie to update
return View();
}
Method 4 : As a Form Get scenario (full page update).
Suitable for when you need to Get data from database
Get method also same like above just replace [HttpGet]
on Action method and FormMethod.Get
for View's form method.
I hope this will help to you.
If you keep grabbing bits from your data, you might want to use a bitfield. You'll just have to set up a struct and load it with only ones and zeroes:
struct bitfield{
unsigned int bit : 1
}
struct bitfield *bitstream;
then later on load it like this (replacing char with int or whatever data you are loading):
long int i;
int j, k;
unsigned char c, d;
bitstream=malloc(sizeof(struct bitfield)*charstreamlength*sizeof(char));
for (i=0; i<charstreamlength; i++){
c=charstream[i];
for(j=0; j < sizeof(char)*8; j++){
d=c;
d=d>>(sizeof(char)*8-j-1);
d=d<<(sizeof(char)*8-1);
k=d;
if(k==0){
bitstream[sizeof(char)*8*i + j].bit=0;
}else{
bitstream[sizeof(char)*8*i + j].bit=1;
}
}
}
Then access elements:
bitstream[bitpointer].bit=...
or
...=bitstream[bitpointer].bit
All of this is assuming are working on i86/64, not arm, since arm can be big or little endian.
Can you be a bit more specific about what you're trying to do and how you're trying to do it?
If you're attempting to invoke the program using the <exec>
task you might do the following:
<exec executable="name-of-executable">
<arg value="arg0"/>
<arg value="arg1"/>
</exec>
JQuery has solution:
$( "#foo" ).one( "click", function() {
alert( "This will be displayed only once." );
});
equivalent:
$( "#foo" ).on( "click", function( event ) {
alert( "This will be displayed only once." );
$( this ).off( event );
});
Try this:
myfile %>% mutate(V5 = (V1 == 1 & V2 != 4) + 2 * (V2 == 4 & V3 != 1))
giving:
V1 V2 V3 V4 V5
1 1 2 3 5 1
2 2 4 4 1 2
3 1 4 1 1 0
4 4 5 1 3 0
5 5 5 5 4 0
or this:
myfile %>% mutate(V5 = ifelse(V1 == 1 & V2 != 4, 1, ifelse(V2 == 4 & V3 != 1, 2, 0)))
giving:
V1 V2 V3 V4 V5
1 1 2 3 5 1
2 2 4 4 1 2
3 1 4 1 1 0
4 4 5 1 3 0
5 5 5 5 4 0
Suggest you get a better name for your data frame. myfile makes it seem as if it holds a file name.
Above used this input:
myfile <-
structure(list(V1 = c(1L, 2L, 1L, 4L, 5L), V2 = c(2L, 4L, 4L,
5L, 5L), V3 = c(3L, 4L, 1L, 1L, 5L), V4 = c(5L, 1L, 1L, 3L, 4L
)), .Names = c("V1", "V2", "V3", "V4"), class = "data.frame", row.names = c("1",
"2", "3", "4", "5"))
Update 1 Since originally posted dplyr has changed %.%
to %>%
so have modified answer accordingly.
Update 2 dplyr now has case_when
which provides another solution:
myfile %>%
mutate(V5 = case_when(V1 == 1 & V2 != 4 ~ 1,
V2 == 4 & V3 != 1 ~ 2,
TRUE ~ 0))
First is a reference to a pointer, second is a reference to a pointer to a pointer. See also FAQ on how pointers and references differ.
void foo(int*& x, int**& y) {
// modifying x or y here will modify a or b in main
}
int main() {
int val = 42;
int *a = &val;
int **b = &a;
foo(a, b);
return 0;
}
i used this trick
private void lv_TavComEmpty_ColumnClick(object sender, ColumnClickEventArgs e)
{
ListView lv = (ListView)sender;
//propriety SortOrder make me some problem on graphic layout
//i use this tag to set last order
if (lv.Tag == null || (int)lv.Tag > 0)
//if (lv.Sorting == SortOrder.Ascending)
{
ListViewItem[] tmp = lv.Items.Cast<ListViewItem>().OrderBy(t => t.SubItems[e.Column].Text).ToArray();
lv.Items.Clear();
lv.Items.AddRange(tmp);
lv.Tag = -1;
//lv.Sorting = SortOrder.Descending;
}
else
{
ListViewItem[] tmp = lv.Items.Cast<ListViewItem>().OrderByDescending(t => t.SubItems[e.Column].Text).ToArray();
lv.Items.Clear();
lv.Items.AddRange(tmp);
lv.Tag = +1;
//lv.Sorting = SortOrder.Ascending;
}
}
Better use $_SERVER['REQUEST_METHOD']
:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// …
}
If it is inline, the browser should attempt to render it within the browser window. If it cannot, it will resort to an external program, prompting the user.
With attachment, it will immediately go to the user, and not try to load it in the browser, whether it can or not.
I think the best option for you is to enclose both divs by another div. Then you can make it by CSS in the following way:
<html>
<head>
<style>
div.both:hover .image { border: 1px solid blue }
div.both:hover .layer { border: 1px solid blue }
</style>
</head>
<body>
<div class="section">
<div class="both">
<div class="image"><img src="myImage.jpg" /></div>
<div class="layer">Lorem Ipsum</div>
</div>
</div>
</body>
</html>
You need to dynamically allocate your matrix. For instance:
int* mat;
int dimx,dimy;
scanf("%d", &dimx);
scanf("%d", &dimy);
mat = malloc(dimx * dimy * sizeof(int));
This creates a linear array which can hold the matrix. At this point you can decide whether you want to access it column or row first. I would suggest making a quick macro which calculates the correct offset in the matrix.
Further to @Penn's comment, and in case the link breaks, you can also achieve this by setting the Default
property of the button to True
(you can set this in the properties window, open by hitting F4)
That way whenever Return is hit, VBA knows to activate the button's click event. Similarly setting the Cancel
property of a button to True
would cause that button's click event to run whenever ESC key is hit (useful for gracefully exiting the Userform)
Source: Olivier Jacot-Descombes's answer accessible here https://stackoverflow.com/a/22793040/6609896
It sounds like you're going to have to create a new project in Xcode, go into the old directory, and drag all your source files, nibs, and resources into the Xcode files sidebar in the new project. It shouldn't take more than a few minutes, unless you really did a lot of work with custom build settings or targets. Either that, or revert to the last check-in in your source control and manually add any code files which changed between now and then.
Try Fragment, if you don't want any of above.
In your case, we can write
import React, {useState, Fragment} from 'react'
const thisIsMyCopy = Fragment('<p>copy copy copy <strong>strong copy</strong></p>')
render: function() {
return (
<div className="content">{thisIsMyCopy}</div>
);
}
If you using hook want to set it in a state somewhere with any condition
const [thisIsMyCopy, setThisIsMyCopy] = useState(<Fragment><p>copy copy copy <strong>strong copy</strong></p></Fragment>);
1. Installing OpenCV 2.4.3
First, get OpenCV 2.4.3 from sourceforge.net. Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\
.
Wait until all files get extracted. It will create a new directory C:\opencv
which
contains OpenCV header files, libraries, code samples, etc.
Now you need to add the directory C:\opencv\build\x86\vc10\bin
to your system PATH. This directory contains OpenCV DLLs required for running your code.
Open Control Panel → System → Advanced system settings → Advanced Tab → Environment variables...
On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin;
(3), then click Ok.
On some computers, you may need to restart your computer for the system to recognize the environment path variables.
This will completes the OpenCV 2.4.3 installation on your computer.
2. Create a new project and set up Visual C++
Open Visual C++ and select File → New → Project... → Visual C++ → Empty Project. Give a name for your project (e.g: cvtest
) and set the project location (e.g: c:\projects
).
Click Ok. Visual C++ will create an empty project.
Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest
and select Properties → VC++ Directories.
Select Include Directories to add a new entry and type C:\opencv\build\include
.
Click Ok to close the dialog.
Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib
.
Click Ok to close the dialog.
Back to the property dialog, select Linker → Input → Additional Dependencies to add new entries. On the popup dialog, type the files below:
opencv_calib3d243d.lib
opencv_contrib243d.lib
opencv_core243d.lib
opencv_features2d243d.lib
opencv_flann243d.lib
opencv_gpu243d.lib
opencv_haartraining_engined.lib
opencv_highgui243d.lib
opencv_imgproc243d.lib
opencv_legacy243d.lib
opencv_ml243d.lib
opencv_nonfree243d.lib
opencv_objdetect243d.lib
opencv_photo243d.lib
opencv_stitching243d.lib
opencv_ts243d.lib
opencv_video243d.lib
opencv_videostab243d.lib
Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).
Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.
NOTE:
These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to repeat adding the OpenCV directories and in Additional Dependencies section, use:
opencv_core243.lib
opencv_imgproc243.lib
...
instead of:
opencv_core243d.lib
opencv_imgproc243d.lib
...
You've done setting up Visual C++, now is the time to write the real code. Right click your project and select Add → New Item... → Visual C++ → C++ File.
Name your file (e.g: loadimg.cpp
) and click Ok. Type the code below in the editor:
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
Mat im = imread("c:/full/path/to/lena.jpg");
if (im.empty())
{
cout << "Cannot load image!" << endl;
return -1;
}
imshow("Image", im);
waitKey(0);
}
The code above will load c:\full\path\to\lena.jpg
and display the image. You can
use any image you like, just make sure the path to the image is correct.
Type F5 to compile the code, and it will display the image in a nice window.
And that is your first OpenCV program!
3. Where to go from here?
Now that your OpenCV environment is ready, what's next?
c:\opencv\samples\cpp
.i have this problem , a few time problem is recycleView put in ScrollView object
After checking implementation, the reason appears to be the following. If RecyclerView gets put into a ScrollView, then during measure step its height is unspecified (because ScrollView allows any height) and, as a result, gets equal to minimum height (as per implementation) which is apparently zero.
You have couple of options for fixing this:
(Can be followed for android.support.v4.widget.NestedScrollView
as well)
You can also use String.format("%3.3s", "abcdefgh")
. The first digit is the minimum length (the string will be left padded if it's shorter), the second digit is the maxiumum length and the string will be truncated if it's longer. So
System.out.printf("'%3.3s' '%3.3s'", "abcdefgh", "a");
will produce
'abc' ' a'
(you can remove quotes, obviously).
var myString = "echoHello";
window[myString] = function() {
alert("Hello!");
}
echoHello();
Say no to the evil eval. Example here: https://jsfiddle.net/Shaz/WmA8t/
Open the dll with a hex editor, like HxD
If the there is a "dt" on the 9th line it is 64bit.
If there is an "L." on the 9th line it is 32bit.
Why do we use:
1) cin.ignore
2) cin.clear
?
Simply:
1) To ignore (extract and discard) values that we don't want on the stream
2) To clear the internal state of stream. After using cin.clear internal state is set again back to goodbit, which means that there are no 'errors'.
Long version:
If something is put on 'stream' (cin) then it must be taken from there. By 'taken' we mean 'used', 'removed', 'extracted' from stream. Stream has a flow. The data is flowing on cin like water on stream. You simply cannot stop the flow of water ;)
Look at the example:
string name; //line 1
cout << "Give me your name and surname:"<<endl;//line 2
cin >> name;//line 3
int age;//line 4
cout << "Give me your age:" <<endl;//line 5
cin >> age;//line 6
What happens if the user answers: "Arkadiusz Wlodarczyk" for first question?
Run the program to see for yourself.
You will see on console "Arkadiusz" but program won't ask you for 'age'. It will just finish immediately right after printing "Arkadiusz".
And "Wlodarczyk" is not shown. It seems like if it was gone (?)*
What happened? ;-)
Because there is a space between "Arkadiusz" and "Wlodarczyk".
"space" character between the name and surname is a sign for computer that there are two variables waiting to be extracted on 'input' stream.
The computer thinks that you are tying to send to input more than one variable. That "space" sign is a sign for him to interpret it that way.
So computer assigns "Arkadiusz" to 'name' (2) and because you put more than one string on stream (input) computer will try to assign value "Wlodarczyk" to variable 'age' (!). The user won't have a chance to put anything on the 'cin' in line 6 because that instruction was already executed(!). Why? Because there was still something left on stream. And as I said earlier stream is in a flow so everything must be removed from it as soon as possible. And the possibility came when computer saw instruction cin >> age;
Computer doesn't know that you created a variable that stores age of somebody (line 4). 'age' is merely a label. For computer 'age' could be as well called: 'afsfasgfsagasggas' and it would be the same. For him it's just a variable that he will try to assign "Wlodarczyk" to because you ordered/instructed computer to do so in line (6).
It's wrong to do so, but hey it's you who did it! It's your fault! Well, maybe user, but still...
All right all right. But how to fix it?!
Let's try to play with that example a bit before we fix it properly to learn a few more interesting things :-)
I prefer to make an approach where we understand things. Fixing something without knowledge how we did it doesn't give satisfaction, don't you think? :)
string name;
cout << "Give me your name and surname:"<<endl;
cin >> name;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << cin.rdstate(); //new line is here :-)
After invoking above code you will notice that the state of your stream (cin) is equal to 4 (line 7). Which means its internal state is no longer equal to goodbit. Something is messed up. It's pretty obvious, isn't it? You tried to assign string type value ("Wlodarczyk") to int type variable 'age'. Types doesn't match. It's time to inform that something is wrong. And computer does it by changing internal state of stream. It's like: "You f**** up man, fix me please. I inform you 'kindly' ;-)"
You simply cannot use 'cin' (stream) anymore. It's stuck. Like if you had put big wood logs on water stream. You must fix it before you can use it. Data (water) cannot be obtained from that stream(cin) anymore because log of wood (internal state) doesn't allow you to do so.
Oh so if there is an obstacle (wood logs) we can just remove it using tools that is made to do so?
Yes!
internal state of cin set to 4 is like an alarm that is howling and making noise.
cin.clear clears the state back to normal (goodbit). It's like if you had come and silenced the alarm. You just put it off. You know something happened so you say: "It's OK to stop making noise, I know something is wrong already, shut up (clear)".
All right let's do so! Let's use cin.clear().
Invoke below code using "Arkadiusz Wlodarczyk" as first input:
string name;
cout << "Give me your name and surname:"<<endl;
cin >> name;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << cin.rdstate() << endl;
cin.clear(); //new line is here :-)
cout << cin.rdstate()<< endl; //new line is here :-)
We can surely see after executing above code that the state is equal to goodbit.
Great so the problem is solved?
Invoke below code using "Arkadiusz Wlodarczyk" as first input:
string name;
cout << "Give me your name and surname:"<<endl;
cin >> name;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << cin.rdstate() << endl;;
cin.clear();
cout << cin.rdstate() << endl;
cin >> age;//new line is here :-)
Even tho the state is set to goodbit after line 9 the user is not asked for "age". The program stops.
WHY?!
Oh man... You've just put off alarm, what about the wood log inside a water?* Go back to text where we talked about "Wlodarczyk" how it supposedly was gone.
You need to remove "Wlodarczyk" that piece of wood from stream. Turning off alarms doesn't solve the problem at all. You've just silenced it and you think the problem is gone? ;)
So it's time for another tool:
cin.ignore can be compared to a special truck with ropes that comes and removes the wood logs that got the stream stuck. It clears the problem the user of your program created.
So could we use it even before making the alarm goes off?
Yes:
string name;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
int age;
cout << "Give me your age:" << endl;
cin >> age;
The "Wlodarczyk" is gonna be removed before making the noise in line 7.
What is 10000 and '\n'?
It says remove 10000 characters (just in case) until '\n' is met (ENTER). BTW It can be done better using numeric_limits but it's not the topic of this answer.
So the main cause of problem is gone before noise was made...
Why do we need 'clear' then?
What if someone had asked for 'give me your age' question in line 6 for example: "twenty years old" instead of writing 20?
Types doesn't match again. Computer tries to assign string to int. And alarm starts. You don't have a chance to even react on situation like that. cin.ignore won't help you in case like that.
So we must use clear in case like that:
string name;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
int age;
cout << "Give me your age:" << endl;
cin >> age;
cin.clear();
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
But should you clear the state 'just in case'?
Of course not.
If something goes wrong (cin >> age;) instruction is gonna inform you about it by returning false.
So we can use conditional statement to check if the user put wrong type on the stream
int age;
if (cin >> age) //it's gonna return false if types doesn't match
cout << "You put integer";
else
cout << "You bad boy! it was supposed to be int";
All right so we can fix our initial problem like for example that:
string name;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
int age;
cout << "Give me your age:" << endl;
if (cin >> age)
cout << "Your age is equal to:" << endl;
else
{
cin.clear();
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
cout << "Give me your age name as string I dare you";
cin >> age;
}
Of course this can be improved by for example doing what you did in question using loop while.
BONUS:
You might be wondering. What about if I wanted to get name and surname in the same line from the user? Is it even possible using cin if cin interprets each value separated by "space" as different variable?
Sure, you can do it two ways:
1)
string name, surname;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin >> surname;
cout << "Hello, " << name << " " << surname << endl;
2) or by using getline function.
getline(cin, nameOfStringVariable);
and that's how to do it:
string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);
cout << "Hello, " << nameAndSurname << endl;
The second option might backfire you in case you use it after you use 'cin' before the getline.
Let's check it out:
a)
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << "Your age is" << age << endl;
string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);
cout << "Hello, " << nameAndSurname << endl;
If you put "20" as age you won't be asked for nameAndSurname.
But if you do it that way:
b)
string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);
cout << "Hello, " << nameAndSurname << endl;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << "Your age is" << age << endll
everything is fine.
WHAT?!
Every time you put something on input (stream) you leave at the end white character which is ENTER ('\n') You have to somehow enter values to console. So it must happen if the data comes from user.
b) cin characteristics is that it ignores whitespace, so when you are reading in information from cin, the newline character '\n' doesn't matter. It gets ignored.
a) getline function gets the entire line up to the newline character ('\n'), and when the newline char is the first thing the getline function gets '\n', and that's all to get. You extract newline character that was left on stream by user who put "20" on stream in line 3.
So in order to fix it is to always invoke cin.ignore(); each time you use cin to get any value if you are ever going to use getline() inside your program.
So the proper code would be:
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cin.ignore(); // it ignores just enter without arguments being sent. it's same as cin.ignore(1, '\n')
cout << "Your age is" << age << endl;
string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);
cout << "Hello, " << nameAndSurname << endl;
I hope streams are more clear to you know.
Hah silence me please! :-)
This is how you can do it-
HTML-
<div style="overflow:hidden; height:100%">
<div style="float:left">a<br>b</div>
<table cellpadding="0" cellspacing="0" style="height:100%;">
<tr><td>This is the content of a table that takes 100% height</td></tr>
</table>
</div>
CSS-
html,body
{
height:100%;
background-color:grey;
}
table
{
background-color:yellow;
}
See the DEMO
Update: Well, if you are not looking for applying 100% height to your parent containers, then here is a jQuery solution that should help you-
Script-
$(document).ready(function(){
var b= $(window).height(); //gets the window's height, change the selector if you are looking for height relative to some other element
$("#tab").css("height",b);
});
start the sql server agent, that should fix your problem
It was already posted but here it is with PDO (same query)...
$connection = new PDO ( "mysql:host=host_db; dbname=name_db", user_db, pass_db );
if ($connection->query ("DESCRIBE table_name" )) {
echo "exist";
} else {
echo "doesn't exist";
}
Works like a charm for me....
And here's another approach (i think it is slower)...
if ($connection->query ( "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = 'db_name' AND table_name ='tbl_name'" )->fetch ()) {
echo "exist";
} else {
echo "doesn't exist";
}
You can also play with this query:
SHOW TABLE STATUS FROM db_name LIKE 'tbl_name'
I think this was suggested to use in the mysql page.
I was facing the same problem! I've added the code below in wp-config.php file (in any line) and it's working now!
define('FS_METHOD', 'direct');
For windows: Go to your "system properties" please.then follow as bellow.
Advanced system settings(from left sidebar)->Environment variables(very last option)->path(from lower box/system variables called as I know)->edit
then concatenate the "php" location you have in your pc (usually it is where your xampp is installed say c:/xampp/php)
N.B : Please never forget to set semicolon (;) between your recent concatenated path and the existed path in your "Path"
Something like C:\Program Files\Git\usr\bin;C:\xampp\php
Hope this will help.Happy coding. :) :)
A better JQuery answer would be:
$('#ParentContainer').scroll(function() {
$('#FixedDiv').animate({top:$(this).scrollTop()});
});
You can also add a number after scrollTop i.e .scrollTop() + 5 to give it buff.
A good suggestion would also to limit the duration to 100 and go from default swing to linear easing.
$('#ParentContainer').scroll(function() {
$('#FixedDiv').animate({top:$(this).scrollTop()},100,"linear");
})
This works fine in java.
It basically converts all accented characters into their deAccented counterparts followed by their combining diacritics. Now you can use a regex to strip off the diacritics.
import java.text.Normalizer;
import java.util.regex.Pattern;
public String deAccent(String str) {
String nfdNormalizedString = Normalizer.normalize(str, Normalizer.Form.NFD);
Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");
return pattern.matcher(nfdNormalizedString).replaceAll("");
}
You can use the .not()
method or :not()
selector
Code based on your example:
$("ul#list li").not(".active") // not method
$("ul#list li:not(.active)") // not selector
This is just a sample code, but it may help you get on your way:
Public Sub testIt()
Workbooks("Workbook2").Activate
ActiveWorkbook.Sheets("Sheet2").Activate
ActiveSheet.Range("B3").Select
ActiveCell.EntireRow.Insert
End Sub
I am assuming that you can open the book (called Workbook2
in the example).
I think (but I'm not sure) you can squash all this in a single line of code:
Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert
This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.
Several comments refer to Arel, without providing an example.
Here is an Arel example of a case-insensitive search:
Product.where(Product.arel_table[:name].matches('Blue Jeans'))
The advantage of this type of solution is that it is database-agnostic - it will use the correct SQL commands for your current adapter (matches
will use ILIKE
for Postgres, and LIKE
for everything else).
When a
and b
are 1-dimensional sequences, numpy.cov(a,b)[0][1]
is equivalent to your cov(a,b)
.
The 2x2 array returned by np.cov(a,b)
has elements equal to
cov(a,a) cov(a,b)
cov(a,b) cov(b,b)
(where, again, cov
is the function you defined above.)
Try using 0xFFF000 instead and pass that into the Color.HSVToColor method.
Pure CSS Workaround:
I was using both bootstrap and jQuery UI and changing the order of adding the scripts broke some other objects. I ended up using pure CSS workaround:
.ui-dialog-titlebar-close {
background: url("http://code.jquery.com/ui/1.10.3/themes/smoothness/images/ui-icons_888888_256x240.png") repeat scroll -93px -128px rgba(0, 0, 0, 0);
border: medium none;
}
.ui-dialog-titlebar-close:hover {
background: url("http://code.jquery.com/ui/1.10.3/themes/smoothness/images/ui-icons_222222_256x240.png") repeat scroll -93px -128px rgba(0, 0, 0, 0);
}
A common cause I wanted to suggest for this situation:
Sometimes a customer is running Skype, which is using port 443 without their realizing it. When they go to start Tomcat or Apache, it appears to start but cannot bind with port 443. This is the exact message that the user would receive in the browser. The fix is to stop what was running on port 443 and re-start the webserver so it can bind with port 443.
The customer can re-start Skype after starting the webserver, and Skype will detect that port 443 is in use and choose a different port to use.
If you have Unicode/nChar/nVarChar values you are concatenating, then SQL Server will implicitly convert your string to nVarChar(4000), and it is unfortunately too dumb to realize it will truncate your string or even give you a Warning that data has been truncated for that matter!
When concatenating long strings (or strings that you feel could be long) always pre-concatenate your string building with CAST('' as nVarChar(MAX)) like so:
SET @Query = CAST('' as nVarChar(MAX))--Force implicit conversion to nVarChar(MAX)
+ 'SELECT...'-- some of the query gets set here
+ '...'-- more query gets added on, etc.
What a pain and scary to think this is just how SQL Server works. :(
I know other workarounds on the web say to break up your code into multiple SET/SELECT assignments using multiple variables, but this is unnecessary given the solution above.
For those who hit an 8000 character max, it was probably because you had no Unicode so it was implicitly converted to VarChar(8000).
Explanation:
What's happening behind the scenes is that even though the variable you are assigning to uses (MAX), SQL Server will evaluate the right-hand side of the value you are assigning first and default to nVarChar(4000) or VarChar(8000) (depending on what you're concatenating). After it is done figuring out the value (and after truncating it for you) it then converts it to (MAX) when assigning it to your variable, but by then it is too late.
What happens is when these elements are called before the DOM is loaded these kind of errors come up. Always use:
window.onload = function(){
this.keywordsInput.nativeElement.focus();
}
As with most things, there's the general rule and then there are specific circumstances. If you are doing a closed, captured application so that you know how a given object is going to be used, then you can exercise more freedom to favor visibility and/or efficiency. If you're developing a class which is going to be used publicly by others beyond your control, then lean towards the getter/setter model. As with all things, just use common sense. It's often ok to do an initial round with publics and then change them to getter/setters later.
Well, it depends on what language you are using, but in general they are 2 separate configurations, each with its own settings. By default, Debug includes debug information in the compiled files (allowing easy debugging) while Release usually has optimizations enabled.
As far as conditional compilation goes, they each define different symbols that can be checked in your program, but they are language-specific macros.
mysqli_select_db()
should have 2 parameters, the connection link and the database name -
mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));
Using mysqli_error
in the die statement will tell you exactly what is wrong as opposed to a generic error message.
In C# and Java, the arithmatic expression on the right hand side of the assignment evaluates to int by default. That's why you need to cast back to a short, because there is no implicit conversion form int to short, for obvious reasons.
Java LINQ to SQL implementation. Provides full language integration and larger feature set compared to .NET LINQ.
You are talking about SQL Profiler.
Don't edit the vector assets directly. If you're using a vector drawable in an ImageButton, just choose your color in android:tint
.
<ImageButton
android:layout_width="48dp"
android:layout_height="48dp"
android:id="@+id/button"
android:src="@drawable/ic_more_vert_24dp"
android:tint="@color/primary" />
Using docker-compose, I accomplished this by creating a service that mounts the volumes that I need and committing the image of the container. Then, in the subsequent service, I rely on the previously committed image, which has all of the data stored at mounted locations. You will then have have to copy these files to their ultimate destination, as host mounted directories do not get committed when running a docker commit
command
You don't have to use docker-compose to accomplish this, but it makes life a bit easier
# docker-compose.yml
version: '3'
services:
stage:
image: alpine
volumes:
- /host/machine/path:/tmp/container/path
command: bash -c "cp -r /tmp/container/path /final/container/path"
setup:
image: stage
# setup.sh
# Start "stage" service
docker-compose up stage
# Commit changes to an image named "stage"
docker commit $(docker-compose ps -q stage) stage
# Start setup service off of stage image
docker-compose up setup
The question is already answered, however when I first saw it I thought of NodeJS Buffer. But it is way slower than the +, so it is likely that nothing can be faster than + in string concetanation.
Tested with the following code:
function a(){
var s = "hello";
var p = "world";
s = s + p;
return s;
}
function b(){
var s = new Buffer("hello");
var p = new Buffer("world");
s = Buffer.concat([s,p]);
return s;
}
var times = 100000;
var t1 = new Date();
for( var i = 0; i < times; i++){
a();
}
var t2 = new Date();
console.log("Normal took: " + (t2-t1) + " ms.");
for ( var i = 0; i < times; i++){
b();
}
var t3 = new Date();
console.log("Buffer took: " + (t3-t2) + " ms.");
Output:
Normal took: 4 ms.
Buffer took: 458 ms.
You need to build query from "data" object using the following function
function buildQuery(obj) {
var Result= '';
if(typeof(obj)== 'object') {
jQuery.each(obj, function(key, value) {
Result+= (Result) ? '&' : '';
if(typeof(value)== 'object' && value.length) {
for(var i=0; i<value.length; i++) {
Result+= [key+'[]', encodeURIComponent(value[i])].join('=');
}
} else {
Result+= [key, encodeURIComponent(value)].join('=');
}
});
}
return Result;
}
and then proceed with
var data= {
"subject:title":"Test Name",
"subject:description":"Creating test subject to check POST method API",
"sub:tags": ["facebook:work, facebook:likes"],
"sampleSize" : 10,
"values": ["science", "machine-learning"]
}
$.ajax({
type: 'POST',
url: "http://localhost:8080/project/server/rest/subjects",
data: buildQuery(data),
error: function(e) {
console.log(e);
}
});
Note that if the object you are talking about has a custom property model (such as DataRowView
etc for DataTable
), then you need to use TypeDescriptor
; the good news is that this still works fine for regular classes (and can even be much quicker than reflection):
foreach(PropertyDescriptor prop in TypeDescriptor.GetProperties(obj)) {
Console.WriteLine("{0} = {1}", prop.Name, prop.GetValue(obj));
}
This also provides easy access to things like TypeConverter
for formatting:
string fmt = prop.Converter.ConvertToString(prop.GetValue(obj));
swift 4.0
let stringNumber = "123"
let number = Int(stringNumber) //here number is of type "Int?"
//using Forced Unwrapping
if number != nil {
//string is converted to Int
}
you could also use Optional Binding other than forced binding.
eg:
if let number = Int(stringNumber) {
// number is of type Int
}
My first post...
I tried this: change 'tr' for 'td' and you will get all HTMLRowElements into an Array, and using textContent will change from Object into String
var dataArray = [];
var data = table.find('td'); //Get All HTML td elements
// Save important data into new Array
for (var i = 0; i <= data.size() - 1; i = i + 4)
{
dataArray.push(data[i].textContent, data[i + 1].textContent, data[i + 2].textContent);
}
Please check in your server specification again, if you have changed your port number to something else. And change the port number in your link whatever new port number it is.
Also check whether your server is running properly before you try accessing your localhost.
The 1st element as in no hard returns. A hard return I guess = an empty node/element in the DOM which becomes the 1st element disabling the doc compatability meta tag.
Depending on the boost version libboost-system comes with the -mt suffix which should indicate the libraries multithreading capability.
So if -lboost_system
cannot be found by the linker try -lboost_system-mt
.
There is a difference between each parameter.
The -DskipTests
skip running tests phase, it means at the end of this process you will have your tests compiled.
The -Dmaven.test.skip=true
skip compiling and running tests phase.
As the parameter -Dmaven.test.skip=true
skip compiling you don't have the tests artifact.
For more information just read the surfire documentation: http://maven.apache.org/plugins-archives/maven-surefire-plugin-2.12.4/examples/skipping-test.html
To install OpenCV in Anaconda, start up the Anaconda command prompt and install OpenCV with
conda install -c https://conda.anaconda.org/menpo opencv3
Test that it works in your Anaconda Spyder or IPython console with
import cv2
You can also check the installed version using:
cv2.__version__
public static String getDateTime() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM dd, yyyy HH:mm:ss", Locale.getDefault());
Date date = new Date();
return simpleDateFormat.format(date);
}
Here's an easy way for Windows users.
// CustomCell.swift
protocol CustomCellDelegate {
func tapDeleteButton(at cell: CustomCell)
}
class CustomCell: UICollectionViewCell {
var delegate: CustomCellDelegate?
fileprivate let deleteButton: UIButton = {
let button = UIButton(frame: .zero)
button.setImage(UIImage(named: "delete"), for: .normal)
button.addTarget(self, action: #selector(deleteButtonTapped(_:)), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
@objc fileprivate func deleteButtonTapped(_sender: UIButton) {
delegate?.tapDeleteButton(at: self)
}
}
// ViewController.swift
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier, for: indexPath) as? CustomCell else {
fatalError("Unexpected cell instead of CustomCell")
}
cell.delegate = self
return cell
}
}
extension ViewController: CustomCellDelegate {
func tapDeleteButton(at cell: CustomCell) {
// Here we get the indexPath of the cell what we tapped on.
let indexPath = collectionView.indexPath(for: cell)
}
}
You cannot achieve the desired solution with CSS z-index either, as z-index is only relative to the parent element. So if you have parents A and B with respective children a and b, b's z-index is only relative to other children of B and a's z-index is only relative to other children of A.
The z-index of A and B are relative to each other if they share the same parent element, but all of the children of one will share the same relative z-index at this level.
You better use CSS for that, after all, this is what CSS is for. If you don't want to do that, go with Dorwand's answer.
I don’t know for sure but I’m reading a book right now and what I am getting is that a program need to handle its signal ( as when I press CTRL-C
). Now a program can use SIG_IGN
to ignore all signals or SIG_DFL
to restore the default action.
Now if you do $ command &
then this process running as background process simply ignores all signals that will occur. For foreground processes these signals are not ignored.
Rxjs 5.5 “ Property ‘map’ does not exist on type Observable.
The problem was related to the fact that you need to add pipe around all operators.
Change this,
this.myObservable().map(data => {})
to this
this.myObservable().pipe(map(data => {}))
And
Import map like this,
import { map } from 'rxjs/operators';
It will solve your issues.
if(!empty($web))
{
echo 'Something';
}
The easiest way to do this on Vista, Win 7 and above is enumerating token groups and looking for the current integrity level (or the administrators sid, if only group memberhip is important):
Check if we are running elevated:
whoami /groups | find "S-1-16-12288" && Echo I am running elevated, so I must be an admin anyway ;-)
Check if we belong to local administrators:
whoami /groups | find "S-1-5-32-544" && Echo I am a local admin
Check if we belong to domain admins:
whoami /groups | find "-512 " && Echo I am a domain admin
The following article lists the integrity level SIDs windows uses: http://msdn.microsoft.com/en-us/library/bb625963.aspx
One way to solve this problem is to get the starting points from the values themselves:
var minLen, maxLen uint
if len(sliceOfThings) > 0 {
minLen = sliceOfThings[0].minLen
maxLen = sliceOfThings[0].maxLen
for _, thing := range sliceOfThings[1:] {
if minLen > thing.minLen { minLen = thing.minLen }
if maxLen < thing.maxLen { maxLen = thing.maxLen }
}
}
Fix: Cannot use the special principal ‘sa’. Microsoft SQL Server, Error: 15405
When importing a database in your SQL instance you would find yourself with Cannot use the special principal 'sa'. Microsoft SQL Server, Error: 15405 popping out when setting the sa user as the DBO of the database. To fix this, Open SQL Management Studio and Click New Query. Type:
USE mydatabase
exec sp_changedbowner 'sa', 'true'
Close the new query and after viewing the security of the sa, you will find that that sa is the DBO of the database. (14444)
Source: http://www.noelpulis.com/fix-cannot-use-the-special-principal-sa-microsoft-sql-server-error-15405/
php artisan serve
this command get the env contents for the first time and if you update .env file need to restart it.
in my case my username and dbname is valid and php artisan migrate worked
but need to cntrl+c , to cancel php artisan serve , and run it again
php artisan serve
You can do that: Postman -> Import -> Link -> {root_url}/v2/api-docs
Make sure to fully specify the version number of the API as something like "v2.11"
and not "2.11"
I'm not sure what it defaults to if this is incorrect, but I got some odd errors trying to just retrieve the email when I missed the v
.
If you are running on a linux environment, basically your app does not have rights for the default port.
Try 8181 by giving the following option on VM.
-Dserver.port=8181
For me, none of suggestions worked giving me the errors of syntax, so I just gave a try using phpmyadmin(version 4.9.2), (10.4.10-MariaDB) and added id
column with auto-increment primary key. Id
column was nicely added from the first element.
Query output was:
ALTER TABLE table_name
ADD id
INT NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (id
);
Declare a variable in component.ts and initialize it to some value
buttonDisabled: boolean;
ngOnInit() {
this.buttonDisabled = false;
}
Now in .html or in the template, you can put following code:
<button disabled="{{buttonDisabled}}"> Click Me </button>
Now you can enable/disable button by changing value of buttonDisabled
variable.
I am not sure how to see the actual rows/records that come back.
Stored procedures do not return records. They may have a cursor as an output parameter, which is a pointer to a select statement. But it requires additional action to actually bring back rows from that cursor.
In SQL Developer, you can execute a procedure that returns a ref cursor as follows
var rc refcursor
exec proc_name(:rc)
After that, if you execute the following, it will show the results from the cursor:
print rc
As per this example:
import numpy as np
import matplotlib.pyplot as plt
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
plt.scatter(x, y)
plt.show()
will produce:
To unpack your data from pairs into lists use zip
:
x, y = zip(*li)
So, the one-liner:
plt.scatter(*zip(*li))
For me the most elegant solution is this one:
XMLGregorianCalendar result = DatatypeFactory.newInstance()
.newXMLGregorianCalendar("2014-01-07");
Using Java 8.
Extended example:
XMLGregorianCalendar result = DatatypeFactory.newInstance()
.newXMLGregorianCalendar("2014-01-07");
System.out.println(result.getDay());
System.out.println(result.getMonth());
System.out.println(result.getYear());
This prints out:
7
1
2014
My utils method for get current date time using Calendar
when our minSdkVersion < 26.
fun Date.toString(format: String, locale: Locale = Locale.getDefault()): String {
val formatter = SimpleDateFormat(format, locale)
return formatter.format(this)
}
fun getCurrentDateTime(): Date {
return Calendar.getInstance().time
}
Using
import ...getCurrentDateTime
import ...toString
...
...
val date = getCurrentDateTime()
val dateInString = date.toString("yyyy/MM/dd HH:mm:ss")
for (Map.Entry<String, ArrayList<String>> entry : test1.entrySet()) {
String key = entry.getKey();
ArrayList<String> value = entry.getValue();
// now work with key and value...
}
By the way, you should really declare your variables as the interface type instead, such as Map<String, List<String>>
.
This is now IsEnabled
takePicturebutton.IsEnabled = false; // true
Use name()
when you want to make a comparison or use the hardcoded value for some internal use in your code.
Use toString()
when you want to present information to a user (including a developper looking at a log). Never rely in your code on toString()
giving a specific value. Never test it against a specific string. If your code breaks when someone correctly changes the toString()
return, then it was already broken.
From the javadoc (emphasis mine) :
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
Using regex
to parse html is not recommended
regex
is used for regularly occurring patterns.html
is not regular with it's format(except xhtml
).For example html
files are valid even if you don't have a closing tag
!This could break your code.
Use an html parser like htmlagilitypack
You can use this code to retrieve all href's
in anchor tag using HtmlAgilityPack
HtmlDocument doc = new HtmlDocument();
doc.Load(yourStream);
var hrefList = doc.DocumentNode.SelectNodes("//a")
.Select(p => p.GetAttributeValue("href", "not found"))
.ToList();
hrefList
contains all href`s
In View:
<Button
Height="50" Width="50"
Style="{StaticResource MyButtonStyle}"
Command="{Binding SmallDisp}" CommandParameter="{Binding}"
Cursor="Hand" Visibility="{Binding Path=AdvancedFormat}"/>
In view Model:
public _advancedFormat = Visibility.visible (whatever you start with)
public Visibility AdvancedFormat
{
get{return _advancedFormat;}
set{
_advancedFormat = value;
//raise property changed here
}
You will need to have a property changed event
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
PropertyChanged.Raise(this, e);
}
protected void OnPropertyChanged(string propertyName)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
This is how they use Model-view-viewmodel
But since you want it binded to a boolean, You will need some converter. Another way is to set a boolean outside and when that button is clicked then set the property_advancedFormat to your desired visibility.
CAUTION:
The begin <code> end while <condition>
is rejected by Ruby's author Matz. Instead he suggests using Kernel#loop
, e.g.
loop do
# some code here
break if <condition>
end
Here's an email exchange in 23 Nov 2005 where Matz states:
|> Don't use it please. I'm regretting this feature, and I'd like to
|> remove it in the future if it's possible.
|
|I'm surprised. What do you regret about it?
Because it's hard for users to tell
begin <code> end while <cond>
works differently from
<code> while <cond>
RosettaCode wiki has a similar story:
During November 2005, Yukihiro Matsumoto, the creator of Ruby, regretted this loop feature and suggested using Kernel#loop.
some great answers here, but they do not tackle how to use super()
in the case where different classes in the hierarchy have different signatures ... especially in the case of __init__
to answer that part and to be able to effectively use super()
i'd suggest reading my answer super() and changing the signature of cooperative methods.
here's just the solution to this scenario:
- the top-level classes in your hierarchy must inherit from a custom class like
SuperObject
:- if classes can take differing arguments, always pass all arguments you received on to the super function as keyword arguments, and, always accept
**kwargs
.
class SuperObject:
def __init__(self, **kwargs):
print('SuperObject')
mro = type(self).__mro__
assert mro[-1] is object
if mro[-2] is not SuperObject:
raise TypeError(
'all top-level classes in this hierarchy must inherit from SuperObject',
'the last class in the MRO should be SuperObject',
f'mro={[cls.__name__ for cls in mro]}'
)
# super().__init__ is guaranteed to be object.__init__
init = super().__init__
init()
example usage:
class A(SuperObject):
def __init__(self, **kwargs):
print("A")
super(A, self).__init__(**kwargs)
class B(SuperObject):
def __init__(self, **kwargs):
print("B")
super(B, self).__init__(**kwargs)
class C(A):
def __init__(self, age, **kwargs):
print("C",f"age={age}")
super(C, self).__init__(age=age, **kwargs)
class D(B):
def __init__(self, name, **kwargs):
print("D", f"name={name}")
super(D, self).__init__(name=name, **kwargs)
class E(C,D):
def __init__(self, name, age, *args, **kwargs):
print( "E", f"name={name}", f"age={age}")
super(E, self).__init__(name=name, age=age, *args, **kwargs)
E(name='python', age=28)
output:
E name=python age=28
C age=28
A
D name=python
B
SuperObject
If you do things with time and dates Carbon is you best friend;
Install the package then:
$theDay = Carbon::make("2010-01-21 00:00:00.0");
$theDay->isToday();
$theDay->isPast();
$theDay->isFuture();
if($theDay->lt(Carbon::today()) || $theDay->gt(Carbon::today()))
lt = less than, gt = greater than
As in the question:
$theDay->gt(Carbon::today()) ? true : false;
and much more;
My guess is that byteArrayIn
doesn't contain valid image data.
Please give more information though:
byteArrayIn
from, and are you sure it should contain a valid image?You don't need any webpack configuration for this..
In your component just give image path. By default react will know its in public directory.
<img src="/image.jpg" alt="image" />
Just create the database using createdb
CLI tool:
PGHOST="my.database.domain.com"
PGUSER="postgres"
PGDB="mydb"
createdb -h $PGHOST -p $PGPORT -U $PGUSER $PGDB
If the database exists, it will return an error:
createdb: database creation failed: ERROR: database "mydb" already exists
The error indicates that the preflight is getting a redirect response. This can happen for a number of reasons. Find out where you are getting redirected to for clues to why it is happening. Check the network tab in Developer Tools.
One reason, as @Peter T mentioned, is that the API likely requires HTTPS connections rather than HTTP and all requests over HTTP get redirected. The Location
header returned by the 302
response would say the same url with http
changed to https
in this case.
Another reason might be that your authentication token is not getting sent, or is not correct. Most servers are set up to redirect all requests that don't include an authentication token to the login page. Again, check your Location
header to see if this is where you're getting sent and also take a look to make sure the browser sent your auth token with the request.
Oftentimes, a server will be configured to always redirect requests that don't have auth tokens to the login page - including your preflight/OPTIONS
requests. This is a problem. Change the server configuration to permit OPTIONS
requests from non-authenticated users.
To add to these answers, if you have an R script containing calls that generate plots to screen (the native device), then these can all be saved to a pdf file (the default device for a non-interactive shell) "Rplots.pdf" (the default name) by redirecting the script into R from the terminal (assuming you are running linux or OS X), e.g.:
R < myscript.R --no-save
This could be converted to jpg/png as necessary
Re: using icon in :before
–
recent Font Awesome builds include the .fa-icon()
mixin for SASS and LESS. This will automatically include the font-family
as well as some rendering tweaks (e.g. -webkit-font-smoothing
). Thus you can do, e.g.:
// Add "?" icon to header.
h1:before {
.fa-icon();
content: "\f059";
}
In my case I was using Windows 7 with the 64-bit OS. We installed the 64-bit Java SE and 64-bit ADT Bundle. With that set up, we couldn't get the SDK manager to work correctly (specifically, no downloads allowed and it didn't show all the API download options). After trying all of the above answers and from other posts, we decided to look into the Java set up and realized it might the 64-bit configuration that's giving the ADT bundle grief (I vaguely recall seeing/reading this issue before).
So we uninstalled Java 64-bit and reinstalled the 32-bit, and then used the 32-bit ADT bundle, and it worked correctly. The system user was already an admin, so we didn't need to "Run as Administrator"
Your XML is slightly wrong, you need to add any class exclusions within an excludes parent field, so your above configuration should look like the following as per the Jacoco docs
<configuration>
<excludes>
<exclude>**/*Config.*</exclude>
<exclude>**/*Dev.*</exclude>
</excludes>
</configuration>
The values of the exclude fields should be class paths (not package names) of the compiled classes relative to the directory target/classes/ using the standard wildcard syntax
* Match zero or more characters
** Match zero or more directories
? Match a single character
You may also exclude a package and all of its children/subpackages this way:
<exclude>some/package/**/*</exclude>
This will exclude every class in some.package
, as well as any children. For example, some.package.child
wouldn't be included in the reports either.
I have tested and my report goal reports on a reduced number of classes using the above.
If you are then pushing this report into Sonar, you will then need to tell Sonar to exclude these classes in the display which can be done in the Sonar settings
Settings > General Settings > Exclusions > Code Coverage
Sonar Docs explains it a bit more
Running your command above
mvn clean verify
Will show the classes have been excluded
No exclusions
[INFO] --- jacoco-maven-plugin:0.7.4.201502262128:report (post-test) @ ** ---
[INFO] Analyzed bundle '**' with 37 classes
With exclusions
[INFO] --- jacoco-maven-plugin:0.7.4.201502262128:report (post-test) @ ** ---
[INFO] Analyzed bundle '**' with 34 classes
Hope this helps
I finally found some time to create this tool. You can install SnappySnippet from Github. It allows easy HTML+CSS extraction from the specified (last inspected) DOM node. Additionally, you can send your code straight to CodePen or JSFiddle. Enjoy!
::before
and ::after
pseudo-elementsSnappySnippet is open source, and you can find the code on GitHub.
Since I've learned quite a lot while making this, I've decided to share some of the problems I've experienced and my solutions to them, maybe someone will find it interesting.
At first I've tried retrieving the original CSS rules (coming from CSS files on the website). Quite amazingly, this is very simple thanks to window.getMatchedCSSRules()
, however, it didn't work out well. The problem was that we were taking only a part of the HTML and CSS selectors that were matching in the context of the whole document, which were not matching anymore in the context of an HTML snippet. Since parsing and modifying selectors didn't seem like a good idea, I gave up on this attempt.
Then, I've started from something that @CollectiveCognition suggested - getComputedStyle()
. However, I really wanted to separate CSS form HTML instead of inlining all styles.
The solution here wasn't very beautiful but quite straightforward. I've assigned IDs to all nodes in the selected subtree and used that ID to create appropriate CSS rules.
Assigning IDs to the nodes worked out nicely, however I found out that each of my CSS rules has ~300 properties making the whole CSS unreadable.
Turns out that getComputedStyle()
returns all possible CSS properties and values calculated for the given element. Some of them where empty, some had browser default values. To remove default values I had to get them from the browser first (and each tag has different default values). The solution was to compare the styles of the element coming from the website with the same element inserted into an empty <iframe>
. The logic here was that there are no style sheets in an empty <iframe>
, so each element I've appended there had only default browser styles. This way I was able to get rid of most of the properties that were insignificant.
Next thing I have spotted was that properties having shorthand equivalent were unnecessarily printed out (e.g. there was border: solid black 1px
and then border-color: black;
, border-width: 1px
itd.).
To solve this I've simply created a list of properties that have shorthand equivalents and filtered them out from the results.
The number of properties in each rule was significantly lower after the previous operation, but I've found that I sill had a lot of -webkit-
prefixed properties that I've never hear of (-webkit-app-region
? -webkit-text-emphasis-position
?).
I was wondering if I should keep any of these properties because some of them seemed useful (-webkit-transform-origin
, -webkit-perspective-origin
etc.). I haven't figured out how to verify this, though, and since I knew that most of the time these properties are just garbage, I decided to remove them all.
The next problem I have spotted was that the same CSS rules are repeated over and over (e.g. for each <li>
with the exact same styles there was the same rule in the CSS output created).
This was just a matter of comparing rules with each other and combining these that had exactly the same set of properties and values. As a result, instead of #LI_1{...}, #LI_2{...}
I got #LI_1, #LI_2 {...}
.
Since I was happy with the result, I moved to HTML. It looked like a mess, mostly because the outerHTML
property keeps it formatted exactly as it was returned from the server.
The only thing HTML code taken from outerHTML
needed was a simple code reformatting. Since it's something available in every IDE, I was sure that there is a JavaScript library that does exactly that. And it turns out that I was right (jquery-clean). What's more, I've got unnecessary attributes removal extra (style
, data-ng-repeat
etc.).
Since there is a chance that in some circumstances filters mentioned above may break CSS in the snippet, I've made all of them optional. You can disable them from the Settings menu.
in function
def handleUpload():
if 'photo' in request.files:
photo = request.files['photo']
if photo.filename != '':
image = request.files['photo']
image_string = base64.b64encode(image.read())
image_string = image_string.decode('utf-8')
#use this to remove b'...' to get raw string
return render_template('handleUpload.html',filestring = image_string)
return render_template('upload.html')
in html file
<html>
<head>
<title>Simple file upload using Python Flask</title>
</head>
<body>
{% if filestring %}
<h1>Raw image:</h1>
<h1>{{filestring}}</h1>
<img src="data:image/png;base64, {{filestring}}" alt="alternate" />.
{% else %}
<h1></h1>
{% endif %}
</body>
As mentioned in a different post Read .txt file from workspace groovy script in Jenkins I was struggling to make it work for the pom modules for a file in the workspace, in the Extended Choice Parameter. Here is my solution with the printlns:
import groovy.util.XmlSlurper
import java.util.Map
import jenkins.*
import jenkins.model.*
import hudson.*
import hudson.model.*
try{
//get Jenkins instance
def jenkins = Jenkins.instance
//get job Item
def item = jenkins.getItemByFullName("The_JOB_NAME")
println item
// get workspacePath for the job Item
def workspacePath = jenkins.getWorkspaceFor (item)
println workspacePath
def file = new File(workspacePath.toString()+"\\pom.xml")
def pomFile = new XmlSlurper().parse(file)
def pomModules = pomFile.modules.children().join(",")
return pomModules
} catch (Exception ex){
println ex.message
}
Remove the : before last-child and the :after and used
ul li:not(last-child){
content:' |';
}
Hopefully,it should work
In my case, simply using the uxterm
command instead of xterm
solved the problem. It's available in /opt/X11/bin/uxterm
by installing the XQuartz package provided by Apple.
You just needed to cast the unsigned char
into a char
as the string
class doesn't have a constructor that accepts unsigned char
:
unsigned char* uc;
std::string s( reinterpret_cast< char const* >(uc) ) ;
However, you will need to use the length argument in the constructor if your byte array contains nulls, as if you don't, only part of the array will end up in the string (the array up to the first null)
size_t len;
unsigned char* uc;
std::string s( reinterpret_cast<char const*>(uc), len ) ;
[[[UIDevice currentDevice] systemVersion] floatValue]
Based on semver, you can use
Hyphen Ranges X.Y.Z - A.B.C
1.2.3-2.3.4
Indicates >=1.2.3 <=2.3.4
X-Ranges
1.2.x
1.X
1.2.*
Tilde Ranges
~1.2.3
~1.2
Indicates allowing patch-level changes or minor version changes.
Caret Ranges ^1.2.3 ^0.2.5 ^0.0.4
Allows changes that do not modify the left-most non-zero digit in the [major, minor, patch] tuple
^1.2.x
(means >=1.2.0 <2.0.0)^0.0.x
(means >=0.0.0 <0.1.0)^0.0
(means >=0.0.0 <0.1.0)To be absolutely clear... what you describe does not conflict with the spec in any way. The spec talks about the values Hibernate assigns to your entities, not the values actually stored in the database sequence.
However, there is the option to get the behavior you are looking for. First see my reply on Is there a way to dynamically choose a @GeneratedValue strategy using JPA annotations and Hibernate? That will give you the basics. As long as you are set up to use that SequenceStyleGenerator, Hibernate will interpret allocationSize
using the "pooled optimizer" in the SequenceStyleGenerator. The "pooled optimizer" is for use with databases that allow an "increment" option on the creation of sequences (not all databases that support sequences support an increment). Anyway, read up about the various optimizer strategies there.
You can pass the element into the function <input type="button" value="mybutton1" onclick="dosomething(this)">test
by passing this. Then in the function you can access the value like this:
function dosomething(element) {
console.log(element.value);
}
So I did with
sudo usermod -a -G dialout <my-username>
.
You need to log out after you add yourself to a group so those changes are applied. Just log out and log in again and the menu should be available.
I use:
public synchronized int generateViewId() {
Random rand = new Random();
int id;
while (findViewById(id = rand.nextInt(Integer.MAX_VALUE) + 1) != null);
return id;
}
By using a random number I always have a huge chance of getting the unique id in first attempt.
Super easy with flexbox. Leave room for some space by changing the columns to col-md-5
<div class="row widgets">
<div class="text-center col-md-5">
Widget 1
</div>
<div class="text-center col-md-5">
Widget 2
</div>
</div>
CSS
.widgets {
display: flex;
justify-content: space-around;
}
You can use
$(window).on('load', function() {
// your code here
});
Which will wait until the page is loaded. $(document).ready()
waits until the DOM is loaded.
In plain JS:
window.addEventListener('load', function() {
// your code here
})
In C++03, aggregate initialization only applies with syntax similar as below, which must be a separate statement and doesn't fit in a ctor initializer.
T var = {...};
function findLongestWord(str) {
str = str.split(" ");
var sorted = str.sort(function(prev,current){
return prev.length - current.length;
});
var index = sorted.length;
str = sorted[index-1];
return str;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
This can be done through the youtube player API:
Working example:
<div id="player"></div>
<script src="http://www.youtube.com/player_api"></script>
<script>
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
width: '640',
height: '390',
videoId: '0Bmhjf0rKe8',
events: {
onReady: onPlayerReady,
onStateChange: onPlayerStateChange
}
});
}
// autoplay video
function onPlayerReady(event) {
event.target.playVideo();
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
alert('done');
}
}
</script>
One way to live-stream a RTSP-based webcam to a HTML5 client (involves re-encoding, so expect quality loss and needs some CPU-power):
On the machine receiving the stream from the camera, don't use FFMPEG but gstreamer. It is able to receive and decode the RTSP-stream, re-encode it and stream it to the icecast server. Example pipeline (only video, no audio):
gst-launch-1.0 rtspsrc location=rtsp://192.168.1.234:554 user-id=admin user-pw=123456 ! rtph264depay ! avdec_h264 ! vp8enc threads=2 deadline=10000 ! webmmux streamable=true ! shout2send password=pass ip=<IP_OF_ICECAST_SERVER> port=12000 mount=cam.webm
=> You can then use the <video> tag with the URL of the icecast-stream (http://127.0.0.1:12000/cam.webm) and it will work in every browser and device that supports webm