TreeMap, which is an implementation of the SortedMap interface, would work.
How do I use it ?
Map<Float, MyObject> map = new TreeMap<Float, MyObject>();
you can swipe the key and the value. For example
String[] k = {"Elena", "Thomas", "Hamilton", "Suzie", "Phil"};
int[] v = {341, 273, 278, 329, 445};
TreeMap<Integer,String>a=new TreeMap();
for (int i = 0; i < k.length; i++)
a.put(v[i],k[i]);
System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());
a.remove(a.firstEntry().getKey());
System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());
Adding to the other excellent posts.
Sometimes you don't want to specify the number of arguments and want to use keys for them (the compiler will complain if one argument passed in a dictionary is not used in the method).
def manyArgs1(args):
print args.a, args.b #note args.c is not used here
def manyArgs2(args):
print args.c #note args.b and .c are not used here
class Args: pass
args = Args()
args.a = 1
args.b = 2
args.c = 3
manyArgs1(args) #outputs 1 2
manyArgs2(args) #outputs 3
Then you can do things like
myfuns = [manyArgs1, manyArgs2]
for fun in myfuns:
fun(args)
you can use this simple code that did not use jQuery or other libraries
var a=({});
//check is an empty object
if(JSON.stringify(a)=='{}') {
alert('it is empty');
} else {
alert('it is not empty');
}
JSON class and it's functions (parse and stringify) are very usefull but has some problems with IE7 that you can fix it with this simple code http://www.json.org/js.html.
Other Simple Way (simplest Way) :
you can use this way without using jQuery or JSON object.
var a=({});
function isEmptyObject(obj) {
if(typeof obj!='object') {
//it is not object, so is not empty
return false;
} else {
var x,i=0;
for(x in obj) {
i++;
}
if(i>0) {
//this object has some properties or methods
return false;
} else {
//this object has not any property or method
return true;
}
}
}
alert(isEmptyObject(a)); //true is alerted
I used this way to do that for multiple blocks without conjuring new JavaScript code:
<a href="#" data-toggle="thatblock">Show/Hide Content</a>
<div id="thatblock" style="display: none">
Here is some description that will appear when we click on the button
</div>
Then a JavaScript portion for all such cases:
$(function() {
$('*[data-toggle]').click(function() {
$('#'+$(this).attr('data-toggle')).toggle();
return false;
});
});
What works best for me is using quote()
and eval()
together.
For example, let's print each column using a for loop
:
Columns <- names(dat)
for (i in 1:ncol(dat)){
dat[, eval(quote(Columns[i]))] %>% print
}
I like to use:
git diff HEAD^
Or if I only want to diff a specific file:
git diff HEAD^ -- /foo/bar/baz.txt
About the Count() method, if the IEnumarable is an ICollection, then we can't iterate across all items because we can retrieve the Count field of ICollection, if the IEnumerable is not an ICollection we must iterate across all items using a while with a MoveNext, take a look the .NET Framework Code:
public static int Count<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
throw Error.ArgumentNull("source");
ICollection<TSource> collectionoft = source as ICollection<TSource>;
if (collectionoft != null)
return collectionoft.Count;
ICollection collection = source as ICollection;
if (collection != null)
return collection.Count;
int count = 0;
using (IEnumerator<TSource> e = source.GetEnumerator())
{
checked
{
while (e.MoveNext()) count++;
}
}
return count;
}
Reference: Reference Source Enumerable
Here is a solution if you need to hook up some methods to @User for use in your views. No solution for any serious membership customization, but if the original question was needed for views alone then this perhaps would be enough. The below was used for checking a variable returned from a authorizefilter, used to verify if some links wehere to be presented or not(not for any kind of authorization logic or access granting).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Principal;
namespace SomeSite.Web.Helpers
{
public static class UserHelpers
{
public static bool IsEditor(this IPrincipal user)
{
return null; //Do some stuff
}
}
}
Then just add a reference in the areas web.config, and call it like below in the view.
@User.IsEditor()
this can be done this way
Overloaded Copy Constructor
/*
* Soumil Nitin SHah
* Github: https://github.com/soumilshah1995
*/
#include <iostream>
using namespace std;
class Matrix{
public:
/*
* Declare the Row and Column
*
*/
int r_size;
int c_size;
int **arr;
public:
/*
* Constructor and Destructor
*/
Matrix(int r_size, int c_size):r_size{r_size},c_size{c_size}
{
arr = new int*[r_size];
// This Creates a 2-D Pointers
for (int i=0 ;i < r_size; i++)
{
arr[i] = new int[c_size];
}
// Initialize all the Vector to 0 initially
for (int row=0; row<r_size; row ++)
{
for (int column=0; column < c_size; column ++)
{
arr[row][column] = 0;
}
}
std::cout << "Constructor -- creating Array Size ::" << r_size << " " << c_size << endl;
}
~Matrix()
{
std::cout << "Destructpr -- Deleting Array Size ::" << r_size <<" " << c_size << endl;
}
Matrix(const Matrix &source):Matrix(source.r_size, source.c_size)
{
for (int row=0; row<source.r_size; row ++)
{
for (int column=0; column < source.c_size; column ++)
{
arr[row][column] = source.arr[row][column];
}
}
cout << "Copy Constructor " << endl;
}
public:
/*
* Operator Overloading
*/
friend std::ostream &operator<<(std::ostream &os, Matrix & rhs)
{
int rowCounter = 0;
int columnCOUNTER = 0;
int globalCounter = 0;
for (int row =0; row < rhs.r_size; row ++)
{
for (int column=0; column < rhs.c_size ; column++)
{
globalCounter = globalCounter + 1;
}
rowCounter = rowCounter + 1;
}
os << "Total There are " << globalCounter << " Elements" << endl;
os << "Array Elements are as follow -------" << endl;
os << "\n";
for (int row =0; row < rhs.r_size; row ++)
{
for (int column=0; column < rhs.c_size ; column++)
{
os << rhs.arr[row][column] << " ";
}
os <<"\n";
}
return os;
}
void operator()(int row, int column , int Data)
{
arr[row][column] = Data;
}
int &operator()(int row, int column)
{
return arr[row][column];
}
Matrix &operator=(Matrix &rhs)
{
cout << "Assingment Operator called " << endl;cout <<"\n";
if(this == &rhs)
{
return *this;
} else
{
delete [] arr;
arr = new int*[r_size];
// This Creates a 2-D Pointers
for (int i=0 ;i < r_size; i++)
{
arr[i] = new int[c_size];
}
// Initialize all the Vector to 0 initially
for (int row=0; row<r_size; row ++)
{
for (int column=0; column < c_size; column ++)
{
arr[row][column] = rhs.arr[row][column];
}
}
return *this;
}
}
};
int main()
{
Matrix m1(3,3); // Initialize Matrix 3x3
cout << m1;cout << "\n";
m1(0,0,1);
m1(0,1,2);
m1(0,2,3);
m1(1,0,4);
m1(1,1,5);
m1(1,2,6);
m1(2,0,7);
m1(2,1,8);
m1(2,2,9);
cout << m1;cout <<"\n"; // print Matrix
cout << "Element at Position (1,2) : " << m1(1,2) << endl;
Matrix m2(3,3);
m2 = m1;
cout << m2;cout <<"\n";
print(m2);
return 0;
}
The difference is in the return values, i.e:
Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in application/x-www-form-urlencoded media type. This differs from the » RFC 1738 encoding (see rawurlencode()) in that for historical reasons, spaces are encoded as plus (+) signs.
Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits. This is the encoding described in » RFC 1738 for protecting literal characters from being interpreted as special URL delimiters, and for protecting URLs from being mangled by transmission media with character conversions (like some email systems).
The two are very similar, but the latter (rawurlencode) will replace spaces with a '%' and two hex digits, which is suitable for encoding passwords or such, where a '+' is not e.g.:
echo '<a href="ftp://user:', rawurlencode('foo @+%/'),
'@ftp.example.com/x.txt">';
//Outputs <a href="ftp://user:foo%20%40%2B%25%[email protected]/x.txt">
You can open a command prompt and do a
route print
and see your current routing table.
You can modify it by
route add d.d.d.d mask m.m.m.m g.g.g.g
route delete d.d.d.d mask m.m.m.m g.g.g.g
route change d.d.d.d mask m.m.m.m g.g.g.g
these seem to work
I run a ping d.d.d.d -t change the route and it changes. (my test involved routing to a dead route and the ping stopped)
Why not use a mechanism similar to Apache cron jobs? http://en.wikipedia.org/wiki/Cron
For calendar\scheduling I'd use slightly different values for "bits" to accommodate standard calendar reoccurence events - instead of [day of week (0 - 7), month (1 - 12), day of month (1 - 31), hour (0 - 23), min (0 - 59)]
-- I'd use something like [Year (repeat every N years), month (1 - 12), day of month (1 - 31), week of month (1-5), day of week (0 - 7)]
Hope this helps.
$('div.alldivs :first-child');
Or you can just refer to the id directly:
$('#div1');
As suggested, you might be better of using the child selector:
$('div.alldivs > div:first-child')
If you dont have to use first-child
, you could use :first
as also suggested, or $('div.alldivs').children(0)
.
Yes, it is normal. This is because you checkout a single commit, that doesnt have a head. Especially it is (sooner or later) not a head of any branch.
But there is usually no problem with that state. You may create a new branch from the tag, if this makes you feel safer :)
It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.
Edit: This is what the forums say:
By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.
To disable:
/system/bin/bugmailer.sh must be deleted/renamed.
There should be a folder on your SD card called "bug reports".
Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948
And this one: http://forum.xda-developers.com/showthread.php?t=1405639
Usually you don't have to worry about calculating them as your assembler (or linker) will take of getting the calculations right. Let's say you have a small function:
func:
slti $t0, $a0, 2
beq $t0, $zero, cont
ori $v0, $zero, 1
jr $ra
cont:
...
jal func
...
When translating the above code into a binary stream of instructions the assembler (or linker if you first assembled into an object file) it will be determined where in memory the function will reside (let's ignore position independent code for now). Where in memory it will reside is usually specified in the ABI or given to you if you're using a simulator (like SPIM which loads the code at 0x400000
- note the link also contains a good explanation of the process).
Assuming we're talking about the SPIM case and our function is first in memory, the slti
instruction will reside at 0x400000
, the beq
at 0x400004
and so on. Now we're almost there! For the beq
instruction the branch target address is that of cont
(0x400010
) looking at a MIPS instruction reference we see that it is encoded as a 16-bit signed immediate relative to the next instruction (divided by 4 as all instructions must reside on a 4-byte aligned address anyway).
That is:
Current address of instruction + 4 = 0x400004 + 4 = 0x400008
Branch target = 0x400010
Difference = 0x400010 - 0x400008 = 0x8
To encode = Difference / 4 = 0x8 / 4 = 0x2 = 0b10
Encoding of beq $t0, $zero, cont
0001 00ss ssst tttt iiii iiii iiii iiii
---------------------------------------
0001 0001 0000 0000 0000 0000 0000 0010
As you can see you can branch to within -0x1fffc .. 0x20000
bytes. If for some reason, you need to jump further you can use a trampoline (an unconditional jump to the real target placed placed within the given limit).
Jump target addresses are, unlike branch target addresses, encoded using the absolute address (again divided by 4). Since the instruction encoding uses 6 bits for the opcode, this only leaves 26 bits for the address (effectively 28 given that the 2 last bits will be 0) therefore the 4 bits most significant bits of the PC register are used when forming the address (won't matter unless you intend to jump across 256 MB boundaries).
Returning to the above example the encoding for jal func
is:
Destination address = absolute address of func = 0x400000
Divided by 4 = 0x400000 / 4 = 0x100000
Lower 26 bits = 0x100000 & 0x03ffffff = 0x100000 = 0b100000000000000000000
0000 11ii iiii iiii iiii iiii iiii iiii
---------------------------------------
0000 1100 0001 0000 0000 0000 0000 0000
You can quickly verify this, and play around with different instructions, using this online MIPS assembler i ran across (note it doesn't support all opcodes, for example slti
, so I just changed that to slt
here):
00400000: <func> ; <input:0> func:
00400000: 0000002a ; <input:1> slt $t0, $a0, 2
00400004: 11000002 ; <input:2> beq $t0, $zero, cont
00400008: 34020001 ; <input:3> ori $v0, $zero, 1
0040000c: 03e00008 ; <input:4> jr $ra
00400010: <cont> ; <input:5> cont:
00400010: 0c100000 ; <input:7> jal func
I had to add allowFullScreen attribute to the "parent" iframe. The case of the attribute does matter. I don't think Firefox or Edge/IE11 has a browser specific allowFullScreen attribute. So it looks something like this:
<iframe allowFullScreen='allowFullScreen' src='http://api.youtube.com/...'/>
I would use the element.addEventListener
method to link it to a function. From that function you can call multiple functions.
The advantage I see in binding an event to a single function and then calling multiple functions is that you can perform some error checking, have some if else statements so that some functions only get called if certain criteria are met.
If you are using React try this custom Image component:
import React, { useRef } from 'react';
import PropTypes from 'prop-types';
import defaultErrorImage from 'assets/images/default-placeholder-image.png';
const Image = ({ src, alt, className, onErrorImage }) => {
const imageEl = useRef(null);
return (
<img
src={src}
alt={alt}
className={className}
onError={() => {
imageEl.current.src = onErrorImage;
}}
ref={imageEl}
/>
);
};
Image.defaultProps = {
onErrorImage: defaultErrorImage,
};
Image.propTypes = {
src: PropTypes.string.isRequired,
alt: PropTypes.string.isRequired,
className: PropTypes.string.isRequired,
onErrorImage: PropTypes.string,
};
export default Image;
If you're willing to include the jQuery UI library, in addition to jQuery itself, then you can simply use hide()
, with additional arguments, as follows:
$(document).ready(
function(){
$('#slider').click(
function(){
$(this).hide('slide',{direction:'right'},1000);
});
});
Without using jQuery UI, you could achieve your aim just using animate()
:
$(document).ready(
function(){
$('#slider').click(
function(){
$(this)
.animate(
{
'margin-left':'1000px'
// to move it towards the right and, probably, off-screen.
},1000,
function(){
$(this).slideUp('fast');
// once it's finished moving to the right, just
// removes the the element from the display, you could use
// `remove()` instead, or whatever.
}
);
});
});
If you do choose to use jQuery UI, then I'd recommend linking to the Google-hosted code, at: https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js
I might have another (simple) workaround for this...
Since String.fromCharCode(key) returns weird things upon AZERTY keyboard (numerical keypad returns code as g for 1, and 1 for & character ..
I've realized catching the final value on keyup within the input to reset it to an arbitrary value is a simpler, lightweight & bugproof method (could also be done via some regex ... to keep decimals and so on ... don't have to filter other Ctrl, Home, Del, and Enter events...)
Usage with jq :
<input class='pn'>
<script>
function pn(el){nb=el.value;if(isNaN(nb) || nb<1)el.value=1;}
jQuery('.pn').keyup(function(){pn(this);});
</script>
Onkeyup attribute:
<input onkeyup='positiveNumericInput(this)'>
<script>function positiveNumericInput(el){nb=el.value;if(isNaN(nb) || nb<1)el.value=1;}</script>
Use a bytecode editor, like:
Be careful because you need a very good knowledge of the Java bytecode.
You can also change the class at runtime with bytecode weaving (like AspectJ).
It's better to use the select event instead. The change event is bound to keydown as Wil said. So if you want to listen to change on selection use select like that.
$("#yourcomponent").autocomplete({
select: function(event, ui) {
console.log(ui);
}
});
I had the same problem even though I had:
a freshly downloaded JDK 1.8.0
JAVA_HOME is set
java -version on command line reports 1.8
Java in control panel is set to 1.8
downloaded Eclipse Mars
Eclipse only let me choose a compiler compliance level op to 1.7 in the compiler preferences, even though my installed JRE is 1.8.0. I also couldn't see a 1.8 in the Execution Environments underneath Installed JREs, only a JavaSE-1.7 (which I haven't even got installed!). When I clicked on that, it shows "jdk1.8.0" as a compatible JRE, so I selected that, but still no change.
Then I unzipped Eclipse Mars into a brand new directory, created a new project, and now I can select 1.8, hurrah! That greatly reduced the "Duplicate methods named spliterator..." errors I was getting when compiling my code under Java 1.8, however, there is still one left:
Duplicate default methods named spliterator with the parameters () and () are inherited from the types List and Set.
However, that's likely because I'm extending AbstractList and implementing Set, so I've fixed that for now by removing the implements Set because it doesn't really add anything in my case (other than signifying that my collection has only unique elements)
//If both the values are less than the current node then traverse the left subtree //Or If both the values are greater than the current node then traverse the right subtree //Or LCA is the current node
public BSTNode findLowestCommonAncestor(BSTNode currentRoot, int a, int b){
BSTNode commonAncestor = null;
if (currentRoot == null) {
System.out.println("The Tree does not exist");
return null;
}
int currentNodeValue = currentRoot.getValue();
//If both the values are less than the current node then traverse the left subtree
//Or If both the values are greater than the current node then traverse the right subtree
//Or LCA is the current node
if (a < currentNodeValue && b < currentNodeValue) {
commonAncestor = findLowestCommonAncestor(currentRoot.getLeft(), a, b);
} else if (a > currentNodeValue && b > currentNodeValue) {
commonAncestor = findLowestCommonAncestor(currentRoot.getRight(), a, b);
} else {
commonAncestor = currentRoot;
}
return commonAncestor;
}
If and only if i had to use some
js library, i would do that with SMTPJs library.It offers encryption to your credentials such as username, password etc.
Try the vim-way:
ex -s +"g/foo/d" -cwq file.txt
Have a look at this jQuery plugin: jquery.confirm.
<a href="home" class="confirm">Go to home</a>
and then:
$(".confirm").confirm();
This will show a confirmation popup before proceeding to following the link.
There's a demo here: http://myclabs.github.com/jquery.confirm/
You need to download the JavaMail API, and put the relevant jar files in your classpath.
There are two ways to use this variable:
passing it as a command line argument just like Job mentioned:
cmake -DCMAKE_INSTALL_PREFIX=< install_path > ..
assigning value to it in CMakeLists.txt
:
SET(CMAKE_INSTALL_PREFIX < install_path >)
But do remember to place it BEFORE PROJECT(< project_name>)
command, otherwise it will not work!
Using configure() method two times is responsible the problem for me. Instead of using like this :
Configuration configuration = new Configuration().configure();
configuration.configure("/main/resources/hibernate.cfg.xml");
Now, I am using like this, problem does not exist anymore.
Configuration configuration = new Configuration();
configuration.configure("/main/resources/hibernate.cfg.xml");
P.S: My hibernate.cfg.xml file is located at "src/main/resources/hibernate.cfg.xml",too. The code belove works for me. at hibernate-5
public class HibernateUtil {
private static SessionFactory sessionFactory ;
static {
try{
Configuration configuration = new Configuration();
configuration.configure("/main/resources/hibernate.cfg.xml");
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
}
catch(Exception e){
e.printStackTrace();
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
create another class and increase the with size with 2px example
.enquiry_fld_normal{
width:278px !important;
}
.enquiry_fld_normal_select{
width:280px !important;
}
Here's an example program that will send myfile.mp3 by streaming it from disk (that is, it doesn't read the whole file into memory before sending the file). The server listens on port 2000.
[Update] As mentioned by @Aftershock in the comments, util.pump
is gone and was replaced with a method on the Stream prototype called pipe
; the code below reflects this.
var http = require('http'),
fileSystem = require('fs'),
path = require('path');
http.createServer(function(request, response) {
var filePath = path.join(__dirname, 'myfile.mp3');
var stat = fileSystem.statSync(filePath);
response.writeHead(200, {
'Content-Type': 'audio/mpeg',
'Content-Length': stat.size
});
var readStream = fileSystem.createReadStream(filePath);
// We replaced all the event handlers with a simple call to readStream.pipe()
readStream.pipe(response);
})
.listen(2000);
Taken from http://elegantcode.com/2011/04/06/taking-baby-steps-with-node-js-pumping-data-between-streams/
//Get
var p = $("#elementId");
var offset = p.offset();
//set
$("#secondElementId").offset({ top: offset.top, left: offset.left});
select count(*) from(select count(SID) from Test where Date = '2012-12-10' group by SID)
select count(*) from(select count(SID) from Test where Date = '2012-12-10' group by SID)
should works
For the form, use:
<form name="form1" action="<?=$_SERVER['PHP_SELF'];?>" method="get">
and for getting the value, use the get method as follows:
$value = $_GET['name_to_send_using_get'];
use:
import six
if isinstance(obj, six.text_type)
inside the six library it is represented as:
if PY3:
string_types = str,
else:
string_types = basestring,
For finding the right path I'm using
var pathToJson = Path.Combine("my","path","config","default.Business.Area.json");
var r = new StreamReader(pathToJson);
var myJson = r.ReadToEnd();
// my/path/config/default.Business.Area.json
[...] do parsing here
Path.Combine uses the Path.PathSeparator and it checks whether the first path has already a separator at the end so it will not duplicate the separators. Additionally, it checks whether the path elements to combine have invalid chars.
Using bootstrap multi select
Ajax
function() { $.ajax({
type : "get",
url : "OperatorController",
data : "input=" + $('#province').val(),
success : function(msg) {
var arrayOfObjects = eval(msg);
$("#operators").multiselect('dataprovider',
arrayOfObjects);
// $('#output').append(obj);
},
dataType : 'text'
});}
}
In Servlet
request.getParameter("input")
Here's typescript version. works on "react-router-dom": "^4.3.1"
export const AppRouter: React.StatelessComponent = () => {
return (
<BrowserRouter>
<Switch>
<Route exact path="/problem/:problemId" render={props => <ProblemPage {...props.match.params} />} />
<Route path="/" exact component={App} />
</Switch>
</BrowserRouter>
);
};
and component
export class ProblemPage extends React.Component<ProblemRouteTokens> {
public render(): JSX.Element {
return <div>{this.props.problemId}</div>;
}
}
where ProblemRouteTokens
export interface ProblemRouteTokens { problemId: string; }
Not sure of this is helpful but this what worked for me in Rails 4
Foo.where.not(bar: nil)
Use
npx react-native-rename <newName>
With custom Bundle Identifier (Android only. For iOS, please use Xcode)
$ npx react-native-rename <newName> -b <bundleIdentifier>
First, Switch to new branch (optional but recommended)
$ git checkout -b rename-app
Then, Rename your app $ npx react-native-rename "Travel App"
With custom Bundle Identifier
$ npx react-native-rename "Travel App" -b com.junedomingo.travelapp
After you change the name, please make sure you go to the android folder and run gradlew clean
. then go back to the main project and run npx react-native run-android
.
Also If you have google-services.json file in your previous project, change accordingly with the new one ... then you are good to go :)
See More here https://github.com/junedomingo/react-native-rename#readme
Bash allow u to use =~ to test if the substring is contained. Ergo, the use of negate will allow to test the opposite.
fullstring="123asdf123"
substringA=asdf
substringB=gdsaf
# test for contains asdf, gdsaf and for NOT CONTAINS gdsaf
[[ $fullstring =~ $substring ]] && echo "found substring $substring in $fullstring"
[[ $fullstring =~ $substringB ]] && echo "found substring $substringB in $fullstring" || echo "failed to find"
[[ ! $fullstring =~ $substringB ]] && echo "did not find substring $substringB in $fullstring"
To convert integer to char only 0 to 9 will be converted. As we know 0's ASCII value is 48 so we have to add its value to the integer value to convert in into the desired character hence
int i=5;
char c = i+'0';
This kind of problems are caused by two reasons:
If most of dependencies can be downloaded, then the reason 1 may be the most likely bug. On the contrary, if most of dependencies have the problem, then u should take a look at settings.xml.
Well, I have tried to fix my problem the whole afternoon, and finally I got it. My problem occurs in settings.xml, not the lose or wrong spelling of settings.xml, but the lose of activeProfiles.
Add %CATALINA_HOME%/bin
to path system variable.
Go to Environment Variables
screen under System Variables
there will be a Path
variable edit the variable and add ;%CATALINA_HOME%\bin
to the variable then click OK
to save the changes. Close all opened command prompts then open a new command prompt and try to use the command startup.bat
.
on windows 10, Notepad 7.8.5, i found this solution to convert from CRLF to LF.
Edit > Format end of line
and choose either Windows(CR+LF)
or Unix(LF)
///UPDATED DEMO 2 WATCH SOLUTION////
I hope that is the solution you're looking for! DEMO1 DEMO2
With that solution the only scrollbar in the page is on your contents section in the middle! In that section build your structure with a sidebar or whatever you want!
You can do that with that code here:
<div class="navTop">
<h1>Title</h1>
<nav>Dynamic menu</nav>
</div>
<div class="container">
<section>THE CONTENTS GOES HERE</section>
</div>
<footer class="bottomFooter">
Footer
</footer>
With that css:
.navTop{
width:100%;
border:1px solid black;
float:left;
}
.container{
width:100%;
float:left;
overflow:scroll;
}
.bottomFooter{
float:left;
border:1px solid black;
width:100%;
}
And a bit of jquery:
$(document).ready(function() {
function setHeight() {
var top = $('.navTop').outerHeight();
var bottom = $('footer').outerHeight();
var totHeight = $(window).height();
$('section').css({
'height': totHeight - top - bottom + 'px'
});
}
$(window).on('resize', function() { setHeight(); });
setHeight();
});
DEMO 1
If you don't want jquery
<div class="row">
<h1>Title</h1>
<nav>NAV</nav>
</div>
<div class="row container">
<div class="content">
<div class="sidebar">
SIDEBAR
</div>
<div class="contents">
CONTENTS
</div>
</div>
<footer>Footer</footer>
</div>
CSS
*{
margin:0;padding:0;
}
html,body{
height:100%;
width:100%;
}
body{
display:table;
}
.row{
width: 100%;
background: yellow;
display:table-row;
}
.container{
background: pink;
height:100%;
}
.content {
display: block;
overflow:auto;
height:100%;
padding-bottom: 40px;
box-sizing: border-box;
}
footer{
position: fixed;
bottom: 0;
left: 0;
background: yellow;
height: 40px;
line-height: 40px;
width: 100%;
text-align: center;
}
.sidebar{
float:left;
background:green;
height:100%;
width:10%;
}
.contents{
float:left;
background:red;
height:100%;
width:90%;
overflow:auto;
}
DEMO 2
Displaying left middle and right of there parents. If you have more then 3 elements then use nth-child() for them.
HTML sample:
<body>
<ul class="nav-tabs">
<li><a id="btn-tab-business" class="btn-tab nav-tab-selected" onclick="openTab('business','btn-tab-business')"><i class="fas fa-th"></i>Business</a></li>
<li><a id="btn-tab-expertise" class="btn-tab" onclick="openTab('expertise', 'btn-tab-expertise')"><i class="fas fa-th"></i>Expertise</a></li>
<li><a id="btn-tab-quality" class="btn-tab" onclick="openTab('quality', 'btn-tab-quality')"><i class="fas fa-th"></i>Quality</a></li>
</ul>
</body>
CSS sample:
.nav-tabs{
position: relative;
padding-bottom: 50px;
}
.nav-tabs li {
display: inline-block;
position: absolute;
list-style: none;
}
.nav-tabs li:first-child{
top: 0px;
left: 0px;
}
.nav-tabs li:last-child{
top: 0px;
right: 0px;
}
.nav-tabs li:nth-child(2){
top: 0px;
left: 50%;
transform: translate(-50%, 0%);
}
2017 I know... but someone is facing this problem during their code maintenance.
This error happened when I tried:
maskedbox.Mask = "#.###"
maskedbox.Text = "12345678"
To fix that, just set PromptInclude property to "false".
I found a solution for this problem try to run this command in terminal
ps -ef | grep postgres
kill process by this command
sudo kill -9 PID
You can just convert everything to lowercase for the purposes of sorting:
SELECT * FROM NOTES ORDER BY LOWER(title);
If you want to make sure that the uppercase ones still end up ahead of the lowercase ones, just add that as a secondary sort:
SELECT * FROM NOTES ORDER BY LOWER(title), title;
Suggest you add handling to test if any of the sheets to be renamed already exist:
Sub Test()
Dim ws As Worksheet
Dim ws1 As Worksheet
Dim strErr As String
On Error Resume Next
For Each ws In ActiveWorkbook.Sheets
Set ws1 = Sheets(ws.Name & "_v1")
If ws1 Is Nothing Then
ws.Name = ws.Name & "_v1"
Else
strErr = strErr & ws.Name & "_v1" & vbNewLine
End If
Set ws1 = Nothing
Next
On Error GoTo 0
If Len(strErr) > 0 Then MsgBox strErr, vbOKOnly, "these sheets already existed"
End Sub
For IntelliJ Idea, go to your project structure (File, Project Structure), and add the mysql connector .jar file to your global library. Once there, right click on it and chose 'Add to Modules'. Hit Apply / OK and you should be good to go.
Solution is :-
This basically forces your PC to restart because by default it does not restart after a kernel panic.
You're storing the .Text
properties of the textboxes directly into the database, this doesn't work. The .Text
properties are String
s (i.e. simple text) and not typed as DateTime
instances. Do the conversion first, then it will work.
Do this for each date parameter:
Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) )
Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse
or DateTime.TryParseExact
, but implementing that is an exercise for the reader.
This is my version:
public String convertBytestoString(InputStream inputStream)
{
int bytes;
byte[] buffer = new byte[1024];
bytes = inputStream.read(buffer);
String stringData = new String(buffer,0,bytes);
return stringData;
}
I just added "-?" parameter. It makes Psexec copy executable to remote machine. So it works without access errors.
Crude, but sufficient for restricting loading larger resources such as video files on phones vs tablet/desktop - simply look for small width or height to cover both orientations. Obviously, if the desktop browser has been resized the below could erroneously detect a phone, but that's fine / close enough for my use case.
Why 480, bcs that's what looks about right based on the info I've found re phone device dimensions.
if(document.body.clientWidth < 480 || document.body.clientHeight < 480) {
//this is a mobile device
}
In my case i was trying to present the viewController (i have the reference of the viewController in the TabBarViewController) from different view controllers and it was crashing with the above message. In that case to avoid presenting you can use
viewController.isBeingPresented
!viewController.isBeingPresented {
// Present your ViewController only if its not present to the user currently.
}
Might help someone.
To manually find the minimum of an array you don't need to know the minimum value of float:
float myFloats[];
...
float minimum = myFloats[0];
for (int i = 0; i < myFloatsSize; ++i)
{
if (myFloats[i] < minimum)
{
minimum = myFloats[i];
}
}
And similar code for the maximum value.
as @Jörg W Mittag pointed out: in jruby, fix num size is always 8 bytes long. This code snippet shows the truth:
fmax = ->{
if RUBY_PLATFORM == 'java'
2**63 - 1
else
2**(0.size * 8 - 2) - 1
end
}.call
p fmax.class # Fixnum
fmax = fmax + 1
p fmax.class #Bignum
Try this:
Dim colHeader(12)
colHeader = ("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")
Unfortunately the code found online was VB.NET not VBA.
A co-worker prefers the first form, telling it is an optimization, preferring to re-use a declaration.
I prefer the second one (and try to persuade my co-worker! ;-)), having read that:
Anyway, it falls in the category of premature optimization that rely in quality of compiler and/or JVM.
print(mat.__str__())
where mat is variable refering to your matrix object
For Gradle
users, if you are using Eclipse or one of its offshoots(I am using STS 4.5.1.RELEASE
), all that you need to do is:
In build.gradle, you ONLY need these 2 "extra" instructions:
dependencies {
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
}
Right-click on your project > Gradle > Refresh Gradle Project. The lombok-"version".jar
will appear inside your project's Project and External Dependencies
Right-click on that lombok-"version".jar
> Run As > Java Application (similar to double-clicking on the actual jar or running java -jar lombok-"version".jar
on the command line.)
A GUI will appear, follow the instructions and one of the thing it does is to copy lombok.jar
to your IDE's root.
The only other thing you will need to do(outside of the GUI) is to add that lombok.jar
to your project build path
That's it!
You can achieve it by code also, In you Global.asax file in Session_Start event write response.redirect to your start page like following.
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Response.Redirect("~/Index.aspx");
}
You can get redirect page name from database or any other storage to change the application start page while application is running no need to edit web.config or change any IIS settings
What's wrong with:
clob.getSubString(1, (int) clob.length());
?
For example Oracle oracle.sql.CLOB
performs getSubString()
on internal char[]
which defined in oracle.jdbc.driver.T4CConnection
and just System.arraycopy()
and next wrap to String
... You never get faster reading than System.arraycopy()
.
UPDATE Get driver ojdbc6.jar, decompile CLOB
implementation, and study which case could be faster based on the internals knowledge.
Most cases where you would need to pass by reference are where you need to return more than one value back to the caller. A "best practice" is to use multiple return values, which is much easier to do in Python than in languages like Java.
Here's a simple example:
def RectToPolar(x, y):
r = (x ** 2 + y ** 2) ** 0.5
theta = math.atan2(y, x)
return r, theta # return 2 things at once
r, theta = RectToPolar(3, 4) # assign 2 things at once
<input type="text" name="myinput" id="myinput" onkeypress="return isNumber(event);" />
and in the js:
function isNumber(e){
e = e || window.event;
var charCode = e.which ? e.which : e.keyCode;
return /\d/.test(String.fromCharCode(charCode));
}
or you can write it in a complicated bu useful way:
<input onkeypress="return /\d/.test(String.fromCharCode(((event||window.event).which||(event||window.event).which)));" type="text" name="myinput" id="myinput" />
Note:cross-browser and regex in literal.
You can create lib folder inside app you press right click and select directory you named as libs its will be worked
Method 1:
public void onClick(View v) {
Intent i = new Intent(currentActivity.this, SecondActivity.class);
startActivty(i);
}
Method 2:
Button button = (Button) findViewById(R.id.mybutton);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(this, "Button Clicked", Toast.LENGTH_LONG).show();
}
});
Use the C++ streams.
std::string plop("123");
std::stringstream str(plop);
int x;
str >> x;
/* Lets not forget to error checking */
if (!str)
{
// The conversion failed.
// Need to do something here.
// Maybe throw an exception
}
PS. This basic principle is how the boost library lexical_cast<>
works.
My favorite method is the boost lexical_cast<>
#include <boost/lexical_cast.hpp>
int x = boost::lexical_cast<int>("123");
It provides a method to convert between a string and number formats and back again. Underneath it uses a string stream so anything that can be marshaled into a stream and then un-marshaled from a stream (Take a look at the >> and << operators).
I found this old Thread while google'ing for generate_204 as Android seems to use this to determine if the wlan is open (response 204 is received) closed (no response at all) or blocked (redirect to captive portal is present). In that case a notification is shown that a log-in to WiFi is required...
If using TextViews in tabs this selector definition worked for me (tried Klaus Balduino's but it did not):
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Active tab -->
<item
android:state_selected="true"
android:state_focused="false"
android:state_pressed="false"
android:color="#000000" />
<!-- Inactive tab -->
<item
android:state_selected="false"
android:state_focused="false"
android:state_pressed="false"
android:color="#FFFFFF" />
</selector>
calculate the height of each link no do this
document.getElementById("products").style.height= height_of_each_link* no_of_link
The above answers are bit outdated. Although those method work, but by using below method, you can share any text to a predefined number. The below method works for android, WhatsApp web, IOS etc.
You just need to use this format:
<a href="https://api.whatsapp.com/send?phone=whatsappphonenumber&text=urlencodedtext"></a>
UPDATE-- Use this from now(Nov-2018)
<a href="https://wa.me/whatsappphonenumber/?text=urlencodedtext"></a>
Use: https://wa.me/15551234567
Don't use: https://wa.me/+001-(555)1234567
To create your own link with a pre-filled message that will automatically appear in the text field of a chat, use https://wa.me/whatsappphonenumber/?text=urlencodedtext where whatsappphonenumber is a full phone number in international format and URL-encodedtext is the URL-encoded pre-filled message.
Example:https://wa.me/15551234567?text=I'm%20interested%20in%20your%20car%20for%20sale
To create a link with just a pre-filled message, use https://wa.me/?text=urlencodedtext
Example:https://wa.me/?text=I'm%20inquiring%20about%20the%20apartment%20listing
After clicking on the link, you will be shown a list of contacts you can send your message to.
For more information, see https://www.whatsapp.com/faq/en/general/26000030
In cases where you have multiple directives on a single DOM element and where the
order in which they’re applied matters, you can use the priority
property to order their
application. Higher numbers run first. The default priority is 0 if you don’t specify one.
EDIT: after the discussion, here's the complete working solution. The key was to remove the attribute: element.removeAttr("common-things");
, and also element.removeAttr("data-common-things");
(in case users specify data-common-things
in the html)
angular.module('app')
.directive('commonThings', function ($compile) {
return {
restrict: 'A',
replace: false,
terminal: true, //this setting is important, see explanation below
priority: 1000, //this setting is important, see explanation below
compile: function compile(element, attrs) {
element.attr('tooltip', '{{dt()}}');
element.attr('tooltip-placement', 'bottom');
element.removeAttr("common-things"); //remove the attribute to avoid indefinite loop
element.removeAttr("data-common-things"); //also remove the same attribute with data- prefix in case users specify data-common-things in the html
return {
pre: function preLink(scope, iElement, iAttrs, controller) { },
post: function postLink(scope, iElement, iAttrs, controller) {
$compile(iElement)(scope);
}
};
}
};
});
Working plunker is available at: http://plnkr.co/edit/Q13bUt?p=preview
Or:
angular.module('app')
.directive('commonThings', function ($compile) {
return {
restrict: 'A',
replace: false,
terminal: true,
priority: 1000,
link: function link(scope,element, attrs) {
element.attr('tooltip', '{{dt()}}');
element.attr('tooltip-placement', 'bottom');
element.removeAttr("common-things"); //remove the attribute to avoid indefinite loop
element.removeAttr("data-common-things"); //also remove the same attribute with data- prefix in case users specify data-common-things in the html
$compile(element)(scope);
}
};
});
Explanation why we have to set terminal: true
and priority: 1000
(a high number):
When the DOM is ready, angular walks the DOM to identify all registered directives and compile the directives one by one based on priority
if these directives are on the same element. We set our custom directive's priority to a high number to ensure that it will be compiled first and with terminal: true
, the other directives will be skipped after this directive is compiled.
When our custom directive is compiled, it will modify the element by adding directives and removing itself and use $compile service to compile all the directives (including those that were skipped).
If we don't set terminal:true
and priority: 1000
, there is a chance that some directives are compiled before our custom directive. And when our custom directive uses $compile to compile the element => compile again the already compiled directives. This will cause unpredictable behavior especially if the directives compiled before our custom directive have already transformed the DOM.
For more information about priority and terminal, check out How to understand the `terminal` of directive?
An example of a directive that also modifies the template is ng-repeat
(priority = 1000), when ng-repeat
is compiled, ng-repeat
make copies of the template element before other directives get applied.
Thanks to @Izhaki's comment, here is the reference to ngRepeat
source code: https://github.com/angular/angular.js/blob/master/src/ng/directive/ngRepeat.js
You can't (and shouldn't) block processing with a sleep function. However, you can use setTimeout
to kick off a function after a delay:
setTimeout(function(){alert("hi")}, 1000);
Depending on your needs, setInterval
might be useful, too.
Groupby A:
In [0]: grp = df.groupby('A')
Within each group, sum over B and broadcast the values using transform. Then sort by B:
In [1]: grp[['B']].transform(sum).sort('B')
Out[1]:
B
2 -2.829710
5 -2.829710
1 0.253651
4 0.253651
0 0.551377
3 0.551377
Index the original df by passing the index from above. This will re-order the A values by the aggregate sum of the B values:
In [2]: sort1 = df.ix[grp[['B']].transform(sum).sort('B').index]
In [3]: sort1
Out[3]:
A B C
2 baz -0.528172 False
5 baz -2.301539 True
1 bar -0.611756 True
4 bar 0.865408 False
0 foo 1.624345 False
3 foo -1.072969 True
Finally, sort the 'C' values within groups of 'A' using the sort=False
option to preserve the A sort order from step 1:
In [4]: f = lambda x: x.sort('C', ascending=False)
In [5]: sort2 = sort1.groupby('A', sort=False).apply(f)
In [6]: sort2
Out[6]:
A B C
A
baz 5 baz -2.301539 True
2 baz -0.528172 False
bar 1 bar -0.611756 True
4 bar 0.865408 False
foo 3 foo -1.072969 True
0 foo 1.624345 False
Clean up the df index by using reset_index
with drop=True
:
In [7]: sort2.reset_index(0, drop=True)
Out[7]:
A B C
5 baz -2.301539 True
2 baz -0.528172 False
1 bar -0.611756 True
4 bar 0.865408 False
3 foo -1.072969 True
0 foo 1.624345 False
foreach(var newAnimal in NewAnimals)
Animals.Add(newAnimal.Key,newAnimal.Value)
Note: this throws an exception on a duplicate key.
Or if you really want to go the extension method route(I wouldn't), then you could define a general AddRange
extension method that works on any ICollection<T>
, and not just on Dictionary<TKey,TValue>
.
public static void AddRange<T>(this ICollection<T> target, IEnumerable<T> source)
{
if(target==null)
throw new ArgumentNullException(nameof(target));
if(source==null)
throw new ArgumentNullException(nameof(source));
foreach(var element in source)
target.Add(element);
}
(throws on duplicate keys for dictionaries)
To check if integer like poster wants:
if (+data===parseInt(data)) {return true} else {return false}
notice + in front of data (converts string to number), and === for exact.
Here are examples:
data=10
+data===parseInt(data)
true
data="10"
+data===parseInt(data)
true
data="10.2"
+data===parseInt(data)
false
You will find complete list of time zone with its GMToffsets
here and you can use "Name of Time Zone" column value to find time zone by ID
e.g
TimeZoneInfo objTimeZoneInfo = TimeZoneInfo.FindTimeZoneById("Dateline Standard Time");
You will get time zone info class that contains dateline standard time time zone which is used for GMT-12:00.
You will notice you have no value attr in the input
tags.
Also, although not shown, make sure the Javascript is run after the html is in place.
App Engine gives developers the ability to control Google Compute Engine cores, as well as provide a web-facing front end for Google Compute Engine data processing applications.
On the other hand, Compute Engine offers direct and complete operating system management of your virtual machines. To present your App, you're going to need resources, and Google Cloud Storage is ideal for storing your assets and data, whatever they're used for. You get fast data access with hosting around the globe. Reliability is guaranteed at a 99.95% up-time, and Google also provides the ability to back up and restore your data, and believe it or not, storage is unlimited.
You can manage your assets with Google Cloud Storage, storing, retrieving, displaying, and deleting them. You can also quickly read and write to flat datasheets that are kept in Cloud Storage. Next in the Google Cloud lineup is BigQuery. With BigQuery, you can analyze massive amounts of data, we're talking millions of records, within seconds. Access is handled via a straightforward UI, or a Representational State Transfer, or REST interface.
Data storage is, as you might suspect, not a problem, and scales to hundreds of TB. BigQuery is accessible via a host of client libraries, including those for Java, .NET, Python, Go, Ruby, PHP, and Javascript. A SQL-like syntax called NoSQL is available which can be accessed through these client libraries, or through a web user interface. Finally, let's talk about the Google Cloud platform database options, Cloud SQL and Cloud Datastore.
There is a major difference. Cloud SQL is for relational databases, primarily MySQL, whereas Cloud Datastore is for non-relational databases using noSQL. With Cloud SQL, you have the choice of either hosting in the US, Europe, or Asia, with 100 GB of storage, and 16 GB of RAM per database instance.
Cloud Datastore is available at no charge for up to 50 K read/write instructions per month and 1 GB of data stored also per month. There is a fee if you exceed these quotas, however. App Engine can also work with other lesser known, more targeted members of the Google Cloud platform, including the Cloud Endpoints for creating API backends, Google Prediction API for data analysis and trend forecasting, or the Google Translate API, for multilingual output.
While you can do a fair amount with App Engine on its own, It's potential skyrockets when you factor in its ability to work easily and efficiently with its fellow Google Cloud platform services.
Ken's answer is basically right but I'd like to chime in on the "why would you want to use one over the other?" part of your question.
The base interface you choose for your repository has two main purposes. First, you allow the Spring Data repository infrastructure to find your interface and trigger the proxy creation so that you inject instances of the interface into clients. The second purpose is to pull in as much functionality as needed into the interface without having to declare extra methods.
The Spring Data core library ships with two base interfaces that expose a dedicated set of functionalities:
CrudRepository
- CRUD methodsPagingAndSortingRepository
- methods for pagination and sorting (extends CrudRepository
)The individual store modules (e.g. for JPA or MongoDB) expose store-specific extensions of these base interfaces to allow access to store-specific functionality like flushing or dedicated batching that take some store specifics into account. An example for this is deleteInBatch(…)
of JpaRepository
which is different from delete(…)
as it uses a query to delete the given entities which is more performant but comes with the side effect of not triggering the JPA-defined cascades (as the spec defines it).
We generally recommend not to use these base interfaces as they expose the underlying persistence technology to the clients and thus tighten the coupling between them and the repository. Plus, you get a bit away from the original definition of a repository which is basically "a collection of entities". So if you can, stay with PagingAndSortingRepository
.
The downside of directly depending on one of the provided base interfaces is two-fold. Both of them might be considered as theoretical but I think they're important to be aware of:
Page
or Pageable
in your code anyway. Spring Data is not any different from any other general purpose library like commons-lang or Guava. As long as it provides reasonable benefit, it's just fine.CrudRepository
, you expose a complete set of persistence method at once. This is probably fine in most circumstances as well but you might run into situations where you'd like to gain more fine-grained control over the methods expose, e.g. to create a ReadOnlyRepository
that doesn't include the save(…)
and delete(…)
methods of CrudRepository
.The solution to both of these downsides is to craft your own base repository interface or even a set of them. In a lot of applications I have seen something like this:
interface ApplicationRepository<T> extends PagingAndSortingRepository<T, Long> { }
interface ReadOnlyRepository<T> extends Repository<T, Long> {
// Al finder methods go here
}
The first repository interface is some general purpose base interface that actually only fixes point 1 but also ties the ID type to be Long
for consistency. The second interface usually has all the find…(…)
methods copied from CrudRepository
and PagingAndSortingRepository
but does not expose the manipulating ones. Read more on that approach in the reference documentation.
The repository abstraction allows you to pick the base repository totally driven by you architectural and functional needs. Use the ones provided out of the box if they suit, craft your own repository base interfaces if necessary. Stay away from the store specific repository interfaces unless unavoidable.
Using Firefox, you will need the screengrab addon.
You can use getattr
getattr(module, class_name)
to access the class. More complete code:
module = __import__(module_name)
class_ = getattr(module, class_name)
instance = class_()
As mentioned below, we may use importlib
import importlib
module = importlib.import_module(module_name)
class_ = getattr(module, class_name)
instance = class_()
I came across this myself. I used .on
so it looks a bit different but I did this:
$('#element').on('keypress', function() {
//code to be executed
}).on('keydown', function(e) {
if (e.keyCode==8)
$('element').trigger('keypress');
});
Adding my Work Around here. I needed to delete ssn typed by user so i did this in jQuery
$(this).bind("keydown", function (event) {
// Allow: backspace, delete
if (event.keyCode == 46 || event.keyCode == 8)
{
var tempField = $(this).attr('name');
var hiddenID = tempField.substr(tempField.indexOf('_') + 1);
$('#' + hiddenID).val('');
$(this).val('')
return;
} // Allow: tab, escape, and enter
else if (event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
else
{
// Ensure that it is a number and stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105))
{
event.preventDefault();
}
}
});
Go to c:/wamp/apps/phpadmin3.5.2 Make a new subfolder called ‘upload’ Edit config.inc.php to find and update this line: $cfg[‘UploadDir’] = ‘upload’ Now when you import a database, you will give a drop-down list in web server upload directory with all the files in this directory. Chose the file you want and you are done.
Based on what @J. Calleja said, you have two choices
If you want to random access the element of Mat, just simply use
Mat.at<data_Type>(row_num, col_num) = value;
If you want to continuous access, OpenCV provides Mat iterator compatible with STL iterator
and it's more C++
style
MatIterator_<double> it, end;
for( it = I.begin<double>(), end = I.end<double>(); it != end; ++it)
{
//do something here
}
or
for(int row = 0; row < mat.rows; ++row) {
float* p = mat.ptr(row); //pointer p points to the first place of each row
for(int col = 0; col < mat.cols; ++col) {
*p++; // operation here
}
}
If you have any difficulty to understand how Method 2 works, I borrow the picture from a blog post in the article Dynamic Two-dimensioned Arrays in C, which is much more intuitive and comprehensible.
See the picture below.
This example allows you to get more information when there is an error in your code. Basically, it buffers messages and only outputs those at a certain log level (e.g. Warn) unless a certain condition is met (e.g. there has been an error, so the log level is >= Error), then it will output more info (e.g. all messages from log levels >= Trace). Because the messages are buffered, this lets you gather trace information about what happened before an Error or ErrorException was logged - very useful!
I adapted this one from an example in the source code. I was thrown at first because I left out the AspNetBufferingWrapper
(since mine isn't an ASP app) - it turns out that the PostFilteringWrapper requires some buffered target. Note that the target-ref
element used in the above-linked example cannot be used in NLog 1.0 (I am using 1.0 Refresh for a .NET 4.0 app); it is necessary to put your target inside the wrapper block. Also note that the logic syntax (i.e. greater-than or less-than symbols, < and >) has to use the symbols, not the XML escapes for those symbols (i.e. >
and <
) or else NLog will error.
app.config:
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
throwExceptions="true" internalLogToConsole="true" internalLogLevel="Warn" internalLogFile="nlog.log">
<variable name="appTitle" value="My app"/>
<variable name="csvPath" value="${specialfolder:folder=Desktop:file=${appTitle} log.csv}"/>
<targets async="true">
<!--The following will keep the default number of log messages in a buffer and write out certain levels if there is an error and other levels if there is not. Messages that appeared before the error (in code) will be included, since they are buffered.-->
<wrapper-target xsi:type="BufferingWrapper" name="smartLog">
<wrapper-target xsi:type="PostFilteringWrapper">
<!--<target-ref name="fileAsCsv"/>-->
<target xsi:type="File" fileName="${csvPath}"
archiveAboveSize="4194304" concurrentWrites="false" maxArchiveFiles="1" archiveNumbering="Sequence"
>
<layout xsi:type="CsvLayout" delimiter="Tab" withHeader="false">
<column name="time" layout="${longdate}" />
<column name="level" layout="${level:upperCase=true}"/>
<column name="message" layout="${message}" />
<column name="callsite" layout="${callsite:includeSourcePath=true}" />
<column name="stacktrace" layout="${stacktrace:topFrames=10}" />
<column name="exception" layout="${exception:format=ToString}"/>
<!--<column name="logger" layout="${logger}"/>-->
</layout>
</target>
<!--during normal execution only log certain messages-->
<defaultFilter>level >= LogLevel.Warn</defaultFilter>
<!--if there is at least one error, log everything from trace level-->
<when exists="level >= LogLevel.Error" filter="level >= LogLevel.Trace" />
</wrapper-target>
</wrapper-target>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="smartLog"/>
</rules>
</nlog>
</configuration>
this looks like PHP to me. I'll delete if it's some other language.
Simply unset($arr[1]);
Type "Sysout
" and then Ctrl+Space
. It expands to
System.out.println();
apt-get install python-setuptools python-pip
or
apt-get install python3-setuptools python3-pip
you'd also want to install the python packages...
Good guestion! -- where I have not yet found a satisfying answer for my case, the answer I provide here works for me, but may not be future proof...
If one uses gcc (clang?) and have -Werror
and -Wbad-function-cast
defined,
int val = (int)pow(10,9);
will result:
error: cast from function call of type 'double' to non-matching type 'int' [-Werror=bad-function-cast]
(for a good reason, overflow and where values are rounded needs to be thought out)
EDIT: 2020-08-30: So, my use case casting the value from function returning double to int, and chose pow() to represent that in place of a private function somewhere. Then I sidestepped thinking pow() more. (See comments more why pow() used below could be problematic...).
After properly thought out (that parameters to pow() are good), int val = pow(10,9);
seems to work with gcc 9.2 x86-64 ...
but note:
printf("%d\n", pow(10,4));
may output e.g.
-1121380856
(did for me) where
int i = pow(10,4); printf("%d\n", i);
printed
10000
in one particular case I tried.
First you convert VARCHAR to DATE and then back to CHAR. I do this almost every day and never found any better way.
select TO_CHAR(TO_DATE(DOJ,'MM/DD/YYYY'), 'MM/DD/YYYY') from EmpTable
textarea {
white-space: pre;
overflow-wrap: normal;
overflow-x: scroll;
}
white-space: nowrap
also works if you don't care about whitespace, but of course you don't want that if you're working with code (or indented paragraphs or any content where there might deliberately be multiple spaces) ... so i prefer pre
.
overflow-wrap: normal
(was word-wrap
in older browsers) is needed in case some parent has changed that setting; it can cause wrapping even if pre
is set.
also -- contrary to the currently accepted answer -- textareas do often wrap by default. pre-wrap
seems to be the default on my browser.
While it can be annoying when used as an anti-piracy measure, I can see there might be some instances where it'd be legitimate, so:
function disableCopyPaste(elm) {
// Disable cut/copy/paste key events
elm.onkeydown = interceptKeys
// Disable right click events
elm.oncontextmenu = function() {
return false
}
}
function interceptKeys(evt) {
evt = evt||window.event // IE support
var c = evt.keyCode
var ctrlDown = evt.ctrlKey||evt.metaKey // Mac support
// Check for Alt+Gr (http://en.wikipedia.org/wiki/AltGr_key)
if (ctrlDown && evt.altKey) return true
// Check for ctrl+c, v and x
else if (ctrlDown && c==67) return false // c
else if (ctrlDown && c==86) return false // v
else if (ctrlDown && c==88) return false // x
// Otherwise allow
return true
}
I've used event.ctrlKey
rather than checking for the key code as on most browsers on Mac OS X Ctrl/Alt "down" and "up" events are never triggered, so the only way to detect is to use event.ctrlKey
in the e.g. c event after the Ctrl key is held down. I've also substituted ctrlKey
with metaKey
for macs.
Limitations of this method:
edit
->copy
menu item in e.g. Firefox can still allow copy/pasting.if you are using matplotlib version 3.1.1 or above, you can try:
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
x = [1, 3, 4, 6, 7, 9]
y = [0, 0, 5, 8, 8, 8]
classes = ['A', 'B', 'C']
values = [0, 0, 1, 2, 2, 2]
colours = ListedColormap(['r','b','g'])
scatter = plt.scatter(x, y,c=values, cmap=colours)
plt.legend(handles=scatter.legend_elements()[0], labels=classes)
Actually there is a freeware version of EMS's SQL Manager which is quite powerful
(a[n:]+[default])[0]
This is probably better as a
gets larger
(a[n:n+1]+[default])[0]
This works because if a[n:]
is an empty list if n => len(a)
Here is an example of how this works with range(5)
>>> range(5)[3:4]
[3]
>>> range(5)[4:5]
[4]
>>> range(5)[5:6]
[]
>>> range(5)[6:7]
[]
And the full expression
>>> (range(5)[3:4]+[999])[0]
3
>>> (range(5)[4:5]+[999])[0]
4
>>> (range(5)[5:6]+[999])[0]
999
>>> (range(5)[6:7]+[999])[0]
999
In Oracle below query can give the desired result.
SELECT group,person,Age,
ROWNUMBER() OVER (PARTITION BY group ORDER BY age desc ,person asc) as rankForEachGroup
FROM tablename where rankForEachGroup=1
1) Install packages
$ sudo apt update;sudo apt install --no-install-recommends ubuntu-desktop
$ sudo apt install gnome-panel gnome-settings-daemon metacity nautilus gnome-terminal vnc4server
2) Edit /usr/bin/vncserver file and modify as below
Find this line
"# exec /etc/X11/xinit/xinitrc\n\n".
And add these lines below.
"gnome-session &\n".
"gnome-panel &\n".
"gnome-settings-daemon &\n".
"metacity &\n".
"nautilus &\n".
"gnome-terminal &\n".
3) Create VNC password and vnc session for the user using "vncserver" command.
lonely@ubuntu:~$ vncserver
You will require a password to access your desktops.
Password:
Verify:
xauth: file /home/lonely/.Xauthority does not exist
New 'ubuntu:1 (lonely)' desktop is ubuntu:1
Creating default startup script /home/lonely/.vnc/xstartup
Starting applications specified in /home/lonely/.vnc/xstartup
Log file is /home/lonely/.vnc/ubuntu:1.log
Now you can access GUI using IP/Domain and port 1
stackoverflow.com:1
Tested on AWS and digital ocean .
For AWS, you have to allow port 5901 on firewall
To kill session
$ vncserver -kill :1
Refer:
https://linode.com/docs/applications/remote-desktop/install-vnc-on-ubuntu-16-04/
Refer this guide to create permanent sessions as service
http://www.krizna.com/ubuntu/enable-remote-desktop-ubuntu-16-04-vnc/
try this css:
/* Show in default resolution screen*/
#container2 {
width: 960px;
position: relative;
margin:0 auto;
line-height: 1.4em;
}
/* If in mobile screen with maximum width 479px. The iPhone screen resolution is 320x480 px (except iPhone4, 640x960) */
@media only screen and (max-width: 479px){
#container2 { width: 90%; }
}
Here the demo: http://jsfiddle.net/ongisnade/CG9WN/
Two variants on what's already been given:
git archive --format=tar --remote=git://git.foo.com/project.git HEAD:path/to/directory filename | tar -O -xf -
and:
git archive --format=zip --remote=git://git.foo.com/project.git HEAD:path/to/directory filename | funzip
These write the file to standard output.
Yes, the moment jQuery sees the URL belongs to a different domain, it assumes that call as a cross domain call, thus crossdomain:true
is not required here.
Also, important to note that you cannot make a synchronous call with $.ajax
if your URL belongs to a different domain (cross domain) or you are using JSONP. Only async calls are allowed.
Note: you can call the service synchronously if you specify the async:false
with your request.
To convert UTC time to Local you have to use moment.local()
.
For more info see docs
var date = moment.utc().format('YYYY-MM-DD HH:mm:ss');
console.log(date); // 2015-09-13 03:39:27
var stillUtc = moment.utc(date).toDate();
var local = moment(stillUtc).local().format('YYYY-MM-DD HH:mm:ss');
console.log(local); // 2015-09-13 09:39:27
var date = moment.utc().format();_x000D_
console.log(date, "- now in UTC"); _x000D_
_x000D_
var local = moment.utc(date).local().format();_x000D_
console.log(local, "- UTC now to local");
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
_x000D_
You may find that you have to link with the math libraries on whatever system you're using, something like:
gcc -o myprog myprog.c -L/path/to/libs -lm
^^^ - this bit here.
Including headers lets a compiler know about function declarations but it does not necessarily automatically link to the code required to perform that function.
Failing that, you'll need to show us your code, your compile command and the platform you're running on (operating system, compiler, etc).
The following code compiles and links fine:
#include <math.h>
int main (void) {
int max = sqrt (9);
return 0;
}
Just be aware that some compilation systems depend on the order in which libraries are given on the command line. By that, I mean they may process the libraries in sequence and only use them to satisfy unresolved symbols at that point in the sequence.
So, for example, given the commands:
gcc -o plugh plugh.o -lxyzzy
gcc -o plugh -lxyzzy plugh.o
and plugh.o
requires something from the xyzzy
library, the second may not work as you expect. At the point where you list the library, there are no unresolved symbols to satisfy.
And when the unresolved symbols from plugh.o
do appear, it's too late.
git pull
is like running git fetch
then git merge
git pull --rebase
is like git fetch
then git rebase
git pull
is like a git fetch
+ git merge
.
"In its default mode, git pull is shorthand for
git fetch
followed bygit merge
FETCH_HEAD" More precisely,git pull
runsgit fetch
with the given parameters and then callsgit merge
to merge the retrieved branch heads into the current branch"
(Ref: https://git-scm.com/docs/git-pull)
'But what is the difference between git pull
VS git fetch
+ git rebase
'
Again, from same source:
git pull --rebase
"With --rebase, it runs git rebase instead of git merge."
'the difference between merge
and rebase
'
that is answered here too:
https://git-scm.com/book/en/v2/Git-Branching-Rebasing
(the difference between altering the way version history is recorded)
I believe it's because #ID styles trump .class styles when computing the final style of an element. Try changing your li
from class
to id
, or you can try adding !important to your class, like this:
li.sub-navigation-home-news
{
color: #C1C1C1; !important
Thanks for the tip, i used this to get my date "20071122" parsed, I needed to add datetimestyles, I used none and it worked:
DateTime dt = DateTime.MinValue;
DateTime.TryParseExact("20071122", "yyyyMMdd", null,System.Globalization.DateTimeStyles.None, out dt);
We can directly subtract dates to get difference in Days.
SET SERVEROUTPUT ON ;
DECLARE
V_VAR NUMBER;
BEGIN
V_VAR:=TO_DATE('2000-01-02', 'YYYY-MM-DD') - TO_DATE('2000-01-01', 'YYYY-MM-DD') ;
DBMS_OUTPUT.PUT_LINE(V_VAR);
END;
for those who are having the issue of it still not letting you save once it is changed according to answer below, do the following:
tools -> options -> designers -> Table and Database Designers -> uncheck "prevent saving changes that require table re-creation" box -> OK
and try to save as it should work now
I had a similar problem with HTML input fields in MVC. The web paged only showed the first keyword of the field. Example: input field: "The quick brown fox" Displayed value: "The"
The resolution was to put the variable in quotes in the value statement as follows:
<input class="ParmInput" type="text" id="respondingRangerUnit" name="respondingRangerUnit"
onchange="validateInteger(this.value)" value="@ViewBag.respondingRangerUnit">
First you should try with Proguard (This clean all code unused)
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
minSdkVersion 16
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
Personally, I'd append the element to the form instead of hacking the serialized data, e.g.
moredata = 'your custom data here';
// do what you like with the input
$input = $('<input type="text" name="moredata"/>').val(morevalue);
// append to the form
$('#myForm').append($input);
// then..
data: $('#myForm').serialize()
That way, you don't have to worry about ?
or &
I know I'm coming to this late, but what the heck.
I've got almost the exact same code as Kris, using just one Activity but with 2 different layouts/views, and I want to switch between the layouts at will.
As a test, I added 2 menu options, each one switches the view:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item1:
setContentView(R.layout.main);
return true;
case R.id.item2:
setContentView(R.layout.alternate);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Note, I've got one Activity class. This works perfectly. So I have no idea why people are suggesting using different Activities / Intents. Maybe someone can explain why my code works and Kris's didn't.
Yes easy.
wget --spider www.bluespark.co.nz
That will give you
Resolving www.bluespark.co.nz... 210.48.79.121
Connecting to www.bluespark.co.nz[210.48.79.121]:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/html]
200 OK
I had the same problem. My customer ordered me Python 3.4 script that updates XLS (not XLSX) Excel files.
The 1st package xlrd was installed by "pip install" without problems in my Python home.
The 2nd one xlwt needed to say "pip install xlwt-future" to be compatible.
The 3rd one xlutils has no support for Python 3, but I adapted it a little bit and now it works at least for dummy script:
#!C:\Python343\python
from xlutils.copy import copy # http://pypi.python.org/pypi/xlutils
from xlrd import open_workbook # http://pypi.python.org/pypi/xlrd
from xlwt import easyxf # http://pypi.python.org/pypi/xlwt
file_path = 'C:\Dev\Test_upd.xls'
rb = open_workbook('C:\Dev\Test.xls',formatting_info=True)
r_sheet = rb.sheet_by_index(0) # read only copy to introspect the file
wb = copy(rb) # a writable copy (I can't read values out of this, only write to it)
w_sheet = wb.get_sheet(0) # the sheet to write to within the writable copy
w_sheet.write(1, 1, 'Value')
wb.save(file_path)
I attached the file here: http://ifolder.su/43507580
Write to [email protected] if it got expired.
P.S.: Some functions are not called in the dummy example, so maybe they will need for an adaptation also. Who wants to do it, fix exceptions one-by-one with a google help. It's not a very difficult task, because the package code is small...
If something does not work, when coming thru the front-door, then take the back-door:
drop table if exists apples;
create table if not exists apples(variety char(10) primary key, price int);
insert into apples values('fuji', 5), ('gala', 6);
drop table if exists apples_new;
create table if not exists apples_new like apples;
insert into apples_new select * from apples;
update apples_new
set price = (select price from apples where variety = 'gala')
where variety = 'fuji';
rename table apples to apples_orig;
rename table apples_new to apples;
drop table apples_orig;
It's fast. The bigger the data, the better.
If you can restrict it to just (Open Office XML format) *.xlsx files, then probably the most popular library would be EPPLus.
Bonus is, there are no other dependencies. Just install using nuget:
Install-Package EPPlus
If you are getting this in a C# projet, check if you are running in 64-bit or 32-bit mode with the following code:
if (IntPtr.Size == 4)
{
Console.WriteLine("This is 32-Bit!");
}
else if (IntPtr.Size == 8)
{
Console.WriteLine("This is 64 Bit!");
}
If you find that you are running in 64-Bit mode, you may want to try switching to 32-Bit (or vice versa). You can follow this guide to force your application to run as 64 or 32 bit (X64 and X86 respectively). You have to make sure that Platform Target
in your project properties is not set to Any CPU
and that it is explicitley set.
Switching that option from Any CPU
to X86
resolved my error and I was able to connect to the Oracle provider.
You can also use redirect()
method like this:-
return redirect('https://stackoverflow.com/');
In the same vein as martineau's response, the best solution is often not to check. For example, the code
if x in d:
foo = d[x]
else:
foo = bar
is normally written
foo = d.get(x, bar)
which is shorter and more directly speaks to what you mean.
Another common case is something like
if x not in d:
d[x] = []
d[x].append(foo)
which can be rewritten
d.setdefault(x, []).append(foo)
or rewritten even better by using a collections.defaultdict(list)
for d
and writing
d[x].append(foo)
Why don't you just compile your VB
code into a library(.dll
).Reference it later from your code and that's it. Managed dlls
contain MSIL
to which both c#
and vb
are compiled.
In addition to Gaby aka's method, we can find elements inside htmlObject
in this way -
htmlObj.find("#box").html();
Fiddle is available here - http://jsfiddle.net/ashwyn/76gL3/
Use the following library:
import javax.swing.JOptionPane;
Input at the top of the code-line. You must only add this, because the other things is done correctly!
If you use that forumla in the name manager you are creating a dynamic range which uses "this sheet" in place of a specific sheet.
As Jerry says, Sheet1!A1 refers to cell A1 on Sheet1. If you create a named range and omit the Sheet1 part you will reference cell A1 on the currently active sheet. (omitting the sheet reference and using it in a cell formula will error).
edit: my bad, I was using $A$1 which will lock it to the A1 cell as above, thanks pnuts :p
There's a free php script made by Celeron Dude that can do this called Celeron Dude Indexer 2. It doesn't require .htaccess
The source code is easy to understand and provides a good starting point.
Here's a download link: https://gitlab.com/desbest/celeron-dude-indexer/
Some good answers, but the problem with all solutions I have tried is that the images doesn´t fade into each other. Instead the first one fades completely out and than the next one fades in.
After a few hours of testing a found this sollution. Thx to http://www.1squarepear.com/adding-a-responsive-bootstrap-image-carousel-that-fades-instead-of-slides/
Add this in the css:
.carousel.fade {
opacity: 1;
}
.carousel.fade .item {
transition: opacity ease-out .7s;
left: 0;
opacity: 0; /* hide all slides */
top: 0;
position: absolute;
width: 100%;
display: block;
}
.carousel.fade .item:first-child {
top: auto;
opacity: 1; /* show first slide */
position: relative;
}
.carousel.fade .item.active {
opacity: 1;
}
If you've got ther JSON data coming in as a string (e.g. '[{"id":1,"name":"Charles"},{"id":8,"name":"John"},{"id":13,"name":"Sally"}]')
Then I'd use JSON.net and use Linq to JSON to get the values out...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request["items"] != null)
{
var items = Request["items"].ToString(); // Get the JSON string
JArray o = JArray.Parse(items); // It is an array so parse into a JArray
var a = o.SelectToken("[0].name").ToString(); // Get the name value of the 1st object in the array
// a == "Charles"
}
}
}
Looks like a combination of componentDidMount
and componentDidUpdate
will get the job done. The first is called after the initial rendering, when the DOM is available, the second is called after any subsequent renderings, once the updated DOM is available. In my case, I both have them delegate to a common function to do the same thing.
Your welcome page is set as That Servlet . So all css , images path should be given relative to that servlet DIR . which is a bad idea ! why do you need the servlet as a home page ? set .jsp as index page and redirect to any page from there ?
are you trying to populate any fields from db is that why you are using servlet ?
The chosen answer is a good answer, but be careful with the object returned.
string test = null;
string test2 = "";
if (test is string)
Console.WriteLine("This will never be hit.");
if (test2 is string)
Console.WriteLine("Always hit.");
Extrapolating...
string test = GetDefault(typeof(string));
if (test is string)
Console.WriteLine("This will never be hit.");
It looks as if you are using the URL.toString
result as the argument to the FileReader
constructor. URL.toString
is a bit broken, and instead you should generally use url.toURI().toString()
. In any case, the string is not a file path.
Instead, you should either:
URL
to ServicesLoader
and let it call openStream
or similar.Class.getResourceAsStream
and just pass the stream over, possibly inside an InputSource
. (Remember to check for nulls as the API is a bit messy.)in your css file do img { float: left; }
and h1 {float: left; }
Not very elegant, but I add a set value with the same number of leading zeroes I desire to the numeric I want to convert, and use RIGHT function.
Example:
SELECT RIGHT(CONVERT(CHAR(7),1000000 + @number2),6)
Result: '000867'
If I understand the situation correctly, you are just passing json data through the http body, instead of application/x-www-form-urlencoded
data.
You can fetch this data with this snippet:
$request_body = file_get_contents('php://input');
If you are passing json, then you can do:
$data = json_decode($request_body);
$data
then contains the json data is php array.
php://input
is a so called wrapper.
php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".
I know this is an old question, but just in case you are trying to do the same thing in ASP.NET Core, here is how you can create the UrlHelper inside an action:
var urlHelper = new UrlHelper(this.ControllerContext);
Or, you could just use the Controller.Url
property if you inherit from Controller
.
strstr(request, "favicon") != NULL
From man nano
:
-T cols (--tabsize=cols)
Set the size (width) of a tab to cols columns.
The value of cols must be greater than 0. The default value is 8.
-E (--tabstospaces)
Convert typed tabs to spaces.
For example, to set the tab size to 4, replace tabs with spaces, and edit the file "foo.txt", you would run the command:
nano -ET4 foo.txt
From man nanorc
:
set tabsize n
Use a tab size of n columns. The value of n must be greater than 0.
The default value is 8.
set/unset tabstospaces
Convert typed tabs to spaces.
Edit your ~/.nanorc
file (create it if it does not exist), and add those commands to it. For example:
set tabsize 4
set tabstospaces
Nano will use these settings by default whenever it is launched, but command-line flags will override them.
Here '~' refers to the root directory ,where Home is controller and Download_Excel_File is actionmethod
<a href="~/Home/Download_Excel_File" />
Another info: If you want use a Route Constraint, imagine that you want force that parameter has int datatype, then you need use this syntax:
[Route("v1/location/**{deviceOrAppid:int?}**", Name = "AddNewLocation")]
The ? character is put always before the last } character
For more information see: Optional URI Parameters and Default Values
This is quick-and-dirty (and not formally valid HTML5), but it seems to work -- and it is inline as per the question:
<table border='1' style='border-collapse:collapse'>
No further styling of <tr>
/<td>
tags is required (for a basic table grid).
This simple example shows how to capture curl output, and use it in a bash script
function main
{
\curl -vs 'http://google.com' 2>&1
# note: add -o /tmp/ignore.png if you want to ignore binary output, by saving it to a file.
}
# capture output of curl to a variable
OUT=$(main)
# search output for something using grep.
echo
echo "$OUT" | grep 302
echo
echo "$OUT" | grep title
Here is another example which is working
public class EnregistrementVideoStackActivity extends Activity implements SurfaceHolder.Callback {
private SurfaceHolder surfaceHolder;
private SurfaceView surfaceView;
public MediaRecorder mrec = new MediaRecorder();
private Button startRecording = null;
File video;
private Camera mCamera;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_surface);
Log.i(null , "Video starting");
startRecording = (Button)findViewById(R.id.buttonstart);
mCamera = Camera.open();
surfaceView = (SurfaceView) findViewById(R.id.surface_camera);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
menu.add(0, 0, 0, "StartRecording");
menu.add(0, 1, 0, "StopRecording");
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case 0:
try {
startRecording();
} catch (Exception e) {
String message = e.getMessage();
Log.i(null, "Problem Start"+message);
mrec.release();
}
break;
case 1: //GoToAllNotes
mrec.stop();
mrec.release();
mrec = null;
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
protected void startRecording() throws IOException
{
mrec = new MediaRecorder(); // Works well
mCamera.unlock();
mrec.setCamera(mCamera);
mrec.setPreviewDisplay(surfaceHolder.getSurface());
mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
mrec.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
mrec.setPreviewDisplay(surfaceHolder.getSurface());
mrec.setOutputFile("/sdcard/zzzz.3gp");
mrec.prepare();
mrec.start();
}
protected void stopRecording() {
mrec.stop();
mrec.release();
mCamera.release();
}
private void releaseMediaRecorder(){
if (mrec != null) {
mrec.reset(); // clear recorder configuration
mrec.release(); // release the recorder object
mrec = null;
mCamera.lock(); // lock camera for later use
}
}
private void releaseCamera(){
if (mCamera != null){
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (mCamera != null){
Parameters params = mCamera.getParameters();
mCamera.setParameters(params);
}
else {
Toast.makeText(getApplicationContext(), "Camera not available!", Toast.LENGTH_LONG).show();
finish();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
mCamera.stopPreview();
mCamera.release();
}
}
camera_surface.xml
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<SurfaceView
android:id="@+id/surface_camera"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />
<Button
android:id="@+id/buttonstart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/record_start" />
</RelativeLayout>
And of course include these permission in manifest:
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Code offset dynamic for dynamic page
var pos=$('#send').offset().top;
$('#loading').offset({ top : pos-220});
static class ArrayExtensions
{
public static int FindIndex<T>(this T[] array, Predicate<T> match)
{
return Array.FindIndex(array, match);
}
}
Usage
int[] array = { 9,8,7,6,5 };
var index = array.FindIndex(i => i == 7);
Console.WriteLine(index); // Prints "2"
I wrote this first not reading the question properly...
static class ArrayExtensions
{
public static int IndexOf<T>(this T[] array, T value)
{
return Array.IndexOf(array, value);
}
}
Usage
int[] array = { 9,8,7,6,5 };
var index = array.IndexOf(7);
Console.WriteLine(index); // Prints "2"
In Typescript and ES6 you can also use for..of:
for (var product of products) {
console.log(product.product_desc)
}
which will be transcoded to javascript:
for (var _i = 0, products_1 = products; _i < products_1.length; _i++) {
var product = products_1[_i];
console.log(product.product_desc);
}
I had a problem with the answer by @mwaskorn, namely that
g.set_xticklabels(rotation=30)
fails, because this also requires the labels. A bit easier than the answer by @Aman is to just add
plt.xticks(rotation=45)
I would have to say SimpleXML takes the cake because it is firstly an extension, written in C, and is very fast. But second, the parsed document takes the form of a PHP object. So you can "query" like $root->myElement
.
On the one hand, throwing exceptions is inherently expensive, because the stack has to be unwound etc.
On the other hand, accessing a value in a dictionary by its key is cheap, because it's a fast, O(1) operation.
BTW: The correct way to do this is to use TryGetValue
obj item;
if(!dict.TryGetValue(name, out item))
return null;
return item;
This accesses the dictionary only once instead of twice.
If you really want to just return null
if the key doesn't exist, the above code can be simplified further:
obj item;
dict.TryGetValue(name, out item);
return item;
This works, because TryGetValue
sets item
to null
if no key with name
exists.
You could also use MessageFormat too
Prepare for Segue in Swift 4.2 and Swift 5.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "OrderVC") {
// pass data to next view
let viewController = segue.destination as? MyOrderDetailsVC
viewController!.OrderData = self.MyorderArray[selectedIndex]
}
}
How to Call segue On specific Event(Like Button Click etc):
performSegue(withIdentifier: "OrderVC", sender: self)
I guess you'll need absolute position
.vertical_banner {position:relative;}
#bottom_link{position:absolute; bottom:0;}
If you are working with the configuratior you can set the @grid-gutter-width
from 30px
to 0
I just realized why I was having so much trouble - in MATLAB you can't store strings of different lengths as an array using square brackets. Using square brackets concatenates strings of varying lengths into a single character array.
>> a=['matlab','is','fun']
a =
matlabisfun
>> size(a)
ans =
1 11
In a character array, each character in a string counts as one element, which explains why the size of a is 1X11.
To store strings of varying lengths as elements of an array, you need to use curly braces to save as a cell array. In cell arrays, each string is treated as a separate element, regardless of length.
>> a={'matlab','is','fun'}
a =
'matlab' 'is' 'fun'
>> size(a)
ans =
1 3
For those looking for a dynamic solution to embed Matplotlib in PyQt5 (even plot data using drag and drop). In PyQt5 you need to use super on the main window class to accept the drops. The dropevent function can be used to get the filename and rest is simple:
def dropEvent(self,e):
"""
This function will enable the drop file directly on to the
main window. The file location will be stored in the self.filename
"""
if e.mimeData().hasUrls:
e.setDropAction(QtCore.Qt.CopyAction)
e.accept()
for url in e.mimeData().urls():
if op_sys == 'Darwin':
fname = str(NSURL.URLWithString_(str(url.toString())).filePathURL().path())
else:
fname = str(url.toLocalFile())
self.filename = fname
print("GOT ADDRESS:",self.filename)
self.readData()
else:
e.ignore() # just like above functions
For starters the reference complete code gives this output:
An interesting note: it appears that attempting to cast from an object to a list on the JavaFX Application thread always results in a ClassCastException.
I had the same issue as you, and no answer helped. After playing around for a while, the only thing I could narrow it down to was the thread. Running the code to cast on any other thread other than the UI thread succeeds as expected, and as the other answers in this section suggest.
Thus, be careful that your source isn't running on the JavaFX application thread.
To: Killercam Thanks for your solutions. I tried the first solution for an hour, but didn't work for me.
I used scripts generate method to move data from SQL Server 2012 to SQL Server 2008 R2 as steps bellow:
In the 2012 SQL Management Studio
It works for me.
You cannot mix JS and PHP that way, PHP is rendered before the page is sent to the browser (i.e. before the JS is run)
You can use window.location to change your current page.
$('.entry a:first').click(function() {
window.location = "http://google.ca";
});
Use __cplusplus
as suggested.
Only one note for Microsoft compiler, use Zc:__cplusplus
compiler switch to enable __cplusplus
Source https://devblogs.microsoft.com/cppblog/msvc-now-correctly-reports-__cplusplus/
open your php.ini, make sure it's set to:
display_errors = On
restart your server.
Swift 3.1, Swift 3.2, Swift 4
if let urlFromStr = URL(string: "instagram://app") {
if UIApplication.shared.canOpenURL(urlFromStr) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(urlFromStr, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(urlFromStr)
}
}
}
Add these in Info.plist :
<key>LSApplicationQueriesSchemes</key>
<array>
<string>instagram</string>
</array>
Use <div style="position:fixed;bottom:0;height:auto;margin-top:40px;width:100%;text-align:center">I am footer</div>
. Footer will not go upwards
Simplest Answer:
inputString = str(input("Please type a sentence: "))
vowel_count = 0
inputString =inputString.lower()
vowel_count+=inputString.count("a")
vowel_count+=inputString.count("e")
vowel_count+=inputString.count("i")
vowel_count+=inputString.count("o")
vowel_count+=inputString.count("u")
print(vowel_count)
If your table columns contains duplicate data and If you directly apply row_ number() and create PARTITION on column, there is chance to have result in duplicated row and with row number value.
To remove duplicate row, you need one more INNER query in from clause which eliminates duplicate rows and then it will give output to it's foremost outer FROM clause where you can apply PARTITION and ROW_NUMBER ().
As like below example:
SELECT DATE, STATUS, TITLE, ROW_NUMBER() OVER (PARTITION BY DATE, STATUS, TITLE ORDER BY QUANTITY ASC) AS Row_Num
FROM (
SELECT DISTINCT <column names>...
) AS tbl
It is better to use eager loading when it is possible, because it optimizes the performance of your application.
ex-:
Eager loading
var customers= _context.customers.Include(c=> c.membershipType).Tolist();
lazy loading
In model customer has to define
Public virtual string membershipType {get; set;}
So when querying lazy loading is much slower loading all the reference objects, but eager loading query and select only the object which are relevant.
You do not want to force the garbage collector to run.
However, if you ever did (as a purely academic exercise, of course):
GC.Collect()
1- ngRoute is developed by angular team whereas ui-router is a 3rd party module. 2- ngRoute implements routing based on the route URL whereas ui-router implements routing based on the state of the application. 3- ui-router provides everything that the ng-route provides plus some additional features like nested states and multiple named views.
An abbreviated version of your code worked for me,
class Remote: NSObject {
var data = NSMutableData()
func connect(query:NSString) {
var url = NSURL.URLWithString("http://www.google.com")
var request = NSURLRequest(URL: url)
var conn = NSURLConnection(request: request, delegate: self, startImmediately: true)
}
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
println("didReceiveResponse")
}
func connection(connection: NSURLConnection!, didReceiveData conData: NSData!) {
self.data.appendData(conData)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
println(self.data)
}
deinit {
println("deiniting")
}
}
This is the code I used in the calling class,
class ViewController: UIViewController {
var remote = Remote()
@IBAction func downloadTest(sender : UIButton) {
remote.connect("/apis")
}
}
You didn't specify in your question where you had this code,
var remote = Remote()
remote.connect("/apis")
If var is a local variable, then the Remote class will be deallocated right after the connect(query:NSString) method finishes, but before the data returns. As you can see by my code, I usually implement reinit (or dealloc up to now) just to make sure when my instances go away. You should add that to your Remote class to see if that's your problem.
import serial
ser = serial.Serial(0) # open first serial port
print ser.portstr # check which port was really used
ser.write("hello") # write a string
ser.close() # close port
use https://pythonhosted.org/pyserial/ for more examples
Windows applications usually come with build in print capability, but for a web application, I would choose to simply generate a PDF file.
The simplest way that I found is to generate a PDf file using PDFMake (www.pdfmake.org). You can then offer the user the choice to open or download the generated PDF file.
I would do it something along these lines:
class Foo{
...
};
int main(){
Foo* arrayOfFoo[100]; //[1]
arrayOfFoo[0] = new Foo; //[2]
}
[1] This makes an array of 100 pointers to Foo-objects. But no Foo-objects are actually created.
[2] This is one possible way to instantiate an object, and at the same time save a pointer to this object in the first position of your array.
if you have table and fields on database you can simply use this command :
php artisan db:seed --class=UsersTableSeeder --database=YOURDATABSE
For those searching for the inverse of this, i.e. looking for tables that do not contain a certain column name, here is the query...
SELECT DISTINCT TABLE_NAME FROM information_schema.columns WHERE
TABLE_SCHEMA = 'your_db_name' AND TABLE_NAME NOT IN (SELECT DISTINCT
TABLE_NAME FROM information_schema.columns WHERE column_name =
'column_name' AND TABLE_SCHEMA = 'your_db_name');
This came in really handy when we began to slowly implement use of InnoDB's special ai_col
column and needed to figure out which of our 200 tables had yet to be upgraded.
This can be solved using the decimal
module to get arbitrary precision square roots and easy checks for "exactness":
import math
from decimal import localcontext, Context, Inexact
def is_perfect_square(x):
# If you want to allow negative squares, then set x = abs(x) instead
if x < 0:
return False
# Create localized, default context so flags and traps unset
with localcontext(Context()) as ctx:
# Set a precision sufficient to represent x exactly; `x or 1` avoids
# math domain error for log10 when x is 0
ctx.prec = math.ceil(math.log10(x or 1)) + 1 # Wrap ceil call in int() on Py2
# Compute integer square root; don't even store result, just setting flags
ctx.sqrt(x).to_integral_exact()
# If previous line couldn't represent square root as exact int, sets Inexact flag
return not ctx.flags[Inexact]
For demonstration with truly huge values:
# I just kept mashing the numpad for awhile :-)
>>> base = 100009991439393999999393939398348438492389402490289028439083249803434098349083490340934903498034098390834980349083490384903843908309390282930823940230932490340983098349032098324908324098339779438974879480379380439748093874970843479280329708324970832497804329783429874329873429870234987234978034297804329782349783249873249870234987034298703249780349783497832497823497823497803429780324
>>> sqr = base ** 2
>>> sqr ** 0.5 # Too large to use floating point math
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: int too large to convert to float
>>> is_perfect_power(sqr)
True
>>> is_perfect_power(sqr-1)
False
>>> is_perfect_power(sqr+1)
False
If you increase the size of the value being tested, this eventually gets rather slow (takes close to a second for a 200,000 bit square), but for more moderate numbers (say, 20,000 bits), it's still faster than a human would notice for individual values (~33 ms on my machine). But since speed wasn't your primary concern, this is a good way to do it with Python's standard libraries.
Of course, it would be much faster to use gmpy2
and just test gmpy2.mpz(x).is_square()
, but if third party packages aren't your thing, the above works quite well.
You can get this if you ONLY configure https
as a site binding inside IIS.
You need to add http(80)
as well as https(443)
- at least I did :-)
In brief sense:
Partition Key is nothing but identification for a row, that identification most of the times is the single column (called Primary Key) sometimes a combination of multiple columns (called Composite Partition Key).
Cluster key is nothing but Indexing & Sorting. Cluster keys depend on few things:
What columns you use in where clause except primary key columns.
If you have very large records then on what concern I can divide the date for easy management. Example, I have data of 1million a county population records. So for easy management, I cluster data based on state and after pincode and so on.
You can include CSS styles in an html document with <style></style>
tags.
Example:
<style>
.myClass { background: #f00; }
.myOtherClass { font-size: 12px; }
</style>
Or in C# 3.0 using System.Linq
you can skip the intermediate list:
private Update BuildMetaData(MetaData[] nvPairs)
{
Update update = new Update();
var ip = from nv in nvPairs
select new InputProperty()
{
Name = "udf:" + nv.Name,
Val = nv.Value
};
update.Items = ip.ToArray();
return update;
}
Here is one way of getting the design that you want.
Start with the following HTML:
<div class="container">
<div class="row-fluid">
<div class="span12">
<div class="nav">nav area</div>
<div class="bg-image">
<img src="http://unplugged.ee/wp-content/uploads/2013/03/frank2.jpg">
<h1>This is centered text.</h1>
</div>
<div class="main">main area</div>
</div>
</div>
</div>
Note that the background image is now part of the regular flow of the document.
Apply the following CSS:
.bg-image {
position: relative;
}
.bg-image img {
display: block;
width: 100%;
max-width: 1200px; /* corresponds to max height of 450px */
margin: 0 auto;
}
.bg-image h1 {
position: absolute;
text-align: center;
bottom: 0;
left: 0;
right: 0;
color: white;
}
.nav, .main {
background-color: #f6f6f6;
text-align: center;
}
The image is set an regular flow content with a width of 100%, so it will adjust itself responsively to the width of the parent container. However, you want the height to be no more than 450px, which corresponds to the image width of 1200px, so set the maximum width of the image to 1200px. You can keep the image centered by using display: block
and margin: 0 auto
.
The text is painted over the image by using absolute positioning. In the simplest case, I stretch the h1
element to be the full width of the parent and use text-align: center
to center the text. Use the top or bottom offsets to place the text where it is needed.
If your banner images are going to vary in aspect ratio, you will need to adjust the maximum width value for .bg-image img
dynamically using jQuery/Javascript, but otherwise, this approach has a lot to offer.
See demo at: http://jsfiddle.net/audetwebdesign/EGgaN/
create resource file in drawable
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#3b5998" />
<cornersandroid:radius="15dp"/>
The reason the exception is not caught is because the Foo() method has a void return type and so when await is called, it simply returns. As DoFoo() is not awaiting the completion of Foo, the exception handler cannot be used.
This opens up a simpler solution if you can change the method signatures - alter Foo()
so that it returns type Task
and then DoFoo()
can await Foo()
, as in this code:
public async Task Foo() {
var x = await DoSomethingThatThrows();
}
public async void DoFoo() {
try {
await Foo();
} catch (ProtocolException ex) {
// This will catch exceptions from DoSomethingThatThrows
}
}
A nice online tool: yUML
I found the right answer just by comparing the conversion to 1/1/1970 w/o the local time adjustment;
DateTime date = new DateTime(2011, 4, 1, 12, 0, 0, 0);
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);
TimeSpan span = (date - epoch);
double unixTime =span.TotalSeconds;
You should remove "style" attribute instead of "display" property :
$("span").removeAttr("style");
I've found the following "pattern" to be very useful:
MainCtrl.$inject = ['$scope', '$rootScope', '$location', 'socket', ...];
function MainCtrl (scope, rootscope, location, thesocket, ...) {
where, MainCtrl is a controller. I am uncomfortable relying on the parameter names of the Controller function doing a one-for-one mimic of the instances for fear that I might change names and muck things up. I much prefer explicitly using $inject for this purpose.
I check for both Wi-fi and Mobile internet as follows...
private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
Obviously, It could easily be modified to check for individual specific connection types, e.g., if your app needs the potentially higher speeds of Wi-fi to work correctly etc.
function getFeed(sender, uri) {
jQuery.getFeed({
url: 'proxy.php?url=' + uri,
success: function(feed) {
jQuery(sender).append('<h2>'
+ '<a href="'
+ feed.link
+ '">'
+ feed.title
+ '</a>'
+ '</h2>');
var html = '';
for(var i = 0; i < feed.items.length && i < 5; i++) {
var item = feed.items[i];
html += '<h3>'
+ '<a href="'
+ item.link
+ '">'
+ item.title
+ '</a>'
+ '</h3>';
html += '<div class="updated">'
+ item.updated
+ '</div>';
html += '<div>'
+ item.description
+ '</div>';
}
jQuery(sender).append(html);
}
});
}
<div id="getanewbrowser">
<script type="text/javascript">
getFeed($("#getanewbrowser"), 'http://feeds.feedburner.com/getanewbrowser')
</script>
</div>
You don't need to muck about with extracting parts of the date. Just cast it to a date using to_date and the format in which its stored, then cast that date to a char in the format you want. Like this:
select to_char(to_date('1/10/2011','mm/dd/yyyy'),'mm-dd-yyyy') from dual
In addition to the Oracle instant client, you may also need to install the Oracle ODAC components and put the path to them into your system path. cx_Oracle seems to need access to the oci.dll file that is installed with them.
Also check that you get the correct version (32bit or 64bit) of them that matches your: python, cx_Oracle, and instant client versions.
#include <stdio.h>
void main()
{
int countch=0;
int countwd=1;
printf("Enter your sentence in lowercase: ");
char ch='a';
while(ch!='\r')
{
ch=getche();
if(ch==' ')
countwd++;
else
countch++;
}
printf("\n Words = ",countwd);
printf("Characters = ",countch-1);
getch();
}
lets take this example try putting \n in place of \r it will not work and try to guess why?