You can also use GO + how many times you want to execute the same query.
DELETE TOP (10000) [TARGETDATABASE].[SCHEMA].[TARGETTABLE]
WHERE readTime < dateadd(MONTH,-1,GETDATE());
-- how many times you want the query to repeat
GO 100
\n - simple newline character insertion works:
# Here's the test example - string with newline char:
In [36]: test_line = "Hi!!!\n testing first line.. \n testing second line.. \n and third line....."
# Output:
In [37]: print(test_line)
Hi!!!
testing first line..
testing second line..
and third line.....
There are a few OS-specific routines for beeping.
On a Unix-like OS, try the (n)curses beep() function. This is likely to be more portable than writing '\a'
as others have suggested, although for most terminal emulators that will probably work.
In some *BSDs there is a PC speaker device. Reading the driver source, the SPKRTONE
ioctl seems to correspond to the raw hardware interface, but there also seems to be a high-level language built around write()
-ing strings to the driver, described in the manpage.
It looks like Linux has a similar driver (see this article for example; there is also some example code on this page if you scroll down a bit.).
In Windows there is a function called Beep().
heres another way you can do it html
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app"></div>
<script src="src/index.js"></script>
</body>
</html>
index.js file with path src/index.js
import React from "react";
import { render } from "react-dom";
import "./styles.scss";
const App = () => (
<div>
<h1>Hello test</h1>
</div>
);
render(<App />, document.getElementById("app"));
use this package.json will get u up and running quickly
{
"name": "test-app",
"version": "1.0.0",
"description": "",
"main": "index.html",
"scripts": {
"start": "parcel index.html --open",
"build": "parcel build index.html"
},
"dependencies": {
"react": "16.2.0",
"react-dom": "16.2.0",
"react-native": "0.57.5"
},
"devDependencies": {
"@types/react-native": "0.57.13",
"parcel-bundler": "^1.6.1"
},
"keywords": []
}
I don't see much details about performance and optimizer in the other answers.
Sometimes it is good to know that only INNER JOIN
is associative which means the optimizer has the most option to play with it. It can reorder the join order to make it faster keeping the same result. The optimizer can use the most join modes.
Generally it is a good practice to try to use INNER JOIN
instead of the different kind of joins. (Of course if it is possible considering the expected result set.)
There are a couple of good examples and explanation here about this strange associative behavior:
Another option is to do like this:
<html>
<body>
<?php
//...php code...
?>
<script type="text/javascript">
document.write("Hello World!");
</script>
<?php
//....php code...
?>
</body>
</html>
and if you want to use PHP inside your JavaScript, do like this:
<html>
<body>
<?php
$text = "Hello World!";
?>
<script type="text/javascript">
document.write("<?php echo $text ?>");
</script>
<?php
//....php code...
?>
</body>
</html>
Hope this can help.
use the following code to have a button, in android studio, open an already existing activity.
Button StartButton = (Button) findViewById(R.id.YOUR BUTTONS ID GOES HERE);
StartButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, YOUR ACTIVITY'S ID GOES HERE.class));
}
});
Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.
You can do something like this:
<form action="../" onsubmit="return checkCheckBoxes(this);">
<p><input type="CHECKBOX" name="MyCheckbox" value="This..."> This...</p>
<p><input type="SUBMIT" value="Submit!"></p>
</form>
<script type="text/javascript" language="JavaScript">
<!--
function checkCheckBoxes(theForm) {
if (
theForm.MyCheckbox.checked == false)
{
alert ('You didn\'t choose any of the checkboxes!');
return false;
} else {
return true;
}
}
//-->
</script>
http://lab.artlung.com/validate-checkbox/
Although less legible imho, this can be done without a separate function definition like this:
<form action="../" onsubmit="if (this.MyCheckbox.checked == false) { alert ('You didn\'t choose any of the checkboxes!'); return false; } else { return true; }">
<p><input type="CHECKBOX" name="MyCheckbox" value="This..."> This...</p>
<p><input type="SUBMIT" value="Submit!"></p>
</form>
Apparently nothing happens, it fails in a non-destructive way and gives you a warning.
I've had this happen as well very recently. One way you can solve this is by moving all the files in the non-empty mount point to somewhere else, e.g.:
mv /nonEmptyMountPoint/* ~/Desktop/mountPointDump/
This way your mount point is now empty, and your mount
command will work.
If you can't rename the original file, you could also use a symlink:
ln -s foo-bar.py foo_bar.py
Then you can just:
from foo_bar import *
As ping
works, but telnet
to port 80
does not, the HTTP port 80
is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?).
You need to add some code to your python program, that handles the proxy, like described here:
First of all, why is the map a HashMap<String, ArrayList<String>>
and not a HashMap<String, List<String>>
? Is there some reason why the value must be a specific implementation of interface List
(ArrayList
in this case)?
Arrays.asList
does not return a java.util.ArrayList
, so you can't assign the return value of Arrays.asList
to a variable of type ArrayList
.
Instead of:
allWords = Arrays.asList(strTemp.toLowerCase().split("\\s+"));
Try this:
allWords.addAll(Arrays.asList(strTemp.toLowerCase().split("\\s+")));
As for guidelines... a random search from StackOverflow and the electric interweb...
First choose or create the key you want to use for pushing to Bitbucket. Let's say its public key is at ~/.ssh/bitbucket.pub
~/.ssh/config
: Host bitbucket.org
IdentityFile ~/.ssh/bitbucket
Not an expert on encoding, but after reading these...
... it seems fairly clear that the $OutputEncoding variable only affects data piped to native applications.
If sending to a file from withing PowerShell, the encoding can be controlled by the -encoding
parameter on the out-file
cmdlet e.g.
write-output "hello" | out-file "enctest.txt" -encoding utf8
Nothing else you can do on the PowerShell front then, but the following post may well help you:.
When you write an XML layout, it will be inflated by the Android OS which basically means that it will be rendered by creating view object in memory. Let's call that implicit inflation (the OS will inflate the view for you). For instance:
class Name extends Activity{
public void onCreate(){
// the OS will inflate the your_layout.xml
// file and use it for this activity
setContentView(R.layout.your_layout);
}
}
You can also inflate views explicitly by using the LayoutInflater
. In that case you have to:
LayoutInflater
View
For instance:
LayoutInflater inflater = LayoutInflater.from(YourActivity.this); // 1
View theInflatedView = inflater.inflate(R.layout.your_layout, null); // 2 and 3
setContentView(theInflatedView) // 4
In here:
if (ValidationUtils.isNullOrEmpty(lastName)) {
registrationErrors.add(ValidationErrors.LAST_NAME);
}
if (!ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
you check for null or empty value on lastname, but in isEmailValid you don't check for empty value. Something like this should do
if (ValidationUtils.isNullOrEmpty(email) || !ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
or better yet, fix your ValidationUtils.isEmailValid() to cope with null email values. It shouldn't crash, it should just return false.
If you prefer ByteBuffer
like @kalefranz, there is always the posibility to concatenate two byte[]
(or even more) in one line, like this:
byte[] c = ByteBuffer.allocate(a.length+b.length).put(a).put(b).array();
There are plenty of situations where it makes a lot of sense to have ListView's in a ScrollView.
Here's code based on DougW's suggestion... works in a fragment, takes less memory.
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
int totalHeight = 0;
View view = null;
for (int i = 0; i < listAdapter.getCount(); i++) {
view = listAdapter.getView(i, view, listView);
if (i == 0) {
view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, LayoutParams.WRAP_CONTENT));
}
view.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
totalHeight += view.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
listView.requestLayout();
}
call setListViewHeightBasedOnChildren(listview) on each embedded listview.
I wrote a higher order function to make it work right. We've used this in several projects and it seems to work great. This is how things should have been done from the start, without the "using" paradigm or so on.
TReturn UseService<TChannel, TReturn>(Func<TChannel, TReturn> code)
{
var chanFactory = GetCachedFactory<TChannel>();
TChannel channel = chanFactory.CreateChannel();
bool error = true;
try {
TReturn result = code(channel);
((IClientChannel)channel).Close();
error = false;
return result;
}
finally {
if (error) {
((IClientChannel)channel).Abort();
}
}
}
You can make calls like this:
int a = 1;
int b = 2;
int sum = UseService((ICalculator calc) => calc.Add(a, b));
Console.WriteLine(sum);
This is pretty much just like you have in your example. In some projects, we write strongly typed helper methods, so we end up writing things like "Wcf.UseFooService(f=>f...)".
I find it quite elegant, all things considered. Is there a particular problem you encountered?
This allows other nifty features to be plugged in. For instance, on one site, the site authenticates to the service on behalf of the logged in user. (The site has no credentials by itself.) By writing our own "UseService" method helper, we can configure the channel factory the way we want, etc. We're also not bound to using the generated proxies -- any interface will do.
ASP.NET MVC doesn't work on events like ASP classic; there's no "button click event". Your controller methods correspond to requests sent to the server.
Instead, you need to wrap that form in code something like this:
@using (Html.BeginForm("SignUp", "Account", FormMethod.Post))
{
<!-- form goes here -->
<input type="submit" value="Sign Up" />
}
This will set up a form, and then your submit input will trigger a POST, which will hit your SignUp()
method, assuming your routes are properly set up (the defaults should work).
The warning message
[WARNING] The requested profile "pom.xml" could not be activated because it does not exist.
means that you somehow passed -P pom.xml
to Maven which means "there is a profile called pom.xml
; find it and activate it". Check your environment and your settings.xml
for this flag and also look at all <profile>
elements inside the various XML files.
Usually, mvn help:effective-pom
is also useful to see what the real POM would look like.
Now the error means that you tried to configure Maven to build Java 8 code but you're not using a Java 8 runtime. Solutions:
JAVA_HOME
is your friendpom.xml
to a Java version which you actually have.Related:
If you using ajax to load modal's body such way and want to be able to reload it's content
<a data-toggle="modal" data-target="#myModal" href="./add">Add</a>
<a data-toggle="modal" data-target="#myModal" href="./edit/id">Modify</a>
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<!-- Content will be loaded here -->
</div>
</div>
</div>
use
<script>
$(function() {
$('.modal').on('hidden.bs.modal', function(){
$(this).removeData('bs.modal');
});
});
</script>
They might be just a \r
or a \n
. I just checked and the text visualizer in VS 2010 displays both as newlines as well as \r\n
.
This string
string test = "blah\r\nblah\rblah\nblah";
Shows up as
blah
blah
blah
blah
in the text visualizer.
So you could try
string modifiedString = originalString
.Replace(Environment.NewLine, "<br />")
.Replace("\r", "<br />")
.Replace("\n", "<br />");
here is an example
<a class="facultySelecter" data-faculty="ahs" href="#">Arts and Human Sciences</a></li>
$('.facultySelecter').click(function() {
var unhide = $(this).data("faculty");
});
this would set var unhide as ahs, so use .data("foo") to get the "foo" value of the data-* attribute you're looking to get
The Javadoc for String reveals that String.split()
is what you're looking for in regard to explode
.
Java does not include a "implode" of "join" equivalent. Rather than including a giant external dependency for a simple function as the other answers suggest, you may just want to write a couple lines of code. There's a number of ways to accomplish that; using a StringBuilder
is one:
String foo = "This,that,other";
String[] split = foo.split(",");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < split.length; i++) {
sb.append(split[i]);
if (i != split.length - 1) {
sb.append(" ");
}
}
String joined = sb.toString();
The problem with camel case is that there are often different interpretations of words - for example, checkinService vs checkInService. Going along with Aaron's answer, it is difficult with auto-completion if you have many similarly named repos to have to constantly check if the person who created the repo you care about used a certain breakdown of the upper and lower cases. avoid upper case.
His point about dashes is also well-advised.
I created a small portable wrapper script called "xargsL" around "xargs" which addresses most of the problems.
Contrary to xargs, xargsL accepts one pathname per line. The pathnames may contain any character except (obviously) newline or NUL bytes.
No quoting is allowed or supported in the file list - your file names may contain all sorts of whitespace, backslashes, backticks, shell wildcard characters and the like - xargsL will process them as literal characters, no harm done.
As an added bonus feature, xargsL will not run the command once if there is no input!
Note the difference:
$ true | xargs echo no data
no data
$ true | xargsL echo no data # No output
Any arguments given to xargsL will be passed through to xargs.
Here is the "xargsL" POSIX shell script:
#! /bin/sh # Line-based version of "xargs" (one pathname per line which may contain any # amount of whitespace except for newlines) with the added bonus feature that # it will not execute the command if the input file is empty. # # Version 2018.76.3 # # Copyright (c) 2018 Guenther Brunthaler. All rights reserved. # # This script is free software. # Distribution is permitted under the terms of the GPLv3. set -e trap 'test $? = 0 || echo "$0 failed!" >& 2' 0 if IFS= read -r first then { printf '%s\n' "$first" cat } | sed 's/./\\&/g' | xargs ${1+"$@"} fi
Put the script into some directory in your $PATH and don't forget to
$ chmod +x xargsL
the script there to make it executable.
I know this thread is old now, but here is some decent documentation on Google Docs API. It was ridiculously hard to find, but useful, so maybe it will help you some. http://pythonhosted.org/gdata/docs/api.html.
I used gspread recently for a project to graph employee time data. I don't know how much it might help you, but here's a link to the code: https://github.com/lightcastle/employee-timecards
Gspread made things pretty easy for me. I was also able to add logic in to check for various conditions to create month-to-date and year-to-date results. But I just imported the whole dang spreadsheet and parsed it from there, so I'm not 100% sure that it is exactly what you're looking for. Best of luck.
Update:
Guido van Rossum announced on the mailing list that as of Python 3.7 dict
s in all Python implementations must preserve insertion order.
git init
in the solution folder. That is the proper way to create a repository folder..gitignore
file, so you don't commit unnecessary stuff.git add
git commit
git remote add origin <proper URL>
git push
your codeAlternatively, there are detailed guides here using the Visual Studio integration.
you can use this..
<select name="select_name">
<option value="1"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='1')?' selected="selected"':'');?>>Yes</option>
<option value="2"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='2')?' selected="selected"':'');?>>No</option>
<option value="3"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='3')?' selected="selected"':'');?>>Fine</option>
</select>
Return your promise , return deferred.promise.
It is the promise API that has the 'then' method.
https://docs.angularjs.org/api/ng/service/$q
Calling resolve does not return a promise it only signals the promise that the promise is resolved so it can execute the 'then' logic.
Basic pattern as follows, rinse and repeat
http://plnkr.co/edit/fJmmEP5xOrEMfLvLWy1h?p=preview
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@*" data-semver="1.3.0-beta.5"
src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-controller="test">
<button ng-click="test()">test</button>
</div>
<script>
var app = angular.module("app",[]);
app.controller("test",function($scope,$q){
$scope.$test = function(){
var deferred = $q.defer();
deferred.resolve("Hi");
return deferred.promise;
};
$scope.test=function(){
$scope.$test()
.then(function(data){
console.log(data);
});
}
});
angular.bootstrap(document,["app"]);
</script>
ZonedDateTime.parse(
"Jun 13 2003 23:11:52.454 UTC" ,
DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" )
)
.toInstant()
.toEpochMilli()
1055545912454
This Answer expands on the Answer by Lockni.
DateTimeFormatter
First define a formatting pattern to match your input string by creating a DateTimeFormatter
object.
String input = "Jun 13 2003 23:11:52.454 UTC";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" );
ZonedDateTime
Parse the string as a ZonedDateTime
. You can think of that class as: ( Instant
+ ZoneId
).
ZonedDateTime zdt = ZonedDateTime.parse ( "Jun 13 2003 23:11:52.454 UTC" , f );
zdt.toString(): 2003-06-13T23:11:52.454Z[UTC]
I do not recommend tracking date-time values as a count-from-epoch. Doing so makes debugging tricky as humans cannot discern a meaningful date-time from a number so invalid/unexpected values may slip by. Also such counts are ambiguous, in granularity (whole seconds, milli, micro, nano, etc.) and in epoch (at least two dozen in by various computer systems).
But if you insist you can get a count of milliseconds from the epoch of first moment of 1970 in UTC (1970-01-01T00:00:00
) through the Instant
class. Be aware this means data-loss as you are truncating any nanoseconds to milliseconds.
Instant instant = zdt.toInstant ();
instant.toString(): 2003-06-13T23:11:52.454Z
long millisSinceEpoch = instant.toEpochMilli() ;
1055545912454
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
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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.
For me, this worked:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
If I remove this meta, the  appears again. Hope this helps someone...
Take a look at boost::assign
.
I had a similar problem. I got an exception "Type is not resolved for member 'Microsoft.IdentityModel.Claims.ClaimsPrincipal, Microsoft.IdentityModel, Version = 3.5.0.0, Culture = neutral, PublicKeyToken = 31bf3856ad364e35'.".
I tried to run the ASP.NET application from Visual Studio, which was a reference to a local copy of Microsoft.IdentityModel.dll.
I did not want to install the SDK and I had to copy the library to the directory "C: \ Program Files \ Common Files \ Microsoft Shared \ DevServer \ 10.0" and restart Visual Studio.
If you need a one liner which gets the latest tag name (by tag date) on the current branch:
git for-each-ref refs/tags --sort=-taggerdate --format=%(refname:short) --count=1 --points-at=HEAD
We use this to set the version number in the setup.
Output example:
v1.0.0
Works on Windows, too.
Answer from Varun Rathore is OK but you must consider that starting from Windows Server 2008 R2 and higher the SQLServer service will run under a local virtual account and not anymore under the old well known "NETWORK SERVICE". Due to this, to switch a newly attached DB to "not read only mode", you must setup permissions on the ldf and mdf files for local machine user line "NT SERVICE\MSSQLSERVER" where MSSQLSERVER would be the service name in a pretty standard installation.
Checkout this https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/configure-windows-service-accounts-and-permissions#VA_Desc for details configuring service permissions
SQLite doesn't define any particular extension for this, it's your own choice. Personally, I name them with the .sqlite
extension, just so there isn't any ambiguity when I'm looking at my files later.
Try something like this:
var prop;
for(prop in obj) {
if(!obj.hasOwnProperty(prop)) continue;
console.log(prop + " - "+ obj[prop]);
}
Number Zero parity | zero http://tinyurl.com/oexhr3k
Python code sequence.
# defining function for number parity check
def parity(number):
"""Parity check function"""
# if number is 0 (zero) return 'Zero neither ODD nor EVEN',
# otherwise number&1, checking last bit, if 0, then EVEN,
# if 1, then ODD.
return (number == 0 and 'Zero neither ODD nor EVEN') \
or (number&1 and 'ODD' or 'EVEN')
# cycle trough numbers from 0 to 13
for number in range(0, 14):
print "{0:>4} : {0:08b} : {1:}".format(number, parity(number))
Output:
0 : 00000000 : Zero neither ODD nor EVEN
1 : 00000001 : ODD
2 : 00000010 : EVEN
3 : 00000011 : ODD
4 : 00000100 : EVEN
5 : 00000101 : ODD
6 : 00000110 : EVEN
7 : 00000111 : ODD
8 : 00001000 : EVEN
9 : 00001001 : ODD
10 : 00001010 : EVEN
11 : 00001011 : ODD
12 : 00001100 : EVEN
13 : 00001101 : ODD
Tuples are available since .NET4.0 and support generics:
Tuple<string, int> t = new Tuple<string, int>("Hello", 4);
In previous versions you can use System.Collections.Generic.KeyValuePair<K, V>
or a solution like the following:
public class Pair<T, U> {
public Pair() {
}
public Pair(T first, U second) {
this.First = first;
this.Second = second;
}
public T First { get; set; }
public U Second { get; set; }
};
And use it like this:
Pair<String, int> pair = new Pair<String, int>("test", 2);
Console.WriteLine(pair.First);
Console.WriteLine(pair.Second);
This outputs:
test
2
Or even this chained pairs:
Pair<Pair<String, int>, bool> pair = new Pair<Pair<String, int>, bool>();
pair.First = new Pair<String, int>();
pair.First.First = "test";
pair.First.Second = 12;
pair.Second = true;
Console.WriteLine(pair.First.First);
Console.WriteLine(pair.First.Second);
Console.WriteLine(pair.Second);
That outputs:
test
12
true
var x = document.getElementById("myTable").rows.length;
You can use docker-compose run
instead of docker-compose up
and tack the arguments on the end. For example:
docker-compose run dperson/samba arg1 arg2 arg3
If you need to connect to other docker containers, use can use --service-ports
option:
docker-compose run --service-ports dperson/samba arg1 arg2 arg3
I have been using generic-pool with redis connections in my app - I highly recommend it. Its generic and I definitely know it works with mysql so I don't think you'll have any problems with it and mongo
Why do you use Int64
? AddDays
demands a double
-value to be added. Then you'll need to use the return-value of AddDays.
See here.
I had a similar issue but I had to consider other issues that @apaul34208 example did not tackle. In my case;
Not the most elegant of examples but it does the trick for me. Consider using throttling the window resize (https://lodash.com/)
var TextFit = function(){_x000D_
var container = $('.container');_x000D_
container.each(function(){_x000D_
var container_width = $(this).width(),_x000D_
width_offset = parseInt($(this).data('width-offset')),_x000D_
font_container = $(this).find('.font-container');_x000D_
_x000D_
if ( width_offset > 0 ) {_x000D_
container_width -= width_offset;_x000D_
}_x000D_
_x000D_
font_container.each(function(){_x000D_
var font_container_width = $(this).width(),_x000D_
font_size = parseFloat( $(this).css('font-size') );_x000D_
_x000D_
var diff = Math.max(container_width, font_container_width) - Math.min(container_width, font_container_width);_x000D_
_x000D_
var diff_percentage = Math.round( ( diff / Math.max(container_width, font_container_width) ) * 100 );_x000D_
_x000D_
if (diff_percentage !== 0){_x000D_
if ( container_width > font_container_width ) {_x000D_
new_font_size = font_size + Math.round( ( font_size / 100 ) * diff_percentage );_x000D_
} else if ( container_width < font_container_width ) {_x000D_
new_font_size = font_size - Math.round( ( font_size / 100 ) * diff_percentage );_x000D_
}_x000D_
}_x000D_
$(this).css('font-size', new_font_size + 'px');_x000D_
});_x000D_
});_x000D_
}_x000D_
_x000D_
$(function(){_x000D_
TextFit();_x000D_
$(window).resize(function(){_x000D_
TextFit();_x000D_
});_x000D_
});
_x000D_
.container {_x000D_
width:341px;_x000D_
height:341px;_x000D_
background-color:#000;_x000D_
padding:20px;_x000D_
}_x000D_
.font-container {_x000D_
font-size:131px;_x000D_
text-align:center;_x000D_
color:#fff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="container" data-width-offset="10">_x000D_
<span class="font-container">£5000</span>_x000D_
</div>
_x000D_
You can do it with OpenCV's function imwrite
:
import cv2
cv2.imwrite('Path/Image.jpg', image_name)
I think the most safest downgrade path from PHP7 to PHP5 in Xampp is:
Download a self-packaged version of Xampp with PHP5 from here (as of today this is xampp-win32-5.6.37-0-VC11.zip
).
Rename the php
folder to php7
in Xampp.
Now copy the php
folder from xampp-win32-5.6.37-0-VC11.zip
into your Xampp install folder.
Make a backup from .\xampp\apache\conf\extra\httpd-xampp.conf
file.
Replace this file from xampp-win32-5.6.37-0-VC11.zip
as well.
This way the config files (including php.ini
) has settings from the Xampp team.
Before any changes, to verify changed Apache configs, you can compare both Xampp release folder at .\xampp\apache\conf
with tools like Meld.
I should note that please download PHP 5 and 7 Xampp packages released at the same time.
Notify me if I miss something.
Here we have same question. You can use the following code:
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["yourconnectionstringnamehere"].ConnectionString;
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandText = "DELETE FROM [tablenamehere]";
SqlDataReader data = com.ExecuteReader();
con.Close();
But before you need to import following code to your project:
using System.Configuration;
using System.Data.SqlClient;
This is the specific part of the code that can delete all rows is a table:
DELETE FROM [tablenamehere]
This must be your table name:tablenamehere
- This can delete all rows in table: DELETE FROM
Following Code Works Fine to Get City Name (Using Google Map Geo API) :
HTML
<p><button onclick="getLocation()">Get My Location</button></p>
<p id="demo"></p>
<script src="http://maps.google.com/maps/api/js?key=YOUR_API_KEY"></script>
SCRIPT
var x=document.getElementById("demo");
function getLocation(){
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition,showError);
}
else{
x.innerHTML="Geolocation is not supported by this browser.";
}
}
function showPosition(position){
lat=position.coords.latitude;
lon=position.coords.longitude;
displayLocation(lat,lon);
}
function showError(error){
switch(error.code){
case error.PERMISSION_DENIED:
x.innerHTML="User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML="Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML="The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML="An unknown error occurred."
break;
}
}
function displayLocation(latitude,longitude){
var geocoder;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(latitude, longitude);
geocoder.geocode(
{'latLng': latlng},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var add= results[0].formatted_address ;
var value=add.split(",");
count=value.length;
country=value[count-1];
state=value[count-2];
city=value[count-3];
x.innerHTML = "city name is: " + city;
}
else {
x.innerHTML = "address not found";
}
}
else {
x.innerHTML = "Geocoder failed due to: " + status;
}
}
);
}
'Windows error 2' has dozens of meanings (52 that I could find).
The most common one is ERROR_FILE_NOT_FOUND
, which can be found in winerror.h
. Without more context, that's the best I can guess. Did you check the event logs to see if there's more information there?
In reply to James Craig Burley's answer. In order to make a clean and re-usable design, one might choose for a more object oriented approach. This way methods can be safely bound to the types of the specified map. To me this approach feels cleaner and organized.
Example:
package main
import (
"fmt"
"sort"
)
type myIntMap map[int]string
func (m myIntMap) sort() (index []int) {
for k, _ := range m {
index = append(index, k)
}
sort.Ints(index)
return
}
func main() {
m := myIntMap{
1: "one",
11: "eleven",
3: "three",
}
for _, k := range m.sort() {
fmt.Println(m[k])
}
}
Extended playground example with multiple map types.
In all cases, the map and the sorted slice are decoupled from the moment the for
loop over the map range
is finished. Meaning that, if the map gets modified after the sorting logic, but before you use it, you can get into trouble. (Not thread / Go routine safe). If there is a change of parallel Map write access, you'll need to use a mutex around the writes and the sorted for
loop.
mutex.Lock()
for _, k := range m.sort() {
fmt.Println(m[k])
}
mutex.Unlock()
I had removed files from Compile Sources in Build Phases in Targets. I added main.m
and it worked.
No, it's not allowed. Neither C nor C++ support this feature by default, however TonyK points out (in the comments) that there are extensions to the GNU C compiler that enable this behavior in C.
I would recommend using jQuery with this function:
$(document).ready(function(){
$('#about').addClass('expand');
});
This will add the expand class to an element with id of about when the dom is ready on page load.
There are basically 2 things to bear in mind. You are only allowed to set it to NO if you either don't use encryption at all, or you are part of the exempt regulations. This applies to the following kind of applications:
Source: Chamber of Commerce: https://www.bis.doc.gov/index.php/policy-guidance/encryption/encryption-faqs#15
Consumer applications
- piracy and theft prevention for software or music;
- music, movies, tunes/music, digital photos – players, recorders and organizers
- games/gaming – devices, runtime software, HDMI and other component interfaces, development tools
- LCD TV, Blu-ray / DVD, video on demand (VoD), cinema, digital video recorders (DVRs) / personal video recorders (PVRs) – devices, on-line media guides, commercial content integrity and protection, HDMI and other component interfaces (not videoconferencing);
- printers, copiers, scanners, digital cameras, Internet cameras – including parts and sub-assemblies
- household utilities and appliances
Business / systems applications: systems operations, integration and control. Some examples
business process automation (BPA) – process planning and scheduling, supply chain management, inventory and delivery
transportation – safety and maintenance, systems monitoring and on-board controllers (including aviation, railway, and commercial automotive systems), ‘smart highway’ technologies, public transit operations and fare collection, etc.
industrial, manufacturing or mechanical systems - including robotics, plant safety, utilities, factory and other heavy equipment, facilities systems controllers such as fire alarms and HVAC
medical / clinical – including diagnostic applications, patient scheduling, and medical data records confidentiality
applied geosciences – mining / drilling, atmospheric sampling / weather monitoring, mapping / surveying, dams / hydrology
Research /scientific /analytical. Some examples:
business process management (BPM) – business process abstraction and modeling
scientific visualization / simulation / co-simulation (excluding such tools for computing, networking, cryptanalysis, etc.)
data synthesis tools for social, economic, and political sciences (e.g., economic, population, global climate change, public opinion polling, etc. forecasting and modeling)
Secure intellectual property delivery and installation. Some examples
software download auto-installers and updaters
license key product protection and similar purchase validation
software and hardware design IP protection
computer aided design (CAD) software and other drafting tools
Note: These regulations are also true for testing your app using TestFlight
I agree with somebody's recently deleted post that the differences in performance are so small that, with very very few exceptions, (he got dinged for saying never) you should not make your design decision based upon that.
In your example, where the elements are Objects, the performance difference should be minimal.
If you are dealing with a large number of primitives, an array will offer significantly better performance, both in memory and time.
Try Collections.shuffle(list).If usage of this method is barred for solving the problem, then one can look at the actual implementation.
This works fine with me
List<string> myList = new List<string>();
myList.Add(string.Format("{0}|{1}","hello","1") ;
label:myList[0].split('|')[0]
val: myList[0].split('|')[1]
Try to use Clear() function. It works great for me for disposing.
DataTable dt = GetDataSchema();
//populate dt, do whatever...
dt.Clear();
If you have date in integers, you could use like here:
Date date = new Date();
date.setYear(2010);
date.setMonth(07);
date.setDate(14)
date.setHours(9);
date.setMinutes(0);
date.setSeconds(0);
String time = new SimpleDateFormat("HH:mm:ss").format(date);
Keep shorter folder name, fixed for me.
import React, { Component } from "react";
import axios from "axios";
const CancelToken = axios.CancelToken;
let cancel;
class Abc extends Component {
componentDidMount() {
this.Api();
}
Api() {
// Cancel previous request
if (cancel !== undefined) {
cancel();
}
axios.post(URL, reqBody, {
cancelToken: new CancelToken(function executor(c) {
cancel = c;
}),
})
.then((response) => {
//responce Body
})
.catch((error) => {
if (axios.isCancel(error)) {
console.log("post Request canceled");
}
});
}
render() {
return <h2>cancel Axios Request</h2>;
}
}
export default Abc;
If you want to authenticate against a user name and password and without an authorization cookie, the MVC4 Authorize attribute won't work out of the box. However, you can add the following helper method to your controller to accept basic authentication headers. Call it from the beginning of your controller's methods.
void EnsureAuthenticated(string role)
{
string[] parts = UTF8Encoding.UTF8.GetString(Convert.FromBase64String(Request.Headers.Authorization.Parameter)).Split(':');
if (parts.Length != 2 || !Membership.ValidateUser(parts[0], parts[1]))
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "No account with that username and password"));
if (role != null && !Roles.IsUserInRole(parts[0], role))
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "An administrator account is required"));
}
From the client side, this helper creates a HttpClient
with the authentication header in place:
static HttpClient CreateBasicAuthenticationHttpClient(string userName, string password)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(userName + ':' + password)));
return client;
}
This can be initiated however you want. timeout is the method i used to keep it on the top of the hour.
I had the need for every hour to begin a code block on the hour. So this would start at server startup and run the interval hourly. Basicaly the initial run is to begin the interval within the same minute. So in a second from init, run immediately then on every 5 seconds.
var interval = 1000;
var timing =function(){
var timer = setInterval(function(){
console.log(interval);
if(interval == 1000){ /*interval you dont want anymore or increment/decrement */
interval = 3600000; /* Increment you do want for timer */
clearInterval(timer);
timing();
}
},interval);
}
timing();
Alternately if you wanted to just have something happen at start and then forever at a specific interval you could just call it at the same time as the setInterval. For example:
var this = function(){
//do
}
setInterval(function(){
this()
},3600000)
this()
Here we have this run the first time and then every hour.
this works for me:
v=$(cat <file_path>)
echo $v
The RFC for HTTP (as cited above) dictates that the headers are case-insensitive, however you will find that with certain browsers (I'm looking at you, IE) that capitalizing each of the words tends to be best:
Location: http://stackoverflow.com
Content-Type: text/plain
vs
location: http://stackoverflow.com
content-type: text/plain
This isn't "HTTP" standard, but just another one of the browser quirks, we as developers, have to think about.
The following code works fine:
@using (Html.BeginForm("Upload", "Upload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
}
and generates as expected:
<form action="/Upload/Upload" enctype="multipart/form-data" method="post">
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
</form>
On the other hand if you are writing this code inside the context of other server side construct such as an if
or foreach
you should remove the @
before the using
. For example:
@if (SomeCondition)
{
using (Html.BeginForm("Upload", "Upload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
}
}
As far as your server side code is concerned, here's how to proceed:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Upload");
}
I'd do it in two statements: DROP DATABASE ???
and then CREATE DATABASE ???
The solution is simple.
After installing Node, you should restart your VScode and run npm install command.
Sounds like you got your answer. Passing by value is expensive, but gives you a copy to work with if you need it.
I faced the same issue and it seems like none of the solution above works for Safari. For non-safari browser, this works just fine:
display: block; /* or in-line block according to your requirement */
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
For Safari, this is the one that works for me. Note that the media query to check if the browser is Safari might change over time, so just tinker with the media query if it doesn't work for you. With line-clamp
property, it would also be possible to have multiple lines in the web with ellipsis, see here.
// Media-query for Safari-only browser.
@media not all and (min-resolution: 0.001dpcm) {
@media {
-webkit-line-clamp: 1;
-webkit-box-orient: vertical;
display: -webkit-box;
white-space: normal;
}
}
I have installed IReport 5.6 with Java 7: not working
I tried to install Java 6 and added the path to "ireport.conf" file like the attached screenshot and it worked fine :D
So the steps is :
Install IReport 5.6
Install JDK 6
Edit "ireport.conf" file like the below image and Enjoy ;)
Square brackets:
jsObj['key' + i] = 'example' + 1;
In JavaScript, all arrays are objects, but not all objects are arrays. The primary difference (and one that's pretty hard to mimic with straight JavaScript and plain objects) is that array instances maintain the length
property so that it reflects one plus the numeric value of the property whose name is numeric and whose value, when converted to a number, is the largest of all such properties. That sounds really weird, but it just means that given an array instance, the properties with names like "0"
, "5"
, "207"
, and so on, are all treated specially in that their existence determines the value of length
. And, on top of that, the value of length
can be set to remove such properties. Setting the length
of an array to 0
effectively removes all properties whose names look like whole numbers.
OK, so that's what makes an array special. All of that, however, has nothing at all to do with how the JavaScript [ ]
operator works. That operator is an object property access mechanism which works on any object. It's important to note in that regard that numeric array property names are not special as far as simple property access goes. They're just strings that happen to look like numbers, but JavaScript object property names can be any sort of string you like.
Thus, the way the [ ]
operator works in a for
loop iterating through an array:
for (var i = 0; i < myArray.length; ++i) {
var value = myArray[i]; // property access
// ...
}
is really no different from the way [ ]
works when accessing a property whose name is some computed string:
var value = jsObj["key" + i];
The [ ]
operator there is doing precisely the same thing in both instances. The fact that in one case the object involved happens to be an array is unimportant, in other words.
When setting property values using [ ]
, the story is the same except for the special behavior around maintaining the length
property. If you set a property with a numeric key on an array instance:
myArray[200] = 5;
then (assuming that "200" is the biggest numeric property name) the length
property will be updated to 201
as a side-effect of the property assignment. If the same thing is done to a plain object, however:
myObj[200] = 5;
there's no such side-effect. The property called "200" of both the array and the object will be set to the value 5
in otherwise the exact same way.
One might think that because that length
behavior is kind-of handy, you might as well make all objects instances of the Array constructor instead of plain objects. There's nothing directly wrong about that (though it can be confusing, especially for people familiar with some other languages, for some properties to be included in the length
but not others). However, if you're working with JSON serialization (a fairly common thing), understand that array instances are serialized to JSON in a way that only involves the numerically-named properties. Other properties added to the array will never appear in the serialized JSON form. So for example:
var obj = [];
obj[0] = "hello world";
obj["something"] = 5000;
var objJSON = JSON.stringify(obj);
the value of "objJSON" will be a string containing just ["hello world"]
; the "something" property will be lost.
If you're able to use ES6 JavaScript features, you can use Computed Property Names to handle this very easily:
var key = 'DYNAMIC_KEY',
obj = {
[key]: 'ES6!'
};
console.log(obj);
// > { 'DYNAMIC_KEY': 'ES6!' }
Go to Tools->Options->Text Editor->c#->Advanced and uncheck the first checkbox Enter outlining mode when files open.
This will solve this problem forever
jQuery is just a JavaScript library (simply put, a JavaScript file). All you have to do is put it into your website directory and reference it in your HTML to use it.
For example, in the head tag of your webpage
<script type="text/javascript" src="../Js/jquery.js"></script>
You can download the current jQuery release from Downloading jQuery.
date_format
requires first argument as timestamp
so not the best way to convert a string. Use date_parse
instead.
Also, use %c
for non zero-padded month, %e
for non zero-padded day of the month and %Y
for four digit year.
SELECT date_parse('7/22/2016 6:05:04 PM', '%c/%e/%Y %r')
I think the most up to date gem for the new bootstrap version is form anjlab.
But I don't know if it currently works good with other gems like simple_form when you do rails generate simple_form:install --bootstrap
, etc. you may have to edit some initializers or configurations to fit the new bootstrap version.
You can access user data directly in the twig template without requesting anything in the controller. The user is accessible like that : app.user
.
Now, you can access every property of the user. For example, you can access the username like that : app.user.username
.
Warning, if the user is not logged, the app.user
is null.
If you want to check if the user is logged, you can use the is_granted
twig function. For example, if you want to check if the user has ROLE_ADMIN
, you just have to do is_granted("ROLE_ADMIN")
.
So, in every of your pages you can do :
{% if is_granted("ROLE") %}
Hi {{ app.user.username }}
{% endif %}
Any extension page (except content scripts) has direct access to the background page via chrome.extension.getBackgroundPage()
.
That means, within the popup page, you can just do:
chrome.extension.getBackgroundPage().console.log('foo');
To make it easier to use:
var bkg = chrome.extension.getBackgroundPage();
bkg.console.log('foo');
Now if you want to do the same within content scripts you have to use Message Passing to achieve that. The reason, they both belong to different domains, which make sense. There are many examples in the Message Passing page for you to check out.
Hope that clears everything.
Beware if your page is including other .jsp or .jspf (fragment)! If you don't set
<%@ page session="false" %>
on them as well, the parent page will end up starting a new session and setting the JSESSIONID cookie.
For .jspf pages in particular, this happens if you configured your web.xml with such a snippet:
<jsp-config>
<jsp-property-group>
<url-pattern>*.jspf</url-pattern>
</jsp-property-group>
</jsp-config>
in order to enable scriptlets inside them.
Constant Value Description
----------------------------------------------------------------
vbCr Chr(13) Carriage return
vbCrLf Chr(13) & Chr(10) Carriage return–linefeed combination
vbLf Chr(10) Line feed
vbCr : - return to line beginning
Represents a carriage-return character for print and display functions.
vbCrLf : - similar to pressing Enter
Represents a carriage-return character combined with a linefeed character for print and display
functions.
vbLf : - go to next line
Represents a linefeed character for print and display functions.
Read More from Constants Class
In order to create modular style sheets that are not dependent on the absolute location of a resource, authors may use relative URIs. Relative URIs (as defined in [RFC3986]) are resolved to full URIs using a base URI. RFC 3986, section 5, defines the normative algorithm for this process. For CSS style sheets, the base URI is that of the style sheet, not that of the source document.
For example, suppose the following rule:
body { background: url("yellow") }
is located in a style sheet designated by the URI:
http://www.example.org/style/basic.css
The background of the source document's BODY will be tiled with whatever image is described by the resource designated by the URI
http://www.example.org/style/yellow
User agents may vary in how they handle invalid URIs or URIs that designate unavailable or inapplicable resources.
Taken from the CSS 2.1 spec.
There two ways, what I found either go to the directory where kernels are residing and delete from there. Secondly, using this command below
List all kernels and grap the name of the kernel you want to remove
jupyter kernelspec list
to get the paths of all your kernels.
Then simply uninstall your unwanted-kernel
jupyter kernelspec remove kernel_name
To get date and time of your zone.
Date date = new Date();
DateFormat df = new SimpleDateFormat("MM/dd/YYYY HH:mm a");
df.setTimeZone(TimeZone.getDefault());
df.format(date);
The Best solution to change background checkbox color
input[type=checkbox] {_x000D_
margin-right: 5px;_x000D_
cursor: pointer;_x000D_
font-size: 14px;_x000D_
width: 15px;_x000D_
height: 12px;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
input[type=checkbox]:after {_x000D_
position: absolute;_x000D_
width: 10px;_x000D_
height: 15px;_x000D_
top: 0;_x000D_
content: " ";_x000D_
background-color: #ff0000;_x000D_
color: #fff;_x000D_
display: inline-block;_x000D_
visibility: visible;_x000D_
padding: 0px 3px;_x000D_
border-radius: 3px;_x000D_
}_x000D_
_x000D_
input[type=checkbox]:checked:after {_x000D_
content: "?";_x000D_
font-size: 12px;_x000D_
}
_x000D_
<input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>_x000D_
<input type="checkbox" name="vehicle" value="Car" checked> I have a car<br>_x000D_
_x000D_
<input type="checkbox" name="vehicle" value="Car" checked> I have a bus<br>
_x000D_
Try this code:
var myXmlDocument = new XmlDocument();
myXmlDocument.LoadXml(theString);
I had the same problem in a RecyclerView list with switches, and solved it using @oguzhand answer, but with this code inside the checkedChangeListener:
if (buttonView.isPressed()) {
if (isChecked) {
group.setSelected(true);
} else {
group.setSelected(false);
}
}else{
if (isChecked) {
buttonView.setChecked(false);
} else {
buttonView.setChecked(true);
}
}
(Where 'group' is the entity I want to select/deselect)
Don't fart around with inserting spaces. For one, older versions of IE won't know what you're talking about. Besides that, though, there are cleaner ways in general.
For colorless indents, use the text-indent
property.
p { text-indent: 1em; }
Edit:
If you want the space to be colored, you might consider adding a thick left border to the first letter. (I'd almost-but-not-quite say "instead", because the indent can be an issue if you use both. But it feels dirty to me to rely solely on the border to indent.) You can specify how far away, and how wide, the color is using the first letter's left margin/padding/border width.
p:first-letter { border-left: 1em solid red; }
A txt File with PIPE (|) delimited file can be read as :
df = spark.read.option("sep", "|").option("header", "true").csv("s3://bucket_name/folder_path/file_name.txt")
Any of LinearLayout.LayoutParams
and TableLayout.LayoutParams
worked for me, for buttons the right one is TableRow.LayoutParams
. That is:
TableRow.LayoutParams buttonParams = new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT, 1f);
About using MATCH_PARENT
or WRAP_CONTENT
be the same.
Try this code :
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal">
<ImageView
android:id="@+id/imgBusiness"
android:layout_width="40dp"
android:layout_height="40dp"
android:src="@drawable/back_detail" />
</LinearLayout>
Seems like only real solutions today revolve around scaling out or sharding. All modern databases (NoSQLs as well as NewSQLs) support horizontal scaling right out of the box, at the database layer, without the need for the application to have sharding code or something.
Unfortunately enough, for the trusted good-old MySQL, sharding is not provided "out of the box". ScaleBase (disclaimer: I work there) is a maker of a complete scale-out solution an "automatic sharding machine" if you like. ScaleBae analyzes your data and SQL stream, splits the data across DB nodes, and aggregates in runtime – so you won’t have to! And it's free download.
Don't get me wrong, NoSQLs are great, they're new, new is more choice and choice is always good!! But choosing NoSQL comes with a price, make sure you can pay it...
You can see here some more data about MySQL, NoSQL...: http://www.scalebase.com/extreme-scalability-with-mongodb-and-mysql-part-1-auto-sharding
Hope that helped.
This worked for me
<div style="display: flex; position: absolute; width: 100%;">
<div style="white-space: nowrap; overflow: hidden;text-overflow: ellipsis;">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi.
</div>
</div>
Adding position:absolute
to the parent container made it work.
PS: This is for anyone looking for a solution to dynamically truncating text.
EDIT: This was meant to be an answer for this question but since they are related and it could help someone on this question I shall also leave it here instead of deleting it.
You can first read the whole content of file into a String.
FileInputStream fileInputStream = null;
String data="";
StringBuffer stringBuffer = new StringBuffer("");
try{
fileInputStream=new FileInputStream(filename);
int i;
while((i=fileInputStream.read())!=-1)
{
stringBuffer.append((char)i);
}
data = stringBuffer.toString();
}
catch(Exception e){
LoggerUtil.printStackTrace(e);
}
finally{
if(fileInputStream!=null){
fileInputStream.close();
}
}
Now You will have the whole content into String ( data variable ).
JSONParser parser = new JSONParser();
org.json.simple.JSONArray jsonArray= (org.json.simple.JSONArray) parser.parse(data);
After that you can use jsonArray as you want.
I found a javascript trick, but you have to use the length of the string. Lets say you want 3 lines of width 250px, you can calculate the length per line i.e.
//get the total character length.
//Haha this might vary if you have a text with lots of "i" vs "w"
var totalLength = (width / yourFontSize) * yourNumberOfLines
//then ellipsify
function shorten(text, totalLength) {
var ret = text;
if (ret.length > totalLength) {
ret = ret.substr(0, totalLength-3) + "...";
}
return ret;
}
Yes, many.
Including, but not limited to:
 
or
 
(no character reference available) 
or  
 
or  
 
or  
 
or  
 
(no character reference available) 
or  
 
or  
 
or  
 
or  
span{background-color: red;}
_x000D_
<table>_x000D_
<tr><td>non breaking space:</td><td> <span> </span> or <span> </span></td></tr>_x000D_
<tr><td>narrow no-break space:</td><td> <span> </span></td></tr>_x000D_
<tr><td>en space:</td><td> <span> </span> or <span> </span></td></tr>_x000D_
<tr><td>em space:</td><td> <span> </span> or <span> </span></td></tr>_x000D_
<tr><td>3-per-em space:</td><td> <span> </span> or <span> </span></td></tr>_x000D_
<tr><td>4-per-em space:</td><td> <span> </span> or <span> </span></td></tr>_x000D_
<tr><td>6-per-em space:</td><td> <span> </span></td></tr>_x000D_
<tr><td>figure space:</td><td> <span> </span> or <span> </span></td></tr>_x000D_
<tr><td>punctuation space:</td><td> <span> </span> or <span> </td></tr>_x000D_
<tr><td>thin space:</td><td> <span> </span> or <span> </span></td></tr>_x000D_
<tr><td>hair space:</td><td> <span> </span> or <span> </span></td></tr>_x000D_
</table>
_x000D_
There are no cases where, given an array arr
, that the value of sizeof(arr) / sizeof(arr[0])
is not the count of elements, by the definition of array and sizeof
.
In fact, it's even directly mentioned (§5.3.3/2):
.... When applied to an array, the result is the total number of bytes in the array. This implies that the size of an array of n elements is n times the size of an element.
Emphasis mine. Divide by the size of an element, sizeof(arr[0])
, to obtain n.
Technically $('<div></div>')
will 'create' a div
element (or more specifically a DIV DOM element) but won't add it to your HTML document. You will then need to use that in combination with the other answers to actually do anything useful with it (such as using the append()
method or such like).
The manipulation documentation gives you all the various options on how to add new elements.
Ideally you should use StartWith
or EndWith
.
Here is an example:
DataContext dc = new DCGeneral();
List<Person> lstPerson= dc.GetTable<Person>().StartWith(c=> c.strNombre).ToList();
return lstPerson;
If you're using Node.js:
In that req.user is ObjectId format.
var mongoose = require("mongoose");
var ObjectId = mongoose.Schema.Types.ObjectId;
function getUsers(req, res)
User.findOne({"_id":req.user}, { password: 0 })
.then(data => {
res.send(data);})g
}
exports.getUsers = getUsers;
I was debugging the problem for the better part of the day and when I was close to burning the building I discovered the Process Monitor tool from Sysinternals.
Set it to monitor w3wp.exe
and check last events before it exits after you fire a request in the browser. Hope that helps further readers.
You need to repartition the Dataframe in a single partition and then define the format, path and other parameter to the file in Unix file system format and here you go,
df.repartition(1).write.format('com.databricks.spark.csv').save("/path/to/file/myfile.csv",header = 'true')
Read more about the repartition function Read more about the save function
However, repartition is a costly function and toPandas() is worst. Try using .coalesce(1) instead of .repartition(1) in previous syntax for better performance.
Read more on repartition vs coalesce functions.
Use unshift
, which modifies the existing array by adding the arguments to the beginning:
TheArray.unshift(TheNewObject);
The newer android phones in the market like HTC one, Xperia Z etc have resolutions in the >480dpi range, putting them in the new xxhdpi class as well. The new assets might be useful for them too.
This is ages too late, but good for anyone that is searching the topic. If you're not innoDB, and you're not worried about locking while you dump simply use the option:
--lock-tables=false
First make sure that Dog
class implements the method public String toString()
then use
System.out.println(list.get(index))
where index is the position inside the list. Of course since you provide your implementation you can decide how dog prints itself.
select site where you are facing the problem
Select Below
- Right click on Anonymous Authentication and click on edit and follow below
For a bit more flexibility than with micronyks answer, you can do it like that:
1. In your template, add #myIdentifier
to the element you want to obtain the width from. Example:
<p #myIdentifier>
my-component works!
</p>
2. In your controller, you can use this with @ViewChild('myIdentifier')
to get the width:
import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.scss']
})
export class MyComponentComponent implements AfterViewInit {
constructor() { }
ngAfterViewInit() {
console.log(this.myIdentifier.nativeElement.offsetWidth);
}
@ViewChild('myIdentifier')
myIdentifier: ElementRef;
}
Security
About the security risk with ElementRef
, like this, there is none. There would be a risk, if you would modify the DOM using an ElementRef. But here you are only getting DOM Elements so there is no risk. A risky example of using ElementRef
would be: this.myIdentifier.nativeElement.onclick = someFunctionDefinedBySomeUser;
. Like this Angular doesn't get a chance to use its sanitisation mechanisms since someFunctionDefinedBySomeUser
is inserted directly into the DOM, skipping the Angular sanitisation.
You can do something like this:
<html>
<head><title>My Glossary</title></head>
<body style="margin:0px;">
<div id="top" style="position:fixed;background:white;width:100%;">
<a href="#A">A</a> |
<a href="#B">B</a> |
<a href="#Z">Z</a>
</div>
<div id="term-defs" style="padding-top:1em;">
<dl>
<span id="A"></span>
<dt>foo</dt>
<dd>This is the sound made by a fool</dd>
<!-- and so on ... ->
</dl>
</div>
</body>
</html>
It's the position:fixed that's most important, because it takes the top div from the normal page flow and fixes it at it's pre-determined position. It's also important to use the padding-top:1em because otherwise the term-defs div would start right under the top div. The background and width are there to cover the contents of the term-defs div as they scroll under the top div.
Hope this helps.
One liner if you are using RxJava & RxBindings. Similar approach without the boilerplate. This also solves the hack to suppress warnings as in the answer by Tim Autin.
RxView.layoutChanges(yourView).take(1)
.subscribe(aVoid -> {
// width and height have been calculated here
});
This is it. No need to be unsubscribe, even if never called.
If you really must completely strip out the single quotes you can do this:
Replace(@strip, '''', '')
However, ordinarily you'd replace ' with '' and this will make SQL Server happy when querying the database. The trick with any of the built-in SQL functions (like replace) is that they too require you to double up your single quotes.
So to replace ' with '' in code you'd do this:
Replace(@strip, '''', '''''')
Of course... in some situations you can avoid having to do this entirely if you use parameters when querying the database. Say you're querying the database from a .NET application, then you'd use the SqlParameter class to feed the SqlCommand parameters for the query and all of this single quote business will be taken care of automatically. This is usually the preferred method as SQL parameters will also help prevent SQL injection attacks.
I think this is worthy of a separate answer: although internally unicode data is stored as UTF-16 in Sql Server this is the Little Endian flavour, so if you're calling the database from an external system, you probably need to specify UTF-16LE.
In SQL Server 2016 the wizard is a separate app. (Important: Excel wizard is only available in the 32-bit version of the wizard!). Use the MSDN page for instructions:
On the Start menu, point to All Programs, point toMicrosoft SQL Server , and then click Import and Export Data.
—or—
In SQL Server Data Tools (SSDT), right-click the SSIS Packages folder, and then click SSIS Import and Export Wizard.
—or—
In SQL Server Data Tools (SSDT), on the Project menu, click SSIS Import and Export Wizard.
—or—
In SQL Server Management Studio, connect to the Database Engine server type, expand Databases, right-click a database, point to Tasks, and then click Import Data or Export data.
—or—
In a command prompt window, run DTSWizard.exe, located in C:\Program Files\Microsoft SQL Server\100\DTS\Binn.
After that it should be pretty much the same (possibly with minor variations in the UI) as in @marc_s's answer.
Where do you want to see the output?
Messages being output via Debug.Print
will be displayed in the immediate window which you can open by pressing Ctrl+G.
You can also Activate the so called Immediate Window by clicking View -> Immediate Window on the VBE toolbar
I believe this should also do the job too:
background-size: contain;
It specifies that the image should be resized to fit within the element without losing it's aspect ratio.
To return a value when using try/catch
you can use a temporary variable, e.g.
public static double add(String[] values) {
double sum = 0.0;
try {
int length = values.length;
double arrayValues[] = new double[length];
for(int i = 0; i < length; i++) {
arrayValues[i] = Double.parseDouble(values[i]);
sum += arrayValues[i];
}
} catch(NumberFormatException e) {
e.printStackTrace();
} catch(RangeException e) {
throw e;
} finally {
System.out.println("Thank you for using the program!");
}
return sum;
}
Else you need to have a return in every execution path (try block or catch block) that has no throw
.
Possibly the problem is your two constructor overloads, one that sets the border, the other that doesn't:
public GoBoard(){
this.linien = 9;
this.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
}
public GoBoard(int pLinien){
this.linien = pLinien;
}
If you create a GoBoard object with the second constructor and pass an int parameter, the empty border will not be created. To fix this, consider changing this so both constructors set the border:
// default constructor
public GoBoard(){
this(9); // calls other constructor
}
public GoBoard(int pLinien){
this.linien = pLinien;
this.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
}
edit 1: The border you've added is more for controlling how components are added to your JPanel. If you want to draw in your one JPanel but have a border around the drawing, consider placing this JPanel into another JPanel, a holding JPanel that has the border. For e.g.,
class GoTest {
private static final int JB_WIDTH = 400;
private static final int JB_HEIGHT = JB_WIDTH;
private static void initGui() {
JFrame frame = new JFrame("GoBoard");
GoBoard jboard = new GoBoard();
jboard.setLayout(new BorderLayout(10, 10));
JPanel holdingPanel = new JPanel(new BorderLayout());
int eb = 20;
holdingPanel.setBorder(BorderFactory.createEmptyBorder(0, eb, eb, eb));
holdingPanel.add(jboard, BorderLayout.CENTER);
frame.add(holdingPanel, BorderLayout.CENTER);
jboard.setPreferredSize(new Dimension(JB_WIDTH, JB_HEIGHT));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//!! frame.setSize(400, 400);
frame.pack();
frame.setVisible(true);
}
// .... etc....
Another variation you can try is(expanding @mnel's answer) if you have many temp'x'.
here "n" could be the number of temp variables present
rm(list = c(paste("temp",c(1:n),sep="")))
Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:
Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.
#include <iostream>
#include <iomanip>
#include "modes.h"
#include "aes.h"
#include "filters.h"
int main(int argc, char* argv[]) {
//Key and IV setup
//AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-
//bit). This key is secretly exchanged between two parties before communication
//begins. DEFAULT_KEYLENGTH= 16 bytes
CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );
//
// String and Sink setup
//
std::string plaintext = "Now is the time for all good men to come to the aide...";
std::string ciphertext;
std::string decryptedtext;
//
// Dump Plain Text
//
std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
std::cout << plaintext;
std::cout << std::endl << std::endl;
//
// Create Cipher Text
//
CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );
CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
stfEncryptor.MessageEnd();
//
// Dump Cipher Text
//
std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;
for( int i = 0; i < ciphertext.size(); i++ ) {
std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
}
std::cout << std::endl << std::endl;
//
// Decrypt
//
CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );
CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
stfDecryptor.MessageEnd();
//
// Dump Decrypted Text
//
std::cout << "Decrypted Text: " << std::endl;
std::cout << decryptedtext;
std::cout << std::endl << std::endl;
return 0;
}
For installation details :
sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils
This is what worked for me in the end.
var showMenu = function(el, menu) {
//get the position of the placeholder element
var pos = $(el).offset();
var eWidth = $(el).outerWidth();
var mWidth = $(menu).outerWidth();
var left = (pos.left + eWidth - mWidth) + "px";
var top = 3+pos.top + "px";
//show the menu directly over the placeholder
$(menu).css( {
position: 'absolute',
zIndex: 5000,
left: left,
top: top
} );
$(menu).hide().fadeIn();
};
it does not work for me:
$('#Attachment').replaceWith($(this).clone());
or
$('#Attachment').replaceWith($('#Attachment').clone());
so in asp mvc I use razor features for replacing file input. at first create a variable for input string with Id and Name and then use it for showing in page and replacing on reset button click:
@{
var attachmentInput = Html.TextBoxFor(c => c.Attachment, new { type = "file" });
}
@attachmentInput
<button type="button" onclick="$('#@(Html.IdFor(p => p.Attachment))').replaceWith('@(attachmentInput)');">--</button>
The extra backslash is not actually added; it's just added by the repr()
function to indicate that it's a literal backslash. The Python interpreter uses the repr()
function (which calls __repr__()
on the object) when the result of an expression needs to be printed:
>>> '\\'
'\\'
>>> print '\\'
\
>>> print '\\'.__repr__()
'\\'
To explain in common usecase/purpose or layman way:
TrustStore : As the name indicates, its normally used to store the certificates of trusted entities. A process can maintain a store of certificates of all its trusted parties which it trusts.
keyStore : Used to store the server keys (both public and private) along with signed cert.
During the SSL handshake,
A client tries to access https://
And thus, Server responds by providing a SSL certificate (which is stored in its keyStore)
Now, the client receives the SSL certificate and verifies it via trustStore (i.e the client's trustStore already has pre-defined set of certificates which it trusts.). Its like : Can I trust this server ? Is this the same server whom I am trying to talk to ? No middle man attacks ?
Once, the client verifies that it is talking to server which it trusts, then SSL communication can happen over a shared secret key.
Note : I am not talking here anything about client authentication on server side. If a server wants to do a client authentication too, then the server also maintains a trustStore to verify client. Then it becomes mutual TLS
First import NumberFormat
. Then add this:
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
This will give you two decimal places and put a dollar sign if it's dealing with currency.
import java.text.NumberFormat;
public class Payroll
{
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
int hoursWorked = 80;
double hourlyPay = 15.52;
double grossPay = hoursWorked * hourlyPay;
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
System.out.println("Your gross pay is " + currencyFormatter.format(grossPay));
}
}
Given this code:
char text[50];
if(strlen(text) == 0) {}
Followed by a question about this code:
memset(text, 0, sizeof(text));
if(strlen(text) == 0) {}
I smell confusion. Specifically, in this case:
char text[50];
if(strlen(text) == 0) {}
... the contents of text[]
will be uninitialized and undefined. Thus, strlen(text)
will return an undefined result.
The easiest/fastest way to ensure that a C string is initialized to the empty string is to simply set the first byte to 0.
char text[50];
text[0] = 0;
From then, both strlen(text)
and the very-fast-but-not-as-straightforward (text[0] == 0)
tests will both detect the empty string.
Windows 10 appears to have a keyboard shortcut. According to How to open elevated command prompt in Windows 10 you can press ctrl + shift + enter from the search or start menu after typing cmd
for the search term.
(source: winaero.com)
I notice others have given the non-lambda syntax so just to have this complete I'll put in the lambda syntax equivalent:
Non-lambda (as per James's post):
var name = from i in DataContext.MyTable
where i.ID == 0
select i.Name
Equivalent lambda syntax:
var name = DataContext.MyTable.Where(i => i.ID == 0)
.Select(i => new { Name = i.Name });
There's not really much practical difference, just personal opinion on which you prefer.
The example 1 will not compile. This version of it compiles and runs. It uses lambda features to abbreviate it.
/*
* [RollYourOwnTimeouts.java]
*
* Summary: How to roll your own timeouts.
*
* Copyright: (c) 2016 Roedy Green, Canadian Mind Products, http://mindprod.com
*
* Licence: This software may be copied and used freely for any purpose but military.
* http://mindprod.com/contact/nonmil.html
*
* Requires: JDK 1.8+
*
* Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/
*
* Version History:
* 1.0 2016-06-28 initial version
*/
package com.mindprod.example;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static java.lang.System.*;
/**
* How to roll your own timeouts.
* Based on code at http://stackoverflow.com/questions/19456313/simple-timeout-in-java
*
* @author Roedy Green, Canadian Mind Products
* @version 1.0 2016-06-28 initial version
* @since 2016-06-28
*/
public class RollYourOwnTimeout
{
private static final long MILLIS_TO_WAIT = 10 * 1000L;
public static void main( final String[] args )
{
final ExecutorService executor = Executors.newSingleThreadExecutor();
// schedule the work
final Future<String> future = executor.submit( RollYourOwnTimeout::requestDataFromWebsite );
try
{
// where we wait for task to complete
final String result = future.get( MILLIS_TO_WAIT, TimeUnit.MILLISECONDS );
out.println( "result: " + result );
}
catch ( TimeoutException e )
{
err.println( "task timed out" );
future.cancel( true /* mayInterruptIfRunning */ );
}
catch ( InterruptedException e )
{
err.println( "task interrupted" );
}
catch ( ExecutionException e )
{
err.println( "task aborted" );
}
executor.shutdownNow();
}
/**
* dummy method to read some data from a website
*/
private static String requestDataFromWebsite()
{
try
{
// force timeout to expire
Thread.sleep( 14_000L );
}
catch ( InterruptedException e )
{
}
return "dummy";
}
}
location.reload();
You can use the reload
function in your if
condition for success and the page will reload after the condition is successful.
In Mvc using plain html in View Page with java script onclick
<input type="button" value="GO BACK" class="btn btn-primary"
onclick="location.href='@Request.UrlReferrer'" />
This works great. hope helps someone.
@JuanPieterse has already answered using @Html.ActionLink
so if possible someone can comment or answer using @Url.Action
I would change your approach a bit. First, I would use a BufferedReader
to read the file file in line-by-line using readLine()
. Then split each line on whitespace using String.split("\\s")
and use the size of the resulting array to see how many words are on that line. To get the number of characters you could either look at the size of each line or of each split word (depending of if you want to count whitespace as characters).
Don't split on commas -- it won't work for most CSV files, and this question has wayyyy too many views for the asker's kind of input data to apply to everyone. Parsing CSV is kind of scary since there's no truly official standard, and lots of delimited text writers don't consider edge cases.
This question is old, but I believe there's a better solution now that Papa Parse is available. It's a library I wrote, with help from contributors, that parses CSV text or files. It's the only JS library I know of that supports files gigabytes in size. It also handles malformed input gracefully.
1 GB file parsed in 1 minute:
(Update: With Papa Parse 4, the same file took only about 30 seconds in Firefox. Papa Parse 4 is now the fastest known CSV parser for the browser.)
Parsing text is very easy:
var data = Papa.parse(csvString);
Parsing files is also easy:
Papa.parse(file, {
complete: function(results) {
console.log(results);
}
});
Streaming files is similar (here's an example that streams a remote file):
Papa.parse("http://example.com/bigfoo.csv", {
download: true,
step: function(row) {
console.log("Row:", row.data);
},
complete: function() {
console.log("All done!");
}
});
If your web page locks up during parsing, Papa can use web workers to keep your web site reactive.
Papa can auto-detect delimiters and match values up with header columns, if a header row is present. It can also turn numeric values into actual number types. It appropriately parses line breaks and quotes and other weird situations, and even handles malformed input as robustly as possible. I've drawn on inspiration from existing libraries to make Papa, so props to other JS implementations.
This might work...
from p in db.products
select new
{
Owner = (p.price > 0 ?
from q in db.Users select q.Name :
from r in db.ExternalUsers select r.Name)
}
Way to get Excel data to text file in tab delimited form. Need to use Pandas as well as xlrd.
import pandas as pd
import xlrd
import os
Path="C:\downloads"
wb = pd.ExcelFile(Path+"\\input.xlsx", engine=None)
sheet2 = pd.read_excel(wb, sheet_name="Sheet1")
Excel_Filter=sheet2[sheet2['Name']=='Test']
Excel_Filter.to_excel("C:\downloads\\output.xlsx", index=None)
wb2=xlrd.open_workbook(Path+"\\output.xlsx")
df=wb2.sheet_by_name("Sheet1")
x=df.nrows
y=df.ncols
for i in range(0,x):
for j in range(0,y):
A=str(df.cell_value(i,j))
f=open(Path+"\\emails.txt", "a")
f.write(A+"\t")
f.close()
f=open(Path+"\\emails.txt", "a")
f.write("\n")
f.close()
os.remove(Path+"\\output.xlsx")
print(Excel_Filter)
We need to first generate the xlsx file with filtered data and then convert the information into a text file.
Depending on requirements, we can use \n \t for loops and type of data we want in the text file.
The best option is create a directive and wrap the slider features there. The secret is use $timeout, the jquery code will be called only when DOM is ready.
angular.module('app')
.directive('my-slider',
['$timeout', function($timeout) {
return {
restrict:'E',
scope: true,
template: '<div id="{{ id }}"></div>',
link: function($scope) {
$scope.id = String(Math.random()).substr(2, 8);
$timeout(function() {
angular.element('#'+$scope.id).slider();
});
}
};
}]
);
You need use patches.
import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig2 = plt.figure()
ax2 = fig2.add_subplot(111, aspect='equal')
ax2.add_patch(
patches.Rectangle(
(0.1, 0.1),
0.5,
0.5,
fill=False # remove background
) )
fig2.savefig('rect2.png', dpi=90, bbox_inches='tight')
The element.class selector is for styling situations such as this:
<span class="large"> </span>
<p class="large"> </p>
.large {
font-size:150%; font-weight:bold;
}
p.large {
color:blue;
}
Both your span and p will be assigned the font-size and font-weight from .large, but the color blue will only be assigned to p.
As others have pointed out, what you're working with is descendant selectors.
Always use UTC:
For example I have a schedule component that takes in one parameter DATETIME. When I call this using a GET verb I use the following format where my incoming parameter name is scheduleDate.
Example:
https://localhost/api/getScheduleForDate?scheduleDate=2003-11-21T01:11:11Z
Have you tried beforeUnload? This event fires immediately before the page responds to a navigation request, and this should include the modification of the href.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML>
<HEAD>
<TITLE></TITLE>
<META NAME="Generator" CONTENT="TextPad 4.6">
<META NAME="Author" CONTENT="?">
<META NAME="Keywords" CONTENT="?">
<META NAME="Description" CONTENT="?">
</HEAD>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$(window).unload(
function(event) {
alert("navigating");
}
);
$("#theButton").click(
function(event){
alert("Starting navigation");
window.location.href = "http://www.bbc.co.uk";
}
);
});
</script>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#FF0000" VLINK="#800000" ALINK="#FF00FF" BACKGROUND="?">
<button id="theButton">Click to navigate</button>
<a href="http://www.google.co.uk"> Google</a>
</BODY>
</HTML>
Beware, however, that your event will fire whenever you navigate away from the page, whether this is because of the script, or somebody clicking on a link. Your real challenge, is detecting the different reasons for the event being fired. (If this is important to your logic)
The language itself doesn't support this, but sometimes this is still a useful requirement. Besides the Bunch recipe, you can also write a little method which can access a dictionary using a dotted string:
def get_var(input_dict, accessor_string):
"""Gets data from a dictionary using a dotted accessor-string"""
current_data = input_dict
for chunk in accessor_string.split('.'):
current_data = current_data.get(chunk, {})
return current_data
which would support something like this:
>> test_dict = {'thing': {'spam': 12, 'foo': {'cheeze': 'bar'}}}
>> output = get_var(test_dict, 'thing.spam.foo.cheeze')
>> print output
'bar'
>>
Using HashMap it is walk in the park.
main(){
String[] array ={"a","ab","a","abc","abc","a","ab","ab","a"};
Map<String,Integer> hm = new HashMap();
for(String x:array){
if(!hm.containsKey(x)){
hm.put(x,1);
}else{
hm.put(x, hm.get(x)+1);
}
}
System.out.println(hm);
}
I was just creating the database link incorrectly.
Simple fix for me was to simply change 'SID' to SERVICE_NAME
CREATE DATABASE LINK my_db_link
CONNECT TO myUser IDENTIFIED BY myPassword
USING
'
(
DESCRIPTION=
(
ADDRESS=
(PROTOCOL=TCP)
(HOST=host-name-heren)
(PORT=1521)
)
(CONNECT_DATA=(SID=theNameOfTheDatabase))
)';
Changing
SID=theNameOfTheDatabase
to
SERVICE_NAME=theNameOfTheDatabase
resolved my issue.
You need to :
dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
Then :
dataGridView1.ColumnHeadersHeight = 60;
In w3.js include works like this:
<body>
<div w3-include-HTML="h1.html"></div>
<div w3-include-HTML="content.html"></div>
<script>w3.includeHTML();</script>
</body>
For proper description look into this: https://www.w3schools.com/howto/howto_html_include.asp
I contend that images (files) are NOT usually stored in a database base64 encoded. Instead, they are stored in their raw binary form in a binary (blob) column (or file).
Base64 is only used as a transport mechanism, not for storage. For example, you can embed a base64 encoded image into an XML document or an email message.
Base64 is also stream friendly. You can encode and decode on the fly (without knowing the total size of the data).
While base64 is fine for transport, do not store your images base64 encoded.
Base64 provides no checksum or anything of any value for storage.
Base64 encoding increases the storage requirement by 33% over a raw binary format. It also increases the amount of data that must be read from persistent storage, which is still generally the largest bottleneck in computing. It's generally faster to read less bytes and encode them on the fly. Only if your system is CPU bound instead of IO bound, and you're regularly outputting the image in base64, then consider storing in base64.
Inline images (base64 encoded images embedded in HTML) are a bottleneck themselves--you're sending 33% more data over the wire, and doing it serially (the web browser has to wait on the inline images before it can finish downloading the page HTML).
If you still wish to store images base64 encoded, please, whatever you do, make sure you don't store base64 encoded data in a UTF8 column then index it.
These things tend to be simpler if you write them a cell at a time, breaking the lengthy formulas up into smaller ones, where you can check them along the way. You can then hide the intermediate calculations, or roll them all up into a single formula.
For instance, taking James' formula:
=IFERROR(LEFT(A3, FIND(" ", A3, 1)), A3)
Which is only valid in Excel 2007 or later.
Break it up as follows:
B3: =FIND(" ", A3)
C3: =IF(ISERROR(B3),A3,LEFT(A3,B3-1))
It's just a little easier to work on, a chunk at a time. Once it's done, you can turn it into
=IF(ISERROR(FIND(" ", A3)),A3,LEFT(A3,FIND(" ", A3)-1))
if you so desire.
I spent four hours trying various permutations & search suggestions.
At last, found this post that worked but not the best solution to change the original code to test it.
set classpath=JDKbin;JDKlib;JREbin;JRElib;myClassLib;.
java <packageName>.<className>
also tried the java ..\<packageName>.<className>
Neither worked.
However first response alone worked. Thank you so much Abhi!!!
"I found one another common reason. If you create the java file inside a package using IDE like eclipse, you will find the package name on the top of your java file like "package pkgName". If you try to run this file from command prompt, you will get the NoClassDefFoundError error. Remove the package name from the java file and use the commands in the command prompt. Wasted 3 hours for this. -- Abhi"
Curious if there is any other way to make it work without having to change the original code? Thank you!
Interestingly, I've faced this issue many times due to different reasons. For e.g. Invalidating cache and restarting has helped as well.
Last I fixed it by correcting my output path in File -> Project Structure -> Project -> Project Compiler Output to : absolute_path_of_package/out
for e.g. : /Users/random-guy/myWorkspace/src/DummyProject/out
In Java 8 you can do this:
Instant inst = Instant.parse("2018-12-30T19:34:50.63Z");
// subtract 10 Days to Instant
Instant value = inst.minus(Period.ofDays(10));
// print result
System.out.println("Instant after subtracting Days: " + value);
Accepted answer is correct, but I like to define this little utility in most projects I build.
var types = {
'get': function(prop) {
return Object.prototype.toString.call(prop);
},
'null': '[object Null]',
'object': '[object Object]',
'array': '[object Array]',
'string': '[object String]',
'boolean': '[object Boolean]',
'number': '[object Number]',
'date': '[object Date]',
}
Used like this:
if(types.get(prop) == types.number) {
}
If you're using angular you can even have it cleanly injected:
angular.constant('types', types);
if you use ini_set on the fly then you will find here http://php.net/manual/en/ini.core.php the information that e.g. upload_max_filesize and post_max_size is not changeable on the fly (PHP_INI_PERDIR).
Only a php.ini, .htaccess or vhost config change seems to change these variables.
It depends on the specific use case.
If your table is static and only has a short list of values (and there is just a small chance that this would change during a lifetime of DB), I would recommend this construction:
CREATE TABLE Foo
(
FooCode VARCHAR(16), -- short code or shortcut, but with some meaning.
Name NVARCHAR(128), -- full name of entity, can be used as fallback in case when your localization for some language doesn't exist
LocalizationCode AS ('Foo.' + FooCode) -- This could be a code for your localization table...
)
Of course, when your table is not static at all, using INT as primary key is the best solution.
Many UNIX programs respect the http_proxy
environment variable, curl included. The format curl accepts is [protocol://]<host>[:port]
.
In your shell configuration:
export http_proxy http://proxy.server.com:3128
For proxying HTTPS requests, set https_proxy
as well.
Curl also allows you to set this in your .curlrc
file (_curlrc
on Windows), which you might consider more permanent:
http_proxy=http://proxy.server.com:3128
Hook denotes a place in the code where you dispatch an event of certain type, and if this event was registered before with a proper function to call back, then it would be handled by this registered function, otherwise nothing happens.
with below code you can listen SpaceBar pressing , in middle of your console execution and pause until another key is pressed and also listen for EscapeKey for breaking the main loop
static ConsoleKeyInfo cki = new ConsoleKeyInfo();
while(true) {
if (WaitOrBreak()) break;
//your main code
}
private static bool WaitOrBreak(){
if (Console.KeyAvailable) cki = Console.ReadKey(true);
if (cki.Key == ConsoleKey.Spacebar)
{
Console.Write("waiting..");
while (Console.KeyAvailable == false)
{
Thread.Sleep(250);Console.Write(".");
}
Console.WriteLine();
Console.ReadKey(true);
cki = new ConsoleKeyInfo();
}
if (cki.Key == ConsoleKey.Escape) return true;
return false;
}
You can write like below. Check out the syntax guidelines in this thread
AClass[] array;
...
array = new AClass[]{object1, object2};
If you find arrays annoying better use ArrayList.
You can use find_package to search for available boost libraries. It defers searching for Boost to FindBoost.cmake, which is default installed with CMake.
Upon finding Boost, the find_package()
call will have filled many variables (check the reference for FindBoost.cmake). Among these are BOOST_INCLUDE_DIRS
, Boost_LIBRARIES and Boost_XXX_LIBRARY variabels, with XXX replaced with specific Boost libraries. You can use these to specify include_directories and target_link_libraries.
For example, suppose you would need boost::program_options and boost::regex, you would do something like:
find_package( Boost REQUIRED COMPONENTS program_options regex )
include_directories( ${Boost_INCLUDE_DIRS} )
add_executable( run main.cpp ) # Example application based on main.cpp
# Alternatively you could use ${Boost_LIBRARIES} here.
target_link_libraries( run ${Boost_PROGRAM_OPTIONS_LIBRARY} ${Boost_REGEX_LIBRARY} )
Some general tips:
On
: Boost_USE_STATIC_LIBS
, Boost_USE_MULTITHREADED
, Boost_USE_STATIC_RUNTIME
add_definitions( -DBOOST_ALL_NO_LIB )
add_definitions( -DBOOST_ALL_DYN_LINK )
So the issue is that UTF-8 code unit values have been stored as a sequence of 16-bit code units in a C# string
. You simply need to verify that each code unit is within the range of a byte, copy those values into bytes, and then convert the new UTF-8 byte sequence into UTF-16.
public static string DecodeFromUtf8(this string utf8String)
{
// copy the string as UTF-8 bytes.
byte[] utf8Bytes = new byte[utf8String.Length];
for (int i=0;i<utf8String.Length;++i) {
//Debug.Assert( 0 <= utf8String[i] && utf8String[i] <= 255, "the char must be in byte's range");
utf8Bytes[i] = (byte)utf8String[i];
}
return Encoding.UTF8.GetString(utf8Bytes,0,utf8Bytes.Length);
}
DecodeFromUtf8("d\u00C3\u00A9j\u00C3\u00A0"); // déjà
This is easy, however it would be best to find the root cause; the location where someone is copying UTF-8 code units into 16 bit code units. The likely culprit is somebody converting bytes into a C# string
using the wrong encoding. E.g. Encoding.Default.GetString(utf8Bytes, 0, utf8Bytes.Length)
.
Alternatively, if you're sure you know the incorrect encoding which was used to produce the string, and that incorrect encoding transformation was lossless (usually the case if the incorrect encoding is a single byte encoding), then you can simply do the inverse encoding step to get the original UTF-8 data, and then you can do the correct conversion from UTF-8 bytes:
public static string UndoEncodingMistake(string mangledString, Encoding mistake, Encoding correction)
{
// the inverse of `mistake.GetString(originalBytes);`
byte[] originalBytes = mistake.GetBytes(mangledString);
return correction.GetString(originalBytes);
}
UndoEncodingMistake("d\u00C3\u00A9j\u00C3\u00A0", Encoding(1252), Encoding.UTF8);
Real answer: No, it's not possible.
OK, I have just thought of a way. Overlay your page with a div that covers the whole document. Inside that, create (say) 2,000 x 2,000 <a>
elements (so that the :hover
pseudo-class will work in IE 6, see), each 1 pixel in size. Create a CSS :hover
rule for those <a>
elements that changes a property (let's say font-family
). In your load handler, cycle through each of the 4 million <a>
elements, checking currentStyle
/ getComputedStyle()
until you find the one with the hover font. Extrapolate back from this element to get the co-ordinates within the document.
N.B. DON'T DO THIS.
If you're interested to get the plaintext (body part) from a BLOB
, you could use the CTX_DOC package.
For example, the CTX_DOC.FILTER
procedure can "generate either a plain text or a HTML version of a document". Be aware that CTX_DOC.FILTER
requires an index on the BLOB
column. If you don't want that, you could use the CTX_DOC.POLICY_FILTER
procedure instead, which doesn't require an index.
You can use Create USer to create a user
CREATE LOGIN sam
WITH PASSWORD = '340$Uuxwp7Mcxo7Khy';
USE AdventureWorks;
CREATE USER sam FOR LOGIN sam;
GO
and to Grant (Read-only access) you can use the following
GRANT SELECT TO sam
Hope that helps.
Probably, it will not matter at all. Read this post on Coding Horror ;): http://www.codinghorror.com/blog/archives/001218.html
This is an embed example of video played in HD 1080.
<iframe width="560" height="315" src="http://youtube.com/v/IplDUxTQxsE&vq=hd1080" frameborder="0" allowfullscreen="1"></iframe>
Let's break apart the code:http://youtube.com/v/
video_id
&vq=hd1080
Video id for that video: IplDUxTQxsE you will see this type of random code in the link of every YouTube video.
So far so good, this trick works for playing full HD videos directly on webpages!
You can change the quality to 720 too. &vq=hd720
HTML/JSP Markup:
<form:option
data-libelle="${compte.libelleCompte}"
data-raison="${compte.libelleSociale}" data-rib="${compte.numeroCompte}" <c:out value="${compte.libelleCompte} *MAD*"/>
</form:option>
JQUERY CODE: Event: change
var $this = $(this);
var $selectedOption = $this.find('option:selected');
var libelle = $selectedOption.data('libelle');
To have a element libelle.val() or libelle.text()
with pretty-print format:
import json
with open(path_to_file, 'w') as file:
json_string = json.dumps(sample, default=lambda o: o.__dict__, sort_keys=True, indent=2)
file.write(json_string)
If you want a destructive backspace, you'll need something like
"\b \b"
i.e. a backspace, a space, and another backspace.
Applets from what I remember do not need a main method, though I am not sure they are technically a program.
If you have multiple tables in the same worksheet you can give each table an object name and read the table using the OleDb method as shown here: http://vbktech.wordpress.com/2011/05/10/c-net-reading-and-writing-to-multiple-tables-in-the-same-microsoft-excel-worksheet/
In your onCreate() in your activity housing your fragments add a backstack change listener like so:
fragmentManager.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
List<Fragment> f = fragmentManager.getFragments();
Fragment frag = f.get(0);
currentFragment = frag.getClass().getSimpleName();
}
});
(Nb. my fragmentManager is declared global) Now every time you change fragment the currentFragment String will become the name of the current fragment. Then in the activities onBackPressed() you can control the actions of your back button as so:
@Override
public void onBackPressed() {
switch (currentFragment) {
case "FragmentOne":
// your code here
return;
case "FragmentTwo":
// your code here
return;
default:
fragmentManager.popBackStack();
// default action for any other fragment (return to previous)
}
}
I can confirm that this method works for me.
Update : Kotlin
override fun onBackPressed() {
when(supportFragmentManager.fragments[0].javaClass.simpleName){
"FragmentOne" -> doActionOne()
"FragmentTwo" -> doActionTwo()
else -> supportFragmentManager.popBackStack()
}
}
Visual Studio in left panel is Python "interactive Select karnel"
Pyton 3.7.x anaconda3/python.exe ('base':conda) I'm this fixing
By the way, to prevent this from happening in the first place, simply press Ctrl+C in terminal while SimpleHTTPServer is still running normally. This will "properly" stop the server and release the port so you don't have to find and kill the process again before restarting the server.
(Mods: I did try to put this comment on the best answer where it belongs, but I don't have enough reputation.)
I know this is an old question, but there is a more elegant way to remove duplicates in a NSArray
if you don't care about the order.
If we use Object Operators from Key Value Coding we can do this:
uniquearray = [yourarray valueForKeyPath:@"@distinctUnionOfObjects.self"];
As AnthoPak also noted it is possible to remove duplicates based on a property. An example would be: @distinctUnionOfObjects.name
With the suggestions @jhadesdev and the explanations from others, I've found the issue here.
After adding the code to see what was visible to the various class loaders I found this:
All versions of log4j Logger:
zip:<snip>war/WEB-INF/lib/log4j-1.2.17.jar!/org/apache/log4j/Logger.class
All versions of log4j visible from the classloader of the OAuthAuthorizer class:
zip:<snip>war/WEB-INF/lib/log4j-1.2.17.jar!/org/apache/log4j/Logger.class
All versions of XMLConfigurator:
jar:<snip>com.bea.core.bea.opensaml2_1.0.0.0_6-1-0-0.jar!/org/opensaml/xml/XMLConfigurator.class
zip:<snip>war/WEB-INF/lib/ipp-java-aggcat-v1-devkit-1.0.2.jar!/org/opensaml/xml/XMLConfigurator.class
zip:<snip>war/WEB-INF/lib/xmltooling-1.3.1.jar!/org/opensaml/xml/XMLConfigurator.class
All versions of XMLConfigurator visible from the classloader of the OAuthAuthorizer class:
jar:<snip>com.bea.core.bea.opensaml2_1.0.0.0_6-1-0-0.jar!/org/opensaml/xml/XMLConfigurator.class
zip:<snip>war/WEB-INF/lib/ipp-java-aggcat-v1-devkit-1.0.2.jar!/org/opensaml/xml/XMLConfigurator.class
zip:<snip>war/WEB-INF/lib/xmltooling-1.3.1.jar!/org/opensaml/xml/XMLConfigurator.class
I noticed that another version of XMLConfigurator was possibly getting picked up.
I decompiled that class and found this at line 60 (where the error was in the original stack trace) private static final Logger log = Logger.getLogger(XMLConfigurator.class);
and that class was importing from org.apache.log4j.Logger
!
So it was this class that was being loaded and used. My fix was to rename the jar file that contained this file as I can't find where I explicitly or indirectly load it. Which may pose a problem when I actually deploy.
Thanks for all help and the much needed lesson on class loading.
Here's a google chrome extension that'll allow you to download your reviews: https://chrome.google.com/webstore/detail/my-play-store-reviews/ldggikfajgoedghjnflfafiiheagngoa?hl=en
It's impossible to say without seeing your actual code. Likely the reason is a code path through your function that doesn't execute a return
statement. When the code goes down that path, the function ends with no value returned, and so returns None
.
Updated: It sounds like your code looks like this:
def b(self, p, data):
current = p
if current.data == data:
return True
elif current.data == 1:
return False
else:
self.b(current.next, data)
That else clause is your None
path. You need to return the value that the recursive call returns:
else:
return self.b(current.next, data)
BTW: using recursion for iterative programs like this is not a good idea in Python. Use iteration instead. Also, you have no clear termination condition.
I know this is a jQuery
related question, but now days with JS ES6 things are much easier. Since there is no pure javascript
answer, I thought I could add a simple pure javascript
solution to this, which in my opinion is much cleaner, by using the fetch()
API. This a modern way to implements network requests. In your case, since you already have a form element we can simply use it to build our request.
const form = document.forms["orderproductForm"];
const formInputs = form.getElementsByTagName("input");
let formData = new FormData();
for (let input of formInputs) {
formData.append(input.name, input.value);
}
fetch(form.action,
{
method: form.method,
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error.message))
.finally(() => console.log("Done"));
Honestly, I feel more comfortable with Alfred blog definitions:
Object: real world objects shares 2 main characteristics, state and behavior. Human have state (name, age) and behavior (running, sleeping). Car have state (current speed, current gear) and behavior (applying brake, changing gear). Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields and exposes its behavior through methods.
Class: is a “template” / “blueprint” that is used to create objects. Basically, a class will consists of field, static field, method, static method and constructor. Field is used to hold the state of the class (eg: name of Student object). Method is used to represent the behavior of the class (eg: how a Student object going to stand-up). Constructor is used to create a new Instance of the Class.
Instance: An instance is a unique copy of a Class that representing an Object. When a new instance of a class is created, the JVM will allocate a room of memory for that class instance.
Given the next example:
public class Person {
private int id;
private String name;
private int age;
public Person (int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (id != other.id)
return false;
return true;
}
public static void main(String[] args) {
//case 1
Person p1 = new Person(1, "Carlos", 20);
Person p2 = new Person(1, "Carlos", 20);
//case 2
Person p3 = new Person(2, "John", 15);
Person p4 = new Person(3, "Mary", 17);
}
}
For case 1, there are two instances of the class Person, but both instances represent the same object.
For case 2, there are two instances of the class Person, but each instance represent a different object.
So class, object and instance are different things. Object and instance are not synonyms as is suggested in the answer selected as right answer.
I'm not aware of anything in base R, but it's straight-forward to make a function to do this using substr
and nchar
:
x <- "some text in a string"
substrRight <- function(x, n){
substr(x, nchar(x)-n+1, nchar(x))
}
substrRight(x, 6)
[1] "string"
substrRight(x, 8)
[1] "a string"
This is vectorised, as @mdsumner points out. Consider:
x <- c("some text in a string", "I really need to learn how to count")
substrRight(x, 6)
[1] "string" " count"
How the hash is computed does usually not depend on the hashtable, but on the items added to it. In frameworks/base class libraries such as .net and Java, each object has a GetHashCode() (or similar) method returning a hash code for this object. The ideal hash code algorithm and the exact implementation depends on the data represented by in the object.
I like doing:
var menu = document.getElementsByTagName('div');
for (var i = 0; menu[i]; i++) {
...
}
There is no call to the length of the array on every iteration.
The minimum configuration to properly run sqlplus
from the shell is to set ORACLE_HOME
and LD_LIBRARY_PATH
. For ease of use, you might want to set the PATH
accordingly too.
Assuming you have unzipped the required archives in /opt/oracle/instantclient_11_1
:
$ export ORACLE_HOME=/opt/oracle/instantclient_11_1
$ export LD_LIBRARY_PATH="$ORACLE_HOME"
$ export PATH="$ORACLE_HOME:$PATH"
$ sqlplus
SQL*Plus: Release 11.1.0.7.0 - Production on Wed Dec 31 14:06:06 2014
...
Had the same problem and none of the CSS solutions presented here worked.
What worked for me was setting up a height="360" without setting any width. My photos aren't the same size and like this they have room to adjust their with but keep the height fixed.
This expands the ternary option into if/else which minified is equivalent to the ternary option but doesn't sacrifice readability.
const clamp = (value, min, max) => {
if (value < min) return min;
if (value > max) return max;
return value;
}
Minifies to 35b (or 43b if using function
):
const clamp=(c,a,l)=>c<a?a:c>l?l:c;
Also, depending on what perf tooling or browser you use you get various outcomes of whether the Math based implementation or ternary based implementation is faster. In the case of roughly the same performance, I would opt for readability.
I've changed the recursion to iteration.
def MovingTheBall(listOfBalls,position,numCell):
while 1:
stop=1
positionTmp = (position[0]+choice([-1,0,1]),position[1]+choice([-1,0,1]),0)
for i in range(0,len(listOfBalls)):
if positionTmp==listOfBalls[i].pos:
stop=0
if stop==1:
if (positionTmp[0]==0 or positionTmp[0]>=numCell or positionTmp[0]<=-numCell or positionTmp[1]>=numCell or positionTmp[1]<=-numCell):
stop=0
else:
return positionTmp
Works good :D
The other answers are all good. For Xilinx FPGA designs, it is best not to use global reset lines, and use initial
blocks for reset conditions for most logic. Here is the white paper from Ken Chapman (Xilinx FPGA guru)
http://japan.xilinx.com/support/documentation/white_papers/wp272.pdf
As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().
Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static
for the example. Once it's done, add this line in your server code:
app.use("/static", express.static('./static/'));
This will effectively serve every file in your "static" folder via the /static route.
Querying your index.js file in the client thus becomes:
<script src="static/index.js"></script>
Apart from what people have already mentioned I am just introducing indexes to the mix.
So imagine a large collection, with let's say over 1 million documents and you have to run a query like this.
The WiredTiger Internal cache will have to keep all that data in the cache if you have to run this query on it, if not that data will be fed into the WT Internal Cache either from FS Cache or Disk before the retrieval from DB is done (in batches if being called for from a driver connected to database & given that 1 million documents are not returned in 1 go, cursor comes into play)
Covered query can be an alternative. Copying the text from docs directly.
When an index covers a query, MongoDB can both match the query conditions and return the results using only the index keys; i.e. MongoDB does not need to examine documents from the collection to return the results.
When an index covers a query, the explain result has an IXSCAN stage that is not a descendant of a FETCH stage, and in the executionStats, the totalDocsExamined is 0.
Query : db.getCollection('qaa').find({roll_no : {$gte : 0}},{_id : 0, roll_no : 1})
Index : db.getCollection('qaa').createIndex({roll_no : 1})
If the index here is in WT Internal Cache then it would be a straight forward process to get the values. An index has impact on the write performance of the system thus this would make more sense if the reads are a plenty compared to the writes.
As Charles Duffey has stated, XML parsers are best parsed with a proper XML parsing tools. For one time job the following should work.
grep -oPm1 "(?<=<title>)[^<]+"
$ echo "$data"
<item>
<title>15:54:57 - George:</title>
<description>Diane DeConn? You saw Diane DeConn!</description>
</item>
<item>
<title>15:55:17 - Jerry:</title>
<description>Something huh?</description>
$ title=$(grep -oPm1 "(?<=<title>)[^<]+" <<< "$data")
$ echo "$title"
15:54:57 - George:
A simpler approach like the one Ioannis Filippidis do :
import matplotlib.pyplot as plt
import numpy as np
# evenly sampled time at 200ms intervals
tMin=-1 ;tMax=10
t = np.arange(tMin, tMax, 0.1)
# red dashes, blue points default
plt.plot(t, 22*t, 'r--', t, t**2, 'b')
factor=3/4 ;offset=20 # text position in view
textPosition=[(tMax+tMin)*factor,22*(tMax+tMin)*factor]
plt.text(textPosition[0],textPosition[1]+offset,'22 t',color='red',fontsize=20)
textPosition=[(tMax+tMin)*factor,((tMax+tMin)*factor)**2+20]
plt.text(textPosition[0],textPosition[1]+offset, 't^2', bbox=dict(facecolor='blue', alpha=0.5),fontsize=20)
plt.show()
public class JSONPage {
Logger log = Logger.getLogger("com.prodapt.autotest.gui.design.EditTestData");
public static final JFrame JSONFrame = new JFrame();
public final JPanel jPanel = new JPanel();
JLabel IdLabel = new JLabel("JSON ID*");
JLabel DataLabel = new JLabel("JSON Data*");
JFormattedTextField JId = new JFormattedTextField("Auto Generated");
JTextArea JData = new JTextArea();
JButton Cancel = new JButton("Cancel");
JButton Add = new JButton("Add");
public void JsonPage() {
JSONFrame.getContentPane().add(jPanel);
JSONFrame.add(jPanel);
JSONFrame.setSize(400, 250);
JSONFrame.setResizable(false);
JSONFrame.setVisible(false);
JSONFrame.setTitle("Add JSON Data");
JSONFrame.setLocationRelativeTo(null);
jPanel.setLayout(null);
JData.setWrapStyleWord(true);
JId.setEditable(false);
IdLabel.setBounds(20, 30, 120, 25);
JId.setBounds(100, 30, 120, 25);
DataLabel.setBounds(20, 60, 120, 25);
JData.setBounds(100, 60, 250, 75);
Cancel.setBounds(80, 170, 80, 30);
Add.setBounds(280, 170, 50, 30);
jPanel.add(IdLabel);
jPanel.add(JId);
jPanel.add(DataLabel);
jPanel.add(JData);
jPanel.add(Cancel);
jPanel.add(Add);
SwingUtilities.updateComponentTreeUI(JSONFrame);
Cancel.addActionListener(new ActionListener() {
@SuppressWarnings("deprecation")
@Override
public void actionPerformed(ActionEvent e) {
JData.setText("");
JSONFrame.hide();
TestCasePage.testCaseFrame.show();
}
});
Add.addActionListener(new ActionListener() {
@SuppressWarnings("deprecation")
@Override
public void actionPerformed(ActionEvent e) {
try {
PreparedStatement pStatement = DAOHelper.getInstance()
.createJSON(
ConnectionClass.getInstance()
.getConnection());
pStatement.setString(1, null);
if (JData.getText().toString().isEmpty()) {
JOptionPane.showMessageDialog(JSONFrame,
"Must Enter JSON Path");
} else {
// System.out.println(eleSelectBy);
pStatement.setString(2, JData.getText());
pStatement.executeUpdate();
JOptionPane.showMessageDialog(JSONFrame, "!! Added !!");
log.info("JSON Path Added"+JData);
JData.setText("");
JSONFrame.hide();
}
} catch (SQLException e1) {
JData.setText("");
log.info("Error in Adding JSON Path");
e1.printStackTrace();
}
}
});
}
}
My UI has a vertical scrolling list of thumbs within a thumbbar The goal was to make the current thumb right in the center of the thumbbar. I started from the approved answer, but found that there were a few tweaks to truly center the current thumb. hope this helps someone else.
markup:
<ul id='thumbbar'>
<li id='thumbbar-123'></li>
<li id='thumbbar-124'></li>
<li id='thumbbar-125'></li>
</ul>
jquery:
// scroll the current thumb bar thumb into view
heightbar = $('#thumbbar').height();
heightthumb = $('#thumbbar-' + pageid).height();
offsetbar = $('#thumbbar').scrollTop();
$('#thumbbar').animate({
scrollTop: offsetthumb.top - heightbar / 2 - offsetbar - 20
});
maybe SSL
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
// ignore ssl error
if (handler != null){
handler.proceed();
} else {
super.onReceivedSslError(view, null, error);
}
}
You can try using USING
:
The optional
USING
clause specifies how to compute the new column value from the old; if omitted, the default conversion is the same as an assignment cast from old data type to new. AUSING
clause must be provided if there is no implicit or assignment cast from old to new type.
So this might work (depending on your data):
alter table presales alter column code type numeric(10,0) using code::numeric;
-- Or if you prefer standard casting...
alter table presales alter column code type numeric(10,0) using cast(code as numeric);
This will fail if you have anything in code
that cannot be cast to numeric; if the USING fails, you'll have to clean up the non-numeric data by hand before changing the column type.