U can use :
$(document).ready(function () {
$('#ID').keyup(function () {
var val = $(this).val();
len = val.length;
if (len >= 140) {
$(this).text(val.substring(0, 140));
} else {
console.log(140 - len);
$('#charNum').empty().append(140 - len);
}
});
});
One like with events
(keydown)="$event.keyCode != 32 ? $event:$event.preventDefault()"
$('.form-fild input,.form-fild textarea').focus(function() {_x000D_
$(this).parent().addClass('open');_x000D_
});_x000D_
_x000D_
$('.form-fild input,.form-fild textarea').blur(function() {_x000D_
$(this).parent().removeClass('open');_x000D_
});
_x000D_
.open {_x000D_
color:red; _x000D_
}_x000D_
.form-fild {_x000D_
position: relative;_x000D_
margin: 30px 0;_x000D_
}_x000D_
.form-fild label {_x000D_
position: absolute;_x000D_
top: 5px;_x000D_
left: 10px;_x000D_
padding:5px;_x000D_
}_x000D_
_x000D_
.form-fild.open label {_x000D_
top: -25px;_x000D_
left: 10px;_x000D_
/*background: #ffffff;*/_x000D_
}_x000D_
.form-fild input[type="text"] {_x000D_
padding-left: 80px;_x000D_
}_x000D_
.form-fild textarea {_x000D_
padding-left: 80px;_x000D_
}_x000D_
.form-fild.open textarea, _x000D_
.form-fild.open input[type="text"] {_x000D_
padding-left: 10px;_x000D_
}_x000D_
textarea,_x000D_
input[type="text"] {_x000D_
padding: 10px;_x000D_
width: 100%;_x000D_
}_x000D_
textarea,_x000D_
input,_x000D_
.form-fild.open label,_x000D_
.form-fild label {_x000D_
-webkit-transition: all 0.2s ease-in-out;_x000D_
-moz-transition: all 0.2s ease-in-out;_x000D_
-o-transition: all 0.2s ease-in-out;_x000D_
transition: all 0.2s ease-in-out;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<form>_x000D_
<div class="form-fild">_x000D_
<label>Name :</label>_x000D_
<input type="text">_x000D_
</div>_x000D_
<div class="form-fild">_x000D_
<label>Email :</label>_x000D_
<input type="text">_x000D_
</div>_x000D_
<div class="form-fild">_x000D_
<label>Number :</label>_x000D_
<input type="text">_x000D_
</div>_x000D_
<div class="form-fild">_x000D_
<label>Message :</label>_x000D_
<textarea cols="10" rows="5"></textarea>_x000D_
</div>_x000D_
</form>_x000D_
</div>_x000D_
</div>
_x000D_
Oracle's JVM implementation for Java 8 got rid of the PermGen model and replaced it with Metaspace.
<!DOCTYPE html
PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en-US">
<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon"
type="image/png"
href="http://example.com/myicon.png">
</head>
<body>
...
</body>
</html>
rel="shortcut icon"
should be rel="icon"
Source: W3C
You have a few options including the "Round-trip ("O") format specifier".
var date1 = new DateTime(2008, 3, 1, 7, 0, 0);
Console.WriteLine(date1.ToString("O"));
Console.WriteLine(date1.ToString("s", System.Globalization.CultureInfo.InvariantCulture));
Output
2008-03-01T07:00:00.0000000
2008-03-01T07:00:00
However, DateTime + TimeZone may present other problems as described in the blog post DateTime and DateTimeOffset in .NET: Good practices and common pitfalls:
DateTime has countless traps in it that are designed to give your code bugs:
1.- DateTime values with DateTimeKind.Unspecified are bad news.
2.- DateTime doesn't care about UTC/Local when doing comparisons.
3.- DateTime values are not aware of standard format strings.
4.- Parsing a string that has a UTC marker with DateTime does not guarantee a UTC time.
This didn't work for me:
`socket.disconnect()`
This did work for me:
socket.disconnect(true)
Handing over true
will close the underlaying connection to the client and not just the namespace the client is connected to Socket IO Documentation.
An example use case: Client did connect to web socket server with invalid access token (access token handed over to web socket server with connection params). Web socket server notifies the client that it is going to close the connection, because of his invalid access token:
// (1) the server code emits
socket.emit('invalidAccessToken', function(data) {
console.log(data); // (4) server receives 'invalidAccessTokenEmitReceived' from client
socket.disconnect(true); // (5) force disconnect client
});
// (2) the client code listens to event
// client.on('invalidAccessToken', (name, fn) => {
// // (3) the client ack emits to server
// fn('invalidAccessTokenEmitReceived');
// });
If you have python installed completely, it can save you the hassle. All you need to do is enter the following command in your respective shell:
pip install pyqt5
And contrary to popular belief, AS LONG AS YOU HAVE PIP INSTALLED, you can do this on virtually any OS... Hope this helped!
If you have to use a distutils setup.py
script, there are some commandline options for forcing an installation destination. See http://docs.python.org/install/index.html#alternate-installation. If this problem repeats, you can setup a distutils configuration file, see http://docs.python.org/install/index.html#inst-config-files.
Setting the PYTHONPATH variable is described in tihos post.
class A{
public:
static const char* SOMETHING() { return "something"; }
};
I do it all the time - especially for expensive const default parameters.
class A{
static
const expensive_to_construct&
default_expensive_to_construct(){
static const expensive_to_construct xp2c(whatever is needed);
return xp2c;
}
};
This is what I did:
EF:
using (var context = new SomeDBContext())
{
foreach (var item in model.ShopItems) // ShopItems is a posted list with values
{
var feature = context.Shop
.Where(h => h.ShopID == 123 && h.Type == item.Type).ToList();
feature.ForEach(a => a.SortOrder = item.SortOrder);
}
context.SaveChanges();
}
Hope helps someone.
To draw your layout under statusbar:
values/styles.xml
<item name="android:windowTranslucentStatus">true</item>
values-v21/styles.xml
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@color/colorPrimaryDark</item>
Use CoordinatorLayout/DrawerLayout which already take care of the fitsSystemWindows parameter or create your own layout to like this:
public class FitsSystemWindowConstraintLayout extends ConstraintLayout {
private Drawable mStatusBarBackground;
private boolean mDrawStatusBarBackground;
private WindowInsetsCompat mLastInsets;
private Map<View, int[]> childsMargins = new HashMap<>();
public FitsSystemWindowConstraintLayout(Context context) {
this(context, null);
}
public FitsSystemWindowConstraintLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public FitsSystemWindowConstraintLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
if (ViewCompat.getFitsSystemWindows(this)) {
ViewCompat.setOnApplyWindowInsetsListener(this, new android.support.v4.view.OnApplyWindowInsetsListener() {
@Override
public WindowInsetsCompat onApplyWindowInsets(View view, WindowInsetsCompat insets) {
FitsSystemWindowConstraintLayout layout = (FitsSystemWindowConstraintLayout) view;
layout.setChildInsets(insets, insets.getSystemWindowInsetTop() > 0);
return insets.consumeSystemWindowInsets();
}
});
setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
TypedArray typedArray = context.obtainStyledAttributes(new int[]{android.R.attr.colorPrimaryDark});
try {
mStatusBarBackground = typedArray.getDrawable(0);
} finally {
typedArray.recycle();
}
} else {
mStatusBarBackground = null;
}
}
public void setChildInsets(WindowInsetsCompat insets, boolean draw) {
mLastInsets = insets;
mDrawStatusBarBackground = draw;
setWillNotDraw(!draw && getBackground() == null);
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (child.getVisibility() != GONE) {
if (ViewCompat.getFitsSystemWindows(this)) {
ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) child.getLayoutParams();
if (ViewCompat.getFitsSystemWindows(child)) {
ViewCompat.dispatchApplyWindowInsets(child, insets);
} else {
int[] childMargins = childsMargins.get(child);
if (childMargins == null) {
childMargins = new int[]{layoutParams.leftMargin, layoutParams.topMargin, layoutParams.rightMargin, layoutParams.bottomMargin};
childsMargins.put(child, childMargins);
}
if (layoutParams.leftToLeft == LayoutParams.PARENT_ID) {
layoutParams.leftMargin = childMargins[0] + insets.getSystemWindowInsetLeft();
}
if (layoutParams.topToTop == LayoutParams.PARENT_ID) {
layoutParams.topMargin = childMargins[1] + insets.getSystemWindowInsetTop();
}
if (layoutParams.rightToRight == LayoutParams.PARENT_ID) {
layoutParams.rightMargin = childMargins[2] + insets.getSystemWindowInsetRight();
}
if (layoutParams.bottomToBottom == LayoutParams.PARENT_ID) {
layoutParams.bottomMargin = childMargins[3] + insets.getSystemWindowInsetBottom();
}
}
}
}
}
requestLayout();
}
public void setStatusBarBackground(Drawable bg) {
mStatusBarBackground = bg;
invalidate();
}
public Drawable getStatusBarBackgroundDrawable() {
return mStatusBarBackground;
}
public void setStatusBarBackground(int resId) {
mStatusBarBackground = resId != 0 ? ContextCompat.getDrawable(getContext(), resId) : null;
invalidate();
}
public void setStatusBarBackgroundColor(@ColorInt int color) {
mStatusBarBackground = new ColorDrawable(color);
invalidate();
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mDrawStatusBarBackground && mStatusBarBackground != null) {
int inset = mLastInsets != null ? mLastInsets.getSystemWindowInsetTop() : 0;
if (inset > 0) {
mStatusBarBackground.setBounds(0, 0, getWidth(), inset);
mStatusBarBackground.draw(canvas);
}
}
}
}
main_activity.xml
<FitsSystemWindowConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<ImageView
android:layout_width="0dp"
android:layout_height="0dp"
android:fitsSystemWindows="true"
android:scaleType="centerCrop"
android:src="@drawable/toolbar_background"
app:layout_constraintBottom_toBottomOf="@id/toolbar"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="0dp"
android:layout_height="?attr/actionBarSize"
android:background="@android:color/transparent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="0dp"
android:gravity="center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@id/toolbar">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Content"
android:textSize="48sp" />
</LinearLayout>
</FitsSystemWindowConstraintLayout>
Result:
First of all, I'd recommend using the ISO-8601 standard format for date/time - it works regardless of the language and regional settings on your SQL Server. ISO-8601 is the YYYYMMDD
format - no spaces, no dashes - just the data:
select * from tblErrorLog
where errorDate = '20081220'
Second of all, you need to be aware that SQL Server 2005 DATETIME
always includes a time. If you check for exact match with just the date part, you'll get only rows that match with a time of 0:00:00 - nothing else.
You can either use any of the recommend range queries mentioned, or in SQL Server 2008, you could use the DATE
only date time - or you could do a check something like:
select * from tblErrorLog
where DAY(errorDate) = 20 AND MONTH(errorDate) = 12 AND YEAR(errorDate) = 2008
Whichever works best for you.
If you need to do this query often, you could either try to normalize the DATETIME
to include only the date, or you could add computed columns for DAY, MONTH and YEAR:
ALTER TABLE tblErrorLog
ADD ErrorDay AS DAY(ErrorDate) PERSISTED
ALTER TABLE tblErrorLog
ADD ErrorMonth AS MONTH(ErrorDate) PERSISTED
ALTER TABLE tblErrorLog
ADD ErrorYear AS YEAR(ErrorDate) PERSISTED
and then you could query more easily:
select * from tblErrorLog
where ErrorMonth = 5 AND ErrorYear = 2009
and so forth. Since those fields are computed and PERSISTED, they're always up to date and always current, and since they're peristed, you can even index them if needed.
You explained the difference correctly. It just depends on if you want x to increment before every run through a loop, or after that. It depends on your program logic, what is appropriate.
An important difference when dealing with STL-Iterators (which also implement these operators) is, that it++ creates a copy of the object the iterator points to, then increments, and then returns the copy. ++it on the other hand does the increment first and then returns a reference to the object the iterator now points to. This is mostly just relevant when every bit of performance counts or when you implement your own STL-iterator.
Edit: fixed the mixup of prefix and suffix notation
One of reasons why you will get this Notice: Array to string conversion in… is that you are combining group of arrays. Example, sorting out several first and last names.
To echo elements of array properly, you can use the function, implode(separator, array)
Example:
implode(' ', $var)
result:
first name[1], last name[1]
first name[2], last name[2]
More examples from W3C.
This works fine for me:
<style type="text/css">_x000D_
#table {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
}_x000D_
</style>
_x000D_
For me, just changing Height and Width to 100% doesn’t do it for me, and neither do setting left, right, top and bottom to 0, but using them both together will do the trick.
I also recommend pt versus cm or mm as it's more precise. Also, I cannot get @page to work in Chrome (version 30.0.1599.69 m) It ignores anything I put for the margins, large or small. But, you can get it to work with body margins on the document, weird.
Did you try InputMethodManager.SHOW_IMPLICIT
in first window.
and for hiding in second window use InputMethodManager.HIDE_IMPLICIT_ONLY
EDIT :
If its still not working then probably you are putting it at the wrong place. Override onFinishInflate()
and show/hide there.
@override
public void onFinishInflate() {
/* code to show keyboard on startup */
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(mUserNameEdit, InputMethodManager.SHOW_IMPLICIT);
}
Traditionally, if you only want to change the variable in your terminal windows, set it in .bashrc
file, which is sourced each time a new terminal is opened. .profile
file is not sourced each time you open a new terminal.
See the difference between .profile and .bashrc in question: What's the difference between .bashrc, .bash_profile, and .environment?
.bashrc
should solve your problem. However, it is not the proper solution since you are using Ubuntu. See the relevant Ubuntu help page "Session-wide environment variables". Thus, no wonder that .profile
does not work for you. I use Ubuntu 12.04 and xfce. I set up my .profile
and it is simply not taking effect even if I log out and in. Similar experience here. So you may have to use .pam_environment
file and totally forget about .profile
, and .bashrc
. And NOTE that .pam_environment
is not a script file.
In the VSCode launch.json you can use "env" and configure all your environment variables there:
{
"version": "0.2.0",
"configurations": [
{
"env": {
"NODE_ENV": "development",
"port":"1337"
},
...
}
]
}
Given the lack of information regarding the original image size, specifying percentages for the width and height would result in highly erratic results. If you are trying to ensure that an image will fit within a specific location on your page then you'll need to use some server side code to manage that rescaling.
In this mode you can find all element which has class active and remove it
try this
$(document).ready(function() {
$(this.attr('id')).click(function () {
$(document).find('.active').removeClass('active');
var DivId = $(this).attr('id');
alert(DivId);
$(this).addClass('active');
});
});
What i did:
I added the following line inside of ROOT/index.jsp
<meta http-equiv="refresh" content="0;url=/somethingelse/index.jsp"/>
You can also have Git store your credentials permanently using the following:
git config credential.helper store
Note: While this is convenient, Git will store your credentials in clear text in a local file (.git-credentials) under your project directory (see below for the "home" directory). If you don't like this, delete this file and switch to using the cache option.
If you want Git to resume to asking you for credentials every time it needs to connect to the remote repository, you can run this command:
git config --unset credential.helper
To store the passwords in .git-credentials
in your %HOME%
directory as opposed to the project directory: use the --global
flag
git config --global credential.helper store
you can do this :
private void setRowNumber(DataGridView dgv)
{
foreach (DataGridViewRow row in dgv.Rows)
{
row.HeaderCell.Value = row.Index + 1;
}
dgv.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);
}
One way would be to use Array reduce..
const max = data.reduce(function(prev, current) {
return (prev.y > current.y) ? prev : current
}) //returns object
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce http://caniuse.com/#search=reduce (IE9 and above)
If you don't need to support IE (only Edge), or can use a pre-compiler such as Babel you could use the more terse syntax.
const max = data.reduce((prev, current) => (prev.y > current.y) ? prev : current)
As others have said, the SVN Book is the best place to start and a great reference once you've gotten your sea legs. Now, to your questions ...
How often do you commit? As often as one would press ctrl + s?
Often, but not as often as you press ctrl + s. It's a matter of personal taste and/or team policy. Personally I would say commit when you complete a functional piece of code, however small.
What is a Branch and what is a Tag and how do you control them?
First, trunk is where you do your active development. It is the mainline of your code. A branch is some deviation from the mainline. It could be a major deviation, like a previous release, or just a minor tweak you want to try out. A tag is a snapshot of your code. It's a way to attach a label or bookmark to a particular revision.
It's also worth mentioning that in subversion, trunk, branches and tags are only convention. Nothing stops you from doing work in tags or having branches that are your mainline, or disregarding the tag-branch-trunk scheme all together. But, unless you have a very good reason, it's best to stick with convention.
What goes into the SVN? Only Source Code or do you share other files here aswell?
Also a personal or team choice. I prefer to keep anything related to the build in my repository. That includes config files, build scripts, related media files, docs, etc. You should not check in files that need to be different on each developer's machine. Nor do you need to check in by-products of your code. I'm thinking mostly of build folders, object files, and the like.
You should try :
<?php
echo CI_VERSION;
?>
Or check the file system/core/CodeIgniter.php
Without dict, try this solution:
x, y, z = 0, 1, 3
offset = ord('c')
[chr(i + offset) for i in (x,y,z)]
and gives:
['c', 'd', 'f']
The problem in my case was that the "receiver mountpoint" was incorrectly mounted. It was in read-only mode (for some extrange reason). It looked like rsync was copying the files, but it was not. I checked my fstab file and changed mount options to default, re-mount file system and execute rsync again. All fine then.
For Mac, run the below command in a terminal window:
echo export "PATH=$HOME/Library/Python/2.7/bin:$PATH"
In addition to the above answers, $
has no special meaning in javascript,it is free to be used in object naming. In jQuery, it is simply used as an alias for the jQuery object and jQuery() function.
However, you may encounter situations where you want to use it in conjunction with another JS library that also uses $, which would result a naming conflict. There is a method in JQuery just for this reason, jQuery.noConflict()
.
Here is a sample from jQuery doc's:
<script src="other_lib.js"></script>
<script src="jquery.js"></script>
<script>
$.noConflict();
// Code that uses other library's $ can follow here.
</script>
Alternatively, you can also use a like this
(function ($) {
// Code in which we know exactly what the meaning of $ is
} (jQuery));
export https_proxy=http://user:pswd@host:port
^^^^
Use http
for https_proxy instead of https
What I have noticed apart from next() scans only upto space where as nextLine() scans the entire line is that next waits till it gets a complete token where as nextLine() does not wait for complete token, when ever '\n' is obtained(i.e when you press enter key) the scanner cursor moves to the next line and returns the previous line skipped. It does not check for the whether you have given complete input or not, even it will take an empty string where as next() does not take empty string
public class ScannerTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int cases = sc.nextInt();
String []str = new String[cases];
for(int i=0;i<cases;i++){
str[i]=sc.next();
}
}
}
Try this program by changing the next() and nextLine() in for loop, go on pressing '\n' that is enter key without any input, you can find that using nextLine() method it terminates after pressing given number of cases where as next() doesnot terminate untill you provide and input to it for the given number of cases.
This works (I feel so idiotic):
C:\Windows\System32\cmd.exe /C runas /savecred /user:OtherUser DebugTarget.Exe
The above command will ask for your password everytime, so for less frustration, you can use /savecred. You get asked only once. (but works only for Home Edition and Starter, I think)
The prompt:
Password for 'https://[email protected]':
suggests, that you are using https not ssh. SSH urls start with git@, for example:
[email protected]:beginninggit/alias.git
Even if you work alone, with a single repo that you own, the operation:
git push
will cause:
Password for 'https://[email protected]':
if the remote origin starts with https
.
Check your remote with:
git remote -v
The remote depends on git clone
. If you want to use ssh clone the repo using its ssh url, for example:
git clone [email protected]:user/repo.git
I suggest you to start with git push
and git pull
for your private repo.
If that works, you have two joices suggested by Lazy Badger:
I provided the configuration values to word hosted .nET Compoent as follows.
A .NET Class Library component being called/hosted in MS Word. To provide configuration values to my component, I created winword.exe.config in C:\Program Files\Microsoft Office\OFFICE11 folder. You should be able to read configurations values like You do in Traditional .NET.
string sMsg = System.Configuration.ConfigurationManager.AppSettings["WSURL"];
Is WebSockets over TCP a fast enough protocol to stream a video of, say, 30fps?
Yes.. it is, take a look at this project. Websockets can easily handle HD videostreaming.. However, you should go for Adaptive Streaming. I explain here how you could implement it.
Currently we're working on a webbased instant messaging application with chat, filesharing and video/webcam support. With some bits and tricks we got streaming media through websockets (used HTML5 Media Capture to get the stream from our webcams).
You need to build a stream API
and a Media Stream Transceiver
to control the related media processing and transport.
If you want immediate first child you need
$(element).first();
If you want particular first element in the dom from your element then use below
var spanElement = $(elementId).find(".redClass :first");
$(spanElement).addClass("yourClassHere");
try out : http://jsfiddle.net/vgGbc/2/
Try npm cache clean --force
if it doesn't work then manually delete %appdata%\npm-cache folder.
and install npm install npm@latest -g
It worked for me.
The code of JS20'07'11 is really incredible simple and direct. One suggestion that I would like to give is to put a exclamation mark in the conditions:
InStr(1, objName.RefersTo, sWsName+"!", vbTextCompare)
Because this will prevent adding a NamedRange in an incorrect Sheet. Eg: If the NamedRange refers to a Sheet named Plan11 and you have another Sheet named Plan1 the code can do some mess when add the ranges if you don't use the exclamation mark.
UPDATE
A correction: It's best to use a regular expression evaluate the name of the Sheet. A simple function that you can use is the following (adapted by http://blog.malcolmp.com/2010/regular-expressions-excel-add-in, enable Microsoft VBScript Regular Expressions 5.5):
Function xMatch(pattern As String, searchText As String, Optional matchIndex As Integer = 1, Optional ignoreCase As Boolean = True) As String
On Error Resume Next
Dim RegEx As New RegExp
RegEx.Global = True
RegEx.MultiLine = True
RegEx.pattern = pattern
RegEx.ignoreCase = ignoreCase
Dim matches As MatchCollection
Set matches = RegEx.Execute(searchText)
Dim i As Integer
i = 1
For Each Match In matches
If i = matchIndex Then
xMatch = Match.Value
End If
i = i + 1
Next
End Function
So, You can use something like that:
xMatch("'?" +sWsName + "'?" + "!", objName.RefersTo, 1) <> ""
instead of
InStr(1, objName.RefersTo, sWsName+"!", vbTextCompare)
This will cover Plan1 and 'Plan1' (when the range refers to more than one cell) variations
TIP: Avoid Sheet names with single quotes ('), :) .
It's not safe, not recommended, but it's possible.
I have experience in an application using the auto-update option in production.
Well, the main problems and risks found in this solution are:
So, I will not recommend to use auto-update in production.
If you really want to use auto-update in production, I recommend:
And, different of the another posts, I don't think the auto-update enabled it's related with "very well paid" DBAs (as mentioned in other posts). DBAs have more important things to do than write SQL statements to create/change/delete tables and columns. These simple everyday tasks can be done and automated by developers and only passed for DBA team to review, not needing Hibernate and DBAs "very well paid" to write them.
You don't need JavaScript to choose your default submit button or input. You just need to mark it up with type="submit"
, and the other buttons mark them with type="button"
. In your example:
<button type="button" onclick="return myFunc1()">Button 1</button>
<input type="submit" name="go" value="Submit"/>
Yes. Use the ternary operator.
condition ? true_expression : false_expression;
Try with this link: http://download.eclipse.org/egit/github/updates
1)Go to Help-> Install new Software
2)Click on Add...
3)Name: eGit Location:http://download.eclipse.org/egit/github/updates
4)Click on OK
5)Accept the licence.
You are good to go
Addition to the accepted answer:
if you are going to use
@Html.ActionLink("LinkName", "ActionName", "ControllerName", new { @id = idValue, @secondParam= = 2 },null)
this will create actionlink where you can't create new custom attribute or style for the link.
However, the 4th parameter in ActionLink extension will solve that problem. Use the 4th parameter for customization in your way.
@Html.ActionLink("LinkName", "ActionName", "ControllerName", new { @id = idValue, @secondParam= = 2 }, new { @class = "btn btn-info", @target = "_blank" })
substitute:
mMyListView.invalidate();
for:
((BaseAdapter) mMyListView.getAdapter()).notifyDataSetChanged();
If that doesnt work, refer to this thread: Android List view refresh
There may be other ways to get your desired result.
Declare @a int
Declare @b int
SET @a = 3
SET @b=2
SELECT cast((cast(@a as float)/ cast(@b as float)) as float)
Here's a short answer
x=' ';
This will print one white space
print(x);
This will print 10 white spaces
print(10*x)
Print 10 whites spaces between Hello & World
print("Hello"+10*x+"world");
Another simple example.
For this sample we can use 100x100 DIV-box:
<div id="box" style="width: 100px; height: 100px; border: solid 1px red;">
// Red box contents here...
</div>
And small jQuery trick:
<script type="text/javascript">
jQuery("#box").bind("resize", function() {
alert("Box was resized from 100x100 to 200x200");
});
jQuery("#box").width(200).height(200).trigger("resize");
</script>
Steps:
That's all. ;-)
Using the "Add Service Reference" tool in Visual Studio, you can insert the address as:
file:///path/to/wsdl/file.wsdl
And it will load properly.
TextBox1.ForeColor = Color.Red;
TextBox1.Font.Bold = True;
Or this can be done using a CssClass (recommended):
.highlight
{
color:red;
font-weight:bold;
}
TextBox1.CssClass = "highlight";
Or the styles can be added inline:
TextBox1.Attributes["style"] = "color:red; font-weight:bold;";
So many ways to do this... for #NetCore use Lib..
using System;
using System.Collections.Generic;
using System.Linq; // only required when .AsEnumerable() is used
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.Rendering;
Model...
namespace MyProject.Models
{
public class MyModel
{
[Required]
[Display(Name = "State")]
public string StatePick { get; set; }
public string state { get; set; }
[StringLength(35, ErrorMessage = "State cannot be longer than 35 characters.")]
public SelectList StateList { get; set; }
}
}
Controller...
namespace MyProject.Controllers
{
/// <summary>
/// create SelectListItem from strings
/// </summary>
/// <param name="isValue">defaultValue is SelectListItem.Value is true, SelectListItem.Text if false</param>
/// <returns></returns>
private SelectListItem newItem(string value, string text, string defaultValue = "", bool isValue = false)
{
SelectListItem ss = new SelectListItem();
ss.Text = text;
ss.Value = value;
// select default by Value or Text
if (isValue && ss.Value == defaultValue || !isValue && ss.Text == defaultValue)
{
ss.Selected = true;
}
return ss;
}
/// <summary>
/// this pulls the state name from _context and sets it as the default for the selectList
/// </summary>
/// <param name="myState">sets default value for list of states</param>
/// <returns></returns>
private SelectList getStateList(string myState = "")
{
List<SelectListItem> states = new List<SelectListItem>();
SelectListItem chosen = new SelectListItem();
// set default selected state to OHIO
string defaultValue = "OH";
if (!string.IsNullOrEmpty(myState))
{
defaultValue = myState;
}
try
{
states.Add(newItem("AL", "Alabama", defaultValue, true));
states.Add(newItem("AK", "Alaska", defaultValue, true));
states.Add(newItem("AZ", "Arizona", defaultValue, true));
states.Add(newItem("AR", "Arkansas", defaultValue, true));
states.Add(newItem("CA", "California", defaultValue, true));
states.Add(newItem("CO", "Colorado", defaultValue, true));
states.Add(newItem("CT", "Connecticut", defaultValue, true));
states.Add(newItem("DE", "Delaware", defaultValue, true));
states.Add(newItem("DC", "District of Columbia", defaultValue, true));
states.Add(newItem("FL", "Florida", defaultValue, true));
states.Add(newItem("GA", "Georgia", defaultValue, true));
states.Add(newItem("HI", "Hawaii", defaultValue, true));
states.Add(newItem("ID", "Idaho", defaultValue, true));
states.Add(newItem("IL", "Illinois", defaultValue, true));
states.Add(newItem("IN", "Indiana", defaultValue, true));
states.Add(newItem("IA", "Iowa", defaultValue, true));
states.Add(newItem("KS", "Kansas", defaultValue, true));
states.Add(newItem("KY", "Kentucky", defaultValue, true));
states.Add(newItem("LA", "Louisiana", defaultValue, true));
states.Add(newItem("ME", "Maine", defaultValue, true));
states.Add(newItem("MD", "Maryland", defaultValue, true));
states.Add(newItem("MA", "Massachusetts", defaultValue, true));
states.Add(newItem("MI", "Michigan", defaultValue, true));
states.Add(newItem("MN", "Minnesota", defaultValue, true));
states.Add(newItem("MS", "Mississippi", defaultValue, true));
states.Add(newItem("MO", "Missouri", defaultValue, true));
states.Add(newItem("MT", "Montana", defaultValue, true));
states.Add(newItem("NE", "Nebraska", defaultValue, true));
states.Add(newItem("NV", "Nevada", defaultValue, true));
states.Add(newItem("NH", "New Hampshire", defaultValue, true));
states.Add(newItem("NJ", "New Jersey", defaultValue, true));
states.Add(newItem("NM", "New Mexico", defaultValue, true));
states.Add(newItem("NY", "New York", defaultValue, true));
states.Add(newItem("NC", "North Carolina", defaultValue, true));
states.Add(newItem("ND", "North Dakota", defaultValue, true));
states.Add(newItem("OH", "Ohio", defaultValue, true));
states.Add(newItem("OK", "Oklahoma", defaultValue, true));
states.Add(newItem("OR", "Oregon", defaultValue, true));
states.Add(newItem("PA", "Pennsylvania", defaultValue, true));
states.Add(newItem("RI", "Rhode Island", defaultValue, true));
states.Add(newItem("SC", "South Carolina", defaultValue, true));
states.Add(newItem("SD", "South Dakota", defaultValue, true));
states.Add(newItem("TN", "Tennessee", defaultValue, true));
states.Add(newItem("TX", "Texas", defaultValue, true));
states.Add(newItem("UT", "Utah", defaultValue, true));
states.Add(newItem("VT", "Vermont", defaultValue, true));
states.Add(newItem("VA", "Virginia", defaultValue, true));
states.Add(newItem("WA", "Washington", defaultValue, true));
states.Add(newItem("WV", "West Virginia", defaultValue, true));
states.Add(newItem("WI", "Wisconsin", defaultValue, true));
states.Add(newItem("WY", "Wyoming", defaultValue, true));
foreach (SelectListItem state in states)
{
if (state.Selected)
{
chosen = state;
break;
}
}
}
catch (Exception err)
{
string ss = "ERR! " + err.Source + " " + err.GetType().ToString() + "\r\n" + err.Message.Replace("\r\n", " ");
ss = this.sendError("Online getStateList Request", ss, _errPassword);
// return error
}
// .AsEnumerable() is not required in the pass.. it is an extension of Linq
SelectList myList = new SelectList(states.AsEnumerable(), "Value", "Text", chosen);
object val = myList.SelectedValue;
return myList;
}
public ActionResult pickState(MyModel pData)
{
if (pData.StateList == null)
{
if (String.IsNullOrEmpty(pData.StatePick)) // state abbrev, value collected onchange
{
pData.StateList = getStateList();
}
else
{
pData.StateList = getStateList(pData.StatePick);
}
// assign values to state list items
try
{
SelectListItem si = (SelectListItem)pData.StateList.SelectedValue;
pData.state = si.Value;
pData.StatePick = si.Value;
}
catch { }
}
return View(pData);
}
}
pickState.cshtml...
@model MyProject.Models.MyModel
@{
ViewBag.Title = "United States of America";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>@ViewBag.Title - Where are you...</h2>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<div class="editor-label">
@Html.DisplayNameFor(model => model.state)
</div>
<div class="display-field">
@Html.DropDownListFor(m => m.StatePick, Model.StateList, new { OnChange = "state.value = this.value;" })
@Html.EditorFor(model => model.state)
@Html.ValidationMessageFor(model => model.StateList)
</div>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
I am also very much new to Dynamic Programming (a powerful algorithm for particular type of problems)
In most simple words, just think dynamic programming as a recursive approach with using the previous knowledge
Previous knowledge is what matters here the most, Keep track of the solution of the sub-problems you already have.
Consider this, most basic example for dp from Wikipedia
Finding the fibonacci sequence
function fib(n) // naive implementation
if n <=1 return n
return fib(n - 1) + fib(n - 2)
Lets break down the function call with say n = 5
fib(5)
fib(4) + fib(3)
(fib(3) + fib(2)) + (fib(2) + fib(1))
((fib(2) + fib(1)) + (fib(1) + fib(0))) + ((fib(1) + fib(0)) + fib(1))
(((fib(1) + fib(0)) + fib(1)) + (fib(1) + fib(0))) + ((fib(1) + fib(0)) + fib(1))
In particular, fib(2) was calculated three times from scratch. In larger examples, many more values of fib, or sub-problems, are recalculated, leading to an exponential time algorithm.
Now, lets try it by storing the value we already found out in a data-structure say a Map
var m := map(0 ? 0, 1 ? 1)
function fib(n)
if key n is not in map m
m[n] := fib(n - 1) + fib(n - 2)
return m[n]
Here we are saving the solution of sub-problems in the map, if we don't have it already. This technique of saving values which we already had calculated is termed as Memoization.
At last, For a problem, first try to find the states (possible sub-problems and try to think of the better recursion approach so that you can use the solution of previous sub-problem into further ones).
SELECT Id 'PatientId',
ISNULL(CONVERT(varchar(50),ParentId),'') 'ParentId'
FROM Patients
ISNULL
always tries to return a result that has the same data type as the type of its first argument. So, if you want the result to be a string (varchar
), you'd best make sure that's the type of the first argument.
COALESCE
is usually a better function to use than ISNULL
, since it considers all argument data types and applies appropriate precedence rules to determine the final resulting data type. Unfortunately, in this case, uniqueidentifier
has higher precedence than varchar
, so that doesn't help.
(It's also generally preferred because it extends to more than two arguments)
declare function dbo.minutes2hours (
@minutes int
)
RETURNS varchar(10)
as
begin
return format(dateadd(minute,@minutes,'00:00:00'), N'HH\:mm','FR-fr')
end
Android Reverse Engineering is possible . Follow these steps to get .java file from apk file.
Step1 . Using dex2jar
dex2jar sampleApp.apk
Step2 . Decompiling .jar using JD-GUI
I know this question is supposedly solved, but I wasn't totally happy with the way it was implemented. I found another source over here on the MSDN blogs that has an overridden XmlTextWriter
class that strips out the namespaces. I tweaked it a bit to get some other things I wanted in such as pretty formatting and preserving the root element. Here is what I have in my project at the moment.
http://blogs.msdn.com/b/kaevans/archive/2004/08/02/206432.aspx
/// <summary>
/// Modified XML writer that writes (almost) no namespaces out with pretty formatting
/// </summary>
/// <seealso cref="http://blogs.msdn.com/b/kaevans/archive/2004/08/02/206432.aspx"/>
public class XmlNoNamespaceWriter : XmlTextWriter
{
private bool _SkipAttribute = false;
private int _EncounteredNamespaceCount = 0;
public XmlNoNamespaceWriter(TextWriter writer)
: base(writer)
{
this.Formatting = System.Xml.Formatting.Indented;
}
public override void WriteStartElement(string prefix, string localName, string ns)
{
base.WriteStartElement(null, localName, null);
}
public override void WriteStartAttribute(string prefix, string localName, string ns)
{
//If the prefix or localname are "xmlns", don't write it.
//HOWEVER... if the 1st element (root?) has a namespace we will write it.
if ((prefix.CompareTo("xmlns") == 0
|| localName.CompareTo("xmlns") == 0)
&& _EncounteredNamespaceCount++ > 0)
{
_SkipAttribute = true;
}
else
{
base.WriteStartAttribute(null, localName, null);
}
}
public override void WriteString(string text)
{
//If we are writing an attribute, the text for the xmlns
//or xmlns:prefix declaration would occur here. Skip
//it if this is the case.
if (!_SkipAttribute)
{
base.WriteString(text);
}
}
public override void WriteEndAttribute()
{
//If we skipped the WriteStartAttribute call, we have to
//skip the WriteEndAttribute call as well or else the XmlWriter
//will have an invalid state.
if (!_SkipAttribute)
{
base.WriteEndAttribute();
}
//reset the boolean for the next attribute.
_SkipAttribute = false;
}
public override void WriteQualifiedName(string localName, string ns)
{
//Always write the qualified name using only the
//localname.
base.WriteQualifiedName(localName, null);
}
}
//Save the updated document using our modified (almost) no-namespace XML writer
using(StreamWriter sw = new StreamWriter(this.XmlDocumentPath))
using(XmlNoNamespaceWriter xw = new XmlNoNamespaceWriter(sw))
{
//This variable is of type `XmlDocument`
this.XmlDocumentRoot.Save(xw);
}
Once you have your Context and know the name of the database, use:
context.deleteDatabase(DATABASE_NAME);
When this line gets run, the database should be deleted.
The script isn't even necessary, split(1) supports the wanted feature out of the box:
split -l 75 auth.log auth.log.
The above command splits the file in chunks of 75 lines a piece, and outputs file on the form: auth.log.aa, auth.log.ab, ...
wc -l
on the original file and output gives:
321 auth.log
75 auth.log.aa
75 auth.log.ab
75 auth.log.ac
75 auth.log.ad
21 auth.log.ae
642 total
<?php
$a=array("1"=>"302","2"=>"302","3"=>"276","4"=>"301","5"=>"302");
print_r(array_values(array_unique($a)));
?>//`output -> Array ( [0] => 302 [1] => 276 [2] => 301 )`
spark.default.parallelism is the default number of partition set by spark which is by default 200. and if you want to increase the number of partition than you can apply the property spark.sql.shuffle.partitions to set number of partition in the spark configuration or while running spark SQL.
Normally this spark.sql.shuffle.partitions it is being used when we have a memory congestion and we see below error: spark error:java.lang.IllegalArgumentException: Size exceeds Integer.MAX_VALUE
so set your can allocate a partition as 256 MB per partition and that you can use to set for your processes.
also If number of partitions is near to 2000 then increase it to more than 2000. As spark applies different logic for partition < 2000 and > 2000 which will increase your code performance by decreasing the memory footprint as data default is highly compressed if >2000.
Regex : ^[\\w!#$%&’*+/=?
{|}~^-]+(?:\.[\w!#$%&’*+/=?{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$
public static boolean isValidEmailId(String email) {
String emailPattern = "^[\\w!#$%&’*+/=?`{|}~^-]+(?:\\.[\\w!#$%&’*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$";
Pattern p = Pattern.compile(emailPattern);
Matcher m = p.matcher(email);
return m.matches();
}
You can't call a non-static method from a static method, because the definition of "non-static" means something that is associated with an instance of the class. You don't have an instance of the class in a static context.
If you trust the host, either add the valid certificate, specify --no-check-certificate
or add:
check_certificate = off
into your ~/.wgetrc
.
In some rare cases, your system time could be out-of-sync therefore invalidating the certificates.
spool "D:\test\test.txt"
select
a.ename
from
employee a
inner join department b
on
(
a.dept_id = b.dept_id
)
;
spool off
This query will spool the sql result in D:\test\test.txt
Shortest way: Click lock icon in address bar. Then click Site settings, then click Reset permissions
The best use case of 'dynamic' type variables for me was when, recently, I was writing a data access layer in ADO.NET (using SQLDataReader) and the code was invoking the already written legacy stored procedures. There are hundreds of those legacy stored procedures containing bulk of the business logic. My data access layer needed to return some sort of structured data to the business logic layer, C# based, to do some manipulations (although there are almost none). Every stored procedures returns different set of data (table columns). So instead of creating dozens of classes or structs to hold the returned data and pass it to the BLL, I wrote the below code which looks quite elegant and neat.
public static dynamic GetSomeData(ParameterDTO dto)
{
dynamic result = null;
string SPName = "a_legacy_stored_procedure";
using (SqlConnection connection = new SqlConnection(DataConnection.ConnectionString))
{
SqlCommand command = new SqlCommand(SPName, connection);
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("@empid", dto.EmpID));
command.Parameters.Add(new SqlParameter("@deptid", dto.DeptID));
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
dynamic row = new ExpandoObject();
row.EmpName = reader["EmpFullName"].ToString();
row.DeptName = reader["DeptName"].ToString();
row.AnotherColumn = reader["AnotherColumn"].ToString();
result = row;
}
}
}
return result;
}
I use one Factory
module that contains one (or more) constructor per class which calls the Init
member of each class.
For example a Point
class:
Class Point
Private X, Y
Sub Init(X, Y)
Me.X = X
Me.Y = Y
End Sub
A Line
class
Class Line
Private P1, P2
Sub Init(Optional P1, Optional P2, Optional X1, Optional X2, Optional Y1, Optional Y2)
If P1 Is Nothing Then
Set Me.P1 = NewPoint(X1, Y1)
Set Me.P2 = NewPoint(X2, Y2)
Else
Set Me.P1 = P1
Set Me.P2 = P2
End If
End Sub
And a Factory
module:
Module Factory
Function NewPoint(X, Y)
Set NewPoint = New Point
NewPoint.Init X, Y
End Function
Function NewLine(Optional P1, Optional P2, Optional X1, Optional X2, Optional Y1, Optional Y2)
Set NewLine = New Line
NewLine.Init P1, P2, X1, Y1, X2, Y2
End Function
Function NewLinePt(P1, P2)
Set NewLinePt = New Line
NewLinePt.Init P1:=P1, P2:=P2
End Function
Function NewLineXY(X1, Y1, X2, Y2)
Set NewLineXY = New Line
NewLineXY.Init X1:=X1, Y1:=Y1, X2:=X2, Y2:=Y2
End Function
One nice aspect of this approach is that makes it easy to use the factory functions inside expressions. For example it is possible to do something like:
D = Distance(NewPoint(10, 10), NewPoint(20, 20)
or:
D = NewPoint(10, 10).Distance(NewPoint(20, 20))
It's clean: the factory does very little and it does it consistently across all objects, just the creation and one Init
call on each creator.
And it's fairly object oriented: the Init
functions are defined inside the objects.
EDIT
I forgot to add that this allows me to create static methods. For example I can do something like (after making the parameters optional):
NewLine.DeleteAllLinesShorterThan 10
Unfortunately a new instance of the object is created every time, so any static variable will be lost after the execution. The collection of lines and any other static variable used in this pseudo-static method must be defined in a module.
bobince's answer will let you know in which cases "height: XX%;" will or won't work.
If you want to create an element with a set ratio (height: % of it's own width), the best way to do that is by effectively setting the height using padding-bottom
. Example for square:
<div class="square-container">
<div class="square-content">
<!-- put your content in here -->
</div>
</div>
.square-container { /* any display: block; element */
position: relative;
height: 0;
padding-bottom: 100%; /* of parent width */
}
.square-content {
position: absolute;
left: 0;
top: 0;
height: 100%;
width: 100%;
}
The square container will just be made of padding, and the content will expand to fill the container. Long article from 2009 on this subject: http://alistapart.com/article/creating-intrinsic-ratios-for-video
I recommend using https://www.npmjs.com/package/express-es6-template-engine - extremely lightwave and blazingly fast template engine. The name is a bit misleading as it can work without expressjs too.
The basics required to integrate express-es6-template-engine
in your app are pretty simple and quite straight forward to implement:
const express = require('express'),_x000D_
es6Renderer = require('express-es6-template-engine'),_x000D_
app = express();_x000D_
_x000D_
app.engine('html', es6Renderer);_x000D_
app.set('views', 'views');_x000D_
app.set('view engine', 'html');_x000D_
_x000D_
app.get('/', function(req, res) {_x000D_
res.render('index', {locals: {title: 'Welcome!'}});_x000D_
});_x000D_
_x000D_
app.listen(3000);
_x000D_
index.html
file locate inside your 'views' directory:
<!DOCTYPE html>
<html>
<body>
<h1>${title}</h1>
</body>
</html>
For Kotlin developers, remember the Java transient
keyword becomes the built-in Kotlin @Transient
annotation. Therefore, make sure you have the JPA import if you're using JPA @Transient
in your entity:
import javax.persistence.Transient
Eclipse > Help > Eclipse Marketplace...
Search for m2e
Install Maven Integration for Eclipse (Juno and newer)
. [It works for Indigo also]
In the below class setter and getter is applied to variable sideLength
class Triangle: {
var sideLength: Double = 0.0
init(sideLength: Double, name: String) { //initializer method
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 3
}
var perimeter: Double {
get { // getter
return 3.0 * sideLength
}
set(newValue) { //setter
sideLength = newValue / 4.0
}
}
var triangle = Triangle(sideLength: 3.9, name: "a triangle")
print(triangle.perimeter) // invoking getter
triangle.perimeter = 9.9 // invoking setter
The following example shows the general best practice to implement IDisposable
interface. Reference
Keep in mind that you need a destructor(finalizer) only if you have unmanaged resources in your class. And if you add a destructor you should suppress Finalization in the Dispose, otherwise it will cause your objects resides in memory for two garbage cycles (Note: Read how Finalization works). Below example elaborate all above.
public class DisposeExample
{
// A base class that implements IDisposable.
// By implementing IDisposable, you are announcing that
// instances of this type allocate scarce resources.
public class MyResource: IDisposable
{
// Pointer to an external unmanaged resource.
private IntPtr handle;
// Other managed resource this class uses.
private Component component = new Component();
// Track whether Dispose has been called.
private bool disposed = false;
// The class constructor.
public MyResource(IntPtr handle)
{
this.handle = handle;
}
// Implement IDisposable.
// Do not make this method virtual.
// A derived class should not be able to override this method.
public void Dispose()
{
Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SupressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
// Dispose(bool disposing) executes in two distinct scenarios.
// If disposing equals true, the method has been called directly
// or indirectly by a user's code. Managed and unmanaged resources
// can be disposed.
// If disposing equals false, the method has been called by the
// runtime from inside the finalizer and you should not reference
// other objects. Only unmanaged resources can be disposed.
protected virtual void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if(!this.disposed)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if(disposing)
{
// Dispose managed resources.
component.Dispose();
}
// Call the appropriate methods to clean up
// unmanaged resources here.
// If disposing is false,
// only the following code is executed.
CloseHandle(handle);
handle = IntPtr.Zero;
// Note disposing has been done.
disposed = true;
}
}
// Use interop to call the method necessary
// to clean up the unmanaged resource.
[System.Runtime.InteropServices.DllImport("Kernel32")]
private extern static Boolean CloseHandle(IntPtr handle);
// Use C# destructor syntax for finalization code.
// This destructor will run only if the Dispose method
// does not get called.
// It gives your base class the opportunity to finalize.
// Do not provide destructors in types derived from this class.
~MyResource()
{
// Do not re-create Dispose clean-up code here.
// Calling Dispose(false) is optimal in terms of
// readability and maintainability.
Dispose(false);
}
}
public static void Main()
{
// Insert code here to create
// and use the MyResource object.
}
}
You can get a list of files last modified later than x days ago with:
find . -mtime -x
Then you just have to tar and zip files in the resulting list, e.g.:
tar czvf mytarfile.tgz `find . -mtime -30`
for all files modified during last month.
public class Sol {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
}
}
A CASE
expression returns a value from the THEN
portion of the clause. You could use it thusly:
SELECT *
FROM sys.indexes i
JOIN sys.partitions p
ON i.index_id = p.index_id
JOIN sys.allocation_units a
ON CASE
WHEN a.type IN (1, 3) AND a.container_id = p.hobt_id THEN 1
WHEN a.type IN (2) AND a.container_id = p.partition_id THEN 1
ELSE 0
END = 1
Note that you need to do something with the returned value, e.g. compare it to 1. Your statement attempted to return the value of an assignment or test for equality, neither of which make sense in the context of a CASE
/THEN
clause. (If BOOLEAN
was a datatype then the test for equality would make sense.)
BeRecursive's answer is the one I used, so that we could standardize on Json.Net (we have MVC5 and WebApi 5 -- WebApi 5 already uses Json.Net), but I found an issue. When you have parameters in your route to which you're POSTing, MVC tries to call the model binder for the URI values, and this code will attempt to bind the posted JSON to those values.
Example:
[HttpPost]
[Route("Customer/{customerId:int}/Vehicle/{vehicleId:int}/Policy/Create"]
public async Task<JsonNetResult> Create(int customerId, int vehicleId, PolicyRequest policyRequest)
The BindModel
function gets called three times, bombing on the first, as it tries to bind the JSON to customerId
with the error: Error reading integer. Unexpected token: StartObject. Path '', line 1, position 1.
I added this block of code to the top of BindModel
:
if (bindingContext.ValueProvider.GetValue(bindingContext.ModelName) != null) {
return base.BindModel(controllerContext, bindingContext);
}
The ValueProvider, fortunately, has route values figured out by the time it gets to this method.
If in addition you want to pipe the output to a separate file, you can do:
On a Sun JVM:
-Xloggc:C:\whereever\jvm.log -verbose:gc -XX:+PrintGCDateStamps
ON an IBM JVM:
-Xverbosegclog:C:\whereever\jvm.log
Underscore vs Lo-Dash by Ben McCormick is the latest article comparing the two:
- Lodash's API is a superset of Underscore.js's.
- Under the hood, Lodash has been completely rewritten.
- Lodash is definitely not slower than Underscore.js.
- What has Lodash added?
- Usability improvements
- Extra functionality
- Performance gains
- Shorthand syntaxes for chaining
- Custom builds to only use what you need
- Semantic versioning and 100% code coverage
There's a distinction to me that scp
is always encrypted with ssh (secure shell), while rsync
isn't necessarily encrypted. More specifically, rsync
doesn't perform any encryption by itself; it's still capable of using other mechanisms (ssh for example) to perform encryption.
In addition to security, encryption also has a major impact on your transfer speed, as well as the CPU overhead. (My experience is that rsync
can be significantly faster than scp
.)
Check out this post for when rsync
has encryption on.
The following code can help you to understand some real world use of predicates (Combined with named iterators).
namespace Predicate
{
class Person
{
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
foreach (Person person in OlderThan(18))
{
Console.WriteLine(person.Age);
}
}
static IEnumerable<Person> OlderThan(int age)
{
Predicate<Person> isOld = x => x.Age > age;
Person[] persons = { new Person { Age = 10 }, new Person { Age = 20 }, new Person { Age = 19 } };
foreach (Person person in persons)
if (isOld(person)) yield return person;
}
}
}
A one-line version of this excellent answer to plot the line of best fit is:
plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))
Using np.unique(x)
instead of x
handles the case where x
isn't sorted or has duplicate values.
You can use following code for enabling and disabling edit text cursor by programmatically.
To Enable cursor
editText.requestFocus();
editText.setCursorVisible(true);
To Disable cursor
editText.setCursorVisible(false);
Using XML enable disable cursor
android:cursorVisible="false/true"
android:focusable="false/true"
To make edit_text Selectable to (copy/cut/paste/select/select all)
editText.setTextIsSelectable(true);
To focus on touch mode write following lines in XML
android:focusableInTouchMode="true"
android:clickable="true"
android:focusable="true"
programmatically
editText.requestFocusFromTouch();
To clear focus on touch mode
editText.clearFocus()
There is no more plugin in netbeans 12. In case someone comes to this page. Tools->Options->Appearance->Look and feel->Flatlaf Dark
if (card1.getRarity() < card2.getRarity()) {
return 1;
However, if card2.getRarity()
is less than card1.getRarity()
you might not return -1.
You similarly miss other cases. I would do this, you can change around depending on your intent:
public int compareTo(Object o) {
if(this == o){
return 0;
}
CollectionItem item = (CollectionItem) o;
Card card1 = CardCache.getInstance().getCard(cardId);
Card card2 = CardCache.getInstance().getCard(item.getCardId());
int comp=card1.getSet() - card2.getSet();
if (comp!=0){
return comp;
}
comp=card1.getRarity() - card2.getRarity();
if (comp!=0){
return comp;
}
comp=card1.getSet() - card2.getSet();
if (comp!=0){
return comp;
}
comp=card1.getId() - card2.getId();
if (comp!=0){
return comp;
}
comp=card1.getCardType() - card2.getCardType();
return comp;
}
}
<form target="_parent" ... />
Using Kevin Vella's idea, I tried using the above on the form element made by PayPal's button generator. Worked for me so that Paypal does not open in a new browser window/tab.
Update
Here's an example:
Generating a button as of today (01-19-2021), PayPal automatically includes target="_top"
on the form
element, but if that doesn't work for your context, try a different target
value. I suggest _parent
-- at least that worked when I was using this PayPal button.
See Form Target Values for more info.
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_parent">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="[email protected]">
<input type="hidden" name="lc" value="US">
<input type="hidden" name="button_subtype" value="services">
<input type="hidden" name="no_note" value="0">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynowCC_LG.gif:NonHostedGuest">
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>
this works for me
$(window).bind('beforeunload', function() {
return 'Do you really want to leave?' ;
});
Strictly with sed:
grep ... | sed -e 's/^\(.\{N\}\).*$/\1/'
change your code to this
$start_date = new DateTime( "@" . $dbResult->db_timestamp );
and it will work fine
Use the following code in your CSS
html { _x000D_
background: url(images/bg.jpg) no-repeat center center fixed; _x000D_
-webkit-background-size: cover;_x000D_
-moz-background-size: cover;_x000D_
-o-background-size: cover;_x000D_
background-size: cover;_x000D_
}
_x000D_
x.times do |i|
something(i+1)
end
First, it depends on your version of R. If you've passed 2.11, you can use aggreggate with multiple results functions(summary, by instance, or your own function). If not, you can use the answer made by Justin.
echo date( "Y-m-d H:i:s", strtotime("2016-10-10 15:00:00")+(60*30) );//2016-10-10 15:30:00
or
echo date( "H:i:s", strtotime("15:00:00")+(60*30) ); // 15:30:00
or
echo date( "H:i:s", strtotime(date("H:i:s"))+(60*30) ); // 15:30:00
In software design high cohesion means that class should do one thing and one thing very well. High cohesion is closely related to Single responsibility principle.
Low coupling suggest that class should have least possible dependencies. Also, dependencies that must exist should be weak dependencies - prefer dependency on interface rather than dependency on concrete class, or prefer composition over inheritance .
High Cohesion and low coupling give us better designed code that is easier to maintain.
You can use this command
npm config delete proxy
It happens because formidable
is prone to severity vulnerability. So, you need to override that by running the above command.
In general you can say session.gc_maxlifetime specifies the maximum lifetime since the last change of your session data (not the last time session_start
was called!). But PHP’s session handling is a little bit more complicated.
Because the session data is removed by a garbage collector that is only called by session_start
with a probability of session.gc_probability devided by session.gc_divisor. The default values are 1 and 100, so the garbage collector is only started in only 1% of all session_start
calls. That means even if the the session is already timed out in theory (the session data had been changed more than session.gc_maxlifetime seconds ago), the session data can be used longer than that.
Because of that fact I recommend you to implement your own session timeout mechanism. See my answer to How do I expire a PHP session after 30 minutes? for more details.
i was having the same problem....the actual issue was missing .jar file which took palce coz of changing my workspace. i just deleted the appcompat folder(which has the".jar" file) from my new workspace and copied it from my old workspace. this solved my problem.
In my case (Oracle), it's WHERE REGEXP_LIKE(column, 'regex.*')
. See here:
SQL Function
Description
REGEXP_LIKE
This function searches a character column for a pattern. Use this function in the WHERE clause of a query to return rows matching the regular expression you specify.
...
REGEXP_REPLACE
This function searches for a pattern in a character column and replaces each occurrence of that pattern with the pattern you specify.
...
REGEXP_INSTR
This function searches a string for a given occurrence of a regular expression pattern. You specify which occurrence you want to find and the start position to search from. This function returns an integer indicating the position in the string where the match is found.
...
REGEXP_SUBSTR
This function returns the actual substring matching the regular expression pattern you specify.
(Of course, REGEXP_LIKE only matches queries containing the search string, so if you want a complete match, you'll have to use '^$'
for a beginning (^
) and end ($
) match, e.g.: '^regex.*$'
.)
Your submission will cancel the redirect or vice versa.
I do not see the reason for the redirect in the first place since why do you have an order form that does nothing.
That said, here is how to do it. Firstly NEVER put code on the submit button but do it in the onsubmit, secondly return false to stop the submission
NOTE This code will IGNORE the action and ONLY execute the script due to the return false/preventDefault
function redirect() {
window.location.replace("login.php");
return false;
}
using
<form name="form1" id="form1" method="post" onsubmit="return redirect()">
<input type="submit" class="button4" name="order" id="order" value="Place Order" >
</form>
Or unobtrusively:
window.onload=function() {
document.getElementById("form1").onsubmit=function() {
window.location.replace("login.php");
return false;
}
}
using
<form id="form1" method="post">
<input type="submit" class="button4" value="Place Order" >
</form>
jQuery:
$("#form1").on("submit",function(e) {
e.preventDefault(); // cancel submission
window.location.replace("login.php");
});
Example:
$("#form1").on("submit", function(e) {_x000D_
e.preventDefault(); // cancel submission_x000D_
alert("this could redirect to login.php"); _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<form id="form1" method="post" action="javascript:alert('Action!!!')">_x000D_
<input type="submit" class="button4" value="Place Order">_x000D_
</form>
_x000D_
I saw this problem because I had obtained a new Mac, and was still using my old Computer's certificate. I had created a new certificate for the new Mac, but had both certificates in my keychain.
In the Organizer, the profile warned that "XCode could not find a valid private-key/certificate pair for this profile in your keychain" even though the old certificate existed in my Keychain.
The solution was to delete the old certificate from my Keychain and delete/revoke of all the profiles which used this old certificate. Then create a new profile with the new certificate and use this.
Hope this helps!
One way to solve the above problem will be to override the hashcode()
.
Also flush the hibernate session before and after save.
getHibernateTemplate().flush();
Explicitly setting the detached object to null
also helps.
I had the same problem when I wrote two upstreams in NGINX conf
upstream php_upstream {
server unix:/var/run/php/my.site.sock;
server 127.0.0.1:9000;
}
...
fastcgi_pass php_upstream;
but in /etc/php/7.3/fpm/pool.d/www.conf
I listened the socket only
listen = /var/run/php/my.site.sock
So I need just socket, no any 127.0.0.1:9000
, and I just removed IP+port upstream
upstream php_upstream {
server unix:/var/run/php/my.site.sock;
}
This could be rewritten without an upstream
fastcgi_pass unix:/var/run/php/my.site.sock;
You must declare the prototype it before using it:
class User;
class MyMessageBox
{
public:
void sendMessage(Message *msg, User *recvr);
Message receiveMessage();
vector<Message> *dataMessageList;
};
class User
{
public:
MyMessageBox dataMsgBox;
};
edit: Swapped the types
If you need to download a folder via a Linux command try this out:
$ scp [email protected]:foobar.txt -r /some/local/directory
Sources:
Related Post: How to download a file from server using SSH?
8)
If adb devices
does not list the device though you have plugged it in to the system, you need to ensure that USB debugging
option is checked in the Developer Options
tab under Settings
. Under Android 4.2.2 and above (from what I have observed), the Developer Options
are hidden unless explicitly revealed. To make Developer Options
active, tap 7 times on the Settings > About device > Build number
. Once done, go back to Settings > Developer Options
and activate USB Debugging
.
Using adb version 1.0.31
, I was able to make the device visible.
After doing it both ways for a few projects my stance is that composer.lock
should not be committed as part of the project.
composer.lock
is build metadata which is not part of the project. The state of dependencies should be controlled through how you're versioning them (either manually or as part of your automated build process) and not arbitrarily by the last developer to update them and commit the lock file.
If you are concerned about your dependencies changing between composer updates then you have a lack of confidence in your versioning scheme. Versions (1.0, 1.1, 1.2, etc) should be immutable and you should avoid "dev-" and "X.*" wildcards outside of initial feature development.
Committing the lock file is a regression for your dependency management system as the dependency version has now gone back to being implicitly defined.
Also, your project should never have to be rebuilt or have its dependencies reacquired in each environment, especially prod. Your deliverable (tar, zip, phar, a directory, etc) should be immutable and promoted through environments without changing.
The decimal operator might be more in line with what you are looking for:
>>> from decimal import Decimal
>>> x = "234243.434"
>>> print Decimal(x)
234243.434
IMHO, there is difference between checking if a module is:
1) installed, or 2) imported:
To check if installed:
Option 1: Using Get-Module
with -ListAvailable
parameter:
If(Get-Module -ListAvailable -Name "<ModuleName>"){'Module is installed'}
Else{'Module is NOT installed'}
Option 2: Using $error
object:
$error.clear()
Import-Module "<ModuleName>" -ErrorAction SilentlyContinue
If($error){Write-Host 'Module is NOT installed'}
Else{Write-Host 'Module is installed'}
To check if imported:
Using Get-Module
with -Name
parameter (which you can omit as it is default anyway):
if ((Get-Module -Name "<ModuleName>")) {
Write-Host "Module is already imported (i.e. its cmdlets are available to be used.)"
}
else {
Write-Warning "Module is NOT imported (must be installed before importing)."
}
in my case I have to update the records which are more than 1000, for this instead of hitting the update query each time I preferred this,
UPDATE mst_users
SET base_id = CASE user_id
WHEN 78 THEN 999
WHEN 77 THEN 88
ELSE base_id END WHERE user_id IN(78, 77)
78,77 are the user Ids and for those user id I need to update the base_id 999 and 88 respectively.This works for me.
You have to manually copy each key/value pair to a new map
. This is a loop that people have to reprogram any time they want a deep copy of a map
.
You can automatically generate the function for this by installing mapper
from the maps
package using
go get -u github.com/drgrib/maps/cmd/mapper
and running
mapper -types string:aStruct
which will generate the file map_float_astruct.go
containing not only a (deep) Copy
for your map but also other "missing" map
functions ContainsKey
, ContainsValue
, GetKeys
, and GetValues
:
func ContainsKeyStringAStruct(m map[string]aStruct, k string) bool {
_, ok := m[k]
return ok
}
func ContainsValueStringAStruct(m map[string]aStruct, v aStruct) bool {
for _, mValue := range m {
if mValue == v {
return true
}
}
return false
}
func GetKeysStringAStruct(m map[string]aStruct) []string {
keys := []string{}
for k, _ := range m {
keys = append(keys, k)
}
return keys
}
func GetValuesStringAStruct(m map[string]aStruct) []aStruct {
values := []aStruct{}
for _, v := range m {
values = append(values, v)
}
return values
}
func CopyStringAStruct(m map[string]aStruct) map[string]aStruct {
copyMap := map[string]aStruct{}
for k, v := range m {
copyMap[k] = v
}
return copyMap
}
Full disclosure: I am the creator of this tool. I created it and its containing package because I found myself constantly rewriting these algorithms for the Go map
for different type combinations.
1.> Change File format to .CSV (semicolon delimited)
To achieve the desired result we need to temporary change the delimiter
setting in the Excel
Options:
Move to File -> Options -> Advanced -> Editing Section
Uncheck the “Use system separators” setting and put a comma in the “Decimal Separator” field.
Now save the file in the .CSV
format and it will be saved in the semicolon delimited format.
This is code I used in Windows. It works.
for item in COOKIES.split(';'):
name,value = item.split('=', 1)
name=name.replace(' ', '').replace('\r', '').replace('\n', '')
value = value.replace(' ', '').replace('\r', '').replace('\n', '')
cookie_dict={
'name':name,
'value':value,
"domain": "", # Google Chrome
"expires": "",
'path': '/',
'httpOnly': False,
'HostOnly': False,
'Secure': False
}
self.driver_.add_cookie(cookie_dict)
Does the second query return any results from the 17th, or just from the 18th?
The first query will only return results from the 17th, or midnight on the 18th.
Try this instead
select *
from LOGS
where check_in >= CONVERT(datetime,'2013-10-17')
and check_in< CONVERT(datetime,'2013-10-19')
It's called on Object Literal
I'm not sure what you want your structure to be, but according to what you have above, where you put the values in variables try this.
var formObject = {"formObject": [
{"firstName": firstName, "lastName": lastName},
{"phoneNumber": phone},
{"address": address},
]}
Although this seems to make more sense (Why do you have an array in the above literal?):
var formObject = {
firstName: firstName
...
}
Add this to an htaccess file (and see edit notes added below):
<IfModule mod_php5.c>
php_value post_max_size 200M
php_value upload_max_filesize 200M
php_value memory_limit 300M
php_value max_execution_time 259200
php_value max_input_time 259200
php_value session.gc_maxlifetime 1200
</IfModule>
Additional resources and information:
2021 EDIT:
As PHP and Apache evolve and grow, I think it is important for me to take a moment to mention a few things to consider and possible "gotchas" to consider:
<IfModule
is loaded.mod_php5.c
in the first line. If you are using PHP 7, you would replace that with mod_php7.c
.php.ini
config file(s). This method is usually only useful in the event your hosting provider does not give you access to change those files. In circumstances where you can edit the PHP configuration, it is recommended that you apply these settings there.You're getting errors because you're attempting to read post variables that haven't been set, they only get set on form submission. Wrap your php code at the bottom in an
if ($_SERVER['REQUEST_METHOD'] === 'POST') { ... }
Also, your code is ripe for SQL injection. At the very least use mysql_real_escape_string
on the post vars before using them in SQL queries. mysql_real_escape_string
is not good enough for a production site, but should score you extra points in class.
You need the following functions to do this in PHP:
strpos
Find the position of the first occurrence of a substring in a string
strrpos
Find the position of the last occurrence of a substring in a string
substr
Return part of a string
Here's the signature of the substr
function:
string substr ( string $string , int $start [, int $length ] )
The signature of the substring
function (Java) looks a bit different:
string substring( int beginIndex, int endIndex )
substring
(Java) expects the end-index as the last parameter, but substr
(PHP) expects a length.
It's not hard, to get the desired length by the end-index in PHP:
$sub = substr($str, $start, $end - $start);
Here is the working code
$start = strpos($message, '-') + 1;
if ($req_type === 'RMT') {
$pt_password = substr($message, $start);
}
else {
$end = strrpos($message, '-');
$pt_password = substr($message, $start, $end - $start);
}
import base64
coded_string = '''Q5YACgA...'''
base64.b64decode(coded_string)
worked for me. At the risk of pasting an offensively-long result, I got:
>>> base64.b64decode(coded_string)
2: 'C\x96\x00\n\x00\x00\x00\x00C\x96\x00\x1b\x00\x00\x00\x00C\x96\x00-\x00\x00\x00\x00C\x96\x00?\x00\x00\x00\x00C\x96\x07M\x00\x00\x00\x00C\x96\x07_\x00\x00\x00\x00C\x96\x07p\x00\x00\x00\x00C\x96\x07\x82\x00\x00\x00\x00C\x96\x07\x94\x00\x00\x00\x00C\x96\x07\xa6Cq\xf0\x7fC\x96\x07\xb8DJ\x81\xc7C\x96\x07\xcaD\xa5\x9dtC\x96\x07\xdcD\xb6\x97\x11C\x96\x07\xeeD\x8b\x8flC\x96\x07\xffD\x03\xd4\xaaC\x96\x08\x11B\x05&\xdcC\x96\x08#\x00\x00\x00\x00C\x96\x085C\x0c\xc9\xb7C\x96\x08GCy\xc0\xebC\x96\x08YC\x81\xa4xC\x96\x08kC\x0f@\x9bC\x96\x08}\x00\x00\x00\x00C\x96\x08\x8e\x00\x00\x00\x00C\x96\x08\xa0\x00\x00\x00\x00C\x96\x08\xb2\x00\x00\x00\x00C\x96\x86\xf9\x00\x00\x00\x00C\x96\x87\x0b\x00\x00\x00\x00C\x96\x87\x1d\x00\x00\x00\x00C\x96\x87/\x00\x00\x00\x00C\x96\x87AA\x0b\xe7PC\x96\x87SCI\xf5gC\x96\x87eC\xd4J\xeaC\x96\x87wD\r\x17EC\x96\x87\x89D\x00F6C\x96\x87\x9bC\x9cg\xdeC\x96\x87\xadB\xd56\x0cC\x96\x87\xbf\x00\x00\x00\x00C\x96\x87\xd1\x00\x00\x00\x00C\x96\x87\xe3\x00\x00\x00\x00C\x96\x87\xf5\x00\x00\x00\x00C\x9cY}\x00\x00\x00\x00C\x9cY\x90\x00\x00\x00\x00C\x9cY\xa4\x00\x00\x00\x00C\x9cY\xb7\x00\x00\x00\x00C\x9cY\xcbC\x1f\xbd\xa3C\x9cY\xdeCCz{C\x9cY\xf1CD\x02\xa7C\x9cZ\x05C+\x9d\x97C\x9cZ\x18C\x03R\xe3C\x9cZ,\x00\x00\x00\x00C\x9cZ?
[stuff omitted as it exceeded SO's body length limits]
\xbb\x00\x00\x00\x00D\xc5!7\x00\x00\x00\x00D\xc5!\xb2\x00\x00\x00\x00D\xc7\x14x\x00\x00\x00\x00D\xc7\x14\xf6\x00\x00\x00\x00D\xc7\x15t\x00\x00\x00\x00D\xc7\x15\xf2\x00\x00\x00\x00D\xc7\x16pC5\x9f\xf9D\xc7\x16\xeeC[\xb5\xf5D\xc7\x17lCG\x1b;D\xc7\x17\xeaB\xe3\x0b\xa6D\xc7\x18h\x00\x00\x00\x00D\xc7\x18\xe6\x00\x00\x00\x00D\xc7\x19d\x00\x00\x00\x00D\xc7\x19\xe2\x00\x00\x00\x00D\xc7\xfe\xb4\x00\x00\x00\x00D\xc7\xff3\x00\x00\x00\x00D\xc7\xff\xb2\x00\x00\x00\x00D\xc8\x001\x00\x00\x00\x00'
What problem are you having, specifically?
The answer depends upon the degree of confidence you place in the data and how your data is being used. For example, if you're using it for mailing or shipping, you'll want to be be confident that the data is correct. If you're just using it as another fraud-prevention mechanism then you could potentially allow a degree of error to creep into the data.
If you want any degree of real accuracy, you're need to go with a service that does real address verification and you're going to have to pay for it. As has been mentioned by Adam, address verification and validation at first seems simple and easy, but it's a black hole fraught with challenges and, unless you've some underlying data to work with, virtually impossible to do by yourself. Trust me, you're actually saving money by using a service. You're welcome to go down this road yourself to experience what I mean, but I can guarantee you'll see the light, so to speak, after even a few hours (or days) of spinning your wheels.
I should mention that I'm the founder of SmartyStreets. We do address validation and verification addresses and we offer this for the USA and international as well. I'm more than happy to personally answer any questions you have on the topic of address cleansing, standardization, and validation.
GUID is Microsoft's implementation of the UUID standard.
Per Wikipedia:
The term GUID usually refers to Microsoft's implementation of the Universally Unique Identifier (UUID) standard.
An updated quote from that same Wikipedia article:
RFC 4122 itself states that UUIDs "are also known as GUIDs". All this suggests that "GUID", while originally referring to a variant of UUID used by Microsoft, has become simply an alternative name for UUID…
Let's say I have code in the directory ~/local_dir/myNewApp
, and I want to put it under 'https://svn.host/existing_path/myNewApp' (while being able to ignore some binaries, vendor libraries, etc.).
svn mkdir https://svn.host/existing_path/myNewApp
cd ~/local_dir
svn co https://svn.host/existing_path/myNewApp
. If your folder has a different name locally than in the repository, you must specify it as an additional argument.svn st
will now show all your files as ?
, which means that they are not currently under revision controlsvn add
on files you want to add to the repository, and add others to svn:ignore
. You may find some useful options with svn help add
, for example --parents
or --depth empty
, when you want selectively add only some files/folders.svn ci
var result = from x in entity
join y in entity2 on new { x.field1, x.field2 } equals new { y.field1, y.field2 }
1.- Yes, but it pretty much refers to the whole memory used by your program.
2.- Yes see Java VM options
-Xms<size> set initial Java heap size
-Xmx<size> set maximum Java heap size
Ie
java -Xmx2g
assign 2 gigabytes of ram as maximum to your app
But you should see if you don't have a memory leak first.
3.- It depends on the program. Try spot memory leaks. This question would be to hard to answer. Lately you can profile using JConsole to try to find out where your memory is going to
With ASP.NET 5 there is no Request variable available anymore. You can access it now with Context.Request
Also there is no IsAjaxRequest() Method anymore, you have to write it by yourself, for example in Extensions\HttpRequestExtensions.cs
using System;
using Microsoft.AspNetCore.Http;
namespace Microsoft.AspNetCore.Mvc
{
public static class HttpRequestExtensions
{
public static bool IsAjaxRequest(this HttpRequest request)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
return (request.Headers != null) && (request.Headers["X-Requested-With"] == "XMLHttpRequest");
}
}
}
I searched for a while now on this and hope that will help some others too ;)
Spring Boot already has support for profile based properties.
Simply add an application-[profile].properties
file and specify the profiles to use using the spring.profiles.active
property.
-Dspring.profiles.active=local
This will load the application.properties
and the application-local.properties
with the latter overriding properties from the first.
If you want just the summary of the exception use:
try
{
test();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
If you want to see the whole stack trace (usually better for debugging) use:
try
{
test();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Another method I sometime use is:
private DoSomthing(int arg1, int arg2, out string errorMessage)
{
int result ;
errorMessage = String.Empty;
try
{
//do stuff
int result = 42;
}
catch (Exception ex)
{
errorMessage = ex.Message;//OR ex.ToString(); OR Free text OR an custom object
result = -1;
}
return result;
}
And In your form you will have something like:
string ErrorMessage;
int result = DoSomthing(1, 2, out ErrorMessage);
if (!String.IsNullOrEmpty(ErrorMessage))
{
MessageBox.Show(ErrorMessage);
}
You can achieve this with setting both the top
and bottom
attributes of the nav to 0
and the position: absolute
. Set the container to position: relative
.
IE11+ and all modern browsers support flexbox.
.container {
display: flex;
flex-direction: column;
}
.child {
flex-grow: 1;
}
Get values, convert it to an array, get array's first element:
map.values().toArray()[0]
W.
If you don't mind a third party dependency, there is a class named Collectors2 in Eclipse Collections which contains methods returning Collectors for summing and summarizing BigDecimal and BigInteger. These methods take a Function as a parameter so you can extract a BigDecimal or BigInteger value from an object.
List<BigDecimal> list = mList(
BigDecimal.valueOf(0.1),
BigDecimal.valueOf(1.1),
BigDecimal.valueOf(2.1),
BigDecimal.valueOf(0.1));
BigDecimal sum =
list.stream().collect(Collectors2.summingBigDecimal(e -> e));
Assert.assertEquals(BigDecimal.valueOf(3.4), sum);
BigDecimalSummaryStatistics statistics =
list.stream().collect(Collectors2.summarizingBigDecimal(e -> e));
Assert.assertEquals(BigDecimal.valueOf(3.4), statistics.getSum());
Assert.assertEquals(BigDecimal.valueOf(0.1), statistics.getMin());
Assert.assertEquals(BigDecimal.valueOf(2.1), statistics.getMax());
Assert.assertEquals(BigDecimal.valueOf(0.85), statistics.getAverage());
Note: I am a committer for Eclipse Collections.
You can create one more class naming
.flex-control-thumbs-without-width li {
width: auto;
float: initial; or none
}
Add this class whenever you need to override like below,
<li class="flex-control-thumbs flex-control-thumbs-without-width"> </li>
And do remove whenever you don't need for other <li>
It doesn't work on Ubuntu 16.04, it seems that some libraries have been forgotten in the python installation package on this one. You should use package manager instead.
Uninstall matplotlib from pip then install it again with apt-get
python 2:
sudo pip uninstall matplotlib
sudo apt-get install python-matplotlib
python 3:
sudo pip3 uninstall matplotlib
sudo apt-get install python3-matplotlib
I realized this task for my needs as follows
set nocount on;
declare @ToDate date = dateadd(month,datediff(month,0,getdate())-1,0)
declare @year varchar(4) = year(@ToDate)
declare @month varchar(2) = month(@ToDate)
declare @sql nvarchar(max)
set @sql = N'
create or alter view dbo.wTempLogs
as
select * from dbo.y2019
where
year(LogDate) = ''_year_''
and
month(LogDate) = ''_month_'' '
select @sql = replace(replace(@sql,'_year_',@year),'_month_',@month)
execute sp_executesql @sql
declare @errmsg nvarchar(max)
set @errMsg = @sql
raiserror (@errMsg, 0,1) with nowait
The .size() method is deprecated as of jQuery 1.8. Use the .length property instead
There is no official, universal, convention for naming JavaScript files.
There are some various options:
scriptName.js
script-name.js
script_name.js
are all valid naming conventions, however I prefer the jQuery suggested naming convention (for jQuery plugins, although it works for any JS)
jquery.pluginname.js
The beauty to this naming convention is that it explicitly describes the global namespace pollution being added.
foo.js
adds window.foo
foo.bar.js
adds window.foo.bar
Because I left out versioning: it should come after the full name, preferably separated by a hyphen, with periods between major and minor versions:
foo-1.2.1.js
foo-1.2.2.js
foo-2.1.24.js
If all you want to do is to remove a merge commit (2) so that it is like it never happened, the command is simply as follows
git rebase --onto <sha of 1> <sha of 2> <blue branch>
And now the purple branch isn't in the commit log of blue at all and you have two separate branches again. You can then squash the purple independently and do whatever other manipulations you want without the merge commit in the way.
this issue occur for me after downgrade Java JDK, after upgrade JDK my problem resolved.
this code works with me
ImageView carView = (ImageView) v.findViewById(R.id.car_icon);
byte[] decodedString = Base64.decode(picture, Base64.NO_WRAP);
InputStream input=new ByteArrayInputStream(decodedString);
Bitmap ext_pic = BitmapFactory.decodeStream(input);
carView.setImageBitmap(ext_pic);
Check here for how to add the activedirectory module if not there by default. This can be done on any machine and then it will allow you to access your active directory "domain control" server.
To prevent problems with stale links (I have found MSDN blogs to disappear for no reason in the past), in essence for Windows 7 you need to download and install Remote Server Administration Tools (KB958830). After installing do the following steps:
Windows server editions should already be OK but if not you need to download and install the Active Directory Management Gateway Service. If any of these links should stop working, you should still be able search for the KB article or download names and find them.
A combination of this http://www.webcheatsheet.com/PHP/send_email_text_html_attachment.php#attachment
with the php upload file example would work. In the upload file example instead of using move_uploaded_file to move it from the temporary folder you would just open it:
$attachment = chunk_split(base64_encode(file_get_contents($tmp_file)));
where $tmp_file = $_FILES['userfile']['tmp_name'];
and send it as an attachment like the rest of the example.
All in one file / self contained:
<? if(isset($_POST['submit'])){
//process and email
}else{
//display form
}
?>
I think its a quick exercise to get what you need working based on the above two available examples.
P.S. It needs to get uploaded somewhere before Apache passes it along to PHP to do what it wants with it. That would be your system's temp folder by default unless it was changed in the config file.
If you need to deal with data.frames that include factors you can use:
df = data.frame(v1=letters[1:5],v2=1:5,v3=letters[10:14],v4=as.factor(letters[1:5]),v5=runif(5),stringsAsFactors=FALSE)
df
v1 v2 v3 v4 v5
1 a 1 j a 0.1774909
2 b 2 k b 0.4405019
3 c 3 l c 0.7042878
4 d 4 m d 0.8829965
5 e 5 n e 0.9702505
sapply(df,class)
v1 v2 v3 v4 v5
"character" "integer" "character" "factor" "numeric"
Use mutate_each_ to convert factors to character then convert all to uppercase
upper_it = function(X){X %>% mutate_each_( funs(as.character(.)), names( .[sapply(., is.factor)] )) %>%
mutate_each_( funs(toupper), names( .[sapply(., is.character)] ))} # convert factor to character then uppercase
Gives
upper_it(df)
v1 v2 v3 v4
1 A 1 J A
2 B 2 K B
3 C 3 L C
4 D 4 M D
5 E 5 N E
While
sapply( upper_it(df),class)
v1 v2 v3 v4 v5
"character" "integer" "character" "character" "numeric"
Scala 2.13+
instead of "breakOut"
c.map(t => (t.getP, t)).to(Mat)
Scroll to "View": https://www.scala-lang.org/blog/2017/02/28/collections-rework.html
This is the solution i found.
Configure DBContext via AddDbContext
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<BloggingContext>(options => options.UseSqlite("Data Source=blog.db"));
}
Add new constructor to your DBContext class
public class BloggingContext : DbContext
{
public BloggingContext(DbContextOptions<BloggingContext> options)
:base(options)
{ }
public DbSet<Blog> Blogs { get; set; }
}
Inject context to your controllers
public class MyController
{
private readonly BloggingContext _context;
public MyController(BloggingContext context)
{
_context = context;
}
...
}
The differences between strong and retain:
The differences between weak and assign:
For file and directory search purpose I would want to offer use specialized multithreading .NET library that possess a wide search opportunities and works very fast.
All information about library you can find on GitHub: https://github.com/VladPVS/FastSearchLibrary
If you want to download it you can do it here: https://github.com/VladPVS/FastSearchLibrary/releases
If you have any questions please ask them.
It is one demonstrative example how you can use it:
class Searcher
{
private static object locker = new object();
private FileSearcher searcher;
List<FileInfo> files;
public Searcher()
{
files = new List<FileInfo>(); // create list that will contain search result
}
public void Startsearch()
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
// create tokenSource to get stop search process possibility
searcher = new FileSearcher(@"C:\", (f) =>
{
return Regex.IsMatch(f.Name, @".*[Dd]ragon.*.jpg$");
}, tokenSource); // give tokenSource in constructor
searcher.FilesFound += (sender, arg) => // subscribe on FilesFound event
{
lock (locker) // using a lock is obligatorily
{
arg.Files.ForEach((f) =>
{
files.Add(f); // add the next received file to the search results list
Console.WriteLine($"File location: {f.FullName}, \nCreation.Time: {f.CreationTime}");
});
if (files.Count >= 10) // one can choose any stopping condition
searcher.StopSearch();
}
};
searcher.SearchCompleted += (sender, arg) => // subscribe on SearchCompleted event
{
if (arg.IsCanceled) // check whether StopSearch() called
Console.WriteLine("Search stopped.");
else
Console.WriteLine("Search completed.");
Console.WriteLine($"Quantity of files: {files.Count}"); // show amount of finding files
};
searcher.StartSearchAsync();
// start search process as an asynchronous operation that doesn't block the called thread
}
}
Activator.CreateInstance()
returns an object, which doesn't have an Output method.
It looks like you come from dynamic programming languages? C# is definetly not that, and what you are trying to do will be difficult.
Since you are loading a specific dll from a specific location, maybe you just want to add it as a reference to your console application?
If you absolutely want to load the assembly via Assembly.Load
, you will have to go via reflection to call any members on c
Something like type.GetMethod("Output").Invoke(c, null);
should do it.
If Not editTransactionRow.pay_id AndAlso String.IsNullOrEmpty(editTransactionRow.pay_id.ToString()) = False Then
stTransactionPaymentID = editTransactionRow.pay_id 'Check for null value
End If
For Those Who Use Static Fragment
In a case if you have a static fragment then It would be preferable. Make an instance object of your fragment
private static MyFragment instance=null;
in onCreate() of MyFragment initialize that instance
instance=this;
also make a function to get Instance
public static MyFragment getInstance(){
return instance;
}
also make functions
public boolean allowBackPressed(){
if(allowBack==true){
return true;
}
return false;
}
//allowBack is a boolean variable that will be set to true at the action
//where you want that your backButton should not close activity. In my case I open
//Navigation Drawer then I set it to true. so when I press backbutton my
//drawer should be get closed
public void performSomeAction(){
//.. Your code
///Here I have closed my drawer
}
In Your Activity You can do
@Override
public void onBackPressed() {
if (MyFragment.getInstance().allowBackPressed()) {
MyFragment.getInstance().performSomeAction();
}
else{
super.onBackPressed();
}
}
I was able to do that by using the "branches to build" parameter:
Branch Specifier (blank for default): tags/[tag-name]
Replace [tag-name] by the name of your tag.
A simple solution with minimal javascript is to use the html attribute pattern (supported by most modern browsers). This works by setting the pattern of the second field to the value of the first field.
Unfortunately, you also need to escape the regex, for which no standard function exists.
<form>
<input type="text" oninput="form.confirm.pattern = escapeRegExp(this.value)">
<input name="confirm" pattern="" title="Fields must match" required>
</form>
<script>
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
</script>
If maven is not creating Local Repository i.e .m2/repository folder then try below step.
In your Eclipse\Spring Tool Suite, Go to Window->preferences-> maven->user settings-> click on Restore Defaults-> Apply->Apply and close
The C-like method may not be as attractive as the other solutions to this question, but added here for completeness:
You can initialise with NULLs like this:
char msg[65536] = {0};
Or to use zeros consider the following:
char msg[65536] = {'0' another 65535 of these separated by comma};
But do not try it as not possible, so use memset!
In the second case, add the following after the memset if you want to use msg as a string.
msg[65536 - 1] = '\0'
Answers to this question also provide further insight.
Why not using jQuery?
$(document).ready(function(){}))
As far as I know, this is the perfect solution.
I was able to do this with the following code, which is taken from an activity (the layout is a very simple one, just containing an ImageView, and is not posted here).
private static final int[] FROM_COLOR = new int[]{49, 179, 110};
private static final int THRESHOLD = 3;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.test_colors);
ImageView iv = (ImageView) findViewById(R.id.img);
Drawable d = getResources().getDrawable(RES);
iv.setImageDrawable(adjust(d));
}
private Drawable adjust(Drawable d)
{
int to = Color.RED;
//Need to copy to ensure that the bitmap is mutable.
Bitmap src = ((BitmapDrawable) d).getBitmap();
Bitmap bitmap = src.copy(Bitmap.Config.ARGB_8888, true);
for(int x = 0;x < bitmap.getWidth();x++)
for(int y = 0;y < bitmap.getHeight();y++)
if(match(bitmap.getPixel(x, y)))
bitmap.setPixel(x, y, to);
return new BitmapDrawable(bitmap);
}
private boolean match(int pixel)
{
//There may be a better way to match, but I wanted to do a comparison ignoring
//transparency, so I couldn't just do a direct integer compare.
return Math.abs(Color.red(pixel) - FROM_COLOR[0]) < THRESHOLD &&
Math.abs(Color.green(pixel) - FROM_COLOR[1]) < THRESHOLD &&
Math.abs(Color.blue(pixel) - FROM_COLOR[2]) < THRESHOLD;
}
You don't. The closest thing you can do is working with Maps to simulate it, or defining your own Objects to deal with.
abs(x-y)
will do exactly what you're looking for:
In [1]: abs(1-2)
Out[1]: 1
In [2]: abs(2-1)
Out[2]: 1
select * from v$session
where sid = to_number(substr(dbms_session.unique_session_id,1,4),'XXXX')
You can use StringEscapeUtils from Apache Commons Logging utility or escape manually using code for each character.
Auto-incrementing the index in a loop:
myArr[(len(myArr)+1)]={"key":"val"}
I have used Meld once, which seemed very nice, and I may try more often. vimdiff works well, if you know vim well. Lastly I would mention I've found xxdiff does a reasonable job for a quick comparison. There are many diff programs out there which do a good job.
It's an attribute wildcard selector. In the sample you've given, it looks for any child element under .show-grid
that has a class that CONTAINS span
.
So would select the <strong>
element in this example:
<div class="show-grid">
<strong class="span6">Blah blah</strong>
</div>
You can also do searches for 'begins with...'
div[class^="something"] { }
which would work on something like this:-
<div class="something-else-class"></div>
and 'ends with...'
div[class$="something"] { }
which would work on
<div class="you-are-something"></div>
Good references
Scraping it to JSON with Node.js would be fun :)
https://github.com/f1lt3r/bitcoin-scraper
[
[
1419033600, // Timestamp (1 for each minute of entire history)
318.58, // Open
318.58, // High
318.58, // Low
318.58, // Close
0.01719605, // Volume (BTC)
5.478317609, // Volume (Currency)
318.58 // Weighted Price (USD)
]
]
As Andreas mentioned all about:
Error:java: invalid source release: 8 in IntelliJ
Error:java: invalid source release: 13 in IntelliJ
Error:java: invalid source release: 14 in IntelliJ...
OR whatever version you are using in Java...
The problem will exist if you do not have it matching inside the below code:
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
This 1.8 in my case, must be matching on your device through MAVEN project library, settings, preferences, project setting and SDK.
xgboost-0.6-cp36-cp36m-win_amd64.whl
for anaconda 3 (python 3.6)C:\
cd C:\
pip install C:\xgboost-0.6-cp36-cp36m-win_amd64.whl
conda update scikit-learn
The following regular expression in Python works well for detecting URL(s) in the text:
source_text = '''
text1
text2
http://url.com/bla1/blah1/
text3
text4
http://url.com/bla2/blah2/
text5
text6 '''
import re
url_reg = r'[a-z]*[:.]+\S+'
result = re.sub(url_reg, '', source_text)
print(result)
Output:
text1
text2
text3
text4
text5
text6
I saw the following solution from another website:
int count_one(int x){
x = (x & (0x55555555)) + ((x >> 1) & (0x55555555));
x = (x & (0x33333333)) + ((x >> 2) & (0x33333333));
x = (x & (0x0f0f0f0f)) + ((x >> 4) & (0x0f0f0f0f));
x = (x & (0x00ff00ff)) + ((x >> 8) & (0x00ff00ff));
x = (x & (0x0000ffff)) + ((x >> 16) & (0x0000ffff));
return x;
}
In addition to @Cristian's answer above, I had to do two more steps to get it working correctly. I will sum all of it here:
R.java
class and the press F6
(Refactor->Move...). It will allow you to move the class to another package, and all references to that class will be updated.build.gradle
file : android / defaultconfig / application ID [source].Just use parseInt()
and be sure to include the radix so you get predictable results:
parseInt(d, 10);
Try this query it ll change the records ends with .com
UPDATE tablename SET email = replace(email, '.com', '.org') WHERE email LIKE '%.com';
For people like me, linq addicts, and based on svick's answer, here a linq approach:
using System.Linq;
//...
//make it linq iterable.
var obj_linq = Response.Cast<KeyValuePair<string, JToken>>();
Now you can make linq expressions like:
JToken x = obj_linq
.Where( d => d.Key == "my_key")
.Select(v => v)
.FirstOrDefault()
.Value;
string y = ((JValue)x).Value;
Or just:
var y = obj_linq
.Where(d => d.Key == "my_key")
.Select(v => ((JValue)v.Value).Value)
.FirstOrDefault();
Or this one to iterate over all data:
obj_linq.ToList().ForEach( x => { do stuff } );
Based off of @Mike Sherrill Cat Recall's answer, this is what worked for me:
ALTER TABLE "Children"
DROP CONSTRAINT "Children_parentId_fkey",
ADD CONSTRAINT "Children_parentId_fkey"
FOREIGN KEY ("parentId")
REFERENCES "Parent"(id)
ON DELETE CASCADE;
Or about the best module I have found http://pypi.python.org/pypi/colorama
=SORT(UNIQUE(A:A))
The above formula works best if you want to list unique values in a column.
Update more information:
If you use flowLayout.estimatedItemSize
, suggest use iOS8.3 later version. Before iOS8.3, it will crash [super layoutAttributesForElementsInRect:rect];
.
The error message is
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'
Second, in iOS8.x version, flowLayout.estimatedItemSize
will cause different section inset setting did not work. i.e. function: (UIEdgeInsets)collectionView:layout:insetForSectionAtIndex:
.
There's no way you can do that changing only that line. You can do:
a = [1]
b = a
a[0] = 2
b[0]
That creates a list, assigns the reference to a, then b also, uses the a reference to set the first element to 2, then accesses using the b reference variable.
By my way of thinking, it already has rounded corners.
In case you want them more rounded, you will need to:
EditText
background (found in your SDK)StateListDrawable
resource that combines those EditText
backgrounds into a single Drawable
, and modify it to point to your more-rounded nine-patch PNG filesStateListDrawable
as the background for your EditText
widgetHow about
$([your selector]).attr('colspan',3);
I would imagine that to work but have no way to test at the moment. Using .attr()
would be the usual jQuery way of setting attributes of elements in the wrapped set.
As has been mentioned in another answer, in order to get this to work would require removing the td elements that have no text in them from the DOM. It may be easier to do this all server side
EDIT:
As was mentioned in the comments, there is a bug in attempting to set colspan using attr() in IE, but the following works in IE6 and FireFox 3.0.13.
notice the use of the attribute colSpan
and not colspan
- the former works in both IE and Firefox, but the latter does not work in IE. Looking at jQuery 1.3.2 source, it would appear that attr()
attempts to set the attribute as a property of the element if
colSpan
exists as a property and defaults to 1 on <td>
HTMLElements in IE and FireFox) using colSpan
as opposed to colspan
works with attr()
because the former is a property defined on the element whereas the latter is not.
the fall-through for attr()
is to attempt to use setAttribute()
on the element in question, setting the value to a string, but this causes problems in IE (bug #1070 in jQuery)
// convert the value to a string (all browsers do this but IE) see #1070
elem.setAttribute( name, "" + value );
In the demo, for each row, the text in each cell is evaluated. If the text is a blank string, then the cell is removed and a counter incremented. The first cell in the row that does not have class="colTime"
has a colspan attribute set to the value of the counter + 1 (for the span it occupies itself).
After this, for each row, the text in the cell with class="colspans"
is set to the colspan attribute values of each cell in the row from left to right.
HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Sandbox</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body { background-color: #000; font: 16px Helvetica, Arial; color: #fff; }
td { text-align: center; }
</style>
</head>
<body>
<table class="tblSimpleAgenda" cellpadding="5" cellspacing="0">
<tbody>
<tr>
<th align="left">Time</th>
<th align="left">Room 1</th>
<th align="left">Room 2</th>
<th align="left">Room 3</th>
<th align="left">Colspans (L -> R)</th>
</tr>
<tr valign="top">
<td class="colTime">09:00 – 10:00</td>
<td class="col1"></td>
<td class="col2">Meeting 2</td>
<td class="col3"></td>
<td class="colspans">holder</td>
</tr>
<tr valign="top">
<td class="colTime">10:00 – 10:45</td>
<td class="col1">Meeting 1</td>
<td class="col2">Meeting 2</td>
<td class="col3">Meeting 3</td>
<td class="colspans">holder</td>
</tr>
<tr valign="top">
<td class="colTime">11:00 – 11:45</td>
<td class="col1">Meeting 1</td>
<td class="col2">Meeting 2</td>
<td class="col3">Meeting 3</td>
<td class="colspans">holder</td>
</tr>
<tr valign="top">
<td class="colTime">11:00 – 11:45</td>
<td class="col1">Meeting 1</td>
<td class="col2">Meeting 2</td>
<td class="col3"></td>
<td class="colspans">holder</td>
</tr>
</tbody>
</table>
</body>
</html>
jQuery code
$(function() {
$('table.tblSimpleAgenda tr').each(function() {
var tr = this;
var counter = 0;
$('td', tr).each(function(index, value) {
var td = $(this);
if (td.text() == "") {
counter++;
td.remove();
}
});
if (counter !== 0) {
$('td:not(.colTime):first', tr)
.attr('colSpan', '' + parseInt(counter + 1,10) + '');
}
});
$('td.colspans').each(function(){
var td = $(this);
var colspans = [];
td.siblings().each(function() {
colspans.push(($(this).attr('colSpan')) == null ? 1 : $(this).attr('colSpan'));
});
td.text(colspans.join(','));
});
});
This is just a demonstration to show that attr()
can be used, but to be aware of it's implementation and the cross-browser quirks that come with it. I've also made some assumptions about your table layout in the demo (i.e. apply the colspan to the first "non-Time" cell in each row), but hopefully you get the idea.
You might be interested in the calc
approach:
font-size: calc(4vw + 4vh + 2vmin);
done. Tweak values till matches your taste.
I installed TortoiseSVN-1.12.2.28653-x64-svn-1.12.2
in Windows 10 with commandline tool enabled. Still it didn't have the svn.exe
file inside the bin
folder.
So I downloaded Apache Subversion commandline tools from https://www.visualsvn.com/files/Apache-Subversion-1.13.0.zip. After unzipping, I have put the following two locations into my PATH variable:
C:\Program Files\TortoiseSVN\bin
E:\Apache-Subversion-1.13.0\bin
Everything works fine for me after this configuration.I wanted to use SVN in VsCode IDE.
If you do import foo
(inside bar.py
) and import bar
(inside foo.py
), it will work fine. By the time anything actually runs, both modules will be fully loaded and will have references to each other.
The problem is when instead you do from foo import abc
(inside bar.py
) and from bar import xyz
(inside foo.py
). Because now each module requires the other module to already be imported (so that the name we are importing exists) before it can be imported.
Iterable is a generic interface. A problem you might be having (you haven't actually said what problem you're having, if any) is that if you use a generic interface/class without specifying the type argument(s) you can erase the types of unrelated generic types within the class. An example of this is in Non-generic reference to generic class results in non-generic return types.
So I would at least change it to:
public class ProfileCollection implements Iterable<Profile> {
private ArrayList<Profile> m_Profiles;
public Iterator<Profile> iterator() {
Iterator<Profile> iprof = m_Profiles.iterator();
return iprof;
}
...
public Profile GetActiveProfile() {
return (Profile)m_Profiles.get(m_ActiveProfile);
}
}
and this should work:
for (Profile profile : m_PC) {
// do stuff
}
Without the type argument on Iterable, the iterator may be reduced to being type Object so only this will work:
for (Object profile : m_PC) {
// do stuff
}
This is a pretty obscure corner case of Java generics.
If not, please provide some more info about what's going on.
@Dennis Roberts: You were absolutely right: My test class was located in src/main/java. Also the value of the "scope" element in the POM for JUnit was "test", although that is how it is supposed to be. The problem was that I had been sloppy when creating the test class in Eclipse, resulting in it being created in src/main/java insted of src/test/java. This became easier to see in Eclipse's Project Explorer view after running "mvn eclipse:eclipse", but your comment was what made me see it first. Thanks.
According to Javax's persistence documentation:
Whether the column is included in SQL UPDATE statements generated by the persistence provider.
It would be best to understand from the official documentation here.
No, there is no built-in support for aggregation queries right now. However there are a few things you could do.
The first is documented here. You can use transactions or cloud functions to maintain aggregate information:
This example shows how to use a function to keep track of the number of ratings in a subcollection, as well as the average rating.
exports.aggregateRatings = firestore
.document('restaurants/{restId}/ratings/{ratingId}')
.onWrite(event => {
// Get value of the newly added rating
var ratingVal = event.data.get('rating');
// Get a reference to the restaurant
var restRef = db.collection('restaurants').document(event.params.restId);
// Update aggregations in a transaction
return db.transaction(transaction => {
return transaction.get(restRef).then(restDoc => {
// Compute new number of ratings
var newNumRatings = restDoc.data('numRatings') + 1;
// Compute new average rating
var oldRatingTotal = restDoc.data('avgRating') * restDoc.data('numRatings');
var newAvgRating = (oldRatingTotal + ratingVal) / newNumRatings;
// Update restaurant info
return transaction.update(restRef, {
avgRating: newAvgRating,
numRatings: newNumRatings
});
});
});
});
The solution that jbb mentioned is also useful if you only want to count documents infrequently. Make sure to use the select()
statement to avoid downloading all of each document (that's a lot of bandwidth when you only need a count). select()
is only available in the server SDKs for now so that solution won't work in a mobile app.
Incase of lookup_food_array is array.
match_stage["favoriteFoods"] = {'$elemMatch': {'$in': lookup_food_array}}
Incase of lookup_food_array is string.
match_stage["favoriteFoods"] = {'$elemMatch': lookup_food_string}
One way to do this would be to pass the instance of ParentClass
to the ChildClass
on construction
public ChildClass
{
private ParentClass parent;
public ChildClass(ParentClass parent)
{
this.parent = parent;
}
public void LoadData(DateTable dt)
{
// do something
parent.CurrentRow++; // or whatever.
parent.UpdateProgressBar(); // Call the method
}
}
Make sure to pass the reference to this
when constructing ChildClass
inside parent:
if(loadData){
ChildClass childClass = new ChildClass(this); // here
childClass.LoadData(this.Datatable);
}
Caveat: This is probably not the best way to organise your classes, but it directly answers your question.
EDIT: In the comments you mention that more than 1 parent class wants to use ChildClass
. This is possible with the introduction of an interface, eg:
public interface IParentClass
{
void UpdateProgressBar();
int CurrentRow{get; set;}
}
Now, make sure to implement that interface on both (all?) Parent Classes and change child class to this:
public ChildClass
{
private IParentClass parent;
public ChildClass(IParentClass parent)
{
this.parent = parent;
}
public void LoadData(DateTable dt)
{
// do something
parent.CurrentRow++; // or whatever.
parent.UpdateProgressBar(); // Call the method
}
}
Now anything that implements IParentClass
can construct an instance of ChildClass
and pass this
to its constructor.
I highly recommend reading the book 'Effective Java' from Joshua Bloch.
I stumbled across this question while hitting this road block myself. I ended up writing a piece of code real quick to handle this ReDim Preserve
on a new sized array (first or last dimension). Maybe it will help others who face the same issue.
So for the usage, lets say you have your array originally set as MyArray(3,5)
, and you want to make the dimensions (first too!) larger, lets just say to MyArray(10,20)
. You would be used to doing something like this right?
ReDim Preserve MyArray(10,20) '<-- Returns Error
But unfortunately that returns an error because you tried to change the size of the first dimension. So with my function, you would just do something like this instead:
MyArray = ReDimPreserve(MyArray,10,20)
Now the array is larger, and the data is preserved. Your ReDim Preserve
for a Multi-Dimension array is complete. :)
And last but not least, the miraculous function: ReDimPreserve()
'redim preserve both dimensions for a multidimension array *ONLY
Public Function ReDimPreserve(aArrayToPreserve,nNewFirstUBound,nNewLastUBound)
ReDimPreserve = False
'check if its in array first
If IsArray(aArrayToPreserve) Then
'create new array
ReDim aPreservedArray(nNewFirstUBound,nNewLastUBound)
'get old lBound/uBound
nOldFirstUBound = uBound(aArrayToPreserve,1)
nOldLastUBound = uBound(aArrayToPreserve,2)
'loop through first
For nFirst = lBound(aArrayToPreserve,1) to nNewFirstUBound
For nLast = lBound(aArrayToPreserve,2) to nNewLastUBound
'if its in range, then append to new array the same way
If nOldFirstUBound >= nFirst And nOldLastUBound >= nLast Then
aPreservedArray(nFirst,nLast) = aArrayToPreserve(nFirst,nLast)
End If
Next
Next
'return the array redimmed
If IsArray(aPreservedArray) Then ReDimPreserve = aPreservedArray
End If
End Function
I wrote this in like 20 minutes, so there's no guarantees. But if you would like to use or extend it, feel free. I would've thought that someone would've had some code like this up here already, well apparently not. So here ya go fellow gearheads.
InputStream is = new FileInputStream("c://filename");
return is;
Just use .split(',')
:
var str = "How are you doing today?";
var n = str.split(" ");
I've bumped into this question because I actually wanted to define a default goal in pom.xml. You can define a default goal under build:
<build>
<defaultGoal>install</defaultGoal>
...
</build>
After that change, you can then simply run mvn
which will do exactly the same as mvn install
.
Note: I don't favor this as a default approach. My use case was to define a profile that downloaded a previous version of that project from Artifactory and wanted to tie that profile to a given phase. For convenience, I can run mvn -Pdownload-jar -Dversion=0.0.9
and don't need to specify a goal/phase there. I think it's reasonable to define a defaultGoal
in a profile which has a very specific function for a particular phase.
The solution is very simple and worked for me.
Try this :
git pull --rebase <url>
then
git push -u origin master
I think that using string is the correct way to go in this case, since you don't know a priori the number of digits in the decimal part. But, it won't work for all cases (e.g. 1.005), as mentioned before by @SingleNegationElimination. Here is my take on this:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char s_value[60], s_integral[60], s_fractional[60];
int i, found = 0, count = 1, integral, fractional;
scanf("%s", s_value);
for (i = 0; s_value[i] != '\0'; i++)
{
if (!found)
{
if (s_value[i] == '.')
{
found = 1;
s_integral[i] = '\0';
continue;
}
s_integral[i] = s_value[i];
count++;
}
else
s_fractional[i - count] = s_value[i];
}
s_fractional[i - count] = '\0';
integral = atoi(s_integral);
fractional = atoi(s_fractional);
printf("value = %s, integral = %d, fractional = %d\n",
s_value, integral, fractional);
return 0;
}
The problem is that you can't use a list
as the key in a dict
, since dict
keys need to be immutable. Use a tuple instead.
This is a list:
[x, y]
This is a tuple:
(x, y)
Note that in most cases, the (
and )
are optional, since ,
is what actually defines a tuple (as long as it's not surrounded by []
or {}
, or used as a function argument).
You might find the section on tuples in the Python tutorial useful:
Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.
And in the section on dictionaries:
Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().
In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.
In addition to the above configurations, I had to set deployment target to "Open Select Deployment Target Dialog", run once (choosing my device from the options listed), and from then on Android Studio was able to see my device even after changing the deployment setting back to "USB Device". My SWAG is that since Android Studio uses its own internal cache to find your device, it has to be initialized first.
in a Visual Basic Macro you would use
pName = ActiveWorkbook.Path ' the path of the currently active file
wbName = ActiveWorkbook.Name ' the file name of the currently active file
shtName = ActiveSheet.Name ' the name of the currently selected worksheet
The first sheet in a workbook can be referenced by
ActiveWorkbook.Worksheets(1)
so after deleting the [Report] tab you would use
ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name
to "work on that sheet later on" you can create a range object like
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]
and continue working on MySheet(rowNum, colNum)
etc. ...
shortcut creation of a range object without defining shtName:
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]
This can be achieved simply with the following code:
var date = new Date();
var components = [
date.getYear(),
date.getMonth(),
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
date.getMilliseconds()
];
var id = components.join("");
Well, here's an example for overloaded constructors.
public class Employee
{
private String name;
private int age;
public Employee()
{
System.out.println("We are inside Employee() constructor");
}
public Employee(String name)
{
System.out.println("We are inside Employee(String name) constructor");
this.name = name;
}
public Employee(String name, int age)
{
System.out.println("We are inside Employee(String name, int age) constructor");
this.name = name;
this.age = age;
}
public Employee(int age)
{
System.out.println("We are inside Employee(int age) constructor");
this.age = age;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
}
In the above example you can see overloaded constructors. Name of the constructors is same but each constructors has different parameters.
Here are some resources which throw more light on constructor overloading in java,
Here is an alternative that is an incremental improvement on several other answers. Assuming settings.aLengthMenu is not multi-dimensional (it can be when DataTables has row lengths and labels) and the data will not change after page load (for simple DOM-loaded DataTables), this function can be inserted to eliminate paging. It hides several paging-related classes.
Perhaps more robust would be setting paging to false inside the function below, however I don't see an API call for that off-hand.
$('#myTable').on('init.dt', function(evt, settings) {
if (settings && settings.aLengthMenu && settings.fnRecordsTotal && settings.fnRecordsTotal() < settings.aLengthMenu[0]) {
// hide pagination controls, fewer records than minimum length
$(settings.nTableWrapper).find('.dataTables_paginate, .dataTables_length, .dataTables_info').hide();
}
}).DataTable();
None of the 7 prior answers mentioned that console.dir
supports extra arguments: depth
, showHidden
, and whether to use colors
.
Of particular interest is depth
, which (in theory) allows travering objects into more than the default 2 levels that console.log
supports.
I wrote "in theory" because in practice when I had a Mongoose object and ran console.log(mongoose)
and console.dir(mongoose, { depth: null })
, the output was the same. What actually recursed deeply into the mongoose
object was using util.inspect
:
import * as util from 'util';
console.log(util.inspect(myObject, {showHidden: false, depth: null}));