@user2302510 solution works not as good as you may expected. Full workaround for both orientations and dynamically data changes is:
public class MyLinearLayoutManager extends LinearLayoutManager {
public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
private int[] mMeasuredDimension = new int[2];
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
int width = 0;
int height = 0;
for (int i = 0; i < getItemCount(); i++) {
measureScrapChild(recycler, i,
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
mMeasuredDimension);
if (getOrientation() == HORIZONTAL) {
width = width + mMeasuredDimension[0];
if (i == 0) {
height = mMeasuredDimension[1];
}
} else {
height = height + mMeasuredDimension[1];
if (i == 0) {
width = mMeasuredDimension[0];
}
}
}
switch (widthMode) {
case View.MeasureSpec.EXACTLY:
width = widthSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
switch (heightMode) {
case View.MeasureSpec.EXACTLY:
height = heightSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
setMeasuredDimension(width, height);
}
private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
int heightSpec, int[] measuredDimension) {
View view = recycler.getViewForPosition(position);
if (view != null) {
RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
getPaddingLeft() + getPaddingRight(), p.width);
int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
getPaddingTop() + getPaddingBottom(), p.height);
view.measure(childWidthSpec, childHeightSpec);
measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
recycler.recycleView(view);
}
}
}
To answer the original question: yes, you can access the index value of a row in apply()
. It is available under the key name
and requires that you specify axis=1
(because the lambda processes the columns of a row and not the rows of a column).
Working example (pandas 0.23.4):
>>> import pandas as pd
>>> df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
>>> df.set_index('a', inplace=True)
>>> df
b c
a
1 2 3
4 5 6
>>> df['index_x10'] = df.apply(lambda row: 10*row.name, axis=1)
>>> df
b c index_x10
a
1 2 3 10
4 5 6 40
For what its worth: A decimal number, is a decimal number, you either round it to some other value or not. Internally, it will approximate a decimal fraction according to the rule of floating point arthmetic and handling. It stays a decimal number (floating point, in JS a double) internally, no matter how you many digits you want to display it with.
To present it for display, you can choose the precision of the display to whatever you want by string conversion. Presentation is a display issue, not a storage thing.
While I share the concerns regarding Java replacements for free-form SQL queries, I really do think people criticizing ORM are doing so because of a generally poor application design.
True OOD is driven by classes and relationships, and ORM gives you consistent mapping of different relationship types and objects. If you use an ORM tool and end up coding query expressions in whatever query language the ORM framework supports (including, but not limited to Java expression trees, query methods, OQL etc.), you are definitely doing something wrong, i.e. your class model most likely doesn't support your requirements in the way it should. A clean application design doesn't really need queries on the application level. I've been refactoring many projects people started out using an ORM framework in the same way as they were used to embed SQL string constants in their code, and in the end everyone was suprised about how simple and maintainable the whole application gets once you match up your class model with the usage model. Granted, for things like search functionality etc. you need a query language, but even then queries are so much constrained that creating an even complex VIEW and mapping that to a read-only persistent class is much nicer to maintain and look at than building expressions in some query language in the code of your application. The VIEW approach also leverages database capabilities and, via materialization, can be much better performance-wise than any hand-written SQL in your Java source. So, I don't see any reason for a non-trivial application NOT to use ORM.
For me, I just changed the selinux from enforcing to permissive and then I was able to start nginx without any error.
Unfortunately these new bootstrap 4 classes do not work like the old ones on a div using collapse
as they set the visible div to block
which starts out visible rather than hidden and if you add an extra div around the collapse
functionality no longer works.
You can use list comprehensions for this problem as it will solve it in only two lines. Code-
n = int(input("Enter the range of the list:\n"))
l1 = [i for i in range(n)] #Creates list of numbers in the range 0 to n
if __name__ == "__main__":
print(l1)
Thank you.
public class Match {
void comp(String s1, String s2) {
char[] charArray1 = s1.toCharArray();
char[] charArray2 = s2.toCharArray();
int length1 = charArray1.length;
int length2 = charArray2.length;
int flag = 0;
if (length1 == length2) {
for (int i = 0; i <= length1 - 1; i++) {
if (charArray1[i] == charArray2[i]) {
System.out.println("index are matched:" + " " + charArray1[i] + " " + "in index-" + i);
} else {
flag = 1;
System.out.println("index are not matched:" + " " + charArray1[i] + " " + "in index-" + i);
System.out.println("index are not matched:" + " " + charArray2[i] + " " + "in index-" + i);
}
}
} else {
System.out.println("Your string are not matched by length");
}
if (flag == 0) {
System.out.println("Your string matched with other String");
} else {
System.out.println("Your string are not matched");
}
}
public static void main(String[] args) {
java.util.Scanner sc = new java.util.Scanner(System.in);
System.out.println("Enter the 1st String:");
String s1 = sc.nextLine();
System.out.println("Enter the 2nd string");
String s2 = sc.nextLine();
Match m = new Match();
m.comp(s1, s2);
}
}
DateTimePicker1.value = Format(Date.Now)
It may need a backslash on the end of the line for continuation (although perhaps that depends on the version of make):
if [ -a myApp ] ; \
then \
rm myApp ; \
fi;
To use font awesome using css follow below steps -
step 1 - Add Fonts of FontAwesome in CSS
/*Font Awesome Fonts*/
@font-face {
font-family: 'FontAwesome';
//in url add your folder path of FontAwsome Fonts
src: url('font-awesome/fontawesome-webfont.ttf') format('truetype');
}
Step - 2 Use below css to apply font on class element of HTML
.sorting_asc:after {
content: "\f0de"; /* this is your text. You can also use UTF-8 character codes as I do here */
font-family: FontAwesome;
padding-left: 10px !important;
vertical-align: middle;
}
And finally, use "sorting_asc" class to apply the css on desired HTML tag/element.
Try docker inspect
, for example:
$ docker inspect --type=image treeder/hello.rb:nada
Error: No such image: treeder/hello.rb:nada
[]
But now with an image that exists, you'll get a bunch of information, eg:
$ docker inspect --type=image treeder/hello.rb:latest
[
{
"Id": "85c5116a2835521de2c52f10ab5dda0ff002a4a12aa476c141aace9bc67f43ad",
"Parent": "ecf63f5eb5e89e5974875da3998d72abc0d3d0e4ae2354887fffba037b356ad5",
"Comment": "",
"Created": "2015-09-23T22:06:38.86684783Z",
...
}
]
And it's in a nice json format.
A less elegant solution is taking the log 'manually' from the user data dir:
Set the user data dir to a fixed place:
options = new ChromeOptions();
capabilities = DesiredCapabilities.chrome();
options.addArguments("user-data-dir=/your_path/");
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
Get the text from the log file chrome_debug.log located in the path you've entered above.
I use this method since RemoteWebDriver
had problems getting the console logs remotely. If you run your test locally that can be easy to retrieve.
Here is a workaround to copy all the objects from one arrayList to another:
ArrayList<Object> myObject = new ArrayList<Object>();
ArrayList<Object> myTempObject = new ArrayList<Object>();
myObject.addAll(myTempObject.subList(0, myTempObject.size()));
subList is intended to return a List with a range of data. so you can copy the whole arrayList or part of it.
What sort of rounding behavior do you want? Do you 2.67 to turn into 3, or 2. If you want to use rounding, try this:
s = '234.67'
i = int(round(float(s)))
Otherwise, just do:
s = '234.67'
i = int(float(s))
Stumbled upon this question/answer while seeking how to compute the row sums of a matrix.
I would just like to add that Matlab's SUM function actually has support for summing for a given dimension, i.e a standard matrix with two dimensions.
So to calculate the column sums do:
colsum = sum(M) % or sum(M, 1)
and for the row sums, simply do
rowsum = sum(M, 2)
My bet is that this is faster than both programming a for loop and converting to cells :)
All this can be found in the matlab help for SUM.
You can do it in CSS, but there isn't much support in browsers other than modern versions of Chrome, Safari and Opera at the moment. Firefox currently only supports SVG masks. See the Caniuse results for more information.
CSS:
p {
color: red;
-webkit-mask-image: -webkit-gradient(linear, left top, left bottom,
from(rgba(0,0,0,1)), to(rgba(0,0,0,0)));
}
The trick is to specify a mask that is itself a gradient that ends as invisible (thru alpha value)
See a demo with a solid background, but you can change this to whatever you want.
Notice also that all the usual image properties are available for mask-image
p {_x000D_
color: red;_x000D_
font-size: 30px;_x000D_
-webkit-mask-image: linear-gradient(to left, rgba(0,0,0,1), rgba(0,0,0,0)), linear-gradient(to right, rgba(0,0,0,1), rgba(0,0,0,0));_x000D_
-webkit-mask-size: 100% 50%;_x000D_
-webkit-mask-repeat: no-repeat;_x000D_
-webkit-mask-position: left top, left bottom;_x000D_
}_x000D_
_x000D_
div {_x000D_
background-color: lightblue;_x000D_
}
_x000D_
<div><p>text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text </p></div>
_x000D_
Now, another approach is available, that is supported by Chrome, Firefox, Safari and Opera.
The idea is to use
mix-blend-mode: hard-light;
that gives transparency if the color is gray. Then, a grey overlay on the element creates the transparency
div {_x000D_
background-color: lightblue;_x000D_
}_x000D_
_x000D_
p {_x000D_
color: red;_x000D_
overflow: hidden;_x000D_
position: relative;_x000D_
width: 200px;_x000D_
mix-blend-mode: hard-light;_x000D_
}_x000D_
_x000D_
p::after {_x000D_
position: absolute;_x000D_
content: "";_x000D_
left: 0px;_x000D_
top: 0px;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
background: linear-gradient(transparent, gray);_x000D_
pointer-events: none;_x000D_
}
_x000D_
<div><p>text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text </p></div>
_x000D_
You are writing to memory you do not own:
int board[2][50]; //make an array with 3 columns (wrong)
//(actually makes an array with only two 'columns')
...
for (i=0; i<num3+1; i++)
board[2][i] = 'O';
^
Change this line:
int board[2][50]; //array with 2 columns (legal indices [0-1][0-49])
^
To:
int board[3][50]; //array with 3 columns (legal indices [0-2][0-49])
^
When creating an array, the value used to initialize: [3]
indicates array size.
However, when accessing existing array elements, index values are zero based.
For an array created: int board[3][50];
Legal indices are board[0][0]...board[2][49]
EDIT To address bad output comment and initialization comment
add an additional "\n" for formatting output:
Change:
...
for (k=0; k<50;k++) {
printf("%d",board[j][k]);
}
}
...
To:
...
for (k=0; k<50;k++) {
printf("%d",board[j][k]);
}
printf("\n");//at the end of every row, print a new line
}
...
Initialize board variable:
int board[3][50] = {0};//initialize all elements to zero
What you may actually want to use is an Iterable
that can return a fresh Iterator
multiple times by calling iterator()
.
//A function that needs to iterate multiple times can be given one Iterable:
public void func(Iterable<Type> ible) {
Iterator<Type> it = ible.iterator(); //Gets an iterator
while (it.hasNext()) {
it.next();
}
it = ible.iterator(); //Gets a NEW iterator, also from the beginning
while (it.hasNext()) {
it.next();
}
}
You must define what the iterator()
method does just once beforehand:
void main() {
LinkedList<String> list; //This could be any type of object that has an iterator
//Define an Iterable that knows how to retrieve a fresh iterator
Iterable<Type> ible = new Iterable<Type>() {
@Override
public Iterator<Type> iterator() {
return list.listIterator(); //Define how to get a fresh iterator from any object
}
};
//Now with a single instance of an Iterable,
func(ible); //you can iterate through it multiple times.
}
You can just create the required CORS configuration as a bean. As per the code below this will allow all requests coming from any origin. This is good for development but insecure. Spring Docs
@Bean
WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
}
}
}
For converting to Gradle is analogue to Maven:
Right click on Project -> submenu Configure -> Convert to Gradle (STS) Project
try this:
powershell "C:\Dummy Directory 1\Foo.ps1 'C:\Dummy Directory 2\File.txt'"
If you are using Netty, you can use:
Somebody asked me to post a link to the framework! that I presented at Open World 2012. This is the full blog post that demonstrates how to architect a solution with external tables.
You can use gcc/clang's unused attribute, however I use these macros in a header to avoid having gcc specific attributes all over the source, also having __attribute__
everywhere is a bit verbose/ugly.
#ifdef __GNUC__
# define UNUSED(x) UNUSED_ ## x __attribute__((__unused__))
#else
# define UNUSED(x) UNUSED_ ## x
#endif
#ifdef __GNUC__
# define UNUSED_FUNCTION(x) __attribute__((__unused__)) UNUSED_ ## x
#else
# define UNUSED_FUNCTION(x) UNUSED_ ## x
#endif
Then you can do...
void foo(int UNUSED(bar)) { ... }
I prefer this because you get an error if you try use bar
in the code anywhere so you can't leave the attribute in by mistake.
and for functions...
static void UNUSED_FUNCTION(foo)(int bar) { ... }
Note 1):
As far as I know, MSVC doesn't have an equivalent to __attribute__((__unused__))
.
Note 2):
The UNUSED
macro won't work for arguments which contain parenthesis,
so if you have an argument like float (*coords)[3]
you can't do,float UNUSED((*coords)[3])
or float (*UNUSED(coords))[3]
, This is the only downside to the UNUSED
macro I found so far, in these cases I fall back to (void)coords;
Count and show keys in a dictionary (run in console):
o=[];count=0; for (i in topicNames) { ++count; o.push(count+": "+ i) } o.join("\n")
Sample output:
"1: Phase-out Left-hand
2: Define All Top Level Taxonomies But Processes
3: 987
4: 16:00
5: Identify suppliers"
Simple count function:
function size_dict(d){c=0; for (i in d) ++c; return c}
To bring the element to the center of the container.
function scrollToCenter() {
var container = $('.container'),
scrollTo = $('.5');
container.animate({
//scrolls to center
scrollTop: scrollTo.offset().top - container.offset().top + scrollTo.scrollTop() - container.height() / 2
});
}
<div class="container">
<div class="1">
1
</div>
<div class="2">
2
</div>
<div class="3">
3
</div>
<div class="4">
4
</div>
<div class="5">
5
</div>
<div class="6">
6
</div>
<div class="7">
7
</div>
<div class="8">
8
</div>
<div class="9">
9
</div>
<div class="10">
10
</div>
</div>
<br>
<br>
<button id="scroll" onclick="scrollToCenter()">
Scroll
</button>
.container {
height: 60px;
overflow-y: scroll;
width 60px;
background-color: white;
}
It is not exact to the center but you will not recognice it on larger bigger elements.
or you can use this, the '-1' means you don't have to specify the number of the elements.
In [3]: a.view(1,-1)
Out[3]:
1 2 3 4 5
[torch.FloatTensor of size 1x5]
You need to unicode each element of the list individually
[x.encode('utf-8') for x in tmp]
you can do something like adding a class to add border radius
HTML:
<a href="#" class="btn btn-default btn-circle"><i class="fa fa-user"></i></a>
CSS:
.btn-circle {
width: 30px;
height: 30px;
text-align: center;
padding: 6px 0;
font-size: 12px;
line-height: 1.42;
border-radius: 15px;
}
in case you wanted to change dimension you need to change the font size or padding accordingly
One of the things I would suggest is to have two separate stylesheets: One with your regular style definitions and another one that contains your images in base64 encoding.
You have to include the base stylesheet before the image stylesheet of course.
This way you will assure that you're regular stylesheet is downloaded and applied as soon as possible to the document, yet at the same time you profit from reduced http-requests and other benefits data-uris give you.
Really old post but in case someone is unaware...
In Visual Studio 2015, you can place a breakpoint on the set
accessor of an Auto-Implemented Property and the debugger will break when the property is updated
public bool IsUpdated
{
get;
set; //set breakpoint on this line
}
Update
Alternatively; @AbdulRaufMujahid has pointed out in the comments that if the auto implemented property is on a single line, you can position your cursor at the get;
or set;
and hit F9
and a breakpoint will be placed accordingly. Nice!
public bool IsUpdated { get; set; }
get radio value by name
$('input').on('className', function(event){
console.log($(this).attr('name'));
if($(this).attr('name') == "worker")
{
resetAll();
}
});
In my case, the problem was in vscode.
I use windows and installed Ubuntu on my computer, so vscode terminal uses the Ubuntu. I just go to settings.json and change to cmd.exe again
Change position:absolute
to position:fixed;
.
Example can be found in this jsFiddle.
Do following:
sudo apt update
sudo apt install python3-pip
source ~/.bashrc
This will surely install pip with all its dependencies. PS this is for python 3 if you want for python 2 replace python3 from the second command to python
sudo apt install python-pip
Have a look at: https://developers.google.com/accounts/docs/OAuth2UserAgent#handlingtheresponse
It says:
Other parameters included in the response include
expires_in
andtoken_type
. These parameters describe the lifetime of the token in seconds...
A regular pull is fetch + merge, but what you want is fetch + rebase. This is an option with the pull
command:
git pull --rebase
As another anwsers told, you can change in a Session Listener. But you can change it directly in your servlet, for example.
getRequest().getSession().setMaxInactiveInterval(123);
Your error is caused by these:
Dim oTable As Table, oRow As Row,
These types, Table
and Row
are not variable types native to Excel. You can resolve this in one of two ways:
Dim oTable as Word.Table, oRow as Word.Row
. This is called early-binding. Object
type: Dim oTable as Object, oRow as Object
. With this method, you do not need to add the reference to Word, but you also lose the intellisense assistance in the VBE.I have not tested your code but I suspect ActiveDocument
won't work in Excel with method #2, unless you properly scope it to an instance of a Word.Application object. I don't see that anywhere in the code you have provided. An example would be like:
Sub DeleteEmptyRows()
Dim wdApp as Object
Dim oTable As Object, As Object, _
TextInRow As Boolean, i As Long
Set wdApp = GetObject(,"Word.Application")
Application.ScreenUpdating = False
For Each oTable In wdApp.ActiveDocument.Tables
The Lazy<T>
version:
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy
= new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance
=> lazy.Value;
private Singleton() { }
}
Requires .NET 4 and C# 6.0 (VS2015) or newer.
In order to format std::string
in a 'sprintf' manner, call snprintf
(arguments nullptr
and 0
) to get length of buffer needed. Write your function using C++11 variadic template like this:
#include <cstdio>
#include <string>
#include <cassert>
template< typename... Args >
std::string string_sprintf( const char* format, Args... args ) {
int length = std::snprintf( nullptr, 0, format, args... );
assert( length >= 0 );
char* buf = new char[length + 1];
std::snprintf( buf, length + 1, format, args... );
std::string str( buf );
delete[] buf;
return str;
}
Compile with C++11 support, for example in GCC: g++ -std=c++11
Usage:
std::cout << string_sprintf("%g, %g\n", 1.23, 0.001);
Typedef allows items to be implicitly assigned to types they are not. Some people try to get around this with extensions; read here at IBM for an explanation of why this is a bad idea.
Edit: While strong type inference is a useful thing, I don't think (and hope we won't) see typedef
rearing it's ugly head in managed languages (ever?).
Edit 2: In C#, you can use a using statement like this at the top of a source file. It's used so you don't have to do the second item shown. The only time you see the name change is when a scope introduces a name collision between two types. The renaming is limited to one file, outside of which every variable/parameter type which used it is known by its full name.
using Path = System.IO.Path;
using System.IO;
Since nobody has mentioned this..
If all you want is an array of values, an easier alternative would be to use the .map()
method. Just remember to call .get()
to convert the jQuery object to an array:
var names = $('.parent input:checked').map(function () {
return this.name;
}).get();
console.log(names);
var names = $('.parent input:checked').map(function () {_x000D_
return this.name;_x000D_
}).get();_x000D_
_x000D_
console.log(names);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="parent">_x000D_
<input type="checkbox" name="name1" />_x000D_
<input type="checkbox" name="name2" />_x000D_
<input type="checkbox" name="name3" checked="checked" />_x000D_
<input type="checkbox" name="name4" checked="checked" />_x000D_
<input type="checkbox" name="name5" />_x000D_
</div>
_x000D_
Pure JavaScript:
var elements = document.querySelectorAll('.parent input:checked');
var names = Array.prototype.map.call(elements, function(el, i) {
return el.name;
});
console.log(names);
var elements = document.querySelectorAll('.parent input:checked');_x000D_
var names = Array.prototype.map.call(elements, function(el, i){_x000D_
return el.name;_x000D_
});_x000D_
_x000D_
console.log(names);
_x000D_
<div class="parent">_x000D_
<input type="checkbox" name="name1" />_x000D_
<input type="checkbox" name="name2" />_x000D_
<input type="checkbox" name="name3" checked="checked" />_x000D_
<input type="checkbox" name="name4" checked="checked" />_x000D_
<input type="checkbox" name="name5" />_x000D_
</div>
_x000D_
I'd just store it as CSV, if it's simple values then it should be all you need (XML is very verbose and serializing to/from it would probably be overkill but that would be an option as well).
Here's a good answer for how to pull out CSVs with LINQ.
I've join some informations posted here and the possibility of personalize components with Angular Material and this is my contribution without external libs and feedback with the name of the chosen file into field:
HTML
<mat-form-field class="columns">
<mat-label *ngIf="selectedFiles; else newFile">{{selectedFiles.item(0).name}}</mat-label>
<ng-template #newFile>
<mat-label>Choose file</mat-label>
</ng-template>
<input matInput disabled>
<button mat-icon-button matSuffix (click)="fileInput.click()">
<mat-icon>attach_file</mat-icon>
</button>
<input hidden (change)="selectFile($event)" #fileInput type="file" id="file">
</mat-form-field>
TS
selectFile(event) {
this.selectedFiles = event.target.files;
}
This is the solution we went with. Simply save the scroll position when the overlay is opened, scroll back to the saved position any time the user attempted to scroll the page, and turn the listener off when the overlay is closed.
It's a bit jumpy on IE, but works like a charm on Firefox/Chrome.
var body = $("body"),_x000D_
overlay = $("#overlay"),_x000D_
overlayShown = false,_x000D_
overlayScrollListener = null,_x000D_
overlaySavedScrollTop = 0,_x000D_
overlaySavedScrollLeft = 0;_x000D_
_x000D_
function showOverlay() {_x000D_
overlayShown = true;_x000D_
_x000D_
// Show overlay_x000D_
overlay.addClass("overlay-shown");_x000D_
_x000D_
// Save scroll position_x000D_
overlaySavedScrollTop = body.scrollTop();_x000D_
overlaySavedScrollLeft = body.scrollLeft();_x000D_
_x000D_
// Listen for scroll event_x000D_
overlayScrollListener = body.scroll(function() {_x000D_
// Scroll back to saved position_x000D_
body.scrollTop(overlaySavedScrollTop);_x000D_
body.scrollLeft(overlaySavedScrollLeft);_x000D_
});_x000D_
}_x000D_
_x000D_
function hideOverlay() {_x000D_
overlayShown = false;_x000D_
_x000D_
// Hide overlay_x000D_
overlay.removeClass("overlay-shown");_x000D_
_x000D_
// Turn scroll listener off_x000D_
if (overlayScrollListener) {_x000D_
overlayScrollListener.off();_x000D_
overlayScrollListener = null;_x000D_
}_x000D_
}_x000D_
_x000D_
// Click toggles overlay_x000D_
$(window).click(function() {_x000D_
if (!overlayShown) {_x000D_
showOverlay();_x000D_
} else {_x000D_
hideOverlay();_x000D_
}_x000D_
});
_x000D_
/* Required */_x000D_
html, body { margin: 0; padding: 0; height: 100%; background: #fff; }_x000D_
html { overflow: hidden; }_x000D_
body { overflow-y: scroll; }_x000D_
_x000D_
/* Just for looks */_x000D_
.spacer { height: 300%; background: orange; background: linear-gradient(#ff0, #f0f); }_x000D_
.overlay { position: fixed; top: 20px; bottom: 20px; left: 20px; right: 20px; z-index: -1; background: #fff; box-shadow: 0 0 5px rgba(0, 0, 0, .3); overflow: auto; }_x000D_
.overlay .spacer { background: linear-gradient(#88f, #0ff); }_x000D_
.overlay-shown { z-index: 1; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<h1>Top of page</h1>_x000D_
<p>Click to toggle overlay. (This is only scrollable when overlay is <em>not</em> open.)</p>_x000D_
<div class="spacer"></div>_x000D_
<h1>Bottom of page</h1>_x000D_
<div id="overlay" class="overlay">_x000D_
<h1>Top of overlay</h1>_x000D_
<p>Click to toggle overlay. (Containing page is no longer scrollable, but this is.)</p>_x000D_
<div class="spacer"></div>_x000D_
<h1>Bottom of overlay</h1>_x000D_
</div>
_x000D_
suppose you don't have column for auto increment like id, no, then you can add using following query:
ALTER TABLE table_name ADD id int NOT NULL AUTO_INCREMENT primary key FIRST
If you've column, then alter to auto increment using following query:
ALTER TABLE table_name MODIFY column_name datatype(length) AUTO_INCREMENT PRIMARY KEY
Use the REPLACE function.
eg: SELECT REPLACE ('t?es?t', '?', 'w');
There are two stages to processing Unicode text. The first is "how can I input it and output it without losing information". The second is "how do I treat text according to local language conventions".
tchrist's post covers both, but the second part is where 99% of the text in his post comes from. Most programs don't even handle I/O correctly, so it's important to understand that before you even begin to worry about normalization and collation.
This post aims to solve that first problem
When you read data into Perl, it doesn't care what encoding it is. It allocates some memory and stashes the bytes away there. If you say print $str
, it just blits those bytes out to your terminal, which is probably set to assume everything that is written to it is UTF-8, and your text shows up.
Marvelous.
Except, it's not. If you try to treat the data as text, you'll see that Something Bad is happening. You need go no further than length
to see that what Perl thinks about your string and what you think about your string disagree. Write a one-liner like: perl -E 'while(<>){ chomp; say length }'
and type in ????
and you get 12... not the correct answer, 4.
That's because Perl assumes your string is not text. You have to tell it that it's text before it will give you the right answer.
That's easy enough; the Encode module has the functions to do that. The generic entry point is Encode::decode
(or use Encode qw(decode)
, of course). That function takes some string from the outside world (what we'll call "octets", a fancy of way of saying "8-bit bytes"), and turns it into some text that Perl will understand. The first argument is a character encoding name, like "UTF-8" or "ASCII" or "EUC-JP". The second argument is the string. The return value is the Perl scalar containing the text.
(There is also Encode::decode_utf8
, which assumes UTF-8 for the encoding.)
If we rewrite our one-liner:
perl -MEncode=decode -E 'while(<>){ chomp; say length decode("UTF-8", $_) }'
We type in ???? and get "4" as the result. Success.
That, right there, is the solution to 99% of Unicode problems in Perl.
The key is, whenever any text comes into your program, you must decode it. The Internet cannot transmit characters. Files cannot store characters. There are no characters in your database. There are only octets, and you can't treat octets as characters in Perl. You must decode the encoded octets into Perl characters with the Encode module.
The other half of the problem is getting data out of your program. That's easy to; you just say use Encode qw(encode)
, decide what the encoding your data will be in (UTF-8 to terminals that understand UTF-8, UTF-16 for files on Windows, etc.), and then output the result of encode($encoding, $data)
instead of just outputting $data
.
This operation converts Perl's characters, which is what your program operates on, to octets that can be used by the outside world. It would be a lot easier if we could just send characters over the Internet or to our terminals, but we can't: octets only. So we have to convert characters to octets, otherwise the results are undefined.
To summarize: encode all outputs and decode all inputs.
Now we'll talk about three issues that make this a little challenging. The first is libraries. Do they handle text correctly? The answer is... they try. If you download a web page, LWP will give you your result back as text. If you call the right method on the result, that is (and that happens to be decoded_content
, not content
, which is just the octet stream that it got from the server.) Database drivers can be flaky; if you use DBD::SQLite with just Perl, it will work out, but if some other tool has put text stored as some encoding other than UTF-8 in your database... well... it's not going to be handled correctly until you write code to handle it correctly.
Outputting data is usually easier, but if you see "wide character in print", then you know you're messing up the encoding somewhere. That warning means "hey, you're trying to leak Perl characters to the outside world and that doesn't make any sense". Your program appears to work (because the other end usually handles the raw Perl characters correctly), but it is very broken and could stop working at any moment. Fix it with an explicit Encode::encode
!
The second problem is UTF-8 encoded source code. Unless you say use utf8
at the top of each file, Perl will not assume that your source code is UTF-8. This means that each time you say something like my $var = '??'
, you're injecting garbage into your program that will totally break everything horribly. You don't have to "use utf8", but if you don't, you must not use any non-ASCII characters in your program.
The third problem is how Perl handles The Past. A long time ago, there was no such thing as Unicode, and Perl assumed that everything was Latin-1 text or binary. So when data comes into your program and you start treating it as text, Perl treats each octet as a Latin-1 character. That's why, when we asked for the length of "????", we got 12. Perl assumed that we were operating on the Latin-1 string "æååã" (which is 12 characters, some of which are non-printing).
This is called an "implicit upgrade", and it's a perfectly reasonable thing to do, but it's not what you want if your text is not Latin-1. That's why it's critical to explicitly decode input: if you don't do it, Perl will, and it might do it wrong.
People run into trouble where half their data is a proper character string, and some is still binary. Perl will interpret the part that's still binary as though it's Latin-1 text and then combine it with the correct character data. This will make it look like handling your characters correctly broke your program, but in reality, you just haven't fixed it enough.
Here's an example: you have a program that reads a UTF-8-encoded text file, you tack on a Unicode PILE OF POO
to each line, and you print it out. You write it like:
while(<>){
chomp;
say "$_ ";
}
And then run on some UTF-8 encoded data, like:
perl poo.pl input-data.txt
It prints the UTF-8 data with a poo at the end of each line. Perfect, my program works!
But nope, you're just doing binary concatenation. You're reading octets from the file, removing a \n
with chomp, and then tacking on the bytes in the UTF-8 representation of the PILE OF POO
character. When you revise your program to decode the data from the file and encode the output, you'll notice that you get garbage ("ð©") instead of the poo. This will lead you to believe that decoding the input file is the wrong thing to do. It's not.
The problem is that the poo is being implicitly upgraded as latin-1. If you use utf8
to make the literal text instead of binary, then it will work again!
(That's the number one problem I see when helping people with Unicode. They did part right and that broke their program. That's what's sad about undefined results: you can have a working program for a long time, but when you start to repair it, it breaks. Don't worry; if you are adding encode/decode statements to your program and it breaks, it just means you have more work to do. Next time, when you design with Unicode in mind from the beginning, it will be much easier!)
That's really all you need to know about Perl and Unicode. If you tell Perl what your data is, it has the best Unicode support among all popular programming languages. If you assume it will magically know what sort of text you are feeding it, though, then you're going to trash your data irrevocably. Just because your program works today on your UTF-8 terminal doesn't mean it will work tomorrow on a UTF-16 encoded file. So make it safe now, and save yourself the headache of trashing your users' data!
The easy part of handling Unicode is encoding output and decoding input. The hard part is finding all your input and output, and determining which encoding it is. But that's why you get the big bucks :)
Here is the key code for each key stroke in JavaScript. You can use that and detect if the user has pressed the Shift key.
backspace 8
tab 9
enter 13
shift 16
ctrl 17
alt 18
pause/break 19
caps lock 20
escape 27
page up 33
page down 34
end 35
home 36
left arrow 37
up arrow 38
right arrow 39
down arrow 40
insert 45
delete 46
0 48
1 49
2 50
3 51
4 52
5 53
6 54
7 55
8 56
9 57
a 65
b 66
c 67
d 68
e 69
f 70
g 71
h 72
i 73
j 74
k 75
l 76
m 77
n 78
o 79
p 80
q 81
r 82
s 83
t 84
u 85
v 86
w 87
x 88
y 89
z 90
left window key 91
right window key 92
select key 93
numpad 0 96
numpad 1 97
numpad 2 98
numpad 3 99
numpad 4 100
numpad 5 101
numpad 6 102
numpad 7 103
numpad 8 104
numpad 9 105
multiply 106
add 107
subtract 109
decimal point 110
divide 111
f1 112
f2 113
f3 114
f4 115
f5 116
f6 117
f7 118
f8 119
f9 120
f10 121
f11 122
f12 123
num lock 144
scroll lock 145
semi-colon 186
equal sign 187
comma 188
dash 189
period 190
forward slash 191
grave accent 192
open bracket 219
back slash 220
close braket 221
single quote 222
Not all browsers handle the keypress event well, so use either the key up or the key down event, like this:
$(document).keydown(function (e) {
if (e.keyCode == 16) {
alert(e.which + " or Shift was pressed");
}
});
Note that if you want to scroll an element instead of the full window, elements don't have the scrollTo
and scrollBy
methods. You should:
var el = document.getElementById("myel"); // Or whatever method to get the element
// To set the scroll
el.scrollTop = 0;
el.scrollLeft = 0;
// To increment the scroll
el.scrollTop += 100;
el.scrollLeft += 100;
You can also mimic the window.scrollTo
and window.scrollBy
functions to all the existant HTML elements in the webpage on browsers that don't support it natively:
Object.defineProperty(HTMLElement.prototype, "scrollTo", {
value: function(x, y) {
el.scrollTop = y;
el.scrollLeft = x;
},
enumerable: false
});
Object.defineProperty(HTMLElement.prototype, "scrollBy", {
value: function(x, y) {
el.scrollTop += y;
el.scrollLeft += x;
},
enumerable: false
});
so you can do:
var el = document.getElementById("myel"); // Or whatever method to get the element, again
// To set the scroll
el.scrollTo(0, 0);
// To increment the scroll
el.scrollBy(100, 100);
NOTE: Object.defineProperty
is encouraged, as directly adding properties to the prototype
is a breaking bad habit (When you see it :-).
For your specific question about WordPress, use the following code:
if (!is_dir(ABSPATH . 'wp-content/uploads')) wp_mkdir_p(ABSPATH . 'wp-content/uploads');
Function Reference: WordPress wp_mkdir_p. ABSPATH is the constant that returns WordPress working directory path.
The following code is for PHP in general.
if (!is_dir('path/to/directory')) mkdir('path/to/directory', 0777, true);
Function reference: PHP is_dir()
I realize this post is old but I wanted to add that I had to take an extra step to get this to work.
Instead of just doing:
pip install pywin32
I had use use the -m
flag to get this to work properly. Without it I was running into an issue where I was still getting the error ImportError: No module named win32com
.
So to fix this you can give this a try:
python -m pip install pywin32
This worked for me and has worked on several version of python where just doing pip install pywin32
did not work.
Versions tested on:
3.6.2, 3.7.6, 3.8.0, 3.9.0a1.
To debug / inspect your rpm I suggest to use redline which is a java program
Usage :
java -cp redline-1.2.1-jar-with-dependencies.jar org.redline_rpm.Scanner foo.rpm
For me I got NumberFormatException when trying to deal with the negative numbers. I used the following for the negative and positive numbers.
System.out.println(Integer.parseUnsignedInt("11111111111111111111111111110111", 2));
Output : -9
I just came across this, while looking for something else.
I would recommend to go with the methods in the os
package. This is because you can make it more general, compensating for any weird case.
You can do something like:
import os
the_file = 'aaaa/bbbb/ccc.ddd'
extensions_list = ['ddd', 'eee', 'fff']
if os.path.splitext(the_file)[-1] in extensions_list:
# Do your thing.
It depends on how you tested it, and possibly on differences in the TCP stack implementation of the personal computer and the server.
For example, if your sendall
always completes immediately (or very quickly) on the personal computer, the connection may simply never have broken during sending. This is very likely if your browser is running on the same machine (since there is no real network latency).
In general, you just need to handle the case where a client disconnects before you're finished, by handling the exception.
Remember that TCP communications are asynchronous, but this is much more obvious on physically remote connections than on local ones, so conditions like this can be hard to reproduce on a local workstation. Specifically, loopback connections on a single machine are often almost synchronous.
Geez, seems like a lot of code going on here for this. Stas above had the right approach for minimal effort. Here is my adaptation (using MVVMLight but should be recognizable)... Oh and the PassEventArgsToCommand="True" is definitely needed as indicated above.
(credit to Laurent Bugnion http://blog.galasoft.ch/archive/2009/10/18/clean-shutdown-in-silverlight-and-wpf-applications.aspx)
... MainWindow Xaml
...
WindowStyle="ThreeDBorderWindow"
WindowStartupLocation="Manual">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Closing">
<cmd:EventToCommand Command="{Binding WindowClosingCommand}" PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
In the view model:
///<summary>
/// public RelayCommand<CancelEventArgs> WindowClosingCommand
///</summary>
public RelayCommand<CancelEventArgs> WindowClosingCommand { get; private set; }
...
...
...
// Window Closing
WindowClosingCommand = new RelayCommand<CancelEventArgs>((args) =>
{
ShutdownService.MainWindowClosing(args);
},
(args) => CanShutdown);
in the ShutdownService
/// <summary>
/// ask the application to shutdown
/// </summary>
public static void MainWindowClosing(CancelEventArgs e)
{
e.Cancel = true; /// CANCEL THE CLOSE - let the shutdown service decide what to do with the shutdown request
RequestShutdown();
}
RequestShutdown looks something like the following but basicallyRequestShutdown or whatever it is named decides whether to shutdown the application or not (which will merrily close the window anyway):
...
...
...
/// <summary>
/// ask the application to shutdown
/// </summary>
public static void RequestShutdown()
{
// Unless one of the listeners aborted the shutdown, we proceed. If they abort the shutdown, they are responsible for restarting it too.
var shouldAbortShutdown = false;
Logger.InfoFormat("Application starting shutdown at {0}...", DateTime.Now);
var msg = new NotificationMessageAction<bool>(
Notifications.ConfirmShutdown,
shouldAbort => shouldAbortShutdown |= shouldAbort);
// recipients should answer either true or false with msg.execute(true) etc.
Messenger.Default.Send(msg, Notifications.ConfirmShutdown);
if (!shouldAbortShutdown)
{
// This time it is for real
Messenger.Default.Send(new NotificationMessage(Notifications.NotifyShutdown),
Notifications.NotifyShutdown);
Logger.InfoFormat("Application has shutdown at {0}", DateTime.Now);
Application.Current.Shutdown();
}
else
Logger.InfoFormat("Application shutdown aborted at {0}", DateTime.Now);
}
}
Here is an implementation, character by character. Should work with "(One Two Three)"
public static string ToInitcap(this string str)
{
if (string.IsNullOrEmpty(str))
return str;
char[] charArray = new char[str.Length];
bool newWord = true;
for (int i = 0; i < str.Length; ++i)
{
Char currentChar = str[i];
if (Char.IsLetter(currentChar))
{
if (newWord)
{
newWord = false;
currentChar = Char.ToUpper(currentChar);
}
else
{
currentChar = Char.ToLower(currentChar);
}
}
else if (Char.IsWhiteSpace(currentChar))
{
newWord = true;
}
charArray[i] = currentChar;
}
return new string(charArray);
}
you can run something like this (paste the code bellow in a .bat, or if you want it to run interractively replace the %%
by %
:
for %%i in (c:\directory\*.xls) do ssconvert %%i %%i.xlsx
If you can run powershell it will be :
Get-ChildItem -Path c:\directory -filter *.xls | foreach {ssconvert $($_.FullName) $($_.baseName).xlsx }
I had a similar issue. The Maven projects have different structure than "Dynamic Web Projects". Eclipse knows only how to deploy the Dynamic Web Projects (project structure used by Web Tools Platform).
In order to solve this and tell Eclipse how to deploy a "maven style" projects, you have to install the M2E Eclipse WTP plugin (I suppose you are already using the m2e plugin).
To install: Preferences->Maven->Discovery->Open Catalog and choose the WTP plugin.
After reinstalling, you will be able to "run on server" those projects which are maven web projects.
Hope that helps,
Let me share my experience for this issue fix.
Open target -> Build phases -> Copy Bundle Resources and remove info.plist.
Note: If you're using any extensions, remove the info.plist of that extension from the Targets.
Hope it helps.
I recommend Javascript, because its relatively fast and more malleable.
<script>
function showStuff(id, text, btn) {
document.getElementById(id).style.display = 'block';
// hide the lorem ipsum text
document.getElementById(text).style.display = 'none';
// hide the link
btn.style.display = 'none';
}
</script>
<td class="post">
<a href="#" onclick="showStuff('answer1', 'text1', this); return false;">Edit</a>
<span id="answer1" style="display: none;">
<textarea rows="10" cols="115"></textarea>
</span>
<span id="text1">Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</span>
</td>
Two things, you can use memory instead of /tmp in any kernel 2.6 by using /dev/shm (Redhat) other distros may vary. Also hget can be reimplemented using read as follows:
function hget {
while read key idx
do
if [ $key = $2 ]
then
echo $idx
return
fi
done < /dev/shm/hashmap.$1
}
In addition by assuming that all keys are unique, the return short circuits the read loop and prevents having to read through all entries. If your implementation can have duplicate keys, then simply leave out the return. This saves the expense of reading and forking both grep and awk. Using /dev/shm for both implementations yielded the following using time hget on a 3 entry hash searching for the last entry :
Grep/Awk:
hget() {
grep "^$2 " /dev/shm/hashmap.$1 | awk '{ print $2 };'
}
$ time echo $(hget FD oracle)
3
real 0m0.011s
user 0m0.002s
sys 0m0.013s
Read/echo:
$ time echo $(hget FD oracle)
3
real 0m0.004s
user 0m0.000s
sys 0m0.004s
on multiple invocations I never saw less then a 50% improvement.
This can all be attributed to fork over head, due to the use of /dev/shm
.
FYI - I have been struggling with this issue for the past 3 hours. tried everything, flushing DNS, using a proxy, resetting catalog using netsh and clearing the routes. nothing worked so i decided to give windows restore a try, I did it using a windows cd -> repair -> system restore and it worked ! couldnt find any solutions online so i figured id post it
In Python 3 (I haven't tried this in Python 2), you can also simply do
with open('output.csv','w',newline='') as f:
writer=csv.writer(f)
writer.writerow(mystuff)
...
as per documentation.
More on this in the doc's footnote:
If newline='' is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use \r\n linendings on write an extra \r will be added. It should always be safe to specify newline='', since the csv module does its own (universal) newline handling.
Looks like problem of configuration for maven compiler in your pom file. Default version java source and target is 1.5, even used JDK has higher version.
To fix, add maven compiler plugin configuration section with higher java version, example:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
For more info check these links:
maybe doesnt exists javaee-api-7.0.jar. download this jar and on your project right clik
You have to use '"+texbox1.Text+"','"+texbox2.Text+"','"+texbox3.Text+"'
Instead of "+texbox1.Text+","+texbox2.Text+","+texbox3.Text+"
Notice the extra single quotes.
Better to use:
DELETE tbl FROM tbl INNER JOIN deleted ON tbl.key=deleted.key
Requests doesn't have an equivalent to Urlib2's read()
.
>>> import requests
>>> response = requests.get("http://www.google.com")
>>> print response.content
'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage"><head>....'
>>> print response.content == response.text
True
It looks like the POST request you are making is returning no content. Which is often the case with a POST request. Perhaps it set a cookie? The status code is telling you that the POST succeeded after all.
Edit for Python 3:
Python now handles data types differently. response.content
returns a sequence of bytes
(integers that represent ASCII) while response.text
is a string
(sequence of chars).
Thus,
>>> print response.content == response.text
False
>>> print str(response.content) == response.text
True
isin()
is ideal if you have a list of exact matches, but if you have a list of partial matches or substrings to look for, you can filter using the str.contains
method and regular expressions.
For example, if we want to return a DataFrame where all of the stock IDs which begin with '600'
and then are followed by any three digits:
>>> rpt[rpt['STK_ID'].str.contains(r'^600[0-9]{3}$')] # ^ means start of string
... STK_ID ... # [0-9]{3} means any three digits
... '600809' ... # $ means end of string
... '600141' ...
... '600329' ...
... ... ...
Suppose now we have a list of strings which we want the values in 'STK_ID'
to end with, e.g.
endstrings = ['01$', '02$', '05$']
We can join these strings with the regex 'or' character |
and pass the string to str.contains
to filter the DataFrame:
>>> rpt[rpt['STK_ID'].str.contains('|'.join(endstrings)]
... STK_ID ...
... '155905' ...
... '633101' ...
... '210302' ...
... ... ...
Finally, contains
can ignore case (by setting case=False
), allowing you to be more general when specifying the strings you want to match.
For example,
str.contains('pandas', case=False)
would match PANDAS
, PanDAs
, paNdAs123
, and so on.
You could try
lsb_release -a
which works on at least Debian and Ubuntu (and since it's LSB, it should surely be on most of the other mainstream distros at least). http://rpmfind.net/linux/RPM/sourceforge/l/ls/lsb/lsb_release-1.0-1.i386.html suggests it's been around quite a while.
It sounds like this
in your code is not referring to your .btn
element. Try referencing it explicitly with a selector:
var votevalue = parseInt($(".btn").data('votevalue'), 10);
Also, don't forget the radix.
This is the best code to centre the div bot horizontally and vertically
div_x000D_
{_x000D_
position:absolute;_x000D_
top:50%;_x000D_
left:50%;_x000D_
transform:translate(-50%,-50%);_x000D_
}
_x000D_
I found this command line utility that doesn't show the GUI output but gave me what I needed: https://github.com/na-ka-na/ExcelCompare
Sample output (taken from the project's readme file):
> excel_cmp xxx.xlsx yyy.xlsx
DIFF Cell at Sheet1!A1 => 'a' v/s 'aa'
EXTRA Cell in WB1 Sheet1!B1 => 'cc'
DIFF Cell at Sheet1!D4 => '4.0' v/s '14.0'
EXTRA Cell in WB2 Sheet1!J10 => 'j'
EXTRA Cell in WB1 Sheet1!K11 => 'k'
EXTRA Cell in WB1 Sheet2!A1 => 'abc'
EXTRA Cell in WB2 Sheet3!A1 => 'haha'
----------------- DIFF -------------------
Sheets: [Sheet1]
Rows: [1, 4]
Cols: [A, D]
----------------- EXTRA WB1 -------------------
Sheets: [Sheet1, Sheet2]
Rows: [1, 11]
Cols: [B, K, A]
----------------- EXTRA WB2 -------------------
Sheets: [Sheet1, Sheet3]
Rows: [10, 1]
Cols: [J, A]
-----------------------------------------
Excel files xxx.xlsx and yyy.xlsx differ
You can implement this code to select image from gallery or camera :-
private ImageView imageview;
private Button btnSelectImage;
private Bitmap bitmap;
private File destination = null;
private InputStream inputStreamImg;
private String imgPath = null;
private final int PICK_IMAGE_CAMERA = 1, PICK_IMAGE_GALLERY = 2;
Now on button click event, you can able to call your method of select Image. This is inside activity's onCreate.
imageview = (ImageView) findViewById(R.id.imageview);
btnSelectImage = (Button) findViewById(R.id.btnSelectImage);
//OnbtnSelectImage click event...
btnSelectImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectImage();
}
});
Outside of your activity's oncreate.
// Select image from camera and gallery
private void selectImage() {
try {
PackageManager pm = getPackageManager();
int hasPerm = pm.checkPermission(Manifest.permission.CAMERA, getPackageName());
if (hasPerm == PackageManager.PERMISSION_GRANTED) {
final CharSequence[] options = {"Take Photo", "Choose From Gallery","Cancel"};
android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(activity);
builder.setTitle("Select Option");
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
dialog.dismiss();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, PICK_IMAGE_CAMERA);
} else if (options[item].equals("Choose From Gallery")) {
dialog.dismiss();
Intent pickPhoto = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, PICK_IMAGE_GALLERY);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
} else
Toast.makeText(this, "Camera Permission error", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, "Camera Permission error", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
inputStreamImg = null;
if (requestCode == PICK_IMAGE_CAMERA) {
try {
Uri selectedImage = data.getData();
bitmap = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bytes);
Log.e("Activity", "Pick from Camera::>>> ");
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
destination = new File(Environment.getExternalStorageDirectory() + "/" +
getString(R.string.app_name), "IMG_" + timeStamp + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
imgPath = destination.getAbsolutePath();
imageview.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == PICK_IMAGE_GALLERY) {
Uri selectedImage = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bytes);
Log.e("Activity", "Pick from Gallery::>>> ");
imgPath = getRealPathFromURI(selectedImage);
destination = new File(imgPath.toString());
imageview.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public String getRealPathFromURI(Uri contentUri) {
String[] proj = {MediaStore.Audio.Media.DATA};
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
Atlast, finally add the camera and write external storage permission to AndroidManifest.xml
It works for me greatly, hope it will also works for you.
Within a Python scope, any assignment to a variable not already declared within that scope creates a new local variable unless that variable is declared earlier in the function as referring to a globally scoped variable with the keyword global
.
Let's look at a modified version of your pseudocode to see what happens:
# Here, we're creating a variable 'x', in the __main__ scope.
x = 'None!'
def func_A():
# The below declaration lets the function know that we
# mean the global 'x' when we refer to that variable, not
# any local one
global x
x = 'A'
return x
def func_B():
# Here, we are somewhat mislead. We're actually involving two different
# variables named 'x'. One is local to func_B, the other is global.
# By calling func_A(), we do two things: we're reassigning the value
# of the GLOBAL x as part of func_A, and then taking that same value
# since it's returned by func_A, and assigning it to a LOCAL variable
# named 'x'.
x = func_A() # look at this as: x_local = func_A()
# Here, we're assigning the value of 'B' to the LOCAL x.
x = 'B' # look at this as: x_local = 'B'
return x # look at this as: return x_local
In fact, you could rewrite all of func_B
with the variable named x_local
and it would work identically.
The order matters only as far as the order in which your functions do operations that change the value of the global x. Thus in our example, order doesn't matter, since func_B
calls func_A
. In this example, order does matter:
def a():
global foo
foo = 'A'
def b():
global foo
foo = 'B'
b()
a()
print foo
# prints 'A' because a() was the last function to modify 'foo'.
Note that global
is only required to modify global objects. You can still access them from within a function without declaring global
.
Thus, we have:
x = 5
def access_only():
return x
# This returns whatever the global value of 'x' is
def modify():
global x
x = 'modified'
return x
# This function makes the global 'x' equal to 'modified', and then returns that value
def create_locally():
x = 'local!'
return x
# This function creates a new local variable named 'x', and sets it as 'local',
# and returns that. The global 'x' is untouched.
Note the difference between create_locally
and access_only
-- access_only
is accessing the global x despite not calling global
, and even though create_locally
doesn't use global
either, it creates a local copy since it's assigning a value.
The confusion here is why you shouldn't use global variables.
You should not call .get() directly. Optional<>, that Stream::max
returns, was designed to benefit from .orElse... inline handling.
If you are sure your arguments have their size of 2+:
list.stream()
.map(u -> u.date)
.max(Date::compareTo)
.orElseThrow(() -> new IllegalArgumentException("Expected 'list' to be of size: >= 2. Was: 0"));
If you support empty lists, then return some default value, for example:
list.stream()
.map(u -> u.date)
.max(Date::compareTo)
.orElse(new Date(Long.MIN_VALUE));
CREDITS to: @JimmyGeers, @assylias from the accepted answer.
I realise that this article may be outdated but still I would like to ask smithsv to correct his source code, it contains many mistakes, I managed to correct most of them but still don't know what kind of object x509 could be.Here is the source code as I think is should be:
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.util.Enumeration;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
public class Connection2 {
public void connect() {
/*
* This is an example to use ONLY p12 file it's not optimazed but it
* work. The pkcs12 file where generated by OpenSSL by me. Example how
* to load p12 file and build Trust zone from it... It outputs
* certificates from p12 file and add good certs to TrustStore
*/
KeyStore ks = KeyStore.getInstance( "pkcs12" );
ks.load( new FileInputStream( cert.pfx ), "passwrd".toCharArray() );
KeyStore jks = KeyStore.getInstance( "JKS" );
jks.load( null );
for( Enumeration t = ks.aliases(); t.hasMoreElements(); ) {
String alias = (String )t.nextElement();
System.out.println( "@:" + alias );
if( ks.isKeyEntry( alias ) ) {
Certificate[] a = ks.getCertificateChain( alias );
for( int i = 0; i == 0; )
jks.setCertificateEntry( x509Cert.getSubjectDN().toString(), x509 );
System.out.println( ks.getCertificateAlias( x509 ) );
System.out.println( "ok" );
}
}
System.out.println( "init Stores..." );
KeyManagerFactory kmf = KeyManagerFactory.getInstance( "SunX509" );
kmf.init( ks, "c1".toCharArray() );
TrustManagerFactory tmf = TrustManagerFactory.getInstance( "SunX509" );
tmf.init( jks );
SSLContext ctx = SSLContext.getInstance( "TLS" );
ctx.init( kmf.getKeyManagers(), tmf.getTrustManagers(), null );
}
}
In ANSI SQL, double quotes quote object names (e.g. tables) which allows them to contain characters not otherwise permitted, or be the same as reserved words (Avoid this, really).
Single quotes are for strings.
However, MySQL is oblivious to the standard (unless its SQL_MODE is changed) and allows them to be used interchangably for strings.
Moreover, Sybase and Microsoft also use square brackets for identifier quoting.
So it's a bit vendor specific.
Other databases such as Postgres and IBM actually adhere to the ansi standard :)
What about:
#region Using Statements
using System;
using System.Xml;
#endregion
class Program {
static void Main( string[ ] args ) {
XmlDocument doc = new XmlDocument( );
//(1) the xml declaration is recommended, but not mandatory
XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration( "1.0", "UTF-8", null );
XmlElement root = doc.DocumentElement;
doc.InsertBefore( xmlDeclaration, root );
//(2) string.Empty makes cleaner code
XmlElement element1 = doc.CreateElement( string.Empty, "body", string.Empty );
doc.AppendChild( element1 );
XmlElement element2 = doc.CreateElement( string.Empty, "level1", string.Empty );
element1.AppendChild( element2 );
XmlElement element3 = doc.CreateElement( string.Empty, "level2", string.Empty );
XmlText text1 = doc.CreateTextNode( "text" );
element3.AppendChild( text1 );
element2.AppendChild( element3 );
XmlElement element4 = doc.CreateElement( string.Empty, "level2", string.Empty );
XmlText text2 = doc.CreateTextNode( "other text" );
element4.AppendChild( text2 );
element2.AppendChild( element4 );
doc.Save( "D:\\document.xml" );
}
}
(1) Does a valid XML file require an xml declaration?
(2) What is the difference between String.Empty and “” (empty string)?
The result is:
<?xml version="1.0" encoding="UTF-8"?>
<body>
<level1>
<level2>text</level2>
<level2>other text</level2>
</level1>
</body>
But I recommend you to use LINQ to XML which is simpler and more readable like here:
#region Using Statements
using System;
using System.Xml.Linq;
#endregion
class Program {
static void Main( string[ ] args ) {
XDocument doc = new XDocument( new XElement( "body",
new XElement( "level1",
new XElement( "level2", "text" ),
new XElement( "level2", "other text" ) ) ) );
doc.Save( "D:\\document.xml" );
}
}
I realise that this is a rather old post and you have probably moved on.
But I had the same problem as you so I decided to write my own program.
The problem with the "xml -> xsd -> classes" route for me was that it just generated a lump of code that was completely unmaintainable and I ended up turfing it.
It is in no way elegant but it did the job for me.
You can get it here: Please make suggestions if you like it.
They're a little more explicit & readable as well.
[class]="{ 'true': 'active', 'false': 'inactive', 'true&false': 'some-other-class' }[ trinaryBoolean ]"
Just another way of accomplishing the same thing, in case you don't like the ternary syntax or ngIf
s (etc).
Posting to Twitter needs the image's actual path on the device to be sent in the request to post. I was finding it mighty difficult to get the actual path and more often than not I would get the wrong path.
To counter that, once you have a Bitmap
, I use that to get the URI from using the getImageUri()
. Subsequently, I use the tempUri
Uri instance to get the actual path as it is on the device.
This is production code and naturally tested. ;-)
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
knop.setVisibility(Button.VISIBLE);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getApplicationContext(), photo);
// CALL THIS METHOD TO GET THE ACTUAL PATH
File finalFile = new File(getRealPathFromURI(tempUri));
System.out.println(mImageCaptureUri);
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
No
Shortish Answer:Only if the other application is designed to allow it, by providing components for you to add into your own application.
Here's another version for us Framework users abandoned by Microsoft. It is 4 times as fast as Array.Clear
and faster than Panos Theof's solution and Eric J's and Petar Petrov's parallel one - up to two times as fast for large arrays.
First I want to present you the function's ancestor, because that makes it easier to understand the code. Performance-wise this is pretty much on par with Panos Theof's code, and for some things that may already be enough:
public static void Fill<T> (T[] array, int count, T value, int threshold = 32)
{
if (threshold <= 0)
throw new ArgumentException("threshold");
int current_size = 0, keep_looping_up_to = Math.Min(count, threshold);
while (current_size < keep_looping_up_to)
array[current_size++] = value;
for (int at_least_half = (count + 1) >> 1; current_size < at_least_half; current_size <<= 1)
Array.Copy(array, 0, array, current_size, current_size);
Array.Copy(array, 0, array, current_size, count - current_size);
}
As you can see, this is based on repeated doubling of the already-initialised part. This is simple and efficient, but it runs afoul of modern memory architectures. Hence was born a version that uses doubling only to create a cache-friendly seed block, which is then blasted iteratively over the target area:
const int ARRAY_COPY_THRESHOLD = 32; // 16 ... 64 work equally well for all tested constellations
const int L1_CACHE_SIZE = 1 << 15;
public static void Fill<T> (T[] array, int count, T value, int element_size)
{
int current_size = 0, keep_looping_up_to = Math.Min(count, ARRAY_COPY_THRESHOLD);
while (current_size < keep_looping_up_to)
array[current_size++] = value;
int block_size = L1_CACHE_SIZE / element_size / 2;
int keep_doubling_up_to = Math.Min(block_size, count >> 1);
for ( ; current_size < keep_doubling_up_to; current_size <<= 1)
Array.Copy(array, 0, array, current_size, current_size);
for (int enough = count - block_size; current_size < enough; current_size += block_size)
Array.Copy(array, 0, array, current_size, block_size);
Array.Copy(array, 0, array, current_size, count - current_size);
}
Note: the earlier code needed (count + 1) >> 1
as limit for the doubling loop to ensure that the final copy operation has enough fodder to cover all that is left. This would not be the case for odd counts if count >> 1
were to be used instead. For the current version this is of no significance since the linear copy loop will pick up any slack.
The size of an array cell must be passed as a parameter because - the mind boggles - generics aren't allowed to use sizeof
unless they use a constraint (unmanaged
) that may or may not become available in the future. Wrong estimates are not a big deal but performance is best if the value is accurate, for the following reasons:
Underestimating the element size can lead to block sizes greater than half the L1 cache, hence increasing the likelihood of copy source data getting evicted from L1 and having to be re-fetched from slower cache levels.
Overestimating the element size results in under-utilisation of the CPU's L1 cache, meaning the linear block copy loop gets executed more often than it would be with optimal utilisation. Thus, more of the fixed loop/call overhead is incurred than strictly necessary.
Here's a benchmark pitting my code against Array.Clear
and the other three solutions mentioned previously. The timings are for filling integer arrays (Int32[]
) of the given sizes. In order to reduce variation caused by cache vagaries etc. each test was executed twice, back to back, and the timings were taken for the second execution.
array size Array.Clear Eric J. Panos Theof Petar Petrov Darth Gizka
-------------------------------------------------------------------------------
1000: 0,7 µs 0,2 µs 0,2 µs 6,8 µs 0,2 µs
10000: 8,0 µs 1,4 µs 1,2 µs 7,8 µs 0,9 µs
100000: 72,4 µs 12,4 µs 8,2 µs 33,6 µs 7,5 µs
1000000: 652,9 µs 135,8 µs 101,6 µs 197,7 µs 71,6 µs
10000000: 7182,6 µs 4174,9 µs 5193,3 µs 3691,5 µs 1658,1 µs
100000000: 67142,3 µs 44853,3 µs 51372,5 µs 35195,5 µs 16585,1 µs
Should the performance of this code not be sufficient then a promising avenue would be parallelising the linear copy loop (with all threads using the same source block), or our good old friend P/Invoke.
Note: clearing and filling of blocks is normally done by runtime routines that branch to highly specialised code using MMX/SSE instructions and whatnot, so in any decent environment one would simply call the respective moral equivalent of std::memset
and be assured of professional performance levels. IOW, by rights the library function Array.Clear
should leave all our hand-rolled versions in the dust. The fact that it is the other way around shows how far out of whack things really are. Same goes for having to roll one's own Fill<>
in the first place, because it is still only in Core and Standard but not in the Framework. .NET has been around for almost twenty years now and we still have to P/Invoke left and right for the most basic stuff or roll our own...
Private Sub CommandButton1_Click()
Dim Data As Object, Employee As Object
Application.ScreenUpdating = False
Set Data = ThisWorkbook.Sheets("Data")
Set Employee = ThisWorkbook.Sheets("Employee Names")
Data.Range("AK1").Value = "Lookup"
Data.Range("AK2:AK" & Data.Range("A1").End(xlDown).Row).Formula = "=VLOOKUP(E2,'Employee Names'!$A:$A,1,0)"
Data.Range("AK2:AK" & Data.Range("A1").End(xlDown).Row).Value = Data.Range("AK2:AK" & Data.Range("A1").End(xlDown).Row).Value
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=5, Criteria1:="<>"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=37, Criteria1:="#N/A"
Application.DisplayAlerts = False
Data.AutoFilter.Range.Offset(1, 0).Rows.SpecialCells(xlCellTypeVisible).Delete (xlShiftUp)
Data.Range("AK:AK").Delete
Data.AutoFilterMode = False
'Selection.AutoFilter
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=7, Criteria1:="="
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=12, Criteria1:="<>"
Worksheets("Data").Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "DrfeeRequested"
Set Dr = ThisWorkbook.Worksheets("DrfeeRequested")
Dr.Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Data.AutoFilterMode = False
'DrfeeRequested.AutoFilterMode = False
Selection.AutoFilter
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=13, Criteria1:="<>"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "RateLockfollowup"
Set Ratefolup = ThisWorkbook.Worksheets("RateLockfollowup")
Ratefolup.Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Data.AutoFilterMode = False
Selection.AutoFilter
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=19, Criteria1:="="
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=13, Criteria1:="<>"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Lockedlefollowup"
Set Lockfolup = ThisWorkbook.Worksheets("Lockedlefollowup")
Lockfolup.Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Data.AutoFilterMode = False
Selection.AutoFilter
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=19, Criteria1:="="
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Hoifollowup"
Set Hoifolup = ThisWorkbook.Worksheets("Hoifollowup")
Hoifolup.Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Data.AutoFilterMode = False
Selection.AutoFilter
TodayDT = Format(Now())
Weekdy = Weekday(Now())
If Weekdy = 2 Then
LastTwoDays = Now() - Weekday(Now(), 3)
ElseIf Weekdy = 3 Then
LastTwoDays = Now() - Weekday(Now(), 3)
ElseIf Weekdy = 4 Then
LastTwoDays = Now() - Weekday(Now(), 3)
ElseIf Weekdy = 5 Then
LastTwoDays = Now() - Weekday(Now(), 3)
ElseIf Weekdy = 6 Then
LastTwoDays = Now() - Weekday(Now(), 3)
Else
MsgBox "Today Satuarday OR Sunday Data is not Available"
End If
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=12, Criteria1:="="
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=11, Criteria1:="<>"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=11, Criteria1:=" TodayDT", Operator:=xlAnd, Criteria2:="LastTwoDays"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "DRfeefollowup"
Set Drfreefolup = ThisWorkbook.Worksheets("DRfeefollowup")
Drfreefolup.Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Data.AutoFilterMode = False
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=15, Criteria1:="yes"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=19, Criteria1:="x"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=12, Criteria1:="<>"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=13, Criteria1:="<>"
'Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=14, criterial:="<>"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Drworkblefiles"
Set Drworkblefiles = ThisWorkbook.Worksheets("Drworkblefiles")
Drworkblefiles.Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Data.Range("A1").AutoFilter
End Sub
Private Sub CommandButton2_Click()
Sheets("Data").Range("A1:AJ" & Sheets("Data").Range("A1").End(xlDown).Row).Clear
MsgBox "Please paste new data in data sheet"
End Sub
Yes you can! For a simple repository that only publish/retrieve artifacts, you can use nginx.
Make sure nginx has http dav module enabled, it should, but nonetheless verify it.
Configure nginx http dav module:
In Windows: d:\servers\nginx\nginx.conf
location / {
# maven repository
dav_methods PUT DELETE MKCOL COPY MOVE;
create_full_put_path on;
dav_access user:rw group:rw all:r;
}
In Linux (Ubuntu): /etc/nginx/sites-available/default
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
# try_files $uri $uri/ =404; # IMPORTANT comment this
dav_methods PUT DELETE MKCOL COPY MOVE;
create_full_put_path on;
dav_access user:rw group:rw all:r;
}
Don't forget to give permissions to the directory where the repo will be located:
sudo chmod +777 /var/www/html/repository
In your project's pom.xml
add the respective configuration:
Retrieve artifacts:
<repositories>
<repository>
<id>repository</id>
<url>http://<your.ip.or.hostname>/repository</url>
</repository>
</repositories>
Publish artifacts:
<build>
<extensions>
<extension>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-http</artifactId>
<version>3.2.0</version>
</extension>
</extensions>
</build>
<distributionManagement>
<repository>
<id>repository</id>
<url>http://<your.ip.or.hostname>/repository</url>
</repository>
</distributionManagement>
To publish artifacts use mvn deploy
. To retrieve artifacts, maven will do it automatically.
And there you have it a simple maven repo.
git show
is more a plumbing command than git log
, and has the same formatting options:
git show -s --format=%B SHA1
I used @LiorH's example and expanded it to:
@XmlRootElement(name="List")
public class JaxbList<T>{
protected List<T> list;
public JaxbList(){}
public JaxbList(List<T> list){
this.list=list;
}
@XmlElement(name="Item")
public List<T> getList(){
return list;
}
}
Note, that it uses generics so you can use it with other classes than String. Now, the application code is simply:
@GET
@Path("/test2")
public JaxbList test2(){
List list=new Vector();
list.add("a");
list.add("b");
return new JaxbList(list);
}
Why doesn't this simple class exist in the JAXB package? Anyone see anything like it elsewhere?
LaTeX will usually not indent the first paragraph of a section. This is standard typographical practice. However, if you really want to override this default setting, use the package indentfirst available on CTAN.
Go to server.xml
and Search for "Context"
tag with a property name "docBase"
.
Remove the duplicate lines here. Then try to restart the server.
This error message happens either because your ProfileDto
class is not registered in the JAXB Content, or the class using it does not use @XmlSeeAlso(ProfileDto.class)
to make processable by JAXB.
About your comment:
I was under the impression the annotations was only needed when the referenced class was a sub-class.
No, they are also needed when not declared in the JAXB context or, for example, when the only class having a static reference to it has this reference annotated with @XmlTransient
. I maintain a tutorial here.
If you have to do group by
using hibernate criteria use projections.groupPropery
like the following,
@Autowired
private SessionFactory sessionFactory;
Criteria crit = sessionFactory.getCurrentSession().createCriteria(studentModel.class);
crit.setProjection(Projections.projectionList()
.add(Projections.groupProperty("studentName").as("name"))
List result = crit.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list();
return result;
IF NOT USING THE SHORT HAND VERSION: Make sure the animation-fill-mode: forwards
is AFTER the animation declaration or it will not work...
animation-fill-mode: forwards;
animation-name: appear;
animation-duration: 1s;
animation-delay: 1s;
vs
animation-name: appear;
animation-duration: 1s;
animation-fill-mode: forwards;
animation-delay: 1s;
Use an SqlDataAdapter when wanting to populate an in-memory DataSet/DataTable from the database. You then have the flexibility to close/dispose off the connection, pass the datatable/set around in memory. You could then manipulate the data and persist it back into the DB using the data adapter, in conjunction with InsertCommand/UpdateCommand.
Use an SqlDataReader when wanting fast, low-memory footprint data access without the need for flexibility for e.g. passing the data around your business logic. This is more optimal for quick, low-memory usage retrieval of large data volumes as it doesn't load all the data into memory all in one go - with the SqlDataAdapter approach, the DataSet/DataTable would be filled with all the data so if there's a lot of rows & columns, that will require a lot of memory to hold.
There are a couple of important things to know about bash's [[ ]]
construction. The first:
Word splitting and pathname expansion are not performed on the words between the
[[
and]]
; tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, process substitution, and quote removal are performed.
The second thing:
An additional binary operator, ‘=~’, is available,... the string to the right of the operator is considered an extended regular expression and matched accordingly... Any part of the pattern may be quoted to force it to be matched as a string.
Consequently, $v
on either side of the =~
will be expanded to the value of that variable, but the result will not be word-split or pathname-expanded. In other words, it's perfectly safe to leave variable expansions unquoted on the left-hand side, but you need to know that variable expansions will happen on the right-hand side.
So if you write: [[ $x =~ [$0-9a-zA-Z] ]]
, the $0
inside the regex on the right will be expanded before the regex is interpreted, which will probably cause the regex to fail to compile (unless the expansion of $0
ends with a digit or punctuation symbol whose ascii value is less than a digit). If you quote the right-hand side like-so [[ $x =~ "[$0-9a-zA-Z]" ]]
, then the right-hand side will be treated as an ordinary string, not a regex (and $0
will still be expanded). What you really want in this case is [[ $x =~ [\$0-9a-zA-Z] ]]
Similarly, the expression between the [[
and ]]
is split into words before the regex is interpreted. So spaces in the regex need to be escaped or quoted. If you wanted to match letters, digits or spaces you could use: [[ $x =~ [0-9a-zA-Z\ ] ]]
. Other characters similarly need to be escaped, like #
, which would start a comment if not quoted. Of course, you can put the pattern into a variable:
pat="[0-9a-zA-Z ]"
if [[ $x =~ $pat ]]; then ...
For regexes which contain lots of characters which would need to be escaped or quoted to pass through bash's lexer, many people prefer this style. But beware: In this case, you cannot quote the variable expansion:
# This doesn't work:
if [[ $x =~ "$pat" ]]; then ...
Finally, I think what you are trying to do is to verify that the variable only contains valid characters. The easiest way to do this check is to make sure that it does not contain an invalid character. In other words, an expression like this:
valid='0-9a-zA-Z $%&#' # add almost whatever else you want to allow to the list
if [[ ! $x =~ [^$valid] ]]; then ...
!
negates the test, turning it into a "does not match" operator, and a [^...]
regex character class means "any character other than ...
".
The combination of parameter expansion and regex operators can make bash regular expression syntax "almost readable", but there are still some gotchas. (Aren't there always?) One is that you could not put ]
into $valid
, even if $valid
were quoted, except at the very beginning. (That's a Posix regex rule: if you want to include ]
in a character class, it needs to go at the beginning. -
can go at the beginning or the end, so if you need both ]
and -
, you need to start with ]
and end with -
, leading to the regex "I know what I'm doing" emoticon: [][-]
)
This new issue is caused by the latest version of Android.
Go to your project root folder, open gradle.properties
, and add the following options:
org.gradle.daemon=true
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
org.gradle.parallel=true
org.gradle.configureondemand=true
Then add these changes in your build.gradle
file:
dexOptions {
incremental = true
preDexLibraries = false
javaMaxHeapSize "4g" // 2g should be also OK
}
Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.
git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67
Then, abort the rebase again.
Why not use let; I find it much easier. Here's an example you may find useful:
start=`date +%s`
# ... do something that takes a while ...
sleep 71
end=`date +%s`
let deltatime=end-start
let hours=deltatime/3600
let minutes=(deltatime/60)%60
let seconds=deltatime%60
printf "Time spent: %d:%02d:%02d\n" $hours $minutes $seconds
Another simple example - calculate number of days since 1970:
let days=$(date +%s)/86400
// This file is PHP.
<html>
<?php
if ($_POST['submit']) {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$confirmpassword = $_POST['confirmpassword'];
$strtadd1 = $_POST['strtadd1'];
$strtadd2 = $_POST['strtadd2'];
$city = $_POST['city'];
$country = $_POST['country'];
$success = '';
// Upon Success.
if ($firstname != '' && $lastname != '' && $email != '' && $password != '' && $confirmpassword != '' && $strtadd1 != '' && $strtadd2 != '' && $city != '' && $country != '') {
// Change $success variable from an empty string.
$success = 'success';
// Insert whatever you want to do upon success.
} else {
// Upon Failure.
echo '<p class="error">Fill in all fields.</p>';
// Set $success variable to an empty string.
$success = '';
}
}
?>
<form method="POST" action="#">
<label class="w">Plan :</label>
<select autofocus="" name="plan" required="required">
<option value="">Select One</option>
<option value="FREE Account">FREE Account</option>
<option value="Premium Account Monthly">Premium Account Monthly</option>
<option value="Premium Account Yearly">Premium Account Yearly</option>
</select>
<br>
<label class="w">First Name :</label><input name="firstname" type="text" placeholder="First Name" required="required" value="<?php if (isset($firstname) && $success == '') {echo $firstname;} ?>"><br>
<label class="w">Last Name :</label><input name="lastname" type="text" placeholder="Last Name" required="required" value="<?php if (isset($lastname) && $success == '') {echo $lastname;} ?>"><br>
<label class="w">E-mail ID :</label><input name="email" type="email" placeholder="Enter Email" required="required" value="<?php if (isset($email) && $success == '') {echo $email;} ?>"><br>
<label class="w">Password :</label><input name="password" type="password" placeholder="********" required="required" value="<?php if (isset($password) && $success == '') {echo $password;} ?>"><br>
<label class="w">Re-Enter Password :</label><input name="confirmpassword" type="password" placeholder="********" required="required" value="<?php if (isset($confirmpassword) && $success == '') {echo $confirmpassword;} ?>"><br>
<label class="w">Street Address 1 :</label><input name="strtadd1" type="text" placeholder="street address first" required="required" value="<?php if (isset($strtadd1) && $success == '') {echo $strtadd1;} ?>"><br>
<label class="w">Street Address 2 :</label><input name="strtadd2" type="text" placeholder="street address second" value="<?php if (isset($strtadd2) && $success == '') {echo $strtadd2;} ?>"><br>
<label class="w">City :</label><input name="city" type="text" placeholder="City" required="required" value="<?php if (isset($city) && $success == '') {echo $city;} ?>"><br>
<label class="w">Country :</label><select autofocus="" id="a1_txtBox1" name="country" required="required" placeholder="select one" value="<?php if (isset($country) && $success == '') {echo $country;} ?>">
<input type="submit" name="submit">
</form>
</html>
Use value="<?php if (isset($firstname) && $success == '') {echo $firstname;} ?>"
You'll then have to create the $success variable--as I did in my example.
The bottom statement is equivalent to:
.half {
flex-grow: 0;
flex-shrink: 0;
flex-basis: 50%;
}
Which, in this case, would be equivalent as the box is not allowed to flex and therefore retains the initial width set by flex-basis.
Flex-basis defines the default size of an element before the remaining space is distributed so if the element were allowed to flex (grow/shrink) it may not be 50% of the width of the page.
I've found that I regularly return to https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for help regarding flexbox :)
As pointed out before, the problem was that the files were not visible by the fpm container. However to share data among containers the recommended pattern is using data-only containers (as explained in this article).
Long story short: create a container that just holds your data, share it with a volume, and link this volume in your apps with volumes_from
.
Using compose (1.6.2 in my machine), the docker-compose.yml
file would read:
version: "2"
services:
nginx:
build:
context: .
dockerfile: nginx/Dockerfile
ports:
- "80:80"
links:
- fpm
volumes_from:
- data
fpm:
image: php:fpm
volumes_from:
- data
data:
build:
context: .
dockerfile: data/Dockerfile
volumes:
- /var/www/html
Note that data
publishes a volume that is linked to the nginx
and fpm
services. Then the Dockerfile
for the data service, that contains your source code:
FROM busybox
# content
ADD path/to/source /var/www/html
And the Dockerfile
for nginx, that just replaces the default config:
FROM nginx
# config
ADD config/default.conf /etc/nginx/conf.d
For the sake of completion, here's the config file required for the example to work:
server {
listen 0.0.0.0:80;
root /var/www/html;
location / {
index index.php index.html;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass fpm:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
}
}
which just tells nginx to use the shared volume as document root, and sets the right config for nginx to be able to communicate with the fpm container (i.e.: the right HOST:PORT
, which is fpm:9000
thanks to the hostnames defined by compose, and the SCRIPT_FILENAME
).
The simplest fix is to make the comparator function be static:
static int comparator (const Bar & first, const Bar & second);
^^^^^^
When invoking it in Count
, its name will be Foo::comparator
.
The way you have it now, it does not make sense to be a non-static member function because it does not use any member variables of Foo
.
Another option is to make it a non-member function, especially if it makes sense that this comparator might be used by other code besides just Foo
.
Nested if's in Excel Are ugly:
=If(G2 < 1, .1, IF(G2 < 5,.15,if(G2 < 15,.2,if(G2 < 30,.5,if(G2 < 100,.1,1.3)))))
That should cover it.
According to the documentation Checks the existence of files in the specified order and uses the first found file for request processing; the processing is performed in the current context. The path to a file is constructed from the file parameter according to the root and alias directives. It is possible to check directory’s existence by specifying a slash at the end of a name, e.g. “$uri/”. If none of the files were found, an internal redirect to the uri specified in the last parameter is made. Important
an internal redirect to the uri specified in the last parameter is made.
So in last parameter you should add your page or code if first two parameters returns false.
location / {
try_files $uri $uri/index.html index.html;
}
Syntax
Datatype[] variable = new Datatype[] { value1,value2.... }
Datatype variable[] = new Datatype[] { value1,value2.... }
Example :
int [] points = new int[]{ 1,2,3,4 };
With EF or LINQ to SQL:
var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();
With LINQ to Objects I suggest to use morelinq extension MaxBy
(get morelinq from nuget):
var item = items.MaxBy(i => i.Value);
import os
import shlex
from subprocess import Popen, PIPE
os.environ.update(key=value)
res = Popen(shlex.split("cmd xxx -xxx"), stdin=PIPE, stdout=PIPE, stderr=PIPE,
env=os.environ, shell=True).communicate('y\ny\ny\n'.encode('utf8'))
stdout = res[0]
stderr = res[1]
import threading
# global variable x
x = 0
def increment():
"""
function to increment global variable x
"""
global x
x += 1
def thread_task():
"""
task for thread
calls increment function 100000 times.
"""
for _ in range(100000):
increment()
def main_task():
global x
# setting global variable x as 0
x = 0
# creating threads
t1 = threading.Thread(target=thread_task)
t2 = threading.Thread(target=thread_task)
# start threads
t1.start()
t2.start()
# wait until threads finish their job
t1.join()
t2.join()
if __name__ == "__main__":
for i in range(10):
main_task()
print("Iteration {0}: x = {1}".format(i,x))
Try to see if SQL snap-ins are present:
get-pssnapin -Registered
Name : SqlServerCmdletSnapin100
PSVersion : 2.0
Description : This is a PowerShell snap-in that includes various SQL Server cmdlets.
Name : SqlServerProviderSnapin100
PSVersion : 2.0
Description : SQL Server Provider
If so
Add-PSSnapin SqlServerCmdletSnapin100 # here lives Invoke-SqlCmd
Add-PSSnapin SqlServerProviderSnapin100
then you can do something like this:
invoke-sqlcmd -inputfile "c:\mysqlfile.sql" -serverinstance "servername\serverinstance" -database "mydatabase" # the parameter -database can be omitted based on what your sql script does.
The file that I was using was saved through Powershell in UTF-8 format. I changed it to ANSI and it fixed the problem.
You could use a group function so that your query always returns a result. ie
MIN(ID_NMB_SRZ)
You have to be very careful on formatting and line spacing in go, everything counts and here is a working sample, try it https://play.golang.org/p/c0zeXKYlmF
package main
import "fmt"
func main() {
testLine := `This is a test line 1
This is a test line 2`
fmt.Println(testLine)
}
You would use the INCLUDE to add one or more columns to the leaf level of a non-clustered index, if by doing so, you can "cover" your queries.
Imagine you need to query for an employee's ID, department ID, and lastname.
SELECT EmployeeID, DepartmentID, LastName
FROM Employee
WHERE DepartmentID = 5
If you happen to have a non-clustered index on (EmployeeID, DepartmentID), once you find the employees for a given department, you now have to do "bookmark lookup" to get the actual full employee record, just to get the lastname column. That can get pretty expensive in terms of performance, if you find a lot of employees.
If you had included that lastname in your index:
CREATE NONCLUSTERED INDEX NC_EmpDep
ON Employee(EmployeeID, DepartmentID)
INCLUDE (Lastname)
then all the information you need is available in the leaf level of the non-clustered index. Just by seeking in the non-clustered index and finding your employees for a given department, you have all the necessary information, and the bookmark lookup for each employee found in the index is no longer necessary --> you save a lot of time.
Obviously, you cannot include every column in every non-clustered index - but if you do have queries which are missing just one or two columns to be "covered" (and that get used a lot), it can be very helpful to INCLUDE those into a suitable non-clustered index.
All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if
to bind them all together in the way I believe you intend.
another way to create a data url from blob url may be using canvas.
var canvas = document.createElement("canvas")
var context = canvas.getContext("2d")
context.drawImage(img, 0, 0) // i assume that img.src is your blob url
var dataurl = canvas.toDataURL("your prefer type", your prefer quality)
as what i saw in mdn, canvas.toDataURL is supported well by browsers. (except ie<9, always ie<9)
Well you can:
If you're expecting that it will be base64, then you can probably just use whatever library is available on your platform to try to decode it to a byte array, throwing an exception if it's not valid base 64. That depends on your platform, of course.
Yes, a table have one or many foreign keys and each foreign keys hava a different parent table.
If you don't mind picking the same item again at some other time:
$items[rand(0, count($items) - 1)];
The system might be running "rootless". Try to set the firmware nvram variable boot-args to "rootless=0". Try to run set of commands:
sudo nvram boot-args="rootless=0";
sudo reboot
After reboot completes, run:
sudo gem install bundler
There is no built-in functions to do that in Php (shame ^^). You want to compare a date string to today, you could use a simple substr
to achieve it:
if (substr($timestamp, 0, 10) === date('Y.m.d')) { today }
elseif (substr($timestamp, 0, 10) === date('Y.m.d', strtotime('-1 day')) { yesterday }
No date conversion, simple.
If the required data is not too large (limits I don´t know, would depend on a lot of things), you might also download the data (in XML, JSON, whatever) from a website/webapp. AFter receiving, execute the SQL statements using the received data creating your tables and inserting the data.
If your mobile app contains lots of data, it might be easier later on to update the data in the installed apps with more accurate data or changes.
Either one of the below three options gets rid of the message (but for different reasons and with different side-effects I suppose):
node_modules
directory or explicitly include
the directory where your app resides (which presumably does not contain files in excess of 100KB)compact
to true
(actually any value other than "auto")compact
to false
(see above)#1 in the above list can be achieved by either excluding the node_modules
directory or be explicitly including the directory where your app resides.
E.g. in webpack.config.js
:
let path = require('path');
....
module: {
loaders: [
...
loader: 'babel',
exclude: path.resolve(__dirname, 'node_modules/')
... or by using include: path.resolve(__dirname, 'app/')
(again in webpack.config.js
).
#2 and #3 in the above list can be accomplished by the method suggested in this answer or (my preference) by editing the .babelrc
file. E.g.:
$ cat .babelrc
{
"presets": ["es2015", "react"],
"compact" : true
}
Tested with the following setup:
$ npm ls --depth 0 | grep babel
+-- [email protected]
+-- [email protected]
+-- [email protected]
+-- [email protected]
In Java 8 with streams, it's pretty simple actually. EDIT: Can be efficient without streams, see lower.
List<String> listA = Arrays.asList("2009-05-18","2009-05-19","2009-05-21");
List<String> listB = Arrays.asList("2009-05-18","2009-05-18","2009-05-19","2009-05-19",
"2009-05-20","2009-05-21","2009-05-21","2009-05-22");
List<String> result = listB.stream()
.filter(not(new HashSet<>(listA)::contains))
.collect(Collectors.toList());
Note that the hash set is only created once: The method reference is tied to its contains method. Doing the same with lambda would require having the set in a variable. Making a variable is not a bad idea, especially if you find it unsightly or harder to understand.
You can't easily negate the predicate without something like this utility method (or explicit cast), as you can't call the negate method reference directly (type inference is needed first).
private static <T> Predicate<T> not(Predicate<T> predicate) {
return predicate.negate();
}
If streams had a filterOut
method or something, it would look nicer.
Also, @Holger gave me an idea. ArrayList
has its removeAll
method optimized for multiple removals, it only rearranges its elements once. However, it uses the contains
method provided by given collection, so we need to optimize that part if listA
is anything but tiny.
With listA
and listB
declared previously, this solution doesn't need Java 8 and it's very efficient.
List<String> result = new ArrayList(listB);
result.removeAll(new HashSet<>(listA));
Both UNION and UNION ALL concatenate the result of two different SQLs. They differ in the way they handle duplicates.
UNION performs a DISTINCT on the result set, eliminating any duplicate rows.
UNION ALL does not remove duplicates, and it therefore faster than UNION.
Note: While using this commands all selected columns need to be of the same data type.
Example: If we have two tables, 1) Employee and 2) Customer
If you want to use a plain javascript API, there is a good example at https://github.com/hongkiat/js-rss-reader/
The complete description at https://www.hongkiat.com/blog/rss-reader-in-javascript/
It uses fetch
method as a global method that asynchronously fetches a resource. Below is a snap of code:
fetch(websiteUrl).then((res) => {
res.text().then((htmlTxt) => {
var domParser = new DOMParser()
let doc = domParser.parseFromString(htmlTxt, 'text/html')
var feedUrl = doc.querySelector('link[type="application/rss+xml"]').href
})
}).catch(() => console.error('Error in fetching the website'))
"Reset" is the way to undo changes locally. When committing, you first select changes to include with "git add"--that's called "staging." And once the changes are staged, then you "git commit" them.
To back out from either the staging or the commit, you "reset" the HEAD. On a branch, HEAD is a git variable that points to the most recent commit. So if you've staged but haven't committed, you "git reset HEAD." That backs up to the current HEAD by taking changes off the stage. It's shorthand for "git reset --mixed HEAD~0."
If you've already committed, then the HEAD has already advanced, so you need to back up to the previous commit. Here you "reset HEAD~1" or "reset HEAD^1" or "reset HEAD~" or "reset HEAD^"-- all reference HEAD minus one.
Which is the better symbol, ~ or ^? Think of the ~ tilde as a single stream -- when each commit has a single parent and it's just a series of changes in sequence, then you can reference back up the stream using the tilde, as HEAD~1, HEAD~2, HEAD~3, for parent, grandparent, great-grandparent, etc. (technically it's finding the first parent in earlier generations).
When there's a merge, then commits have more than one parent. That's when the ^ caret comes into play--you can remember because it shows the branches coming together. Using the caret, HEAD^1 would be the first parent and HEAD^2 would be the second parent of a single commit--mother and father, for example.
So if you're just going back one hop on a single-parent commit, then HEAD~ and HEAD^ are equivalent--you can use either one.
Also, the reset can be --soft, --mixed, or --hard. A soft reset just backs out the commit--it resets the HEAD, but it doesn't check out the files from the earlier commit, so all changes in the working directory are preserved. And --soft reset doesn't even clear the stage (also known as the index), so all the files that were staged will still be on stage.
A --mixed reset (the default) also does not check out the files from the earlier commit, so all changes are preserved, but the stage is cleared. That's why a simple "git reset HEAD" will clear off the stage.
A --hard reset resets the HEAD, and it clears the stage, but it also checks out all the files from the earlier commit and so it overwrites any changes.
If you've pushed the commit to a remote repository, then reset doesn't work so well. You can reset locally, but when you try to push to the remote, git will see that your local HEAD is behind the HEAD in the remote branch and will refuse to push. You may be able to force the push, but git really does not like doing that.
Alternatively, you can stash your changes if you want to keep them, check out the earlier commit, un-stash the changes, stage them, create a new commit, and then push that.
If you want a generic solution without boxing:
public class KeyBasedEqualityComparer<T, TKey> : IEqualityComparer<T>
{
private readonly Func<T, TKey> _keyGetter;
public KeyBasedEqualityComparer(Func<T, TKey> keyGetter)
{
_keyGetter = keyGetter;
}
public bool Equals(T x, T y)
{
return EqualityComparer<TKey>.Default.Equals(_keyGetter(x), _keyGetter(y));
}
public int GetHashCode(T obj)
{
TKey key = _keyGetter(obj);
return key == null ? 0 : key.GetHashCode();
}
}
public static class KeyBasedEqualityComparer<T>
{
public static KeyBasedEqualityComparer<T, TKey> Create<TKey>(Func<T, TKey> keyGetter)
{
return new KeyBasedEqualityComparer<T, TKey>(keyGetter);
}
}
usage:
KeyBasedEqualityComparer<Class_reglement>.Create(x => x.Numf)
As of today (27, February 2020) Oracle announced that it has published all JDBC client libraries from version 11.2.0.4 (e.g. ojdbc6) to 19.3.0 (e.g. ojdbc10) on Maven Central under the group id com.oracle.database:
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc10</artifactId>
<version>19.3.0.0</version>
</dependency>
There's a bit of code that might help:
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class ModalJFrame extends JFrame {
Object currentWindow = this;
public ModalJFrame()
{
super();
super.setTitle("Main JFrame");
super.setSize(500, 500);
super.setResizable(true);
super.setLocationRelativeTo(null);
JMenuBar menuBar = new JMenuBar();
super.setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
JMenu editMenu = new JMenu("Edit");
menuBar.add(fileMenu);
menuBar.add(editMenu);
JMenuItem newAction = new JMenuItem("New");
JMenuItem openAction = new JMenuItem("Open");
JMenuItem exitAction = new JMenuItem("Exit");
JMenuItem cutAction = new JMenuItem("Cut");
JMenuItem copyAction = new JMenuItem("Copy");
JMenuItem pasteAction= new JMenuItem("Paste");
fileMenu.add(newAction);
fileMenu.add(openAction);
fileMenu.addSeparator();
fileMenu.add(exitAction);
editMenu.add(cutAction);
editMenu.add(copyAction);
editMenu.addSeparator();
editMenu.add(pasteAction);
newAction.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
JFrame popupJFrame = new JFrame();
popupJFrame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
((Component) currentWindow).setEnabled(true); }
});
((Component) currentWindow).setEnabled(false);
popupJFrame.setTitle("Pop up JFrame");
popupJFrame.setSize(400, 500);
popupJFrame.setAlwaysOnTop(true);
popupJFrame.setResizable(false);
popupJFrame.setLocationRelativeTo(getRootPane());
popupJFrame.setVisible(true);
popupJFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
}
});
exitAction.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
System.exit(0);
}
});
}
public static void main(String[] args) {
ModalJFrame myWindow = new ModalJFrame();
myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myWindow.setVisible(true);
}
}
So, in this case, it would be nice if Number object would behave like an Array object with the spread operator.
For instance Array object used with the spread operator:
let foo = [0,1,2,3];
console.log(...foo) // returns 0 1 2 3
It works like this because Array object has a built-in iterator.
In our case, we need a Number object to have a similar functionality:
[...3] //should return [0,1,2,3]
To do that we can simply create Number iterator for that purpose.
Number.prototype[Symbol.iterator] = function *() {
for(let i = 0; i <= this; i++)
yield i;
}
Now it is possible to create ranges from 0 to N with the spread operator.
[...N] // now returns 0 ... N array
http://jsfiddle.net/01e4xdv5/4/
Cheers.
if you are using ionic framework, go to config.xml file and change the "version" attribute in the "widget" tag. increase the version number. then rebuild, sign and upload ur apk to play store. that fixed my problem.
Perhaps you wanted to #include<string>
, not <string.h>
. std::string
also needs a namespace qualification, or an explicit using
directive.
For your first question try
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
(available since API 8)
To access individual files in this directory use either File.list() or File.listFiles(). Seems that reporting download progress is only possible in notification, see here.
If you've done something like accidentally npm link
generator-webapp after you've changed it, you can fix it by cloning the right generator and linking that.
git clone https://github.com/yeoman/generator-webapp.git;
# for fixing generator-webapp, replace with your required repository
cd generator-webapp;
npm link;
I had used below snippet of code for this and it worked for me.
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.item);
View child = getLayoutInflater().inflate(R.layout.child, null);
linearLayout.addView(child);
Both Redirect::to()
and Redirect::away()
should work.
Difference
Redirect::to() does additional URL checks and generations. Those additional steps are done in Illuminate\Routing\UrlGenerator and do the following, if the passed URL is not a fully valid URL (even with protocol):
Determines if URL is secure rawurlencode() the URL trim() URL
src : https://medium.com/@zwacky/laravel-redirect-to-vs-redirect-away-dd875579951f
Hibernate doesn't support <exclude-unlisted-classes>false</exclude-unlisted-classes>
under SE, (another poster mentioned this works with TopLink and EclipseLink).
There are tools that will auto-generate the list of classes to persistence.xml e.g. the Import Database Schema wizard in IntelliJ. Once you've got your project's initial classes in persistence.xml it should be simple to add/remove single classes by hand as your project progresses.
I am not sure is it the right way but this one works for me.
First import the component which contains the method you want to call in your component
import myComponent from './MyComponent'
and then call any method of MyCompenent
myComponent.methods.doSomething()
N.B : IF YOU ARE USING PHPSTORM
I spent an hour trying to solve this problem, thinking that it was my php server problem, So i set 'always_populate_raw_post_data' to '-1' in php.ini and nothing worked.
Until i found out that using phpStorm built in server is what causing the problem as detailed in the answer here : Answer by LazyOne Here , So i thought about sharing it.
My solution was:
display: initial;
Then it was crispy sharp
simply,
select sysdate-1 from dual
there's a bunch more info and detail here: http://www.orafaq.com/faq/how_does_one_add_a_day_hour_minute_second_to_a_date_value
you can use:
$('body').ready(function(){
$(document).on('change', '#elemID', function(){
// do something
});
});
It works with me.
For the sake of completeness, let me mention that there are some places (on a Windows PC) to look for javaw.exe
in case it is not found in the path:
(Still Reimeus' suggestion should be your first attempt.)
1.
Java usually stores it's location in Registry, under the following key:
HKLM\Software\JavaSoft\Java Runtime Environement\<CurrentVersion>\JavaHome
2.
Newer versions of JRE/JDK, seem to also place a copy of javaw.exe
in 'C:\Windows\System32', so one might want to check there too (although chances are, if it is there, it will be found in the path as well).
3.
Of course there are the "usual" install locations:
[Note, that for older versions of Windows (XP, Vista(?)), this will only help on english versions of the OS. Fortunately, on later version of Windows "Program Files" will point to the directory regardless of its "display name" (which is language-specific).]
A little while back, I wrote this piece of code to check for javaw.exe
in the aforementioned places. Maybe someone finds it useful:
static protected String findJavaw() {
Path pathToJavaw = null;
Path temp;
/* Check in Registry: HKLM\Software\JavaSoft\Java Runtime Environement\<CurrentVersion>\JavaHome */
String keyNode = "HKLM\\Software\\JavaSoft\\Java Runtime Environment";
List<String> output = new ArrayList<>();
executeCommand(new String[] {"REG", "QUERY", "\"" + keyNode + "\"",
"/v", "CurrentVersion"},
output);
Pattern pattern = Pattern.compile("\\s*CurrentVersion\\s+\\S+\\s+(.*)$");
for (String line : output) {
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
keyNode += "\\" + matcher.group(1);
List<String> output2 = new ArrayList<>();
executeCommand(
new String[] {"REG", "QUERY", "\"" + keyNode + "\"",
"/v", "JavaHome"},
output2);
Pattern pattern2
= Pattern.compile("\\s*JavaHome\\s+\\S+\\s+(.*)$");
for (String line2 : output2) {
Matcher matcher2 = pattern2.matcher(line2);
if (matcher2.find()) {
pathToJavaw = Paths.get(matcher2.group(1), "bin",
"javaw.exe");
break;
}
}
break;
}
}
try {
if (Files.exists(pathToJavaw)) {
return pathToJavaw.toString();
}
} catch (Exception ignored) {}
/* Check in 'C:\Windows\System32' */
pathToJavaw = Paths.get("C:\\Windows\\System32\\javaw.exe");
try {
if (Files.exists(pathToJavaw)) {
return pathToJavaw.toString();
}
} catch (Exception ignored) {}
/* Check in 'C:\Program Files\Java\jre*' */
pathToJavaw = null;
temp = Paths.get("C:\\Program Files\\Java");
if (Files.exists(temp)) {
try (DirectoryStream<Path> dirStream
= Files.newDirectoryStream(temp, "jre*")) {
for (Path path : dirStream) {
temp = Paths.get(path.toString(), "bin", "javaw.exe");
if (Files.exists(temp)) {
pathToJavaw = temp;
// Don't "break", in order to find the latest JRE version
}
}
if (pathToJavaw != null) {
return pathToJavaw.toString();
}
} catch (Exception ignored) {}
}
/* Check in 'C:\Program Files (x86)\Java\jre*' */
pathToJavaw = null;
temp = Paths.get("C:\\Program Files (x86)\\Java");
if (Files.exists(temp)) {
try (DirectoryStream<Path> dirStream
= Files.newDirectoryStream(temp, "jre*")) {
for (Path path : dirStream) {
temp = Paths.get(path.toString(), "bin", "javaw.exe");
if (Files.exists(temp)) {
pathToJavaw = temp;
// Don't "break", in order to find the latest JRE version
}
}
if (pathToJavaw != null) {
return pathToJavaw.toString();
}
} catch (Exception ignored) {}
}
/* Check in 'C:\Program Files\Java\jdk*' */
pathToJavaw = null;
temp = Paths.get("C:\\Program Files\\Java");
if (Files.exists(temp)) {
try (DirectoryStream<Path> dirStream
= Files.newDirectoryStream(temp, "jdk*")) {
for (Path path : dirStream) {
temp = Paths.get(path.toString(), "jre", "bin", "javaw.exe");
if (Files.exists(temp)) {
pathToJavaw = temp;
// Don't "break", in order to find the latest JDK version
}
}
if (pathToJavaw != null) {
return pathToJavaw.toString();
}
} catch (Exception ignored) {}
}
/* Check in 'C:\Program Files (x86)\Java\jdk*' */
pathToJavaw = null;
temp = Paths.get("C:\\Program Files (x86)\\Java");
if (Files.exists(temp)) {
try (DirectoryStream<Path> dirStream
= Files.newDirectoryStream(temp, "jdk*")) {
for (Path path : dirStream) {
temp = Paths.get(path.toString(), "jre", "bin", "javaw.exe");
if (Files.exists(temp)) {
pathToJavaw = temp;
// Don't "break", in order to find the latest JDK version
}
}
if (pathToJavaw != null) {
return pathToJavaw.toString();
}
} catch (Exception ignored) {}
}
return "javaw.exe"; // Let's just hope it is in the path :)
}
try this
"columns": [
{data: "id", name: "aaa", sortable: false},
{data: "userid", name: "userid", sortable: false},
{data: "group_id", name: "group_id", sortable: false},
{data: "group_name", name: "group_name", sortable: false},
{data: "group_member", name: "group_member"},
{data: "group_fee", name: "group_fee"},
{data: "dynamic_type", name: "dynamic_type"},
{data: "dynamic_id", name: "dynamic_id"},
{data: "content", name: "content", sortable: false},
{data: "images", name: "images", sortable: false},
{data: "money", name: "money"},
{data: "is_audit", name: "is_audit", sortable: false},
{data: "audited_at", name: "audited_at", sortable: false}
]
You could use a std::stringstream. You can stream anything into it:
std::stringstream stream;
stream << 5.7;
stream << foo.bar;
std::string s = stream.str();
That should be a quite general approach. (Works only for C++, but you asked the question for this language too.)
Considering the String
you're asking about is
C:\Hello\AnotherFolder\The File Name.PDF
we need to extract everything after the last separator, ie. \
. That is what we are interested in.
You can do
String fullPath = "C:\\Hello\\AnotherFolder\\The File Name.PDF";
int index = fullPath.lastIndexOf("\\");
String fileName = fullPath.substring(index + 1);
This will retrieve the index of the last \
in your String
and extract everything that comes after it into fileName
.
If you have a String
with a different separator, adjust the lastIndexOf
to use that separator. (There's even an overload that accepts an entire String
as a separator.)
I've omitted it in the example above, but if you're unsure where the String
comes from or what it might contain, you'll want to validate that the lastIndexOf
returns a non-negative value because the Javadoc states it'll return
-1 if there is no such occurrence
All I needed was this :
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat sdfLocal = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
try {
String d = sdf.format(new Date());
System.out.println(d);
System.out.println(sdfLocal.parse(d));
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
Output : slightly dubious, but I want only the date to be consistent
2013.08.08 11:01:08
Thu Aug 08 11:01:08 GMT+08:00 2013
"This is a comment in vimrc. It does not have a closing quote
Source: http://vim.wikia.com/wiki/Backing_up_and_commenting_vimrc
On RHEL systems, the /etc/rc.d/init.d/functions
script is intended to provide similar to what you want. If you source that at the top of your init script, all of it's functions become available.
The specific function provided to help with this is daemon
. If you are intending to use it to start a daemon-like program, a simple usage would be:
daemon --user=username command
If that is too heavy-handed for what you need, there is runuser
(see man runuser
for full info; some versions may need -u
prior to the username):
/sbin/runuser username -s /bin/bash -c "command(s) to run as user username"
I am afraid there is no way to get the query string parameters parsed separately from the post parameters. BTW the fact that such API absent may mean that probably you should check your design. Why are you using query string when sending POST? If you really want to send more data into URL use REST-like convention, e.g. instead of sending
http://mycompany.com/myapp/myservlet?first=11&second=22
say:
Easiest way to clear/reset the text field on click is to clear/reset the scope
<input type="text" class="form-control" ng-model="searchAll" ng-click="clearfunction(this)"/>
In Controller
$scope.clearfunction=function(event){
event.searchAll=null;
}
You can also pad a string to the required length using Guava's Strings.padEnd(String input, int minLength, char padding)
A simple way to take a screenshot is through Pygame.
pygame.image.save(Surface, filename)
Where 'Surface' is the surface you are taking a screenshot of, and 'filename' is the file path, name, and type where you save thew image.
You can export as BMP, TGA, PNG, or JPEG. As of Pygame 1.8, PNG, and JPEG also work.
If no file extension is specified it will default to a .TGA file.
You can even use the 'os' library for saving to specific file directories.
An example:
import os
import pygame
surface = pygame.display.set_mode((100, 100), 0, 32)
surface.fill((255, 255, 255))
pygame.draw.circle(surface, (0, 0, 0), (10, 10), 15, 0)
pygame.display.update()
pygame.image.save(surface, os.path.expanduser("~/Desktop/pic.png"))
This saves anything on the 'surface' Surface to the user's desktop as pic.png
Warning: if you want to load the 'monkey patch' or 'open class' from your 'lib' folder, don't use the 'autoload' approach!!!
"config.autoload_paths" approach: only works if you are loading a class that defined only in ONE place. If some class has been already defined somewhere else, then you can't load it again by this approach.
"config/initializer/load_rb_file.rb" approach: always works! whatever the target class is a new class or an "open class" or "monkey patch" for existing class, it always works!
For more details , see: https://stackoverflow.com/a/6797707/445908
For the record, rjson and RJSONIO do change the file type, but they don't really parse per se. For instance, I receive ugly MongoDB data in JSON format, convert it with rjson or RJSONIO, then use unlist and tons of manual correction to actually parse it into a usable matrix.
There are two ways to exit a method early (without quitting the program):
return
keyword.Exceptions should only be used for exceptional circumstances - when the method cannot continue and it cannot return a reasonable value that would make sense to the caller. Usually though you should just return when you are done.
If your method returns void then you can write return without a value:
return;
Specifically about your code:
You should also use curly braces when you write an if statement so that it is clear which statements are inside the body of the if statement:
if (textBox1.Text == String.Empty)
{
textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
}
return; // Are you sure you want the return to be here??
If you are using .NET 4 there is a useful method that depending on your requirements you might want to consider using here: String.IsNullOrWhitespace.
Environment.Newline
instead of "\r\n"
.The following is the correct overload (in your example you are missing a closing }
to the routeValues
anonymous object so your code will throw an exception):
<a href="<%: Url.Action("GetByList", "Listing", new { name = "John", contact = "calgary, vancouver" }) %>">
<span>People</span>
</a>
Assuming you are using the default routes this should generate the following markup:
<a href="/Listing/GetByList?name=John&contact=calgary%2C%20vancouver">
<span>People</span>
</a>
which will successfully invoke the GetByList
controller action passing the two parameters:
public ActionResult GetByList(string name, string contact)
{
...
}
Having an interest in this, I decided to test the suggested methods with the closest "apples to apples" test I could. I wrote a Console app, with the following code:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
namespace SerializationTests
{
class Program
{
static void Main(string[] args)
{
var count = 100000;
var rnd = new Random(DateTime.UtcNow.GetHashCode());
Console.WriteLine("Generating {0} arrays of data...", count);
var arrays = new List<int[]>();
for (int i = 0; i < count; i++)
{
var elements = rnd.Next(1, 100);
var array = new int[elements];
for (int j = 0; j < elements; j++)
{
array[j] = rnd.Next();
}
arrays.Add(array);
}
Console.WriteLine("Test data generated.");
var stopWatch = new Stopwatch();
Console.WriteLine("Testing BinarySerializer...");
var binarySerializer = new BinarySerializer();
var binarySerialized = new List<byte[]>();
var binaryDeserialized = new List<int[]>();
stopWatch.Reset();
stopWatch.Start();
foreach (var array in arrays)
{
binarySerialized.Add(binarySerializer.Serialize(array));
}
stopWatch.Stop();
Console.WriteLine("BinaryFormatter: Serializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);
stopWatch.Reset();
stopWatch.Start();
foreach (var serialized in binarySerialized)
{
binaryDeserialized.Add(binarySerializer.Deserialize<int[]>(serialized));
}
stopWatch.Stop();
Console.WriteLine("BinaryFormatter: Deserializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);
Console.WriteLine();
Console.WriteLine("Testing ProtoBuf serializer...");
var protobufSerializer = new ProtoBufSerializer();
var protobufSerialized = new List<byte[]>();
var protobufDeserialized = new List<int[]>();
stopWatch.Reset();
stopWatch.Start();
foreach (var array in arrays)
{
protobufSerialized.Add(protobufSerializer.Serialize(array));
}
stopWatch.Stop();
Console.WriteLine("ProtoBuf: Serializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);
stopWatch.Reset();
stopWatch.Start();
foreach (var serialized in protobufSerialized)
{
protobufDeserialized.Add(protobufSerializer.Deserialize<int[]>(serialized));
}
stopWatch.Stop();
Console.WriteLine("ProtoBuf: Deserializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);
Console.WriteLine();
Console.WriteLine("Testing NetSerializer serializer...");
var netSerializerSerializer = new ProtoBufSerializer();
var netSerializerSerialized = new List<byte[]>();
var netSerializerDeserialized = new List<int[]>();
stopWatch.Reset();
stopWatch.Start();
foreach (var array in arrays)
{
netSerializerSerialized.Add(netSerializerSerializer.Serialize(array));
}
stopWatch.Stop();
Console.WriteLine("NetSerializer: Serializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);
stopWatch.Reset();
stopWatch.Start();
foreach (var serialized in netSerializerSerialized)
{
netSerializerDeserialized.Add(netSerializerSerializer.Deserialize<int[]>(serialized));
}
stopWatch.Stop();
Console.WriteLine("NetSerializer: Deserializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);
Console.WriteLine("Press any key to end.");
Console.ReadKey();
}
public class BinarySerializer
{
private static readonly BinaryFormatter Formatter = new BinaryFormatter();
public byte[] Serialize(object toSerialize)
{
using (var stream = new MemoryStream())
{
Formatter.Serialize(stream, toSerialize);
return stream.ToArray();
}
}
public T Deserialize<T>(byte[] serialized)
{
using (var stream = new MemoryStream(serialized))
{
var result = (T)Formatter.Deserialize(stream);
return result;
}
}
}
public class ProtoBufSerializer
{
public byte[] Serialize(object toSerialize)
{
using (var stream = new MemoryStream())
{
ProtoBuf.Serializer.Serialize(stream, toSerialize);
return stream.ToArray();
}
}
public T Deserialize<T>(byte[] serialized)
{
using (var stream = new MemoryStream(serialized))
{
var result = ProtoBuf.Serializer.Deserialize<T>(stream);
return result;
}
}
}
public class NetSerializer
{
private static readonly NetSerializer Serializer = new NetSerializer();
public byte[] Serialize(object toSerialize)
{
return Serializer.Serialize(toSerialize);
}
public T Deserialize<T>(byte[] serialized)
{
return Serializer.Deserialize<T>(serialized);
}
}
}
}
The results surprised me; they were consistent when run multiple times:
Generating 100000 arrays of data...
Test data generated.
Testing BinarySerializer...
BinaryFormatter: Serializing took 336.8392ms.
BinaryFormatter: Deserializing took 208.7527ms.
Testing ProtoBuf serializer...
ProtoBuf: Serializing took 2284.3827ms.
ProtoBuf: Deserializing took 2201.8072ms.
Testing NetSerializer serializer...
NetSerializer: Serializing took 2139.5424ms.
NetSerializer: Deserializing took 2113.7296ms.
Press any key to end.
Collecting these results, I decided to see if ProtoBuf or NetSerializer performed better with larger objects. I changed the collection count to 10,000 objects, but increased the size of the arrays to 1-10,000 instead of 1-100. The results seemed even more definitive:
Generating 10000 arrays of data...
Test data generated.
Testing BinarySerializer...
BinaryFormatter: Serializing took 285.8356ms.
BinaryFormatter: Deserializing took 206.0906ms.
Testing ProtoBuf serializer...
ProtoBuf: Serializing took 10693.3848ms.
ProtoBuf: Deserializing took 5988.5993ms.
Testing NetSerializer serializer...
NetSerializer: Serializing took 9017.5785ms.
NetSerializer: Deserializing took 5978.7203ms.
Press any key to end.
My conclusion, therefore, is: there may be cases where ProtoBuf and NetSerializer are well-suited to, but in terms of raw performance for at least relatively simple objects... BinaryFormatter is significantly more performant, by at least an order of magnitude.
YMMV.
So if condition equals the value you want then the php document will run "include" and include will add that document to the current window for example:
`
<?php
$isARequest = true;
if ($isARequest){include('request.html');}/*So because $isARequest is true then it will include request.html but if its not a request then it will insert isNotARequest;*/
else if (!$isARequest) {include('isNotARequest.html')}
?>
`
Since Android 4.2 (API 17) nested fragments become available http://developer.android.com/about/versions/android-4.2.html#NestedFragments
To place fragment inside other fragment use getChildFragmentManager()
It also available in support library!
Based on an Aptana Studio support response, it was confirmed that the Aptana plugin and Android Development Tools collide on this port (i.e. Aptana's Comet server overlapped on this port). Aptana opened a ticket back in 2010.
Unfortunately, it does not appear that Aptana has fixed it yet or made their Comet server port configurable. Changing the port number in eclipse and restarting adb did NOT fix it for me. I finally was forced to uninstall the Aptana plugin.
I have at least one situation where the data is not automatically cleaned up, which would eventually lead to "Out of Memory" errors. In a UserForm I had:
Public mainPicture As StdPicture
...
mainPicture = LoadPicture(PAGE_FILE)
When UserForm was destroyed (after Unload Me
) the memory allocated for the data loaded in the mainPicture
was not being de-allocated. I had to add an explicit
mainPicture = Nothing
in the terminate event.
If you write this yourself these are some of the points to keep in mind
Proper authentication between the device and the Sync Server
A sync protocol between the device and the server. It will usually go in 3 phases, authentication, data exchange, status exchange (which operations worked and which failed)
Pick your payload format. I suggest SyncML based XML mixed with JSON based format to represent the actual data. So SyncML for the protocol, and JSON for the actual data being exchanged. Using JSON Array while manipulating the data is always preferred as it is easy to access data using JSON Array.
Keeping track of data changes on both client and server. You can maintain a changelog of ids that change and pick them up during a sync session. Also, clear the changelog as the objects are successfully synchronized. You can also use a boolean variable to confirm the synchronization status, i.e. last time of sync. It will be helpful for end users to identify the time when last sync is done.
Need to have a way to communicate from the server to the device to start a sync session as data changes on the server. You can use C2DM or write your own persistent tcp based communication. The tcp approach is a lot seamless
A way to replicate data changes across multiple devices
And last but not the least, a way to detect and handle conflicts
Hope this helps as a good starting point.
String mQuery = "SELECT Name,Family From tblName";
Cursor mCur = db.rawQuery(mQuery, new String[]{});
mCur.moveToFirst();
while ( !mCur.isAfterLast()) {
String name= mCur.getString(mCur.getColumnIndex("Name"));
String family= mCur.getString(mCur.getColumnIndex("Family"));
mCur.moveToNext();
}
Name and family are your result
Well, I can understand your pain, but, quite frankly, people like you and I -- or pretty much any regular Stack Overflow user -- are not the rule.
What I mean by that is that... most programmers won't care about that type signature, because they'll never see them! They don't read documentation.
As long as they saw some example of how the code works, and the code doesn't fail them in producing the result they expect, they won't ever look at the documentation. When that fails, they'll look at the documentation and expect to see usage examples at the top.
With these things in mind, I think that:
Anyone (as in, most people) who ever comes across that type signature will mock Scala to no end if they are pre-disposed against it, and will consider it a symbol of Scala's power if they like Scala.
If the documentation isn't enhanced to provide usage examples and explain clearly what a method is for and how to use it, it can detract from Scala adoption a bit.
In the long run, it won't matter. That Scala can do stuff like that will make libraries written for Scala much more powerful and safer to use. These libraries and frameworks will attract programmers atracted to powerful tools.
Programmers who like simplicity and directness will continue to use PHP, or similar languages.
Alas, Java programmers are much into power tools, so, in answering that, I have just revised my expectation of mainstream Scala adoption. I have no doubt at all that Scala will become a mainstream language. Not C-mainstream, but perhaps Perl-mainstream or PHP-mainstream.
Speaking of Java, did you ever replace the class loader? Have you ever looked into what that involves? Java can be scary, if you look at the places framework writers do. It's just that most people don't. The same thing applies to Scala, IMHO, but early adopters have a tendency to look under each rock they encounter, to see if there's something hiding there.
The Substring method on the string class has always felt inadequate to me. Usually when you do a substring, you know the character(s) from where you want to start, and the charachter(s) where you want to end. Thus, I've always felt that have to specify length as the second parameter is stupid. Therefore, I've written my own extension methods. One that takes a startIndex and an endIndex. And one, that takes a startText (string) and endText (string) so you can just specify the text from where to start the substring, and the text for where to end it.
NOTE: I couldn't name the method Substring as in .NET because my first overload takes the same parameter types as one of the .NET overloads. Therefore I named them Subsetstring. Feel free to add to the CodePlex...
public static class StringExtensions
{
/// <summary>
/// Returns a Subset string starting at the specified start index and ending and the specified end
/// index.
/// </summary>
/// <param name="s">The string to retrieve the subset from.</param>
/// <param name="startIndex">The specified start index for the subset.</param>
/// <param name="endIndex">The specified end index for the subset.</param>
/// <returns>A Subset string starting at the specified start index and ending and the specified end
/// index.</returns>
public static string Subsetstring(this string s, int startIndex, int endIndex)
{
if (startIndex > endIndex)
{
throw new InvalidOperationException("End Index must be after Start Index.");
}
if (startIndex < 0)
{
throw new InvalidOperationException("Start Index must be a positive number.");
}
if(endIndex <0)
{
throw new InvalidOperationException("End Index must be a positive number.");
}
return s.Substring(startIndex, (endIndex - startIndex));
}
/// <summary>
/// Finds the specified Start Text and the End Text in this string instance, and returns a string
/// containing all the text starting from startText, to the begining of endText. (endText is not
/// included.)
/// </summary>
/// <param name="s">The string to retrieve the subset from.</param>
/// <param name="startText">The Start Text to begin the Subset from.</param>
/// <param name="endText">The End Text to where the Subset goes to.</param>
/// <param name="ignoreCase">Whether or not to ignore case when comparing startText/endText to the string.</param>
/// <returns>A string containing all the text starting from startText, to the begining of endText.</returns>
public static string Subsetstring(this string s, string startText, string endText, bool ignoreCase)
{
if (string.IsNullOrEmpty(startText) || string.IsNullOrEmpty(endText))
{
throw new ArgumentException("Start Text and End Text cannot be empty.");
}
string temp = s;
if (ignoreCase)
{
temp = s.ToUpperInvariant();
startText = startText.ToUpperInvariant();
endText = endText.ToUpperInvariant();
}
int start = temp.IndexOf(startText);
int end = temp.IndexOf(endText, start);
return Subsetstring(s, start, end);
}
}
Usage:
string s = "This is a tester for my cool extension method!!";
s = s.Subsetstring("tester", "cool",true);
Output: "tester for my "
In the new version of tensorflow 2.0, the process of saving/loading a model is a lot easier. Because of the Implementation of the Keras API, a high-level API for TensorFlow.
To save a model: Check the documentation for reference: https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/keras/models/save_model
tf.keras.models.save_model(model_name, filepath, save_format)
To load a model:
https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/keras/models/load_model
model = tf.keras.models.load_model(filepath)
Check my answer here
The use of Layout Inspector tool can be very convenient when you have a complex view or you are using a third party library where you can't add an id to a view
In general, to make sure something happens no matter what, you use
from exceptions import NameError
try:
f = open(x)
except ErrorType as e:
pass # handle the error
finally:
try:
f.close()
except NameError: pass
finally
blocks will be run whether or not there is an error in the try
block, and whether or not there is an error in any error handling that takes place in except
blocks. If you don't handle an exception that is raised, it will still be raised after the finally
block is excecuted.
The general way to make sure a file is closed is to use a "context manager".
http://docs.python.org/reference/datamodel.html#context-managers
with open(x) as f:
# do stuff
This will automatically close f
.
For your question #2, bar
gets closed on immediately when it's reference count reaches zero, so on del foo
if there are no other references.
Objects are NOT created by __init__
, they're created by __new__
.
http://docs.python.org/reference/datamodel.html#object.new
When you do foo = Foo()
two things are actually happening, first a new object is being created, __new__
, then it is being initialized, __init__
. So there is no way you could possibly call del foo
before both those steps have taken place. However, if there is an error in __init__
, __del__
will still be called because the object was actually already created in __new__
.
Edit: Corrected when deletion happens if a reference count decreases to zero.
Use Str()
Function. It takes three arguments(the number, the number total characters to display, and the number of decimal places to display
Select Str(12345.6789, 12, 3)
displays: ' 12345.679' ( 3 spaces, 5 digits 12345, a decimal point, and three decimal digits (679). - it rounds if it has to truncate, (unless the integer part is too large for the total size, in which case asterisks are displayed instead.)
for a Total of 12 characters, with 3 to the right of decimal point.
Just for anyone who still has an issue, I also had an issue where I typed ngif
rather than ngIf
(notice the capital 'I').
According to this article on sqlserverstudymaterial;
Remember that "%Privileged time" is not based on 100%.It is based on number of processors.If you see 200 for sqlserver.exe and the system has 8 CPU then CPU consumed by sqlserver.exe is 200 out of 800 (only 25%).
If "% Privileged Time" value is more than 30% then it's generally caused by faulty drivers or anti-virus software. In such situations make sure the BIOS and filter drives are up to date and then try disabling the anti-virus software temporarily to see the change.
If "% User Time" is high then there is something consuming of SQL Server. There are several known patterns which can be caused high CPU for processes running in SQL Server including
So i also had a small list where i clearly had the possibility of introducing non-unique values.
I searched for the existence of a unique list of some sort, but then realized that testing the existence of the element before adding it works just fine.
if(not new_element in my_list):
my_list.append(new_element)
I don't know if there are caveats to this simple approach, but it solves my problem.
Python equivalent code for a QMessageBox which consist of a question in it and Yes and No button. When Yes Button is clicked it will pop up another message box saying yes is clicked and same for No button also. You can push your own code after if block.
button_reply = QMessageBox.question(self,"Test", "Are you sure want to quit??", QMessageBox.Yes,QMessageBox.No,)
if button_reply == QMessageBox.Yes:
QMessageBox.information(self, "Test", "Yes Button Was Clicked")
else :
QMessageBox.information(self, "Test", "No Button Was Clicked")
Ask how accidental closures might cause memory leaks in IE.
I don't know if it will fit your needs, but you can also do:
>>> lol = df.values
>>> lol
array([[1, 2, 3],
[3, 4, 5]])
This is just a numpy array from the ndarray module, which lets you do all the usual numpy array things.
The first is easiest(involves less typing), and it is guaranteed to work, all members will be set to 0
[Ref 1].
The second is more readable.
The choice depends on user preference or the one which your coding standard mandates.
[Ref 1] Reference C99 Standard 6.7.8.21:
If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.
Good Read:
C and C++ : Partial initialization of automatic structure
The warning is issued since you are using backslashes in your strings. If you want to avoid the message, type this command "set standard_conforming_strings=on;". Then use "E" before your string including backslashes that you want postgresql to intrepret.
<div style="height: 100px;"> </div>
OR
<div id="foo"/> and set the style as #foo { height: 100px; }
<div class="bar"/> and set the style as .bar{ height: 100px; }
$.ajax({
type: "GET",
url: '<?php echo Base_url("user/your function");?>',
data: {name: mail},
dataType: "jsonp",
jsonp: 'callback',
jsonpCallback: 'chekEmailTaken',
success: function(msg){
}
});
return true;
In controller:
public function ajax_checkjp(){
$checkType = $_GET['name'];
echo $_GET['callback']. '(' . json_encode($result) . ');';
}
if your using php for the backend maybe you can use this code.
// Validate image file size
if (($_FILES["file-input"]["size"] > 2000000)) {
$msg = "Image File Size is Greater than 2MB.";
header("Location: ../product.php?error=$msg");
exit();
}
You want
round(new MathContext(0)); // or perhaps another math context with rounding mode HALF_UP
First of all create a model POJO
import javax.persistence.*;
@Entity
@Table(name = "sys_std_user")
public class StdUser {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "class_id")
public int classId;
@Column(name = "user_name")
public String userName;
//getter,setter
}
Controller
import com.example.demo.models.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import java.util.List;
@RestController
public class HomeController {
@PersistenceUnit
private EntityManagerFactory emf;
@GetMapping("/")
public List<StdUser> actionIndex() {
EntityManager em = emf.createEntityManager(); // Without parameter
List<StdUser> arr_cust = (List<StdUser>)em
.createQuery("SELECT c FROM StdUser c")
.getResultList();
return arr_cust;
}
@GetMapping("/paramter")
public List actionJoin() {
int id = 3;
String userName = "Suresh Shrestha";
EntityManager em = emf.createEntityManager(); // With parameter
List arr_cust = em
.createQuery("SELECT c FROM StdUser c WHERE c.classId = :Id ANd c.userName = :UserName")
.setParameter("Id",id)
.setParameter("UserName",userName)
.getResultList();
return arr_cust;
}
}
Just for anyone who is still looking for answers:
$db['default']['dbdriver'] = 'mysqli'; (make sure you use mysqli, not mysql). (database.php)
I did not found the maven or configure menus but found the following button that solved my problem:
The Concat
method will return an object which implements IEnumerable<T>
by returning an object (call it Cat) whose enumerator will attempt to use the two passed-in enumerable items (call them A and B) in sequence. If the passed-in enumerables represent sequences which will not change during the lifetime of Cat, and which can be read from without side-effects, then Cat may be used directly. Otherwise, it may be a good idea to call ToList()
on Cat
and use the resulting List<T>
(which will represent a snapshot of the contents of A and B).
Some enumerables take a snapshot when enumeration begins, and will return data from that snapshot if the collection is modified during enumeration. If B is such an enumerable, then any change to B which occurs before Cat has reached the end of A will show up in Cat's enumeration, but changes which occur after that will not. Such semantics may likely be confusing; taking a snapshot of Cat can avoid such issues.
For EditText in image above, You have to create two xml files in res-->drawable folder. First will be "bg_edittext_focused.xml" paste the lines of code in it
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#FFFFFF" />
<stroke
android:width="2dip"
android:color="#F6F6F6" />
<corners android:radius="2dip" />
<padding
android:bottom="7dip"
android:left="7dip"
android:right="7dip"
android:top="7dip" />
</shape>
Second file will be "bg_edittext_normal.xml" paste the lines of code in it
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#F6F6F6" />
<stroke
android:width="2dip"
android:color="#F6F6F6" />
<corners android:radius="2dip" />
<padding
android:bottom="7dip"
android:left="7dip"
android:right="7dip"
android:top="7dip" />
</shape>
In res-->drawable folder create another xml file with name "bg_edittext.xml" that will call above mentioned code. paste the following lines of code below in bg_edittext.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/bg_edittext_focused" android:state_focused="true"/>
<item android:drawable="@drawable/bg_edittext_normal"/>
</selector>
Finally in res-->layout-->example.xml file in your case wherever you created your editText you'll call bg_edittext.xml as background
<EditText
:::::
:::::
android:background="@drawable/bg_edittext"
:::::
:::::
/>
Similar to Oksana but add python3
$ brew rm python
$ brew rm python3
$ rm -rf /usr/local/opt/python
$ rm -rf /usr/local/opt/python3
$ brew prune
$ brew install python3
$ brew postinstall python3
Seem now work for pip3 under mac os x 10.13.3 Xcode 9.2
new AlertDialog.Builder(context)
.setTitle("title")
.setMessage("message")
.setPositiveButton(android.R.string.ok, null)
.show();
Source: javaindos.
Let's say your file is in C:\mywork\
Run Command Prompt
C:\> cd \mywork
This makes C:\mywork the current directory.
C:\mywork> dir
This displays the directory contents. You should see filenamehere.java among the files.
C:\mywork> set path=%path%;C:\Program Files\Java\jdk1.5.0_09\bin
This tells the system where to find JDK programs.
C:\mywork> javac filenamehere.java
This runs javac.exe, the compiler. You should see nothing but the next system prompt...
C:\mywork> dir
javac has created the filenamehere.class file. You should see filenamehere.java and filenamehere.class among the files.
C:\mywork> java filenamehere
This runs the Java interpreter. You should then see your program output.
If the system cannot find javac, check the set path command. If javac runs but you get errors, check your Java text. If the program compiles but you get an exception, check the spelling and capitalization in the file name and the class name and the java HelloWorld command. Java is case-sensitive!
I know this is old and answered, but here is another way to do it. Particularly if you don't want the UTF8 BOM at the start of your string and you want the text indented:
using (var ms = new MemoryStream())
using (var x = new XmlTextWriter(ms, new UTF8Encoding(false))
{ Formatting = Formatting.Indented })
{
// ...
return Encoding.UTF8.GetString(ms.ToArray());
}
Firstly, just to check, you need to change into the directory you've created before running git init --bare
. Also, it's conventional to give bare repositories the extension .git
. So you can do
git init --bare test_repo.git
For Git versions < 1.8 you would do
mkdir test_repo.git
cd test_repo.git
git --bare init
To answer your later questions, bare repositories (by definition) don't have a working tree attached to them, so you can't easily add files to them as you would in a normal non-bare repository (e.g. with git add <file>
and a subsequent git commit
.)
You almost always update a bare repository by pushing to it (using git push
) from another repository.
Note that in this case you'll need to first allow people to push to your repository. When inside test_repo.git
, do
git config receive.denyCurrentBranch ignore
Community edit
git init --bare --shared=group
As commented by prasanthv, this is what you want if you are doing this at work, rather than for a private home project.
With Swift 4, NSAttributedStringKey
has a static property called foregroundColor
. foregroundColor
has the following declaration:
static let foregroundColor: NSAttributedStringKey
The value of this attribute is a
UIColor
object. Use this attribute to specify the color of the text during rendering. If you do not specify this attribute, the text is rendered in black.
The following Playground code shows how to set the text color of an NSAttributedString
instance with foregroundColor
:
import UIKit
let string = "Some text"
let attributes = [NSAttributedStringKey.foregroundColor : UIColor.red]
let attributedString = NSAttributedString(string: string, attributes: attributes)
The code below shows a possible UIViewController
implementation that relies on NSAttributedString
in order to update the text and text color of a UILabel
from a UISlider
:
import UIKit
enum Status: Int {
case veryBad = 0, bad, okay, good, veryGood
var display: (text: String, color: UIColor) {
switch self {
case .veryBad: return ("Very bad", .red)
case .bad: return ("Bad", .orange)
case .okay: return ("Okay", .yellow)
case .good: return ("Good", .green)
case .veryGood: return ("Very good", .blue)
}
}
static let minimumValue = Status.veryBad.rawValue
static let maximumValue = Status.veryGood.rawValue
}
final class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var slider: UISlider!
var currentStatus: Status = Status.veryBad {
didSet {
// currentStatus is our model. Observe its changes to update our display
updateDisplay()
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Prepare slider
slider.minimumValue = Float(Status.minimumValue)
slider.maximumValue = Float(Status.maximumValue)
// Set display
updateDisplay()
}
func updateDisplay() {
let attributes = [NSAttributedStringKey.foregroundColor : currentStatus.display.color]
let attributedString = NSAttributedString(string: currentStatus.display.text, attributes: attributes)
label.attributedText = attributedString
slider.value = Float(currentStatus.rawValue)
}
@IBAction func updateCurrentStatus(_ sender: UISlider) {
let value = Int(sender.value.rounded())
guard let status = Status(rawValue: value) else { fatalError("Could not get Status object from value") }
currentStatus = status
}
}
Note however that you don't really need to use NSAttributedString
for such an example and can simply rely on UILabel
's text
and textColor
properties. Therefore, you can replace your updateDisplay()
implementation with the following code:
func updateDisplay() {
label.text = currentStatus.display.text
label.textColor = currentStatus.display.color
slider.value = Float(currentStatus.rawValue)
}
Try creating a duplicate table, preferably a temporary table, without the unique constraint and do your bulk load into that table. Then select only the unique (DISTINCT) items from the temporary table and insert into the target table.
You can use a lightweight library pure-md5. Just a 4.7kb.
$("#file-dialog").change(function() {_x000D_
handleFiles(this.files);_x000D_
});_x000D_
_x000D_
function handleFiles(files) {_x000D_
for (var index = 0; index < files.length; index++) {_x000D_
var file = files[index];_x000D_
var fileReader = new FileReader();_x000D_
fileReader.onload = function(e) {_x000D_
$('body').append(`_x000D_
<div style="margin-top: 2rem;">_x000D_
<span>${file.name}: </span>_x000D_
<span>${(md5(e.target.result))}</span>_x000D_
</div>_x000D_
`);_x000D_
}_x000D_
_x000D_
fileReader.readAsText(file, 'utf-8');_x000D_
}_x000D_
_x000D_
}
_x000D_
body {_x000D_
font-family: sans-serif;_x000D_
}
_x000D_
<script src="https://unpkg.com/[email protected]/lib/index.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="file" id="file-dialog" multiple="true" accept="image/*">
_x000D_
The statement icr=y;
does not make the reference refer to y
; it assigns the value of y
to the variable that icr
refers to, i
.
References are inherently const
, that is you can't change what they refer to. There are 'const
references' which are really 'references to const
', that is you can't change the value of the object they refer to. They are declared const int&
or int const&
rather than int& const
though.
Go to project>clean
and select the project which display error from check box and click ok , it will clear the error for you.
Click the tab which display build automatically in the project menu
And if this also does not work than restart the eclipse and try again it will work.