you can use this simple way
<select onchange="location = this.value;">
<option value="/finished">Finished</option>
<option value="/break">Break</option>
<option value="/issue">Issues</option>
<option value="/downtime">Downtime</option>
</select>
will redirect to route url you can direct to .html page or direct to some link just change value
in option.
geany I recommend
Here's a quick recipe I found:
var gulp = require('gulp');
// npm install gulp yargs gulp-if gulp-uglify
var args = require('yargs').argv;
var gulpif = require('gulp-if');
var uglify = require('gulp-uglify');
var isProduction = args.env === 'production';
gulp.task('scripts', function() {
return gulp.src('**/*.js')
.pipe(gulpif(isProduction, uglify())) // only minify if production
.pipe(gulp.dest('dist'));
});
gulp scripts --env production
Original Ref (not available anymore): https://github.com/gulpjs/gulp/blob/master/docs/recipes/pass-params-from-cli.md
From Updated Ref: https://github.com/gulpjs/gulp/blob/master/docs/recipes/pass-arguments-from-cli.md
// npm install --save-dev gulp gulp-if gulp-uglify minimist
var gulp = require('gulp');
var gulpif = require('gulp-if');
var uglify = require('gulp-uglify');
var minimist = require('minimist');
var knownOptions = {
string: 'env',
default: { env: process.env.NODE_ENV || 'production' }
};
var options = minimist(process.argv.slice(2), knownOptions);
gulp.task('scripts', function() {
return gulp.src('**/*.js')
.pipe(gulpif(options.env === 'production', uglify())) // only minify if production
.pipe(gulp.dest('dist'));
});
gulp scripts --env production
Taken from this answer.
packages.config
file. This is the first time I see ignoring a problem actually makes it go away...
Edit in 2020: if you are viewing this warning, consider upgrading to PackageReference if you can
The element.style property lets you know only the CSS properties that were defined as inline in that element (programmatically, or defined in the style attribute of the element), you should get the computed style.
Is not so easy to do it in a cross-browser way, IE has its own way, through the element.currentStyle property, and the DOM Level 2 standard way, implemented by other browsers is through the document.defaultView.getComputedStyle method.
The two ways have differences, for example, the IE element.currentStyle property expect that you access the CSS property names composed of two or more words in camelCase (e.g. maxHeight, fontSize, backgroundColor, etc), the standard way expects the properties with the words separated with dashes (e.g. max-height, font-size, background-color, etc). ......
function getStyle(el, styleProp) {
var value, defaultView = (el.ownerDocument || document).defaultView;
// W3C standard way:
if (defaultView && defaultView.getComputedStyle) {
// sanitize property name to css notation
// (hyphen separated words eg. font-Size)
styleProp = styleProp.replace(/([A-Z])/g, "-$1").toLowerCase();
return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
} else if (el.currentStyle) { // IE
// sanitize property name to camelCase
styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
return letter.toUpperCase();
});
value = el.currentStyle[styleProp];
// convert other units to pixels on IE
if (/^\d+(em|pt|%|ex)?$/i.test(value)) {
return (function(value) {
var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left;
el.runtimeStyle.left = el.currentStyle.left;
el.style.left = value || 0;
value = el.style.pixelLeft + "px";
el.style.left = oldLeft;
el.runtimeStyle.left = oldRsLeft;
return value;
})(value);
}
return value;
}
}
Since the actual ScrollView
is encapsulated in a CoordinatorLayout
with a Toolbar
...
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay"/>
</android.support.design.widget.AppBarLayout>
<include layout="@layout/list"/>
</android.support.design.widget.CoordinatorLayout>
... I had to define android:layout_marginTop="?attr/actionBarSize"
to make the scrolling working:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
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="wrap_content"
android:layout_marginTop="?attr/actionBarSize">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<!-- UI elements here -->
</android.support.constraint.ConstraintLayout>
</ScrollView>
Above also works with NestedScrollView
instead of ScrollView
.
Defining android:fillViewport="true"
is not needed for me.
Here you go. Just specify the chars you want to allow on the first line.
char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
StringBuilder sb = new StringBuilder(20);
Random random = new Random();
for (int i = 0; i < 20; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
String output = sb.toString();
System.out.println(output);
If you are using this to generate something sensitive like a password reset URL or session ID cookie or temporary password reset, be sure to use
java.security.SecureRandom
instead. Values produced byjava.util.Random
andjava.util.concurrent.ThreadLocalRandom
are mathematically predictable.
@mywolfe02 gives a static range code so his inRange works fine but if you want to add dynamic range then use this one with inRange function of him.this works better with when you want to populate data to fix starting cell and last column is also fixed.
Sub DynamicRange()
Dim sht As Worksheet
Dim LastRow As Long
Dim StartCell As Range
Dim rng As Range
Set sht = Worksheets("xyz")
LastRow = sht.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).row
Set rng = Workbooks("Record.xlsm").Worksheets("xyz").Range(Cells(12, 2), Cells(LastRow, 12))
Debug.Print LastRow
If InRange(ActiveCell, rng) Then
' MsgBox "Active Cell In Range!"
Else
MsgBox "Please select the cell within the range!"
End If
End Sub
Big screen:
Small screen (Mobile)
if this is what you wanted this is code https://plnkr.co/edit/PCCJb9f7f93HT4OubLmM?p=preview
CSS + HTML + JQUERY :
_x000D_
@import "https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700";_x000D_
body {_x000D_
font-family: 'Poppins', sans-serif;_x000D_
background: #fafafa;_x000D_
}_x000D_
_x000D_
p {_x000D_
font-family: 'Poppins', sans-serif;_x000D_
font-size: 1.1em;_x000D_
font-weight: 300;_x000D_
line-height: 1.7em;_x000D_
color: #999;_x000D_
}_x000D_
_x000D_
a,_x000D_
a:hover,_x000D_
a:focus {_x000D_
color: inherit;_x000D_
text-decoration: none;_x000D_
transition: all 0.3s;_x000D_
}_x000D_
_x000D_
.navbar {_x000D_
padding: 15px 10px;_x000D_
background: #fff;_x000D_
border: none;_x000D_
border-radius: 0;_x000D_
margin-bottom: 40px;_x000D_
box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);_x000D_
}_x000D_
_x000D_
.navbar-btn {_x000D_
box-shadow: none;_x000D_
outline: none !important;_x000D_
border: none;_x000D_
}_x000D_
_x000D_
.line {_x000D_
width: 100%;_x000D_
height: 1px;_x000D_
border-bottom: 1px dashed #ddd;_x000D_
margin: 40px 0;_x000D_
}_x000D_
/* ---------------------------------------------------_x000D_
SIDEBAR STYLE_x000D_
----------------------------------------------------- */_x000D_
_x000D_
#sidebar {_x000D_
width: 250px;_x000D_
position: fixed;_x000D_
top: 0;_x000D_
left: 0;_x000D_
height: 100vh;_x000D_
z-index: 999;_x000D_
background: #7386D5;_x000D_
color: #fff !important;_x000D_
transition: all 0.3s;_x000D_
}_x000D_
_x000D_
#sidebar.active {_x000D_
margin-left: -250px;_x000D_
}_x000D_
_x000D_
#sidebar .sidebar-header {_x000D_
padding: 20px;_x000D_
background: #6d7fcc;_x000D_
}_x000D_
_x000D_
#sidebar ul.components {_x000D_
padding: 20px 0;_x000D_
border-bottom: 1px solid #47748b;_x000D_
}_x000D_
_x000D_
#sidebar ul p {_x000D_
color: #fff;_x000D_
padding: 10px;_x000D_
}_x000D_
_x000D_
#sidebar ul li a {_x000D_
padding: 10px;_x000D_
font-size: 1.1em;_x000D_
display: block;_x000D_
color:white;_x000D_
}_x000D_
_x000D_
#sidebar ul li a:hover {_x000D_
color: #7386D5;_x000D_
background: #fff;_x000D_
}_x000D_
_x000D_
#sidebar ul li.active>a,_x000D_
a[aria-expanded="true"] {_x000D_
color: #fff;_x000D_
background: #6d7fcc;_x000D_
}_x000D_
_x000D_
a[data-toggle="collapse"] {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
a[aria-expanded="false"]::before,_x000D_
a[aria-expanded="true"]::before {_x000D_
content: '\e259';_x000D_
display: block;_x000D_
position: absolute;_x000D_
right: 20px;_x000D_
font-family: 'Glyphicons Halflings';_x000D_
font-size: 0.6em;_x000D_
}_x000D_
_x000D_
a[aria-expanded="true"]::before {_x000D_
content: '\e260';_x000D_
}_x000D_
_x000D_
ul ul a {_x000D_
font-size: 0.9em !important;_x000D_
padding-left: 30px !important;_x000D_
background: #6d7fcc;_x000D_
}_x000D_
_x000D_
ul.CTAs {_x000D_
padding: 20px;_x000D_
}_x000D_
_x000D_
ul.CTAs a {_x000D_
text-align: center;_x000D_
font-size: 0.9em !important;_x000D_
display: block;_x000D_
border-radius: 5px;_x000D_
margin-bottom: 5px;_x000D_
}_x000D_
_x000D_
a.download {_x000D_
background: #fff;_x000D_
color: #7386D5;_x000D_
}_x000D_
_x000D_
a.article,_x000D_
a.article:hover {_x000D_
background: #6d7fcc !important;_x000D_
color: #fff !important;_x000D_
}_x000D_
/* ---------------------------------------------------_x000D_
CONTENT STYLE_x000D_
----------------------------------------------------- */_x000D_
_x000D_
#content {_x000D_
width: calc(100% - 250px);_x000D_
padding: 40px;_x000D_
min-height: 100vh;_x000D_
transition: all 0.3s;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
right: 0;_x000D_
}_x000D_
_x000D_
#content.active {_x000D_
width: 100%;_x000D_
}_x000D_
/* ---------------------------------------------------_x000D_
MEDIAQUERIES_x000D_
----------------------------------------------------- */_x000D_
_x000D_
@media (max-width: 768px) {_x000D_
#sidebar {_x000D_
margin-left: -250px;_x000D_
}_x000D_
#sidebar.active {_x000D_
margin-left: 0;_x000D_
}_x000D_
#content {_x000D_
width: 100%;_x000D_
}_x000D_
#content.active {_x000D_
width: calc(100% - 250px);_x000D_
}_x000D_
#sidebarCollapse span {_x000D_
display: none;_x000D_
}_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
_x000D_
<title>Collapsible sidebar using Bootstrap 3</title>_x000D_
_x000D_
<!-- Bootstrap CSS CDN -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<!-- Our Custom CSS -->_x000D_
<link rel="stylesheet" href="style2.css">_x000D_
<!-- Scrollbar Custom CSS -->_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.min.css">_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
_x000D_
_x000D_
<div class="wrapper">_x000D_
<!-- Sidebar Holder -->_x000D_
<nav id="sidebar">_x000D_
<div class="sidebar-header">_x000D_
<h3>Header as you want </h3>_x000D_
</h3>_x000D_
</div>_x000D_
_x000D_
<ul class="list-unstyled components">_x000D_
<p>Dummy Heading</p>_x000D_
<li class="active">_x000D_
<a href="#menu">Animación</a>_x000D_
_x000D_
</li>_x000D_
<li>_x000D_
<a href="#menu">Ilustración</a>_x000D_
_x000D_
_x000D_
</li>_x000D_
<li>_x000D_
<a href="#menu">Interacción</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">Blog</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">Acerca</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">contacto</a>_x000D_
</li>_x000D_
_x000D_
_x000D_
</ul>_x000D_
_x000D_
_x000D_
</nav>_x000D_
_x000D_
<!-- Page Content Holder -->_x000D_
<div id="content">_x000D_
_x000D_
<nav class="navbar navbar-default">_x000D_
<div class="container-fluid">_x000D_
_x000D_
<div class="navbar-header">_x000D_
<button type="button" id="sidebarCollapse" class="btn btn-info navbar-btn">_x000D_
<i class="glyphicon glyphicon-align-left"></i>_x000D_
<span>Toggle Sidebar</span>_x000D_
</button>_x000D_
</div>_x000D_
_x000D_
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
<ul class="nav navbar-nav navbar-right">_x000D_
<li><a href="#">Page</a></li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
</nav>_x000D_
_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
<!-- jQuery CDN -->_x000D_
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>_x000D_
<!-- Bootstrap Js CDN -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<!-- jQuery Custom Scroller CDN -->_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.concat.min.js"></script>_x000D_
_x000D_
<script type="text/javascript">_x000D_
$(document).ready(function() {_x000D_
_x000D_
_x000D_
$('#sidebarCollapse').on('click', function() {_x000D_
$('#sidebar, #content').toggleClass('active');_x000D_
$('.collapse.in').toggleClass('in');_x000D_
$('a[aria-expanded=true]').attr('aria-expanded', 'false');_x000D_
});_x000D_
});_x000D_
</script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
if this is what you want .
You need to escape the dot if you want to split on a literal dot:
String extensionRemoved = filename.split("\\.")[0];
Otherwise you are splitting on the regex .
, which means "any character".
Note the double backslash needed to create a single backslash in the regex.
You're getting an ArrayIndexOutOfBoundsException
because your input string is just a dot, ie "."
, which is an edge case that produces an empty array when split on dot; split(regex)
removes all trailing blanks from the result, but since splitting a dot on a dot leaves only two blanks, after trailing blanks are removed you're left with an empty array.
To avoid getting an ArrayIndexOutOfBoundsException
for this edge case, use the overloaded version of split(regex, limit)
, which has a second parameter that is the size limit for the resulting array. When limit
is negative, the behaviour of removing trailing blanks from the resulting array is disabled:
".".split("\\.", -1) // returns an array of two blanks, ie ["", ""]
ie, when filename
is just a dot "."
, calling filename.split("\\.", -1)[0]
will return a blank, but calling filename.split("\\.")[0]
will throw an ArrayIndexOutOfBoundsException
.
It seems there is no way to do this without custom view. You can get the title view:
View decor = getWindow().getDecorView();
TextView title = (TextView) decor.findViewById(getResources().getIdentifier("action_bar_title", "id", "android"));
But changing of gravity
or layout_gravity
doesn't have an effect.
The problem in the ActionBarView
, which layout its children by itself so changing of layout params of its children also doesn't have an effect.
To see this excecute following code:
ViewGroup actionBar = (ViewGroup) decor.findViewById(getResources().getIdentifier("action_bar", "id", "android"));
View v = actionBar.getChildAt(0);
ActionBar.LayoutParams p = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
p.gravity= Gravity.CENTER;
v.setLayoutParams(p);
v.setBackgroundColor(Color.BLACK);
run pod install inside ios folder then go back to root folder and run npx react-native run-ios
Polling the last modified file property is a simple yet effective solution though. Just define a class extending my FileChangedWatcher
and implement the onModified()
method:
import java.io.File;
public abstract class FileChangedWatcher
{
private File file;
public FileChangedWatcher(String filePath)
{
file = new File(filePath);
}
public void watch() throws InterruptedException
{
long currentModifiedDate = file.lastModified();
while (true)
{
long newModifiedDate = file.lastModified();
if (newModifiedDate != currentModifiedDate)
{
currentModifiedDate = newModifiedDate;
onModified();
}
Thread.sleep(100);
}
}
public String getFilePath()
{
return file.getAbsolutePath();
}
protected abstract void onModified();
}
Use File.AppendAllText instead:
File.AppendAllText(filePath + "log.txt", log);
you can used this way: create extension
extension UIView {
func addTapGesture(action : @escaping ()->Void ){
let tap = MyTapGestureRecognizer(target: self , action: #selector(self.handleTap(_:)))
tap.action = action
tap.numberOfTapsRequired = 1
self.addGestureRecognizer(tap)
self.isUserInteractionEnabled = true
}
@objc func handleTap(_ sender: MyTapGestureRecognizer) {
sender.action!()
}
}
class MyTapGestureRecognizer: UITapGestureRecognizer {
var action : (()->Void)? = nil
}
and use this way:
@IBOutlet weak var testView: UIView!
testView.addTapGesture{
// ...
}
Isn't this what default constructors are for?
class MyModel
{
public MyModel()
{
this.ReturnDate = DateTime.Now;
}
public date ReturnDate {get; set;};
}
Short version: Yes it is faster, with less code!
String concatenation does a lot of work without knowing if it is needed or not (the traditional "is debugging enabled" test known from log4j), and should be avoided if possible, as the {} allows delaying the toString() call and string construction to after it has been decided if the event needs capturing or not. By having the logger format a single string the code becomes cleaner in my opinion.
You can provide any number of arguments. Note that if you use an old version of sljf4j and you have more than two arguments to {}
, you must use the new Object[]{a,b,c,d}
syntax to pass an array instead. See e.g. http://slf4j.org/apidocs/org/slf4j/Logger.html#debug(java.lang.String, java.lang.Object[]).
Regarding the speed: Ceki posted a benchmark a while back on one of the lists.
This is a simple solution for merging two dictionaries where +=
can be applied to the values, it has to iterate over a dictionary only once
a = {'a':1, 'b':2, 'c':3}
dicts = [{'b':3, 'c':4, 'd':5},
{'c':9, 'a':9, 'd':9}]
def merge_dicts(merged,mergedfrom):
for k,v in mergedfrom.items():
if k in merged:
merged[k] += v
else:
merged[k] = v
return merged
for dct in dicts:
a = merge_dicts(a,dct)
print (a)
#{'c': 16, 'b': 5, 'd': 14, 'a': 10}
Another option compatible to 4.0:
Before committing the changes, you can recover the new CayenneDataObject
object(s) from the collection associated to the context, like this:
CayenneDataObject dataObjectsCollection = (CayenneDataObject)cayenneContext.newObjects();
then access the ObjectId
for each one in the collection, like:
ObjectId objectId = dataObject.getObjectId();
Finally you can iterate under the values, where usually the generated-id is going to be the first one of the values (for a single column key) in the Map returned by getIdSnapshot()
, it contains also the column name(s) associated to the PK as key(s):
objectId.getIdSnapshot().values()
Try this and replace '[' & ']' with your string
SELECT SUBSTRING(@TEXT,CHARINDEX('[',@TEXT)+1,(CHARINDEX(']',@TEXT)-CHARINDEX('[',@TEXT))-1)
You're looking for a bijective NxN -> N
mapping. These are used for e.g. dovetailing. Have a look at this PDF for an introduction to so-called pairing functions. Wikipedia introduces a specific pairing function, namely the Cantor pairing function:
Three remarks:
ZxZ -> N
mapping. Cantor's function only works on non-negative numbers. This is not a problem however, because it's easy to define a bijection f : Z -> N
, like so:
If you are using Eclipse, for an existing project (which has a build.gradle
file) you can simply type gradle eclipse
which will create all the Eclipse files and folders for this project.
It takes care of all the dependencies for you and adds them to the project resource path in Eclipse as well.
You need to use the new configuration
option (this works for ng build
and ng serve
as well)
ng serve --configuration=local
or
ng serve -c local
If you look at your angular.json
file, you'll see that you have finer control over settings for each configuration (aot, optimizer, environment files,...)
"configurations": {
"production": {
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
]
}
}
You can get more info here for managing environment specific configurations.
As pointed in the other response below, if you need to add a new 'environment', you need to add a new configuration to the build task and, depending on your needs, to the serve and test tasks as well.
Adding a new environment
Edit:
To make it clear, file replacements must be specified in the build
section. So if you want to use ng serve
with a specific environment
file (say dev2), you first need to modify the build
section to add a new dev2 configuration
"build": {
"configurations": {
"dev2": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.dev2.ts"
}
/* You can add all other options here, such as aot, optimization, ... */
],
"serviceWorker": true
},
Then modify your serve
section to add a new configuration as well, pointing to the dev2 build
configuration you just declared
"serve":
"configurations": {
"dev2": {
"browserTarget": "projectName:build:dev2"
}
Then you can use ng serve -c dev2
, which will use the dev2 config file
@Navaneeth and @Antfish, no need to transform you can do like this also because in above solution only top border is visible so for inside curve you can use bottom border.
.box {_x000D_
width: 500px;_x000D_
height: 100px;_x000D_
border: solid 5px #000;_x000D_
border-color: transparent transparent #000 transparent;_x000D_
border-radius: 0 0 240px 50%/60px;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
Updated 5 September 2010
Seeing as everyone seems to get directed here for this issue, I'm adding my answer to a similar question, which contains the same code as this answer but with full background for those who are interested:
IE's document.selection.createRange doesn't include leading or trailing blank lines
To account for trailing line breaks is tricky in IE, and I haven't seen any solution that does this correctly, including any other answers to this question. It is possible, however, using the following function, which will return you the start and end of the selection (which are the same in the case of a caret) within a <textarea>
or text <input>
.
Note that the textarea must have focus for this function to work properly in IE. If in doubt, call the textarea's focus()
method first.
function getInputSelection(el) {
var start = 0, end = 0, normalizedValue, range,
textInputRange, len, endRange;
if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
start = el.selectionStart;
end = el.selectionEnd;
} else {
range = document.selection.createRange();
if (range && range.parentElement() == el) {
len = el.value.length;
normalizedValue = el.value.replace(/\r\n/g, "\n");
// Create a working TextRange that lives only in the input
textInputRange = el.createTextRange();
textInputRange.moveToBookmark(range.getBookmark());
// Check if the start and end of the selection are at the very end
// of the input, since moveStart/moveEnd doesn't return what we want
// in those cases
endRange = el.createTextRange();
endRange.collapse(false);
if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
start = end = len;
} else {
start = -textInputRange.moveStart("character", -len);
start += normalizedValue.slice(0, start).split("\n").length - 1;
if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
end = len;
} else {
end = -textInputRange.moveEnd("character", -len);
end += normalizedValue.slice(0, end).split("\n").length - 1;
}
}
}
}
return {
start: start,
end: end
};
}
I know this is a late response, but a neat way of doing this is to ping the broadcast address which populates your local arp cache.
This can then be shown by running arp -a which will list all the addresses in you local arp table.
ping 192.168.1.255
arp -a
Hopefully this is a nice neat option that people can use.
If you want to be able to toggle the display of whitespaces on and off, you can install the HighlightWhitespaces plugin
You're setting overflow: hidden
. This will hide anything that's too large for the <div>
, meaning scrollbars won't be shown. Give your <div>
an explicit width and/or height, and change overflow
to auto
:
.scroll {
width: 200px;
height: 400px;
overflow: scroll;
}
If you only want to show a scrollbar if the content is longer than the <div>
, change overflow
to overflow: auto
. You can also only show one scrollbar by using overflow-y
or overflow-x
.
Bear in mid, the MAX value will only be the maximum of committed values. It might return 1234, and you may need to consider that someone has already inserted 1235 but not committed.
Just to spell out what has already been said in brief. I wanted to create an executable JAR file that included my dependencies along with my code. This worked for me:
(1) In the pom, under <build><plugins>, I included:
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2-beta-5</version>
<configuration>
<archive>
<manifest>
<mainClass>dk.certifikat.oces2.some.package.MyMainClass</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
(2) Running mvn compile assembly:assembly produced the desired my-project-0.1-SNAPSHOT-jar-with-dependencies.jar in the project's target directory.
(3) I ran the JAR with java -jar my-project-0.1-SNAPSHOT-jar-with-dependencies.jar
Hope it helps someone on earth. In my case jQuery and $ were available but not when the plugin bootstrapped so I wrapped everything inside a setTimeout. Wrapping inside setTimeout helped me fix the error:
setTimeout(() => {
/** Your code goes here */
!function(t, e) {
}(window);
})
$('controlCheckBox').click(function(){
var temp = $(this).prop('checked');
$('controlledCheckBoxes').prop('checked', temp);
});
Solve the error No bundle URL present
by:
rm -rf ios/build/; kill $(lsof -t -i:8081); react-native run-ios
echo "alias rni=\"kill \$(lsof -t -i:8081); rm -rf ios/build/; react-native run-ios\"" >> ~/.bashrc; source ~/.bashrc
Now you can run React Native iOS build (without worrying about some of the common red error screens of death appearing) with a simple alias shortcut:
rni
Better way to reset your form with jQuery is Simply trigger
a reset
event on your form.
$("#btn1").click(function () {
$("form").trigger("reset");
});
I resolved all of my issues by adding this into project.properties
cordova.system.library.7=com.android.support:appcompat-v7:27.1.0
Try connecting without any password:
mysql -u root
I believe the initial default is no password for the root account (which should obviously be changed as soon as possible).
Based on saikirans solution, I have written this, which helped me. On the .m file:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if(selectedRowIndex && indexPath.row == selectedRowIndex.row) {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
selectedRowIndex = nil;
}
else { self.selectedRowIndex = [indexPath retain]; }
[tableView beginUpdates];
[tableView endUpdates];
}
And on the header file:
@property (retain, nonatomic) NSIndexPath* selectedRowIndex;
I am not very experienced either, so double check for memory leaks etc.
.
character as a wildcard to match any single character.Example regex: a.c
abc // match
a c // match
azc // match
ac // no match
abbc // no match
[]
to match any characters in a set.\w
to match any single alphanumeric character: 0-9
, a-z
, A-Z
, and _
(underscore).\d
to match any single digit.\s
to match any single whitespace character.Example 1 regex: a[bcd]c
abc // match
acc // match
adc // match
ac // no match
abbc // no match
Example 2 regex: a[0-7]c
a0c // match
a3c // match
a7c // match
a8c // no match
ac // no match
a55c // no match
Use the hat in square brackets [^]
to match any single character except for any of the characters that come after the hat ^
.
Example regex: a[^abc]c
aac // no match
abc // no match
acc // no match
a c // match
azc // match
ac // no match
azzc // no match
(Don't confuse the ^
here in [^]
with its other usage as the start of line character: ^
= line start, $
= line end.)
Use the optional character ?
after any character to specify zero or one occurrence of that character. Thus, you would use .?
to match any single character optionally.
Example regex: a.?c
abc // match
a c // match
azc // match
ac // match
abbc // no match
Not knowing exactly what you're trying to achieve, I would suggest looking into the possibility of redesigning you application to use composition rather than inheritance in this case.
Here is a code to get the child elements (In java):
String childTag = childElement.getTagName();
if(childTag.equals("html"))
{
return "/html[1]"+current;
}
WebElement parentElement = childElement.findElement(By.xpath(".."));
List<WebElement> childrenElements = parentElement.findElements(By.xpath("*"));
int count = 0;
for(int i=0;i<childrenElements.size(); i++)
{
WebElement childrenElement = childrenElements.get(i);
String childrenElementTag = childrenElement.getTagName();
if(childTag.equals(childrenElementTag))
{
count++;
}
}
first of all;
a Fragment
must be inside a FragmentActivity
, that's the first rule,
a FragmentActivity
is quite similar to a standart Activity
that you already know, besides having some Fragment oriented methods
second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView
, where you inflate your layout, think of it as the setContentLayout
here is an example:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.fragment_layout, container, false); return mView; }
and continu your work based on that mView, so to find a View
by id, call mView.findViewById(..);
for the FragmentActivity
part:
the xml part "must" have a FrameLayout
in order to inflate a fragment in it
<FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" > </FrameLayout>
as for the inflation part
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();
begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site
collections.defaultdict
can be sub-classed to make a nested dict. Then add any useful iteration methods to that class.
>>> from collections import defaultdict
>>> class nesteddict(defaultdict):
def __init__(self):
defaultdict.__init__(self, nesteddict)
def walk(self):
for key, value in self.iteritems():
if isinstance(value, nesteddict):
for tup in value.walk():
yield (key,) + tup
else:
yield key, value
>>> nd = nesteddict()
>>> nd['new jersey']['mercer county']['plumbers'] = 3
>>> nd['new jersey']['mercer county']['programmers'] = 81
>>> nd['new jersey']['middlesex county']['programmers'] = 81
>>> nd['new jersey']['middlesex county']['salesmen'] = 62
>>> nd['new york']['queens county']['plumbers'] = 9
>>> nd['new york']['queens county']['salesmen'] = 36
>>> for tup in nd.walk():
print tup
('new jersey', 'mercer county', 'programmers', 81)
('new jersey', 'mercer county', 'plumbers', 3)
('new jersey', 'middlesex county', 'programmers', 81)
('new jersey', 'middlesex county', 'salesmen', 62)
('new york', 'queens county', 'salesmen', 36)
('new york', 'queens county', 'plumbers', 9)
That's because $_POST
is pre-populated with form data.
To get JSON data (or any raw input), use php://input
.
$json = json_decode(file_get_contents("php://input"));
You should use this command to set the global installation flocation of npm packages
(git bash) npm config --global set prefix </path/you/want/to/use>/npm
(cmd/git-cmd) npm config --global set prefix <drive:\path\you\want\to\use>\npm
You may also consider the npm-cache
location right next to it. (as would be in a normal nodejs installation on windows)
(git bash) npm config --global set cache </path/you/want/to/use>/npm-cache
(cmd/git-cmd) npm config --global set cache <drive:\path\you\want\to\use>\npm-cache
You need to enclose your <parent>
elements in a surrounding element as XML Documents can have only one root node:
<parents> <!-- I've added this tag -->
<parent>
<child>
Text
</child>
</parent>
<parent>
<child>
<grandchild>
Text
</grandchild>
<grandchild>
Text
</grandchild>
</child>
<child>
Text
</child>
</parent>
</parents> <!-- I've added this tag -->
As you're receiving this markup from somewhere else, rather than generating it yourself, you may have to do this yourself by treating the response as a string and wrapping it with appropriate tags, prior to attempting to parse it as XML.
So, you've a couple of choices:
<parent>
node) and process each as a distinct XML DocumentTry this:
package example.spin.spinnerexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
String[] bankNames={"BOI","SBI","HDFC","PNB","OBC"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Getting the instance of Spinner and applying OnItemSelectedListener on it
Spinner spin = (Spinner) findViewById(R.id.simpleSpinner);
spin.setOnItemSelectedListener(this);
//Creating the ArrayAdapter instance having the bank name list
ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,bankNames);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spin.setAdapter(aa);
}
//Performing action onItemSelected and onNothing selected
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position,long id) {
Toast.makeText(getApplicationContext(), bankNames[position], Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
activity_main.xml:-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<Spinner
android:id="@+id/simpleSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp" />
</RelativeLayout>
May I suggest Node ORM?
https://github.com/dresende/node-orm2
There's documentation on the Readme, supports MySQL, PostgreSQL and SQLite.
MongoDB is available since version 2.1.x (released in July 2013)
UPDATE: This package is no longer maintained, per the project's README. It instead recommends bookshelf and sequelize
It's HTML character references for encoding a character by its decimal code point
Look at the ASCII table here and you'll see that 39 (hex 0x27, octal 47) is the code for apostrophe
Well, deleting an element from array is basically just set difference with one element.
array_diff( [312, 401, 15, 401, 3], [401] ) // removing 401 returns [312, 15, 3]
It generalizes nicely, you can remove as many elements as you like at the same time, if you want.
Disclaimer: Note that my solution produces a new copy of the array while keeping the old one intact in contrast to the accepted answer which mutates. Pick the one you need.
You should use the StringFormat
on the Binding
. You can use either standard string formats, or custom string formats:
<TextBox Text="{Binding Value, StringFormat=N2}" />
<TextBox Text="{Binding Value, StringFormat={}{0:#,#.00}}" />
Note that the StringFormat
only works when the target property is of type string. If you are trying to set something like a Content
property (typeof(object)
), you will need to use a custom StringFormatConverter
(like here), and pass your format string as the ConverterParameter
.
Edit for updated question
So, if your ViewModel
defines the precision, I'd recommend doing this as a MultiBinding
, and creating your own IMultiValueConverter
. This is pretty annoying in practice, to go from a simple binding to one that needs to be expanded out to a MultiBinding
, but if the precision isn't known at compile time, this is pretty much all you can do. Your IMultiValueConverter
would need to take the value, and the precision, and output the formatted string. You'd be able to do this using String.Format
.
However, for things like a ContentControl
, you can much more easily do this with a Style
:
<Style TargetType="{x:Type ContentControl}">
<Setter Property="ContentStringFormat"
Value="{Binding Resolution, StringFormat=N{0}}" />
</Style>
Any control that exposes a ContentStringFormat
can be used like this. Unfortunately, TextBox
doesn't have anything like that.
Simply in the "Find what:" field, type \r
. This means "Ends of the Row". In the "Replace with:" field, you put what you want for instance .xml
if you have several lines, and you are aiming to add that text to the end of the each line, you need to markup the option ". matches newline" in the "Search Mode" group box.
Example:
You have a file name list, but you want to add an extension like .xml. This would be what you need to do and Bang! One shot!:
getClass() has the restriction that objects are only equal to other objects of the same class, the same run time type, as illustrated in the output of below code:
class ParentClass{
}
public class SubClass extends ParentClass{
public static void main(String []args){
ParentClass parentClassInstance = new ParentClass();
SubClass subClassInstance = new SubClass();
if(subClassInstance instanceof ParentClass){
System.out.println("SubClass extends ParentClass. subClassInstance is instanceof ParentClass");
}
if(subClassInstance.getClass() != parentClassInstance.getClass()){
System.out.println("Different getClass() return results with subClassInstance and parentClassInstance ");
}
}
}
Outputs:
SubClass extends ParentClass. subClassInstance is instanceof ParentClass.
Different getClass() return results with subClassInstance and parentClassInstance.
Well, note that the request contains binary data, so I'm not posting the request as such - instead, I've converted every non-printable-ascii character into a dot (".").
POST /cgi-bin/qtest HTTP/1.1
Host: aram
User-Agent: Mozilla/5.0 Gecko/2009042316 Firefox/3.0.10
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://aram/~martind/banner.htm
Content-Type: multipart/form-data; boundary=2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Length: 514
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile1"; filename="r.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile2"; filename="g.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile3"; filename="b.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f--
Note that every line (including the last one) is terminated by a \r\n sequence.
This works like a charm, fast and accurate:
function replace_string_in_file($filename, $string_to_replace, $replace_with){
$content=file_get_contents($filename);
$content_chunks=explode($string_to_replace, $content);
$content=implode($replace_with, $content_chunks);
file_put_contents($filename, $content);
}
Usage:
$filename="users/data/letter.txt";
$string_to_replace="US$";
$replace_with="Yuan";
replace_string_in_file($filename, $string_to_replace, $replace_with);
// never forget about EXPLODE when it comes about string parsing // it's a powerful and fast tool
/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/
Just for reference.
The joys of Maven.
Putting the relative path of the modules to ../pom.xml solved it.
The parent
element has a relativePath
element that you need to point to the directory of the parent. It defaults to ..
As of jQuery 1.7 you should use jQuery.fn.on
with the selector parameter filled:
$(staticAncestors).on(eventName, dynamicChild, function() {});
Explanation:
This is called event delegation and works as followed. The event is attached to a static parent (staticAncestors
) of the element that should be handled. This jQuery handler is triggered every time the event triggers on this element or one of the descendant elements. The handler then checks if the element that triggered the event matches your selector (dynamicChild
). When there is a match then your custom handler function is executed.
Prior to this, the recommended approach was to use live()
:
$(selector).live( eventName, function(){} );
However, live()
was deprecated in 1.7 in favour of on()
, and completely removed in 1.9. The live()
signature:
$(selector).live( eventName, function(){} );
... can be replaced with the following on()
signature:
$(document).on( eventName, selector, function(){} );
For example, if your page was dynamically creating elements with the class name dosomething
you would bind the event to a parent which already exists (this is the nub of the problem here, you need something that exists to bind to, don't bind to the dynamic content), this can be (and the easiest option) is document
. Though bear in mind document
may not be the most efficient option.
$(document).on('mouseover mouseout', '.dosomething', function(){
// what you want to happen when mouseover and mouseout
// occurs on elements that match '.dosomething'
});
Any parent that exists at the time the event is bound is fine. For example
$('.buttons').on('click', 'button', function(){
// do something here
});
would apply to
<div class="buttons">
<!-- <button>s that are generated dynamically and added here -->
</div>
There is no command to do it (like you would do it with MySQL for instance). The number of Redis databases is fixed, and set in the configuration file. By default, you have 16 databases. Each database is identified by a number (not a name).
You can use the following command to know the number of databases:
CONFIG GET databases
1) "databases"
2) "16"
You can use the following command to list the databases for which some keys are defined:
INFO keyspace
# Keyspace
db0:keys=10,expires=0
db1:keys=1,expires=0
db3:keys=1,expires=0
Please note that you are supposed to use the "redis-cli" client to run these commands, not telnet. If you want to use telnet, then you need to run these commands formatted using the Redis protocol.
For instance:
*2
$4
INFO
$8
keyspace
$79
# Keyspace
db0:keys=10,expires=0
db1:keys=1,expires=0
db3:keys=1,expires=0
You can find the description of the Redis protocol here: http://redis.io/topics/protocol
<script type="text/javascript">
$('.datepicker').datepicker({
format: 'dd/mm/yyyy',
todayHighlight:'TRUE',
startDate: '-0d',
autoclose: true,
})
Based on Wikipedia's articles.
A greedy algorithm is an algorithm that follows the problem solving heuristic of making the locally optimal choice at each stage with the hope of finding a global optimum. In many problems, a greedy strategy does not in general produce an optimal solution, but nonetheless a greedy heuristic may yield locally optimal solutions that approximate a global optimal solution in a reasonable time.
We can make whatever choice seems best at the moment and then solve the subproblems that arise later. The choice made by a greedy algorithm may depend on choices made so far but not on future choices or all the solutions to the subproblem. It iteratively makes one greedy choice after another, reducing each given problem into a smaller one.
The idea behind dynamic programming is quite simple. In general, to solve a given problem, we need to solve different parts of the problem (subproblems), then combine the solutions of the subproblems to reach an overall solution. Often when using a more naive method, many of the subproblems are generated and solved many times. The dynamic programming approach seeks to solve each subproblem only once, thus reducing the number of computations: once the solution to a given subproblem has been computed, it is stored or "memo-ized": the next time the same solution is needed, it is simply looked up. This approach is especially useful when the number of repeating subproblems grows exponentially as a function of the size of the input.
We can make whatever choice seems best at the moment and then solve the subproblems that arise later. The choice made by a greedy algorithm may depend on choices made so far but not on future choices or all the solutions to the subproblem. It iteratively makes one greedy choice after another, reducing each given problem into a smaller one. In other words, a greedy algorithm never reconsiders its choices.
This is the main difference from dynamic programming, which is exhaustive and is guaranteed to find the solution. After every stage, dynamic programming makes decisions based on all the decisions made in the previous stage, and may reconsider the previous stage's algorithmic path to solution.
For example, let's say that you have to get from point A to point B as fast as possible, in a given city, during rush hour. A dynamic programming algorithm will look into the entire traffic report, looking into all possible combinations of roads you might take, and will only then tell you which way is the fastest. Of course, you might have to wait for a while until the algorithm finishes, and only then can you start driving. The path you will take will be the fastest one (assuming that nothing changed in the external environment).
On the other hand, a greedy algorithm will start you driving immediately and will pick the road that looks the fastest at every intersection. As you can imagine, this strategy might not lead to the fastest arrival time, since you might take some "easy" streets and then find yourself hopelessly stuck in a traffic jam.
In mathematical optimization, greedy algorithms solve combinatorial problems having the properties of matroids.
Dynamic programming is applicable to problems exhibiting the properties of overlapping subproblems and optimal substructure.
If all else fails try moving (i.e. in bash) all files and directories "away" and adding them back one by one.
I just found out that way that my .htaccess file was referencing a non-existant .htpasswd file. (#silly)
In your template, you have access to all the variables that are members of the current $scope
. So, tobedone
should be $scope.tobedone
, and then you can display it with {{tobedone}}
, or [[tobedone]]
in your case.
In your js/ts file for the html that will be hovered
@Output() elemHovered: EventEmitter<any> = new EventEmitter<any>();
onHoverEnter(): void {
this.elemHovered.emit([`The button was entered!`,this.event]);
}
onHoverLeave(): void {
this.elemHovered.emit([`The button was left!`,this.event])
}
In your HTML that will be hovered
(mouseenter) = "onHoverEnter()" (mouseleave)="onHoverLeave()"
In your js/ts file that will receive info of the hovering
elemHoveredCatch(d): void {
console.log(d)
}
In your HTML element that is connected with catching js/ts file
(elemHovered) = "elemHoveredCatch($event)"
you can create zip file by using following command .It will create zip file of database {dbname} provided.You can later import the following zip file in you mongo DB.
Window filepath=C:\Users\Username\mongo
mongodump --archive={filepath}\+{filename}.gz --gzip --db {dbname}
$before = microtime(true);
$n = 1000;
$numbers = range(1,$n);
$cube_numbers = array_map('cube',$numbers);
function cube($n){
$msg ='even';
if($n%2 !=0){
$msg = 'odd';
}
return "The Number is $n is ".$msg;
}
foreach($cube_numbers as $cube){
echo $cube . "<br/>";
}
$after = microtime(true);
echo $after-$before. 'seconds';
It is important to know not only the types but the mapping of these types to the database types, too:
Source added - Agile Web Development with Rails 4
LocalDateTime.parse( // Parse into an object representing a date with a time-of-day but without time zone and without offset-from-UTC.
"2014/10/29 18:10:45" // Convert input string to comply with standard ISO 8601 format.
.replace( " " , "T" ) // Replace SPACE in the middle with a `T`.
.replace( "/" , "-" ) // Replace SLASH in the middle with a `-`.
)
.atZone( // Apply a time zone to provide the context needed to determine an actual moment.
ZoneId.of( "Europe/Oslo" ) // Specify the time zone you are certain was intended for that input.
) // Returns a `ZonedDateTime` object.
.toInstant() // Adjust into UTC.
.toEpochMilli() // Get the number of milliseconds since first moment of 1970 in UTC, 1970-01-01T00:00Z.
1414602645000
The accepted answer is correct, except that it ignores the crucial issue of time zone. Is your input string 6:10 PM in Paris or Montréal? Or UTC?
Use a proper time zone name. Usually a continent plus city/region. For example, "Europe/Oslo"
. Avoid the 3 or 4 letter codes which are neither standardized nor unique.
The modern approach uses the java.time classes.
Alter your input to conform with the ISO 8601 standard. Replace the SPACE in the middle with a T
. And replace the slash characters with hyphens. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.
String input = "2014/10/29 18:10:45".replace( " " , "T" ).replace( "/" , "-" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;
A LocalDateTime
, like your input string, lacks any concept of time zone or offset-from-UTC. Without the context of a zone/offset, a LocalDateTime
has no real meaning. Is it 6:10 PM in India, Europe, or Canada? Each of those places experience 6:10 PM at different moments, at different points on the timeline. So you must specify which you have in mind if you want to determine a specific point on the timeline.
ZoneId z = ZoneId.of( "Europe/Oslo" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
Now we have a specific moment, in that ZonedDateTime
. Convert to UTC by extracting a Instant
. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = zdt.toInstant() ;
Now we can get your desired count of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z.
long millisSinceEpoch = instant.toEpochMilli() ;
Be aware of possible data loss. The Instant
object is capable of carrying microseconds or nanoseconds, finer than milliseconds. That finer fractional part of a second will be ignored when getting a count of milliseconds.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Update: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. I will leave this section intact for history.
Below is the same kind of code but using the Joda-Time 2.5 library and handling time zone.
The java.util.Date, .Calendar, and .SimpleDateFormat classes are notoriously troublesome, confusing, and flawed. Avoid them. Use either Joda-Time or the java.time package (inspired by Joda-Time) built into Java 8.
Your string is almost in ISO 8601 format. The slashes need to be hyphens and the SPACE in middle should be replaced with a T
. If we tweak that, then the resulting string can be fed directly into constructor without bothering to specify a formatter. Joda-Time uses ISO 8701 formats as it's defaults for parsing and generating strings.
String inputRaw = "2014/10/29 18:10:45";
String input = inputRaw.replace( "/", "-" ).replace( " ", "T" );
DateTimeZone zone = DateTimeZone.forID( "Europe/Oslo" ); // Or DateTimeZone.UTC
DateTime dateTime = new DateTime( input, zone );
long millisecondsSinceUnixEpoch = dateTime.getMillis();
C:\>help if
Performs conditional processing in batch programs.
IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXIST filename command
Use the native PHP $_SERVER['HTTP_USER_AGENT']
variable instead.
After setting the path with the Maven bin location close the prompt window and restart it. Use the echo %path%
command to make sure the path is set with Maven variables then run the command mvn -version
. Somehow if the path is set when the prompt window is running it does not pick the new variables.
it's as simple as not using a table for markup, as stated by Harmen. You're not displaying data after all, you're collecting data.
I'll take for example the question 23 here: http://accessible.netscouts-ggmbh.eu/en/developer.html#fb1_22_5
On paper, it's good as it is. If you had to display the results, it'd probably be OK.
But you can replace it with ... 4 paragraphs with a label and a select (option's would be the headers of the first line). One paragraph per line, this is far more simple.
Simply use
java.util.Collections.sort(list)
without String.CASE_INSENSITIVE_ORDER comparator parameter.
You create a primary key on your fields and let the engine enforce the uniqueness. Doing IF EXISTS logic is incorrect anyway as is flawed with race conditions.
I sometime use this method:
// It is not importnat what timezone your system is set to.
// Get the UTC offset in seconds:
$offset = date("Z");
// Then subtract if from your original timestamp:
$utc_time = date("Y-m-d H:i:s", strtotime($original_time." -".$offset." Seconds"));
Works all MOST of the time.
Like Snukker said, clients1.google.com is where the search suggestions come from. My guess is that they make a request to force clients1.google.com into your DNS cache before you need it, so you will have less latency on the first "real" request.
Google Chrome already does that for any links on a page, and (I think) when you type an address in the location bar. This seems like a way to get all browsers to do the same thing.
try {
InputStream connInputStream = connection.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
int size = connInputStream.available();
int available () Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes.
In entity framework, when object is added to context, its state changes to Added. EF also changes state of each object to added in object tree and hence you are either getting primary key violation error or duplicate records are added in table.
Use std::map<OS_type, std::string>
and populate it with enum as key, and string representation as values, then you can do these:
printf("My OS is %s", enumMap[myOS].c_str());
std::cout << enumMap[myOS] ;
Alternatively, consider using a document databases (such as MongoDB) which natively support rich data structures and nesting.
What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut
or via an instance e.g. shape.lolwut
but be careful while setting it as it will set an instance level attribute not class attribute
class Shape(object):
lolwut = 1
shape = Shape()
print Shape.lolwut, # 1
print shape.lolwut, # 1
# setting shape.lolwut would not change class attribute lolwut
# but will create it in the instance
shape.lolwut = 2
print Shape.lolwut, # 1
print shape.lolwut, # 2
# to change class attribute access it via class
Shape.lolwut = 3
print Shape.lolwut, # 3
print shape.lolwut # 2
output:
1 1 1 2 3 2
Somebody may expect output to be 1 1 2 2 3 3
but it would be incorrect
You have a couple of questions here, so I'll address them separately:
My general rule is: don't. This is something which all but requires a second table (or third) with a foreign key. Sure, it may seem easier now, but what if the use case comes along where you need to actually query for those items individually? It also means that you have more options for lazy instantiation and you have a more consistent experience across multiple frameworks/languages. Further, you are less likely to have connection timeout issues (30,000 characters is a lot).
You mentioned that you were thinking about using ENUM. Are these values fixed? Do you know them ahead of time? If so this would be my structure:
Base table (what you have now):
| id primary_key sequence
| -- other columns here.
Items table:
| id primary_key sequence
| descript VARCHAR(30) UNIQUE
Map table:
| base_id bigint
| items_id bigint
Map table would have foreign keys so base_id maps to Base table, and items_id would map to the items table.
And if you'd like an easy way to retrieve this from a DB, then create a view which does the joins. You can even create insert and update rules so that you're practically only dealing with one table.
If you have to do something like this, why not just use a character delineated string? It will take less processing power than a CSV, XML, or JSON, and it will be shorter.
Personally, I would use TEXT
. It does not sound like you'd gain much by making this a BLOB
, and TEXT
, in my experience, is easier to read if you're using some form of IDE.
If this code fails to operate on every item in the list, it must be because something is throwing an exception before you have completed the list; the likeliest candidate is the method called "insertOrThrow". You could wrap that call in a try-catch structure to handle the exception for whichever items are failing without exiting the loop and the method prematurely.
CREATE TABLE dbo.OwnerType
(
ID int NOT NULL,
Name varchar(50) NULL
)
insert into OwnerType (Name) values ('User');
insert into OwnerType (Name) values ('Group');
I think that would be the most general way to represent what you want instead of using a flag.
The default shell for the RUN
instruction is ["/bin/sh", "-c"]
.
RUN "source file" # translates to: RUN /bin/sh -c "source file"
Using SHELL instruction, you can change default shell for subsequent RUN
instructions in Dockerfile:
SHELL ["/bin/bash", "-c"]
Now, default shell has changed and you don't need to explicitly define it in every RUN instruction
RUN "source file" # now translates to: RUN /bin/bash -c "source file"
Additional Note: You could also add --login
option which would start a login shell. This means ~/.bachrc
for example would be read and you don't need to source it explicitly before your command
Using aggregate function like below :
[
{$group: {_id : {book : '$book',address:'$addr'}, total:{$sum :1}}},
{$project : {book : '$_id.book', address : '$_id.address', total : '$total', _id : 0}}
]
it will give you result like following :
{
"total" : 1,
"book" : "book33",
"address" : "address90"
},
{
"total" : 1,
"book" : "book5",
"address" : "address1"
},
{
"total" : 1,
"book" : "book99",
"address" : "address9"
},
{
"total" : 1,
"book" : "book1",
"address" : "address5"
},
{
"total" : 1,
"book" : "book5",
"address" : "address2"
},
{
"total" : 1,
"book" : "book3",
"address" : "address4"
},
{
"total" : 1,
"book" : "book11",
"address" : "address77"
},
{
"total" : 1,
"book" : "book9",
"address" : "address3"
},
{
"total" : 1,
"book" : "book1",
"address" : "address15"
},
{
"total" : 2,
"book" : "book1",
"address" : "address2"
},
{
"total" : 3,
"book" : "book1",
"address" : "address1"
}
I didn't quite get your expected result format, so feel free to modify this to one you need.
My solution is:
events: {
'apply.daterangepicker #selector': 'function'
}
All those answers are good, but in fact, if you want to understand, the extension directory need to be right if you want all you uncommented extensions to work. Can write a physical or relative path like
extension_dir = "C:/myStack/php/ext"
or
extension_dir = "../../php/ext"
It's relative to the httpd.exe Apache web server (C:\myStack\apache\bin) But if you want it to work with Composer or anything you need the physical path because the cli mode doesn't use the web server !
You may be overcomplicating things, is there any reason you need the stringr package?
df <- data.frame(Date = c("10/9/2009 0:00:00", "10/15/2009 0:00:00"))
as.Date(df$Date, "%m/%d/%Y %H:%M:%S")
[1] "2009-10-09" "2009-10-15"
More generally and if you need the time component as well, use strptime:
strptime(df$Date, "%m/%d/%Y %H:%M:%S")
I'm guessing at what your actual data might look at from the partial results you give.
Best to avoid placing the right column before the left, simply use a negative right-margin.
And be "responsive" by including an @media setting so the right column falls under the left on narrow screens.
<div style="background: #f1f2ea;">
<div id="container">
<div id="content">
<strong>Column 1 - content</strong>
</div>
</div>
<div id="sidebar">
<strong>Column 2 - sidebar</strong>
</div>
<div style="clear:both"></div>
<style type="text/css">
#container {
margin-right: -300px;
float:left;
width:100%;
}
#content {
margin-right: 320px; /* 20px added for center margin */
}
#sidebar {
width:300px;
float:left
}
@media (max-width: 480px) {
#container {
margin-right:0px;
margin-bottom:20px;
}
#content {
margin-right:0px;
width:100%;
}
#sidebar {
clear:left;
}
}
</style>
Use replace(/\s+/g,'')
,
for example:
const stripped = ' My String With A Lot Whitespace '.replace(/\s+/g, '')// 'MyStringWithALotWhitespace'
There's several things you can improve upon here. To start, there's no reason to use an <a>
(anchor) tag since you don't have a link.
Every element can be bound to click and hover events... divs, spans, labels, inputs, etc.
I can't really identify what it is you're trying to do, though. You're mixing the goal with your own implementation and, from what I've seen so far, you're not really sure how to do it. Could you better illustrate what it is you're trying to accomplish?
== EDIT ==
The requirements are still very vague. I've implemented a very quick version of what I'm imagining you're saying ... or something close that illustrates how you might be able to do it. Left me know if I'm on the right track.
The File
class represents the "idea" of a file, not an actual handle to use for I/O. This is why the File
class has a .exists()
method, to tell you if the file exists or not. (How can you have a File
object that doesn't exist?)
By contrast, constructing a new FileInputStream(new File("/my/file"))
gives you an actual stream to read bytes from.
You can try this nice little trick for C++. Take the expression which gives you the array and then append a comma and the number of elements you want to see. Expanding that value will show you elements 0-(N-1) where N is the number you add after the comma.
For example if pArray
is the array, type pArray,10
in the watch window.
I encounter this problem, because I have <VirtualHost>
defined both in httpd.conf and httpd-ssl.conf.
in httpd.conf, it's defined as
<VirtualHost localhost>
in httpd-ssl.conf, it's defined as
<VirtualHost _default_:443>
The following change solved this problem, add :80 in httpd.conf
<VirtualHost localhost:80>
This error is very non-descriptive but the key here is that 'ID' is in uppercase. This indicates that the route has not been correctly set up. To let the application handle URLs with an id, you need to make sure that there's at least one route configured for it. You do this in the RouteConfig.cs located in the App_Start folder. The most common is to add the id as an optional parameter to the default route.
public static void RegisterRoutes(RouteCollection routes)
{
//adding the {id} and setting is as optional so that you do not need to use it for every action
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Now you should be able to redirect to your controller the way you have set it up.
[HttpPost]
public ActionResult RedirectToImages(int id)
{
return RedirectToAction("Index","ProductImageManager", new { id });
//if the action is in the same controller, you can omit the controller:
//RedirectToAction("Index", new { id });
}
In one or two occassions way back I ran into some issues by normal redirect and had to resort to doing it by passing a RouteValueDictionary. More information on RedirectToAction with parameter
return RedirectToAction("Index", new RouteValueDictionary(
new { controller = "ProductImageManager", action = "Index", id = id } )
);
If you get a very similar error but in lowercase 'id', this is usually because the route expects an id parameter that has not been provided (calling a route without the id /ProductImageManager/Index
). See this so question for more information.
Simplest form:
<input :required="test"> // if true
<input :required="!test"> // if false
<input :required="!!test"> // test ? true : false
Using Git for version control
Visual studio code have Integrated Git Support.
Install Git : https://git-scm.com/downloads
1) Initialize your repository
Navigate to directory where you want to initialize Git
Use git init command This will create a empty .git repository
2) Stage the changes
Staging is process of making Git to track our newly added files. For example add a file and type git status. You will find the status that untracked file. So to stage the changes use git add filename. If now type git status, you will find that new file added for tracking.
You can also unstage files. Use git reset
3) Commit Changes
Commiting is the process of recording your changes to repository. To commit the statges changes, you need to add a comment that explains the changes you made since your previous commit.
Use git commit -m message string
We can also commit the multiple files of same type using command git add '*.txt'. This command will commit all files with txt extension.
4) Follow changes
The aim of using version control is to keep all versions of each and every file in our project, Compare the the current version with last commit and keep the log of all changes.
Use git log to see the log of all changes.
Visual studio code’s integrated git support help us to compare the code by double clicking on the file OR Use git diff HEAD
You can also undo file changes at the last commit. Use git checkout -- file_name
5) Create remote repositories
Till now we have created a local repository. But in order to push it to remote server. We need to add a remote repository in server.
Use git remote add origin server_git_url
Then push it to server repository
Use git push -u origin master
Let assume some time has passed. We have invited other people to our project who have pulled our changes, made their own commits, and pushed them.
So to get the changes from our team members, we need to pull the repository.
Use git pull origin master
6) Create Branches
Lets think that you are working on a feature or a bug. Better you can create a copy of your code(Branch) and make separate commits to. When you have done, merge this branch back to their master branch.
Use git branch branch_name
Now you have two local branches i.e master and XXX(new branch). You can switch branches using git checkout master OR git checkout new_branch_name
Commiting branch changes using git commit -m message
Switch back to master using git checkout master
Now we need to merge changes from new branch into our master Use git merge branch_name
Good! You just accomplished your bugfix Or feature development and merge. Now you don’t need the new branch anymore. So delete it using git branch -d branch_name
Now we are in the last step to push everything to remote repository using git push
Hope this will help you
You can do something like this to check if any mysql
process is running or not:
ps aux | grep mysqld
ps aux | grep mysql
Then if it is running you can killall
by using(depending on what all processes are running currently):
killall -9 mysql
killall -9 mysqld
killall -9 mysqld_safe
SELECT IDENT_CURRENT('databasename.dbo.tablename') AS your identity column;
Recursive Python solution
def permute(input_str):
_permute("", input_str)
def _permute(prefix, str_to_permute):
if str_to_permute == '':
print(prefix)
else:
for i in range(len(str_to_permute)):
_permute(prefix+str_to_permute[i], str_to_permute[0:i] + str_to_permute[i+1:])
if __name__ == '__main__':
permute('foobar')
I had this same error and the problem was simply not enough space on my virtual machine. I deleted some unnecessary files and it started working again.
my memory/disk space allocation looked something like this
df -h
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/centos-root 37G 37G 127M 100% /
...
CAST datetime field to date
select CAST(datetime_field as DATE), count(*) as count from table group by CAST(datetime_field as DATE);
Just add
spring.flyway.enabled=false
in application.properties file if you do not want flyway to check the checksum every time you run the application.
While most people have answered the question directly, I wanted to elaborate more on the concept behind it. First, I was drawn to the attention of IME when I created a default Login Activity. It generated some code for me which included the following:
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/prompt_password"
android:imeActionId="@+id/login"
android:imeActionLabel="@string/action_sign_in_short"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true"/>
You should already be familiar with the inputType attribute. This just informs Android the type of text expected such as an email address, password or phone number. The full list of possible values can be found here.
It was, however, the attribute imeOptions="actionUnspecified"
that I didn't understand its purpose. Android allows you to interact with the keyboard that pops up from bottom of screen when text is selected using the InputMethodManager
. On the bottom corner of the keyboard, there is a button, typically it says "Next" or "Done", depending on the current text field. Android allows you to customize this using android:imeOptions
. You can specify a "Send" button or "Next" button. The full list can be found here.
With that, you can then listen for presses on the action button by defining a TextView.OnEditorActionListener
for the EditText
element. As in your example:
editText.setOnEditorActionListener(new EditText.OnEditorActionListener() {
@Override
public boolean onEditorAction(EditText v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
//do here your stuff f
return true;
}
return false;
}
});
Now in my example I had android:imeOptions="actionUnspecified"
attribute. This is useful when you want to try to login a user when they press the enter key. In your Activity, you can detect this tag and then attempt the login:
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Try the Following Code Please.
just only update two values.
1.your_database_name
2.table_name
<?php
$host="localhost";
$username="root";
$password="";
$dbname="your_database_name";
$con = new mysqli($host, $username, $password,$dbname);
$sql_data="select * from table_name";
$result_data=$con->query($sql_data);
$results=array();
filename = "Webinfopen.xls"; // File Name
// Download file
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
while ($row = mysqli_fetch_assoc($result_data)) {
if (!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
echo implode("\t", array_values($row)) . "\r\n";
}
?>
No you can't use case
and in
like this. But you can do
SELECT * FROM Product P
WHERE @Status='published' and P.Status IN (1,3)
or @Status='standby' and P.Status IN (2,5,9,6)
or @Status='deleted' and P.Status IN (4,5,8,10)
or P.Status IN (1,3)
BTW you can reduce that to
SELECT * FROM Product P
WHERE @Status='standby' and P.Status IN (2,5,9,6)
or @Status='deleted' and P.Status IN (4,5,8,10)
or P.Status IN (1,3)
since or P.Status IN (1,3)
gives you also all records of @Status='published' and P.Status IN (1,3)
As others have noted, you can't have immutable arrays in Java.
If you absolutely need a method that returns an array that doesn't influence the original array, then you'd need to clone the array each time:
public int[] getFooArray() {
return fooArray == null ? null : fooArray.clone();
}
Obviously this is rather expensive (as you'll create a full copy each time you call the getter), but if you can't change the interface (to use a List
for example) and can't risk the client changing your internals, then it may be necessary.
This technique is called making a defensive copy.
Check if Column Exist or not in PDO (100%)
{
if(isset($_POST['Add']))
{
$ColumnExist = $dbh->prepare("SELECT * FROM ColumnChecker where column_name='$insert_column_name' LIMIT 1");
$ColumnExist ->execute();
$ColumnName = $ColumnExist->fetch(2);
$Display_Column_Name = $ColumnName['column_name'];
if($Display_Column_Name == $insert_column_name)
{
echo "$Display_Column_Name already exist";
} //*****************************
else
{
$InsertColumn = $dbh->prepare("insert into ColumnChecker ( column_name ) values ('$insert_column_name')");
$InsertColumn->execute();
if($InsertColumn)
{
$Add = $dbh->prepare("ALTER TABLE `$Table` ADD `$insert_column_name` $insert_column_type($insert_column_Length) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ");
$Add->execute();
if($Add)
{
echo 'Table has been updated';
}
else
{
echo 'Sorry! Try again...';
}
}
}
}
}#Add Column into Table :)
It is indeed
language: {
url: '//URL_TO_CDN'
}
The problem is not all of the DataTables (As of this writing) are valid JSON. The Traditional Chinese file for instance is one of them.
To get around this I wrote the following code in JavaScript:
var dataTableLanguages = {
'es': '//cdn.datatables.net/plug-ins/1.10.21/i18n/Spanish.json',
'fr': '//cdn.datatables.net/plug-ins/1.10.21/i18n/French.json',
'ar': '//cdn.datatables.net/plug-ins/1.10.21/i18n/Arabic.json',
'zh-TW': {
"processing": "???...",
"loadingRecords": "???...",
"lengthMenu": "?? _MENU_ ???",
"zeroRecords": "???????",
"info": "??? _START_ ? _END_ ???,? _TOTAL_ ?",
"infoEmpty": "??? 0 ? 0 ???,? 0 ?",
"infoFiltered": "(? _MAX_ ??????)",
"infoPostFix": "",
"search": "??:",
"paginate": {
"first": "???",
"previous": "???",
"next": "???",
"last": "????"
},
"aria": {
"sortAscending": ": ????",
"sortDescending": ": ????"
}
}
};
var language = dataTableLanguages[$('html').attr('lang')];
var opts = {...};
if (language) {
if (typeof language === 'string') {
opts.language = {
url: language
};
} else {
opts.language = language;
}
}
Now use the opts as option object for data table like
$('#list-table').DataTable(opts)
You could use strftime
, but struct tm
doesn't have resolution for parts of seconds. I'm not sure if that's absolutely required for your purposes.
struct tm tm;
/* Set tm to the correct time */
char s[20]; /* strlen("2009-08-10 18:17:54") + 1 */
strftime(s, 20, "%F %H:%M:%S", &tm);
if you are calling from static
method, use :
TestGameTable.class.getClassLoader().getResource("dice.jpg");
Keyboard shortcuts to that are:
For copy: Place cursor on starting of block and press md and then goto end of block and press y'd. This will select the block to paste it press p
For cut: Place cursor on starting of block and press ma and then goto end of block and press d'a. This will select the block to paste it press p
Why not just use the EmailAttribute
?
[Email(ErrorMessage = "Bad email")]
public string Email { get; set; }
Robert Rossney has a good solution. Here's an alternative solution I've used in the past that separates out the "Overlay" from the rest of the content. This solution takes advantage of the attached property Panel.ZIndex
to place the "Overlay" on top of everything else. You can either set the Visibility of the "Overlay" in code or use a DataTrigger
.
<Grid x:Name="LayoutRoot">
<Grid x:Name="Overlay" Panel.ZIndex="1000" Visibility="Collapsed">
<Grid.Background>
<SolidColorBrush Color="Black" Opacity=".5"/>
</Grid.Background>
<!-- Add controls as needed -->
</Grid>
<!-- Use whatever layout you need -->
<ContentControl x:Name="MainContent" />
</Grid>
You can use CTRL+R, CTRL+R or for complex namespace changes use this tool https://marketplace.visualstudio.com/items?itemName=vs-publisher-599079.FixNamespace
The "adjustment" in adjusted R-squared is related to the number of variables and the number of observations.
If you keep adding variables (predictors) to your model, R-squared will improve - that is, the predictors will appear to explain the variance - but some of that improvement may be due to chance alone. So adjusted R-squared tries to correct for this, by taking into account the ratio (N-1)/(N-k-1) where N = number of observations and k = number of variables (predictors).
It's probably not a concern in your case, since you have a single variate.
Some references:
Vishal's example, however great, confuses when it comes to the file name, and I do not see the merit of redefing 'zipfile'.
Here is my example that downloads a zip that contains some files, one of which is a csv file that I subsequently read into a pandas DataFrame:
from StringIO import StringIO
from zipfile import ZipFile
from urllib import urlopen
import pandas
url = urlopen("https://www.federalreserve.gov/apps/mdrm/pdf/MDRM.zip")
zf = ZipFile(StringIO(url.read()))
for item in zf.namelist():
print("File in zip: "+ item)
# find the first matching csv file in the zip:
match = [s for s in zf.namelist() if ".csv" in s][0]
# the first line of the file contains a string - that line shall de ignored, hence skiprows
df = pandas.read_csv(zf.open(match), low_memory=False, skiprows=[0])
(Note, I use Python 2.7.13)
This is the exact solution that worked for me. I just tweaked it a little bit for Python 3 version by removing StringIO and adding IO library
from io import BytesIO
from zipfile import ZipFile
import pandas
import requests
url = "https://www.nseindia.com/content/indices/mcwb_jun19.zip"
content = requests.get(url)
zf = ZipFile(BytesIO(content.content))
for item in zf.namelist():
print("File in zip: "+ item)
# find the first matching csv file in the zip:
match = [s for s in zf.namelist() if ".csv" in s][0]
# the first line of the file contains a string - that line shall de ignored, hence skiprows
df = pandas.read_csv(zf.open(match), low_memory=False, skiprows=[0])
You can use the DataGridViewColumn.Width property to do it:
DataGridViewColumn column = dataGridView.Columns[0];
column.Width = 60;
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcolumn.width.aspx
By the time the query gets to SQL you have to have already expanded the list. The easy way of doing this, if you're using IDs from some internal, trusted data source, where you can be 100% certain they're integers (e.g., if you selected them from your database earlier) is this:
$sql = 'SELECT * WHERE id IN (' . implode(',', $ids) . ')';
If your data are coming from the user, though, you'll need to ensure you're getting only integer values, perhaps most easily like so:
$sql = 'SELECT * WHERE id IN (' . implode(',', array_map('intval', $ids)) . ')';
Add this at your TODO point:
aRange.Columns.AutoFit();
try to change this in your dispatcher-servlet.xml
<!-- Your View Resolver -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basenames" value="views" />
<property name="order" value="1" />
</bean>
<!-- UrlBasedViewResolver to Handle Redirects & Forward -->
<bean id="urlViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView" />
<property name="order" value="2" />
</bean>
What happens is clearly explained here http://projects.nigelsim.org/wiki/RedirectWithSpringWebMvc
str_replace
with arrays just performs all the replacements sequentially. Use strtr
instead to do them all at once:
$new_message = strtr($message, 'lmnopq...', 'abcdef...');
You can get the port number by using server.address().port
like in below code:
var http = require('http');
var serverFunction = function (req, res) {
if (req.url == '/') {
console.log('get method');
res.writeHead(200, { 'content-type': 'text/plain' });
res.end('Hello World');
}
}
var server = http.createServer(serverFunction);
server.listen(3002, function () {
console.log('server is listening on port:', server.address().port);
});
Use compareTo()
Return Values
0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument.
Like
if(date1.compareTo(date2)>0)
I have experienced the same error when trying to build the message below with jQuery. The circular reference happens when reviewerName
was being mistakenly assigned to msg.detail.reviewerName
. JQuery's .val() fixed the issue, see last line.
var reviewerName = $('reviewerName'); // <input type="text" id="taskName" />;
var msg = {"type":"A", "detail":{"managerReview":true} };
msg.detail.reviewerName = reviewerName; // Error
msg.detail.reviewerName = reviewerName.val(); // Fixed
Here is where you went wrong:
this.result = http.get('friends.json')
.map(response => response.json())
.subscribe(result => this.result =result.json());
it should be:
http.get('friends.json')
.map(response => response.json())
.subscribe(result => this.result =result);
or
http.get('friends.json')
.subscribe(result => this.result =result.json());
You have made two mistakes:
1- You assigned the observable itself to this.result
. When you actually wanted to assign the list of friends to this.result
. The correct way to do it is:
you subscribe to the observable. .subscribe
is the function that actually executes the observable. It takes three callback parameters as follow:
.subscribe(success, failure, complete);
for example:
.subscribe(
function(response) { console.log("Success Response" + response)},
function(error) { console.log("Error happened" + error)},
function() { console.log("the subscription is completed")}
);
Usually, you take the results from the success callback and assign it to your variable.
the error callback is self explanatory.
the complete callback is used to determine that you have received the last results without any errors.
On your plunker, the complete callback will always be called after either the success or the error callback.
2- The second mistake, you called .json()
on .map(res => res.json())
, then you called it again on the success callback of the observable.
.map()
is a transformer that will transform the result to whatever you return (in your case .json()
) before it's passed to the success callback
you should called it once on either one of them.
There is an interest in your solution that plot.new()
hasn't though: in the empty plot you "draw" you can write text at specified coordinates with text(x = ..., y = ..., your_text)
.
When you create new Form control, use next:
variable: FormControl = new FormControl({value: '', disabled: true});
If you want change activity, use next:
this.variable.enable()
or
this.variable.disable()
I use this for Windows (binary prefixes):
static readonly string[] BinaryPrefix = { "bytes", "KB", "MB", "GB", "TB" }; // , "PB", "EB", "ZB", "YB"
string GetMemoryString(double bytes)
{
int counter = 0;
double value = bytes;
string text = "";
do
{
text = value.ToString("0.0") + " " + BinaryPrefix[counter];
value /= 1024;
counter++;
}
while (Math.Floor(value) > 0 && counter < BinaryPrefix.Length);
return text;
}
To create a new object you can either use placement new, as mentioned above, or have your class implement a clone() method that creates a copy of the object. You can then call this clone method using a member function pointer as explained above to create new instances of the object. The advantage of clone is that sometimes you may be working with a pointer to a base class where you don't know the type of the object. In this case a clone() method can be easier to use. Also, clone() will let you copy the state of the object if that is what you want.
I used list-style
on both the ul and the li to remove the bullets. I wanted to replace the bullets with a custom character, in this case a 'dash'. That gives a nicely indented effect that works fine when the text wraps.
ul.dashed-list {
list-style: none outside none;
}
ul.dashed-list li:before {
content: "\2014";
float: left;
margin: 0 0 0 -27px;
padding: 0;
}
ul.dashed-list li {
list-style-type: none;
}
_x000D_
<ul class="dashed-list">
<li>text</li>
<li>text</li>
</ul>
_x000D_
You can use COLLATE NOCASE
in your SELECT
query:
SELECT * FROM ... WHERE name = 'someone' COLLATE NOCASE
Additionaly, in SQLite, you can indicate that a column should be case insensitive when you create the table by specifying collate nocase
in the column definition (the other options are binary
(the default) and rtrim
; see here). You can specify collate nocase
when you create an index as well. For example:
create table Test ( Text_Value text collate nocase ); insert into Test values ('A'); insert into Test values ('b'); insert into Test values ('C'); create index Test_Text_Value_Index on Test (Text_Value collate nocase);
Expressions involving Test.Text_Value
should now be case insensitive. For example:
sqlite> select Text_Value from Test where Text_Value = 'B'; Text_Value ---------------- b sqlite> select Text_Value from Test order by Text_Value; Text_Value ---------------- A b C sqlite> select Text_Value from Test order by Text_Value desc; Text_Value ---------------- C b A
The optimiser can also potentially make use of the index for case-insensitive searching and matching on the column. You can check this using the explain
SQL command, e.g.:
sqlite> explain select Text_Value from Test where Text_Value = 'b'; addr opcode p1 p2 p3 ---------------- -------------- ---------- ---------- --------------------------------- 0 Goto 0 16 1 Integer 0 0 2 OpenRead 1 3 keyinfo(1,NOCASE) 3 SetNumColumns 1 2 4 String8 0 0 b 5 IsNull -1 14 6 MakeRecord 1 0 a 7 MemStore 0 0 8 MoveGe 1 14 9 MemLoad 0 0 10 IdxGE 1 14 + 11 Column 1 0 12 Callback 1 0 13 Next 1 9 14 Close 1 0 15 Halt 0 0 16 Transaction 0 0 17 VerifyCookie 0 4 18 Goto 0 1 19 Noop 0 0
I haven't done anything with rank, but I discovered this today with row_number().
select item, name, sold, row_number() over(partition by item order by sold) as row from table_name
This will result in some repeating row numbers since in my case each name holds all items. Each item will be ordered by how many were sold.
+--------+------+-----+----+
|glasses |store1| 30 | 1 |
|glasses |store2| 35 | 2 |
|glasses |store3| 40 | 3 |
|shoes |store2| 10 | 1 |
|shoes |store1| 20 | 2 |
|shoes |store3| 22 | 3 |
+--------+------+-----+----+
Using bash "here string":
$ fspec="/exp/home1/abc.txt"
$ tr "/" "\n" <<< $fspec | tail -1
abc.txt
$ filename=$(tr "/" "\n" <<< $fspec | tail -1)
$ echo $filename
abc.txt
The benefit of the "here string" is that it avoids the need/overhead of running an echo
command. In other words, the "here string" is internal to the shell. That is:
$ tr <<< $fspec
as opposed to:
$ echo $fspec | tr
As others have suggested, you could use the following:
my $find = 'start (.*) end';
my $replace = 'foo $1 bar'; # 'foo \1 bar' is an error.
my $var = "start middle end";
$var =~ s/$find/$replace/ee;
The above is short for the following:
my $find = 'start (.*) end';
my $replace = 'foo $1 bar';
my $var = "start middle end";
$var =~ s/$find/ eval($replace) /e;
I prefer the second to the first since it doesn't hide the fact that eval(EXPR)
is used. However, both of the above silence errors, so the following would be better:
my $find = 'start (.*) end';
my $replace = 'foo $1 bar';
my $var = "start middle end";
$var =~ s/$find/ my $r = eval($replace); die $@ if $@; $r /e;
But as you can see, all of the above allow for the execution of arbitrary Perl code. The following would be far safer:
use String::Substitution qw( sub_modify );
my $find = 'start (.*) end';
my $replace = 'foo $1 bar';
my $var = "start middle end";
sub_modify($var, $find, $replace);
This is phpMyAdmin method.
$query = "INSERT INTO myTable
(mtb_i_idautoinc, mtb_s_string1, mtb_s_string2)
VALUES
(NULL, 'Jagodina', '35000')";
You could have the value of the input field copied to a hidden field whenever focus leaves the input field (which should do what you want). See code below:
<script>
$(document).ready(function(){
$('#myInputElement').bind('change', function(){
var newvalue = $(this).val();
});
$('#myInputElement').blur(function(){
$('#myHiddenInput').val($(this).val());
});
});
</script>
<input id="myInputElement" type="text">
(untested, but it should work).
The error regarding the file extension has been handled, you either use BMP
(without the dot) or pass the output name with the extension already. Now to handle the error you need to properly modify your data in the frequency domain to be saved as an integer image, PIL
is telling you that it doesn't accept float data to save as BMP.
Here is a suggestion (with other minor modifications, like using fftshift
and numpy.array
instead of numpy.asarray
) for doing the conversion for proper visualization:
import sys
import numpy
from PIL import Image
img = Image.open(sys.argv[1]).convert('L')
im = numpy.array(img)
fft_mag = numpy.abs(numpy.fft.fftshift(numpy.fft.fft2(im)))
visual = numpy.log(fft_mag)
visual = (visual - visual.min()) / (visual.max() - visual.min())
result = Image.fromarray((visual * 255).astype(numpy.uint8))
result.save('out.bmp')
If you use a BlockingCollection to schedule the task, the producer can run the potentially long running task and the consumer can use the TryTake method which has timeout and cancellation token built in.
Just call it and supply self
class A:
def m(self, x, y):
print(x+y)
class B:
def call_a(self):
A.m(self, 1, 2)
b = B()
b.call_a()
output: 3
An article at zerokspot entitled Custom filebrowser callbacks in CKEditor 3.0 handles this. The most relevant section is quoted below:
So all you have to do from the file browser when you have a file selected is to call this code with the right callback number (normally 1) and the URL of the selected file:
window.opener.CKEDITOR.tools.callFunction(CKEditorFuncNum,url);
For the quick-uploader the process is quite similar. At first I thought that the editor might be listening for a 200 HTTP return code and perhaps look into some header field or something like that to determine the location of the uploaded file, but then - through some Firebug monitoring - I noticed that all that happens after an upload is the following code:
<script type="text/javascript">
window.parent.CKEDITOR.tools.callFunction(CKEditorFuncNum,url, errorMessage);
</script>
If the upload failed, set the
errorMessage
to some non-zero-length string and empty the url, and vice versa on success.
I realise this is an old question, but another possible consideration depending on your exact requirements is that validating on https://validator.w3.org/ generates warnings as follows:
Warning: The form role is unnecessary for element form.
str_replace('"', "", $string);
str_replace("'", "", $string);
I assume you mean quotation marks?
Otherwise, go for some regex, this will work for html quotes for example:
preg_replace("/<!--.*?-->/", "", $string);
C-style quotes:
preg_replace("/\/\/.*?\n/", "\n", $string);
CSS-style quotes:
preg_replace("/\/*.*?\*\//", "", $string);
bash-style quotes:
preg-replace("/#.*?\n/", "\n", $string);
Etc etc...
Try this:
top.document.getElementById('AppFrame').setAttribute("src",fullPath);
Add this line above you Query
SET IDENTITY_INSERT tbl_content ON
By using transform: works like a charm!
<div class="parent">
<span>center content using transform</span>
</div>
//CSS
.parent {
position: relative;
height: 200px;
border: 1px solid;
}
.parent span {
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
This code does what your need:
<input type="checkbox" id="check" >check it</input>
$("#check").change( function(){
if( $(this).is(':checked') ) {
alert("checked");
}else{
alert("unchecked");
}
});
Also, you can check it on jsfiddle
Please also see this Microsoft Connect report on essentially, how blummin' difficult it is to use PowerShell to run shell commands (oh, the irony).
http://connect.microsoft.com/PowerShell/feedback/details/376207/
They suggest using --%
as a way to force PowerShell to stop trying to interpret the text to the right.
For example:
MSBuild /t:Publish --% /p:TargetDatabaseName="MyDatabase";TargetConnectionString="Data Source=.\;Integrated Security=True" /p:SqlPublishProfilePath="Deploy.publish.xml" Database.sqlproj
Using the Func as mentioned above works but there are also delegates that do the same task and also define intent within the naming:
public delegate double MyFunction(double x);
public double Diff(double x, MyFunction f)
{
double h = 0.0000001;
return (f(x + h) - f(x)) / h;
}
public double MyFunctionMethod(double x)
{
// Can add more complicated logic here
return x + 10;
}
public void Client()
{
double result = Diff(1.234, x => x * 456.1234);
double secondResult = Diff(2.345, MyFunctionMethod);
}
This approach (having all dependencies in a directory and not downloading from an index) only works when the directory contains all packages. The directory should therefore contain all dependencies but also all packages that those dependencies depend on (e.g., six
, pytz
etc).
You should therefore manually include these in requirements.txt
(so that the first step downloads them explicitly) or you should install all packages using PyPI and then pip freeze > requirements.txt
to store the list of all packages needed.
I use this class:
public class JsonContent : StringContent
{
public JsonContent(object obj) :
base(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json")
{ }
}
Sample of usage:
new HttpClient().PostAsync("http://...", new JsonContent(new { x = 1, y = 2 }));
Here is a reference for using EXPLAIN PLAN with Oracle: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/ex_plan.htm), with specific information about the columns found here: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/ex_plan.htm#i18300
Your mention of 'FULL' indicates to me that the query is doing a full-table scan to find your data. This is okay, in certain situations, otherwise an indicator of poor indexing / query writing.
Generally, with explain plans, you want to ensure your query is utilizing keys, thus Oracle can find the data you're looking for with accessing the least number of rows possible. Ultimately, you can sometime only get so far with the architecture of your tables. If the costs remain too high, you may have to think about adjusting the layout of your schema to be more performance based.
Here is worked example See on Plunker
<body ng-controller="MainCtrl">
<input ng-model="search" type="text">
<br>
Showing {{data.length}} Persons; <br>
Filtered {{counted}}
<ul>
<li ng-repeat="person in data | filter:search">
{{person.name}}
</li>
</ul>
</body>
<script>
var app = angular.module('angularjs-starter', [])
app.controller('MainCtrl', function($scope, $filter) {
$scope.data = [
{
"name": "Jim", "age" : 21
}, {
"name": "Jerry", "age": 26
}, {
"name": "Alex", "age" : 25
}, {
"name": "Max", "age": 22
}
];
$scope.counted = $scope.data.length;
$scope.$watch("search", function(query){
$scope.counted = $filter("filter")($scope.data, query).length;
});
});
Use the modulus operator %
, it returns the remainder.
int a = 5;
int b = 3;
if (a % b != 0) {
printf("The remainder is: %i", a%b);
}
Since jQuery 1.6, you can use .is
. Below is the answer from over a year ago...
var a = $('#foo');
var b = a;
if (a.is(b)) {
// the same object!
}
If you want to see if two variables are actually the same object, eg:
var a = $('#foo');
var b = a;
...then you can check their unique IDs. Every time you create a new jQuery object it gets an id.
if ($.data(a) == $.data(b)) {
// the same object!
}
Though, the same could be achieved with a simple a === b
, the above might at least show the next developer exactly what you're testing for.
In any case, that's probably not what you're after. If you wanted to check if two different jQuery objects contain the same set of elements, the you could use this:
$.fn.equals = function(compareTo) {
if (!compareTo || this.length != compareTo.length) {
return false;
}
for (var i = 0; i < this.length; ++i) {
if (this[i] !== compareTo[i]) {
return false;
}
}
return true;
};
var a = $('p');
var b = $('p');
if (a.equals(b)) {
// same set
}
If your backend support CORS, you probably need to add to your request this header:
headers: {"Access-Control-Allow-Origin": "*"}
[Update] Access-Control-Allow-Origin is a response header - so in order to enable CORS - you need to add this header to the response from your server.
But for the most cases better solution would be configuring the reverse proxy, so that your server would be able to redirect requests from the frontend to backend, without enabling CORS.
You can find documentation about CORS mechanism here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Write one table per join, like this:
select tab1.a,tab2.b,tab3.c,tab4.d
from
table1 tab1
inner join table2 tab2 on tab2.fg = tab1.fg
left join table3 tab3 on tab3.xxx = tab1.xxx and tab3.desc = "XYZ"
left join table4 tab4 on tab4.xya = tab3.xya and tab4.ss = tab3.ss
left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk
Note that while my query contains actual left join, your query apparently doesn't.
Since the conditions are in the where, your query should behave like inner joins. (Although I admit I don't know Informix, so maybe I'm wrong there).
The specfific Informix extension used in the question works a bit differently with regards to left joins. Apart from the exact syntax of the join itself, this is mainly in the fact that in Informix, you can specify a list of outer joined tables. These will be left outer joined, and the join conditions can be put in the where clause. Note that this is a specific extension to SQL. Informix also supports 'normal' left joins, but you can't combine the two in one query, it seems.
In Oracle this extension doesn't exist, and you can't put outer join conditions in the where clause, since the conditions will be executed regardless.
So look what happens when you move conditions to the where clause:
select tab1.a,tab2.b,tab3.c,tab4.d
from
table1 tab1
inner join table2 tab2 on tab2.fg = tab1.fg
left join table3 tab3 on tab3.xxx = tab1.xxx
left join table4 tab4 on tab4.xya = tab3.xya
left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk
where
tab3.desc = "XYZ" and
tab4.ss = tab3.ss
Now, only rows will be returned for which those two conditions are true. They cannot be true when no row is found, so if there is no matching row in table3 and/or table4, or if ss
is null in either of the two, one of these conditions is going to return false, and no row is returned. This effectively changed your outer join to an inner join, and as such changes the behavior significantly.
PS: left join
and left outer join
are the same. It means that you optionally join the second table to the first (the left one). Rows are returned if there is only data in the 'left' part of the join. In Oracle you can also right [outer] join
to make not the left, but the right table the leading table. And there is and even full [outer] join
to return a row if there is data in either table.
for others scratching their heads, I came across this error because I had innapropriately const-qualified one of the arguments to a method in a base class, so the derived class member functions were not over-riding it. so make sure you don't have something like
class Base
{
public:
virtual void foo(int a, const int b) = 0;
}
class D: public Base
{
public:
void foo(int a, int b){};
}
You are using the wrong type. The Array(...)
function returns a Variant
, not a String
.
Thus, in the Declaration section of your module (it does not need to be a different module!), you define
Public colHeader As Variant
and somewhere at the beginning of your program code (for example, in the Workbook_Open
event) you initialize it with
colHeader = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")
Another (simple) alternative would be to create a function that returns the array, e.g. something like
Public Function GetHeaders() As Variant
GetHeaders = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")
End Function
This has the advantage that you do not need to initialize the global variable and the drawback that the array is created again on every function call.
This answer attempts to address inputs with an absolute value in the range of 214748364810 (231) – 900719925474099110 (253-1).
In JavaScript, numbers are stored in 64-bit floating point representation, but bitwise operations coerce them to 32-bit integers in two's complement format, so any approach which uses bitwise operations restricts the range of output to -214748364810 (-231) – 214748364710 (231-1).
However, if bitwise operations are avoided and the 64-bit floating point representation is preserved by using only mathematical operations, we can reliably convert any safe integer to 64-bit two's complement binary notation by sign-extending the 53-bit twosComplement
:
function toBinary (value) {
if (!Number.isSafeInteger(value)) {
throw new TypeError('value must be a safe integer');
}
const negative = value < 0;
const twosComplement = negative ? Number.MAX_SAFE_INTEGER + value + 1 : value;
const signExtend = negative ? '1' : '0';
return twosComplement.toString(2).padStart(53, '0').padStart(64, signExtend);
}
function format (value) {
console.log(value.toString().padStart(64));
console.log(value.toString(2).padStart(64));
console.log(toBinary(value));
}
format(8);
format(-8);
format(2**33-1);
format(-(2**33-1));
format(2**53-1);
format(-(2**53-1));
format(2**52);
format(-(2**52));
format(2**52+1);
format(-(2**52+1));
_x000D_
.as-console-wrapper{max-height:100%!important}
_x000D_
For older browsers, polyfills exist for the following functions and values:
As an added bonus, you can support any radix (2–36) if you perform the two's complement conversion for negative numbers in ?64 / log2(radix)? digits by using BigInt
:
function toRadix (value, radix) {
if (!Number.isSafeInteger(value)) {
throw new TypeError('value must be a safe integer');
}
const digits = Math.ceil(64 / Math.log2(radix));
const twosComplement = value < 0
? BigInt(radix) ** BigInt(digits) + BigInt(value)
: value;
return twosComplement.toString(radix).padStart(digits, '0');
}
console.log(toRadix(0xcba9876543210, 2));
console.log(toRadix(-0xcba9876543210, 2));
console.log(toRadix(0xcba9876543210, 16));
console.log(toRadix(-0xcba9876543210, 16));
console.log(toRadix(0x1032547698bac, 2));
console.log(toRadix(-0x1032547698bac, 2));
console.log(toRadix(0x1032547698bac, 16));
console.log(toRadix(-0x1032547698bac, 16));
_x000D_
.as-console-wrapper{max-height:100%!important}
_x000D_
If you are interested in my old answer that used an ArrayBuffer
to create a union between a Float64Array
and a Uint16Array
, please refer to this answer's revision history.
This is a complete procedure to transfer database and logins from an istance to a new one, scripting logins and relocating datafile and log files on the destination. Everything using metascripts.
Sorry for the off-site procedure but scripts are very long. You have to:
- Script logins with original SID and HASHED password
- Create script to backup database using metascripts
- Create script to restore database passing relocate parameters using again metascripts
- Run the generated scripts on source and destination instance.
See details and download scripts following the link above.
If you know you don't have any whitespace in the input:
xargs chmod 755 < file.txt
If there might be whitespace in the paths, and if you have GNU xargs:
tr '\n' '\0' < file.txt | xargs -0 chmod 755
There is a way to do this without installing putty on your Mac. You can easily convert your existing PPK file to a PEM file using PuTTYgen on Windows.
Launch PuTTYgen and then load the existing private key file using the Load button. From the "Conversions" menu select "Export OpenSSH key" and save the private key file with the .pem file extension.
Copy the PEM file to your Mac and set it to be read-only by your user:
chmod 400 <private-key-filename>.pem
Then you should be able to use ssh to connect to your remote server
ssh -i <private-key-filename>.pem username@hostname
I've been using svg filters to achieve similar effects for sprites
<svg id="gray_calendar" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 48 48 48">
<filter id="greyscale">
<feColorMatrix type="saturate" values="0"/>
</filter>
<image width="48" height="10224" xlink:href="tango48i.png" filter="url(#greyscale)"/>
</svg>
<feGaussianBlur stdDeviation="10"/>
example.<image ...>
tag to apply it to any image or even use multiple images.I finally pasted my jar file into the same folder as my JDK so I didn't have to include the paths. I also had to open the command prompt as an admin.
java.exe -jar <jar file name>.jar
On CentOS 7, the following works:
yum install php-soap
This will automatically create a soap.ini under /etc/php.d.
The extension itself for me lives in /usr/lib64/php/modules. You can confirm your extension directory by doing:
php -i | grep extension_dir
Once this has been installed, you can simply restart Apache using the new service manager like so:
systemctl restart httpd
Thanks to Matt Browne for the info about /etc/php.d.
If the schema of id is not of type ObjectId you cannot operate with function : findbyId()
Make a new div with whatever name (I will just use table-split) and give it a width, without adding content to it, while placing it between necessary divs that need to be separated.
You can add whatever width you find necessary. I just used 0.6% because it's what I needed for when I had to do this.
.table-split {_x000D_
display: table-cell;_x000D_
width: 0.6%_x000D_
}
_x000D_
<div class="table-split"></div>
_x000D_
The each
function iterates over an array, calling the supplied function once per element, and setting this
to the active element. This:
function countdown() {
alert(this + "..");
}
$([5, 4, 3, 2, 1]).each(countdown);
will alert 5..
then 4..
then 3..
then 2..
then 1..
Map on the other hand takes an array, and returns a new array with each element changed by the function. This:
function squared() {
return this * this;
}
var s = $([5, 4, 3, 2, 1]).map(squared);
would result in s being [25, 16, 9, 4, 1]
.
Using pandas: pd.Timestamp("today").strftime("%m/%d/%Y")
Try this:
SELECT
'the sqlserver is ' + substring(@@VERSION, 21, 5) AS [sql version]
There is not much which I would like to add to Rody Oldenhuis answer. I usually follow the strategy that all functions which I write should run in Matlab.
Some specific functions I test on both systems, for the following use cases:
a) octave does not need a license server - e.g. if your institution does not support local licenses. I used it once in a situation where the system I used a script on had no connection to the internet and was going to run for a very long time (in a corner in the lab) and used by many different users. Remark: that is not about the license cost, but about the technical issues related.
b) Octave supports other platforms, for example, the Rasberry Pi (http://wiki.octave.org/Rasperry_Pi) - which may come in handy.
I was facing the same problem, unable to create directory on Galaxy S but was able to create it successfully on Nexus and Samsung Droid. How I fixed it was by adding following line of code:
File dir = new File(Environment.getExternalStorageDirectory().getPath()+"/"+getPackageName()+"/");
dir.mkdirs();
arrayList.toArray(new Custom[0]);
EH is good, generally. But C++'s implementation is not very friendly as it's really hard to tell how good your exception catching coverage is. Java for instance makes this easy, the compiler will tend to fail if you don't handle possible exceptions .
You can refer to https://curl.haxx.se/docs/http-cookies.html for a complete tutorial of how to work with cookies. You can use
curl -c /path/to/cookiefile http://yourhost/
to write to a cookie file and start engine and to use cookie you can use
curl -b /path/to/cookiefile http://yourhost/
to read cookies from and start the cookie engine, or if it isn't a file it will pass on the given string.
Iterating through the registry key "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" seems to give a comprehensive list of installed applications.
Aside from the example below, you can find a similar version to what I've done here.
This is a rough example, you'll probaby want to do something to strip out blank rows like in the 2nd link provided.
string registry_key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using(Microsoft.Win32.RegistryKey key = Registry.LocalMachine.OpenSubKey(registry_key))
{
foreach(string subkey_name in key.GetSubKeyNames())
{
using(RegistryKey subkey = key.OpenSubKey(subkey_name))
{
Console.WriteLine(subkey.GetValue("DisplayName"));
}
}
}
Alternatively, you can use WMI as has been mentioned:
ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_Product");
foreach(ManagementObject mo in mos.Get())
{
Console.WriteLine(mo["Name"]);
}
But this is rather slower to execute, and I've heard it may only list programs installed under "ALLUSERS", though that may be incorrect. It also ignores the Windows components & updates, which may be handy for you.
I think I have figured it out, is it right?:
mysql_query("START TRANSACTION");
$a1 = mysql_query("INSERT INTO rarara (l_id) VALUES('1')");
$a2 = mysql_query("INSERT INTO rarara (l_id) VALUES('2')");
if ($a1 and $a2) {
mysql_query("COMMIT");
} else {
mysql_query("ROLLBACK");
}
Firefox does not support the MPEG H.264 (mp4) format at this time, due to a philosophical disagreement with the closed-source nature of the format.
To play videos in all browsers without using plugins, you will need to host multiple copies of each video, in different formats. You will also need to use an alternate form of the video
tag, as seen in the JSFiddle from @TimHayes above, reproduced below. Mozilla claims that only mp4 and WebM are necessary to ensure complete coverage of all major browsers, but you may wish to consult the Video Formats and Browser Support heading on W3C's HTML5 Video page to see which browser supports what formats.
Additionally, it's worth checking out the HTML5 Video page on Wikipedia for a basic comparison of the major file formats.
Below is the appropriate video
tag (you will need to re-encode your video in WebM or OGG formats as well as your existing mp4):
<video id="video" controls='controls'>
<source src="videos/clip.mp4" type="video/mp4"/>
<source src="videos/clip.webm" type="video/webm"/>
<source src="videos/clip.ogv" type="video/ogg"/>
Your browser doesn't seem to support the video tag.
</video>
Updated Nov. 8, 2013
Network infrastructure giant Cisco has announced plans to open-source an implementation of the H.264 codec, removing the licensing fees that have so far proved a barrier to use by Mozilla. Without getting too deep into the politics of it (see following link for that) this will allow Firefox to support H.264 starting in "early 2014". However, as noted in that link, this still comes with a caveat. The H.264 codec is merely for video, and in the MPEG-4 container it is most commonly paired with the closed-source AAC audio codec. Because of this, playback of H.264 video will work, but audio will depend on whether the end-user has the AAC codec already present on their machine.
The long and short of this is that progress is being made, but you still can't avoid using multiple encodings without using a plugin.
The currently chosen best answer is too fuzzy to be reliable.
This feels to me like a fairly safe way to do it:
(Javascript: using jQuery to write it simpler)
$('#form1').submit(doubleSubmit);
function doubleSubmit(e1) {
e1.preventDefault();
e1.stopPropagation();
var post_form1 = $.post($(this).action, $(this).serialize());
post_form1.done(function(result) {
// would be nice to show some feedback about the first result here
$('#form2').submit();
});
};
Post the first form without changing page, wait for the process to complete. Then post the second form. The second post will change the page, but you might want to have some similar code also for the second form, getting a second deferred object (post_form2?).
I didn't test the code, though.
I got the same problem just doing an npm install. Run with antivirus disabled (if you use Windows Defender, turn off Real-Time protection and Cloud-based protection). That worked for me!
Quoting from the gcc manual:
For polymorphic classes (classes with virtual functions), the type_info object is written out along with the vtable [...] For all other types, we write out the type_info object when it is used: when applying `typeid' to an expression, throwing an object, or referring to a type in a catch clause or exception specification.
And a bit earlier on the same page:
If the class declares any non-inline, non-pure virtual functions, the first one is chosen as the “key method” for the class, and the vtable is only emitted in the translation unit where the key method is defined.
So, this error happens when the "key method" is missing its definition, as other answers already mentioned.
If you want to pass in the value to use, you have to use the enum type you declared and directly use the supplied value:
public string CreateFile(string id, string name, string description,
/* --> */ SupportedPermissions supportedPermissions)
{
file = new File
{
Name = name,
Id = id,
Description = description,
SupportedPermissions = supportedPermissions // <---
};
return file.Id;
}
If you instead want to use a fixed value, you don't need any parameter at all. Instead, directly use the enum value. The syntax is similar to a static member of a class:
public string CreateFile(string id, string name, string description) // <---
{
file = new File
{
Name = name,
Id = id,
Description = description,
SupportedPermissions = SupportedPermissions.basic // <---
};
return file.Id;
}
I 'tripped' across my solution after 2 days...XCODE 4.0
I've just upgraded to XCode 4.0 and this code signing issue has been a stunning frustrastion. And I've been doing this for over a year various versions...so if you are having problems, you are not alone.
I have recertified, reprovisioned, drag and dropped, manually edit the project file, deleted PROVISIIONING paths, stopped/started XCODE, stopped started keychain, checked spelling, checked bundle ID's, check my birth certificate, the phase of the moon, and taught my dog morse code...none of it worked!!!!
--bottom line---
If the Debug mode was not the same, it failed the Distribution mode as well...go figure. Hope that helps someone...
Figure: This shows how to find the relevant settings in XCode 4.5.
string saveStaff = "INSERT into student (stud_id,stud_name) " + " VALUES ('" + SI+ "', '" + SN + "');";
cmd = new SqlCommand(saveStaff,con);
cmd.ExecuteNonQuery();
A common way of manipulating the first responder is to use nil targeted actions. This is a way of sending an arbitrary message to the responder chain (starting with the first responder), and continuing down the chain until someone responds to the message (has implemented a method matching the selector).
For the case of dismissing the keyboard, this is the most effective way that will work no matter which window or view is first responder:
[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
This should be more effective than even [self.view.window endEditing:YES]
.
(Thanks to BigZaphod for reminding me of the concept)
You can use chsh to change a user's shell.
Run the following code, for instance, to change your shell to Zsh
chsh -s /bin/zsh
As described in the manpage, and by Lorin, if the shell is not known by the OS, you have to add it to its known list: /etc/shells
.
I would use liquibase for updating your db. hibernate's schema update feature is really only o.k. for a developer while they are developing new features. In a production situation, the db upgrade needs to be handled more carefully.
I just got the same problem today after my Nexus 7 and Galaxy Nexus were updated to Android 4.2.2.
The thing that fixed it for me was to upgrade the SDK platform-tools to r16.0.1. For me, this version was not displayed in my SDK Manager, so I pulled it down from http://dl.google.com/android/repository/platform-tools_r16.0.1-windows.zip directly.
You then need to rename the platform-tools
directory and unzip it to android-sdk-windows/platform-tools
. Using the SDK Manager, I had also updated to the latest sdk-tools before this.
If your whole Eclipse and ADT are ancient, you may need to update them as well, but I didn't need to.
Note: you may need to run SDK Manager twice (once to update itself) before you will see the latest packages.
If you use it in a database, this is a good way:
Set the ip field in database to varchar(250), and then use this:
$theip = $_SERVER["REMOTE_ADDR"];
if (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
$theip .= '('.$_SERVER["HTTP_X_FORWARDED_FOR"].')';
}
if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
$theip .= '('.$_SERVER["HTTP_CLIENT_IP"].')';
}
$realip = substr($theip, 0, 250);
Then you just check $realip against the database ip field
Imagine d.getId is a Long, then wrap like this:
BigInteger l = BigInteger.valueOf(d.getId());
Here is a function that will do it without jQuery:
function getElementOffset(element)
{
var de = document.documentElement;
var box = element.getBoundingClientRect();
var top = box.top + window.pageYOffset - de.clientTop;
var left = box.left + window.pageXOffset - de.clientLeft;
return { top: top, left: left };
}
For me, the biggest benefit to re.compile
is being able to separate definition of the regex from its use.
Even a simple expression such as 0|[1-9][0-9]*
(integer in base 10 without leading zeros) can be complex enough that you'd rather not have to retype it, check if you made any typos, and later have to recheck if there are typos when you start debugging. Plus, it's nicer to use a variable name such as num or num_b10 than 0|[1-9][0-9]*
.
It's certainly possible to store strings and pass them to re.match; however, that's less readable:
num = "..."
# then, much later:
m = re.match(num, input)
Versus compiling:
num = re.compile("...")
# then, much later:
m = num.match(input)
Though it is fairly close, the last line of the second feels more natural and simpler when used repeatedly.
In short, git is trying to access a repo it considers on another filesystem and to tell it explicitly that you're okay with this, you must set the environment variable GIT_DISCOVERY_ACROSS_FILESYSTEM=1
I'm working in a CI/CD environment and using a dockerized git so I have to set it in that environment docker run -e GIT_DISCOVERY_ACROSS_FILESYSTEM=1 -v $(pwd):/git --rm alpine/git rev-parse --short HEAD\
'
If you're curious: Above mounts $(pwd) into the git docker container and passes "rev-parse --short HEAD" to the git command in the container, which it then runs against that mounted volums.
Wikipedia has a fairly detailed explanation:
http://en.wikipedia.org/wiki/Duck_typing
duck typing is a style of dynamic typing in which an object's current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface.
The important note is likely that with duck typing a developer is concerned more with the parts of the object that are consumed rather than what the actual underlying type is.
When I did just a remove the option remained in the ddl on the view, but was gone in the html (if u inspect the page)
$("#ddlSelectList option[value='2']").remove(); //removes the option with value = 2
$('#ddlSelectList').val('').trigger('chosen:updated'); //refreshes the drop down list
I'm afraid your map contains something other than String
objects. If you call toString()
on a String object, you obtain the string itself.
What you get [Ljava.lang.String
indicates you might have a String array.
Another way is to call an external process such as curl.exe. Curl by default displays a progress bar, average download speed, time left, and more all formatted neatly in a table. Put curl.exe in the same directory as your script
from subprocess import call
url = ""
call(["curl", {url}, '--output', "song.mp3"])
Note: You cannot specify an output path with curl, so do an os.rename afterwards
Choosing the right file format is important to building performant data applications. The concepts outlined in this post carry over to Pandas, Dask, Spark, and Presto / AWS Athena.
Column pruning
Column pruning is a big performance improvement that's possible for column-based file formats (Parquet, ORC) and not possible for row-based file formats (CSV, Avro).
Suppose you have a dataset with 100 columns and want to read two of them into a DataFrame. Here's how you can perform this with Pandas if the data is stored in a Parquet file.
import pandas as pd
pd.read_parquet('some_file.parquet', columns = ['id', 'firstname'])
Parquet is a columnar file format, so Pandas can grab the columns relevant for the query and can skip the other columns. This is a massive performance improvement.
If the data is stored in a CSV file, you can read it like this:
import pandas as pd
pd.read_csv('some_file.csv', usecols = ['id', 'firstname'])
usecols
can't skip over entire columns because of the row nature of the CSV file format.
Spark doesn't require users to explicitly list the columns that'll be used in a query. Spark builds up an execution plan and will automatically leverage column pruning whenever possible. Of course, column pruning is only possible when the underlying file format is column oriented.
Popularity
Spark and Pandas have built-in readers writers for CSV, JSON, ORC, Parquet, and text files. They don't have built-in readers for Avro.
Avro is popular within the Hadoop ecosystem. Parquet has gained significant traction outside of the Hadoop ecosystem. For example, the Delta Lake project is being built on Parquet files.
Arrow is an important project that makes it easy to work with Parquet files with a variety of different languages (C, C++, Go, Java, JavaScript, MATLAB, Python, R, Ruby, Rust), but doesn't support Avro. Parquet files are easier to work with because they are supported by so many different projects.
Schema
Parquet stores the file schema in the file metadata. CSV files don't store file metadata, so readers need to either be supplied with the schema or the schema needs to be inferred. Supplying a schema is tedious and inferring a schema is error prone / expensive.
Avro also stores the data schema in the file itself. Having schema in the files is a huge advantage and is one of the reasons why a modern data project should not rely on JSON or CSV.
Column metadata
Parquet stores metadata statistics for each column and lets users add their own column metadata as well.
The min / max column value metadata allows for Parquet predicate pushdown filtering that's supported by the Dask & Spark cluster computing frameworks.
Here's how to fetch the column statistics with PyArrow.
import pyarrow.parquet as pq
parquet_file = pq.ParquetFile('some_file.parquet')
print(parquet_file.metadata.row_group(0).column(1).statistics)
<pyarrow._parquet.Statistics object at 0x11ac17eb0>
has_min_max: True
min: 1
max: 9
null_count: 0
distinct_count: 0
num_values: 3
physical_type: INT64
logical_type: None
converted_type (legacy): NONE
Complex column types
Parquet allows for complex column types like arrays, dictionaries, and nested schemas. There isn't a reliable method to store complex types in simple file formats like CSVs.
Compression
Columnar file formats store related types in rows, so they're easier to compress. This CSV file is relatively hard to compress.
first_name,age
ken,30
felicia,36
mia,2
This data is easier to compress when the related types are stored in the same row:
ken,felicia,mia
30,36,2
Parquet files are most commonly compressed with the Snappy compression algorithm. Snappy compressed files are splittable and quick to inflate. Big data systems want to reduce file size on disk, but also want to make it quick to inflate the flies and run analytical queries.
Mutable nature of file
Parquet files are immutable, as described here. CSV files are mutable.
Adding a row to a CSV file is easy. You can't easily add a row to a Parquet file.
Data lakes
In a big data environment, you'll be working with hundreds or thousands of Parquet files. Disk partitioning of the files, avoiding big files, and compacting small files is important. The optimal disk layout of data depends on your query patterns.