qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
|---|---|---|---|---|---|
17,367,700
|
I have created a form with the option to dynamically add fields with excellent code help from <http://charlie.griefer.com/blog/2009/09/17/jquery-dynamically-adding-form-elements/>. The only issue is that I want the fields to generate without also showing new 'Add' and 'Remove' buttons. How should I go about doing this? I can get it to work by having the buttons displayed underneath the field with a new `<div>` but I want them to be to the right of the field.
```
<script type="text/javascript">
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.clonedInput').length;
var newNum = new Number(num + 1);
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
newElem.children(':first')
.attr('id', 'device' + newNum)
.attr('name', 'device' + newNum);
$('#input' + num).after(newElem);
$('#btnDel').attr('disabled','');
if (newNum == 3)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
var num = $('.clonedInput').length;
$('#input' + num).remove();
$('#btnAdd').attr('disabled','');
if (num-1 == 1)
$('#btnDel').attr('disabled','disabled');
});
$('#btnDel').attr('disabled','disabled');
});
</script>
```
```
<div> Name: <input type="text" name="name" id="name" /></div>
<div id="input1" style="margin-bottom:4px;" class="clonedInput">
Device(s): <input type="text" name="device1" id="device1" />
<input type="button" id="btnAdd" value="Add" />
<input type="button" id="btnDel" value="Remove" />
</div>
```
|
2013/06/28
|
[
"https://Stackoverflow.com/questions/17367700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2532297/"
] |
Like this?
```
var arrClasses = [];
$("div[class*='some-class-']").removeClass(function () { // Select the element divs which has class that starts with some-class-
var className = this.className.match(/some-class-\d+/); //get a match to match the pattern some-class-somenumber and extract that classname
if (className) {
arrClasses.push(className[0]); //if it is the one then push it to array
return className[0]; //return it for removal
}
});
console.log(arrClasses);
```
**[Fiddle](http://jsfiddle.net/ps6hK/)**
**[.removeClass()](http://api.jquery.com/removeClass/)** accepts a callback function to do some operation and return the className to be removed, if nothing to be removed return nothing.
|
**The easy way**
You clould create your own filter :
```
$.fn.hasClassStartsWith = function(className) {
return this.filter('[class^=\''+className+'\'], [class*=\''+className+'\']');
}
var divs = $('div').hasClassStartsWith("some-class-");
console.log(divs.get());
```
[**See fiddle**](http://jsfiddle.net/W7PvB/)
|
17,367,700
|
I have created a form with the option to dynamically add fields with excellent code help from <http://charlie.griefer.com/blog/2009/09/17/jquery-dynamically-adding-form-elements/>. The only issue is that I want the fields to generate without also showing new 'Add' and 'Remove' buttons. How should I go about doing this? I can get it to work by having the buttons displayed underneath the field with a new `<div>` but I want them to be to the right of the field.
```
<script type="text/javascript">
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.clonedInput').length;
var newNum = new Number(num + 1);
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
newElem.children(':first')
.attr('id', 'device' + newNum)
.attr('name', 'device' + newNum);
$('#input' + num).after(newElem);
$('#btnDel').attr('disabled','');
if (newNum == 3)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
var num = $('.clonedInput').length;
$('#input' + num).remove();
$('#btnAdd').attr('disabled','');
if (num-1 == 1)
$('#btnDel').attr('disabled','disabled');
});
$('#btnDel').attr('disabled','disabled');
});
</script>
```
```
<div> Name: <input type="text" name="name" id="name" /></div>
<div id="input1" style="margin-bottom:4px;" class="clonedInput">
Device(s): <input type="text" name="device1" id="device1" />
<input type="button" id="btnAdd" value="Add" />
<input type="button" id="btnDel" value="Remove" />
</div>
```
|
2013/06/28
|
[
"https://Stackoverflow.com/questions/17367700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2532297/"
] |
Like this?
```
var arrClasses = [];
$("div[class*='some-class-']").removeClass(function () { // Select the element divs which has class that starts with some-class-
var className = this.className.match(/some-class-\d+/); //get a match to match the pattern some-class-somenumber and extract that classname
if (className) {
arrClasses.push(className[0]); //if it is the one then push it to array
return className[0]; //return it for removal
}
});
console.log(arrClasses);
```
**[Fiddle](http://jsfiddle.net/ps6hK/)**
**[.removeClass()](http://api.jquery.com/removeClass/)** accepts a callback function to do some operation and return the className to be removed, if nothing to be removed return nothing.
|
You can iterate over each found node and iterate over the classes to find a match; if found, remove the class and log it:
```
var found = [];
$('div[class*="some-class-"]').each(function() {
var classes = this.className.split(/\s+/),
$this = $(this);
$.each(classes, function(i, name) {
if (name.indexOf('some-class-') === 0) {
$this.removeClass(name);
found.push(name);
}
});
});
```
Note that a selector like `div[class*="some-class-"]` is pretty expensive and since you need to perform extra processing anyway, it would be easier to just iterate over all `div` tags and process them:
```
var elements = document.getElementsByTagName('div'),
found = [];
$.each(elements, function(i, element) {
var classes = element.className.split(/\s+/);
$.each(classes, function(i, name) {
if (name.indexOf('some-class-') === 0) {
$(element).removeClass(name);
found.push(name);
}
});
});
```
Modern browsers expose [`Element.classList`](https://developer.mozilla.org/en-US/docs/Web/API/element.classList) which you can use to manipulate class names and [`Array.forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) for iteration:
```
var found = [];
[].forEach.call(document.getElementsByTagName('div'), function(element) {
(function(names, i) {
while (i < names.length) {
var name = names[i];
if (name.indexOf('some-class-') === 0) {
names.remove(name);
found.push(name);
} else {
++i;
}
}
}(element.classList, 0));
});
```
|
17,367,700
|
I have created a form with the option to dynamically add fields with excellent code help from <http://charlie.griefer.com/blog/2009/09/17/jquery-dynamically-adding-form-elements/>. The only issue is that I want the fields to generate without also showing new 'Add' and 'Remove' buttons. How should I go about doing this? I can get it to work by having the buttons displayed underneath the field with a new `<div>` but I want them to be to the right of the field.
```
<script type="text/javascript">
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.clonedInput').length;
var newNum = new Number(num + 1);
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
newElem.children(':first')
.attr('id', 'device' + newNum)
.attr('name', 'device' + newNum);
$('#input' + num).after(newElem);
$('#btnDel').attr('disabled','');
if (newNum == 3)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
var num = $('.clonedInput').length;
$('#input' + num).remove();
$('#btnAdd').attr('disabled','');
if (num-1 == 1)
$('#btnDel').attr('disabled','disabled');
});
$('#btnDel').attr('disabled','disabled');
});
</script>
```
```
<div> Name: <input type="text" name="name" id="name" /></div>
<div id="input1" style="margin-bottom:4px;" class="clonedInput">
Device(s): <input type="text" name="device1" id="device1" />
<input type="button" id="btnAdd" value="Add" />
<input type="button" id="btnDel" value="Remove" />
</div>
```
|
2013/06/28
|
[
"https://Stackoverflow.com/questions/17367700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2532297/"
] |
You could loop through all the elements, pull the class name using a regular expression, and store them in an array:
```js
var classNames = [];
$('div[class*="some-class-"]').each(function(i, el){
var name = (el.className.match(/(^|\s)(some\-class\-[^\s]*)/) || [,,''])[2];
if(name){
classNames.push(name);
$(el).removeClass(name);
}
});
console.log(classNames);
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="class-x some-class-1 other-class"></div>
<div class="some-class-45 class-y"></div>
<div class="some-class-123 something-else"></div>
```
|
**The easy way**
You clould create your own filter :
```
$.fn.hasClassStartsWith = function(className) {
return this.filter('[class^=\''+className+'\'], [class*=\''+className+'\']');
}
var divs = $('div').hasClassStartsWith("some-class-");
console.log(divs.get());
```
[**See fiddle**](http://jsfiddle.net/W7PvB/)
|
17,367,700
|
I have created a form with the option to dynamically add fields with excellent code help from <http://charlie.griefer.com/blog/2009/09/17/jquery-dynamically-adding-form-elements/>. The only issue is that I want the fields to generate without also showing new 'Add' and 'Remove' buttons. How should I go about doing this? I can get it to work by having the buttons displayed underneath the field with a new `<div>` but I want them to be to the right of the field.
```
<script type="text/javascript">
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.clonedInput').length;
var newNum = new Number(num + 1);
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
newElem.children(':first')
.attr('id', 'device' + newNum)
.attr('name', 'device' + newNum);
$('#input' + num).after(newElem);
$('#btnDel').attr('disabled','');
if (newNum == 3)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
var num = $('.clonedInput').length;
$('#input' + num).remove();
$('#btnAdd').attr('disabled','');
if (num-1 == 1)
$('#btnDel').attr('disabled','disabled');
});
$('#btnDel').attr('disabled','disabled');
});
</script>
```
```
<div> Name: <input type="text" name="name" id="name" /></div>
<div id="input1" style="margin-bottom:4px;" class="clonedInput">
Device(s): <input type="text" name="device1" id="device1" />
<input type="button" id="btnAdd" value="Add" />
<input type="button" id="btnDel" value="Remove" />
</div>
```
|
2013/06/28
|
[
"https://Stackoverflow.com/questions/17367700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2532297/"
] |
You can iterate over each found node and iterate over the classes to find a match; if found, remove the class and log it:
```
var found = [];
$('div[class*="some-class-"]').each(function() {
var classes = this.className.split(/\s+/),
$this = $(this);
$.each(classes, function(i, name) {
if (name.indexOf('some-class-') === 0) {
$this.removeClass(name);
found.push(name);
}
});
});
```
Note that a selector like `div[class*="some-class-"]` is pretty expensive and since you need to perform extra processing anyway, it would be easier to just iterate over all `div` tags and process them:
```
var elements = document.getElementsByTagName('div'),
found = [];
$.each(elements, function(i, element) {
var classes = element.className.split(/\s+/);
$.each(classes, function(i, name) {
if (name.indexOf('some-class-') === 0) {
$(element).removeClass(name);
found.push(name);
}
});
});
```
Modern browsers expose [`Element.classList`](https://developer.mozilla.org/en-US/docs/Web/API/element.classList) which you can use to manipulate class names and [`Array.forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) for iteration:
```
var found = [];
[].forEach.call(document.getElementsByTagName('div'), function(element) {
(function(names, i) {
while (i < names.length) {
var name = names[i];
if (name.indexOf('some-class-') === 0) {
names.remove(name);
found.push(name);
} else {
++i;
}
}
}(element.classList, 0));
});
```
|
**The easy way**
You clould create your own filter :
```
$.fn.hasClassStartsWith = function(className) {
return this.filter('[class^=\''+className+'\'], [class*=\''+className+'\']');
}
var divs = $('div').hasClassStartsWith("some-class-");
console.log(divs.get());
```
[**See fiddle**](http://jsfiddle.net/W7PvB/)
|
72,192,162
|
I am trying to solve a problem where i need to find difference of number months between 2 strings
```
"January 2022"
"July 2022"
Answer=7
```
I looked all over internet to find answer but could not, mostly answer used datetime library
Is there any other way to solve this problem?
I tried to create a static dictionary like this but could not proceed further
```
m={
1: "January",
2: "February",
3: "March",
4: "April",
5: "May",
6: "June",
7: "July",
8: "August",
9: "September",
10: "October",
11: "November",
12: "December"
}
```
|
2022/05/10
|
[
"https://Stackoverflow.com/questions/72192162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13184945/"
] |
At first I tried to use `datetime` modules but later if found much simpler way.
1. you reverse the dictionary to convert month to month id
2. convert year to month by mulitplying with 12.
```
month_ids = dict({
"January":1,
"February":2,
"March":3,
"April":4,
"May":5,
"June":6,
"July":7,
"August":8,
"September":9,
"October":10,
"November":11,
"December":12
})
def to_months(month_year):
month_name, year = month_year.strip().split()
return (int(year) * 12) + month_ids[month_name.strip()]
print(to_months("July 2022") - to_months("January 2022"))
```
Note: As per above logic, the difference b/w July/January comes as 6 as this code does not include last month into count. As per your need, you can include +1 if need.
|
Use [`dateutil`](https://dateutil.readthedocs.io/en/stable/index.html):
```
from dateutil import parser, relativedelta
def delta_months(a, b):
""" returns negative delta if b > a """
a = parser.parse(a)
b = parser.parse(b)
delta = relativedelta.relativedelta(a, b)
delta = delta.years * 12 + delta.months
return delta
a = 'January 2022'
b = 'March 2022'
print(delta_months(a, b)) # -2
print(delta_months(b, a)) # 2
```
|
2,619,967
|
Let $m$ be a perfect square of 4 digits, with the digits $\lt 9$. Adding $1$ to each of the digits of $m$ will form another perfect square. Find $m$.
To be honest i'm absolutely lost, i tried with brute force but for this kind of problem i like to get the "elegant" way to solve it.
|
2018/01/25
|
[
"https://math.stackexchange.com/questions/2619967",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/455734/"
] |
$m=a^2$ and $m+1111=b^2$, so $b^2-a^2=(b-a)(b+a)=1111=11\cdot 101$ where $11$ and $101$ are prime. Thus, there are two solutions for $b-a$ and $b+a$ that we need to try:
* $b-a=1, b+a=1111$: $b=556, a=555$, but then $a^2=308025$ and is not a 4-digit number
* $b-a=11, b+a=101$: $b=56, a=45$: $a^2=2025$ and $b^2=3136$ - a solution ($m=2025$)
|
\begin{eqnarray\*}
1000a+100b+10c+d=x^2 \\
1000(a+1)+100(b+1)+10(c+1)+(d+1)=y^2 \\
1111 = y^2-x^2 \\
\color{blue}{11} \times \color{red}{101} = \color{blue}{(y-x)} \color{red}{(y+x)}
\end{eqnarray\*}
Gives $x=45$ and $y=56$.
|
15,144,255
|
I would like to build a treeview like this:
```
People
Person 1
Relatives
Relative 1
Relative 2
Mom
Dad
Pets
Pet 1
Pet 2
```
The problem is that a person has 2 lists (Relatives and Pets) and two Single Items (Mom and Dad). I'm pretty familiar with HierarchicalDataTemplates but I haven't figured out a way to do this- there are lots of examples out there but none seem to mix types like this.
To make things even more interesting, there may be People without a Mom or a Dad (sad but true). The list would need to reflect this.
The data Im using originates from the data base using entity framework, so my list of people already has the correct structure- and I would prefer NOT to have all my objects derive from some common composite object (also in many of the examples) where everyone has a 'Name' and 'Children'. I would like to use the natural properties of each object, like MomsFirstName, PersonsName in the bindings of my datatemplates as well.
Is this possible?
|
2013/02/28
|
[
"https://Stackoverflow.com/questions/15144255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/221515/"
] |
Just a guess but, are you getting a warning about initialization casting a double to a float (using MSVS)? Or possibly it's messing up b/c everything is ending up being cast as an integer b/c of the '4'?
If so, the problem is that when you type out a number it's a double. But you're using it as a float, to resolve it, that number needs to be what is cast. E.g.
```
sphereSA = ((float) 4 * (float) PI * radius * radius);
```
But, it would be better to give the compiler some type information about PI. E.g.
```
namespace MyConstants {
const float PI = 3.141;
}
sphereSA = ((float) 4 * MyConstants::PI * radius * radius);
```
|
You're using the C style cast. The syntax for casts has changed with C++.
You want to look for something like this:
```
dynamic_cast<something*>( yourthing );
```
|
423,748
|
thank you for reading.
I was trying to use some commutators in an array when I found this error :
>
> ! Missing number, treated as zero. a l.9 [a] A
> number should have been here; I inserted '0'. (If you can't figure out
> why I needed to see a number, look up 'weird error' in the index to
> The TeXbook.)
>
>
> ! Illegal unit of measure (pt inserted). Dimensions can be in units of
> em, ex, in, pt, pc, cm, mm, dd, cc, nd, nc, bp, or sp; but yours is a
> new one! I'll assume that you meant to say pt, for printer's points.
> To recover gracefully from this error, it's best to delete the
> erroneous units; e.g., type `2' to delete two letters. (See Chapter 27
> of The TeXbook.)
>
>
> ! Missing = inserted for \ifdim. I was expecting to see '<', '=', or
> '>'. Didn't.
>
>
>
With the following code :
```
\documentclass{article}
\usepackage[english]{babel}
\begin{document}
$$\begin{array}{c}
first ligne\\
[second ligne]
\end{array}$$
\end{document}
```
The code creates a pdf with some text on the second page and some black space on the right of it.
It does compute well when you remove the left bracket [, or when you use the brackets on the first ligne.
Is this related with a \\ [ on two consecutive lines ?
|
2018/03/28
|
[
"https://tex.stackexchange.com/questions/423748",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/159394/"
] |
* in your table you not need `\multirow` cells.
* however, if you persit to have them in your table design, you can exploit new features of `multirow` package, which offer new option `=` by which multiroe cell overtake defined width ov column. for example, that column is of type `p{22mm}`, than `\multirow{2}{=}{<cell content>}` has width 22mm.
* it is not clear, why you define seven columns when the table has only four.
* `multicolum`s (except one) are superfluous.
* i wouldn't have vertical rules in table
* for equations in second, third and fourth column are more readable, if thex are set in `array` nested in `tabularx` cells
[](https://i.stack.imgur.com/qxhwx.png)
(red lines indicate text border).
```
\documentclass[]{IEEEtran}
% Floats
\usepackage{caption}
\captionsetup{justification = centering}
% Math
%\usepackage{amsmath} % loaded by `mathtools`
\usepackage{amssymb}
\usepackage{mathtools}
% Tables
\usepackage{ragged2e}
\usepackage{booktabs, tabularx}
\renewcommand\tabularxcolumn[1]{>{\centering\arraybackslash}m{#1}}
\newcolumntype{C}{>{\Centering} X }
\usepackage{siunitx} % <--- added
\begin{document}
\begin{table*}
\caption{\Large \textbf{A table with multi-rows and multi columns}}
\label{table:fit_WT_par}
\centering
\begin{tabularx}{0.85\textwidth}{@{}>{\hsize=0.16\hsize}C
*{3}{>{\hsize=0.28\hsize}C}
@{}}
\toprule
& \multicolumn{3}{c}{\textbf{WT Model }} \\
\cmidrule(lr){2-4}
\textbf{Fit Type}
& \textbf{GEV MP R} & \textbf{G58-850} & \textbf{E-92} \\
\midrule
Polynomial Fit According to Eq.
& $\begin{array}{@{}lll@{}}
c_{7 }= -9.7 & c_{6} = 531 \\
c_{5} = -122 & c_{4} = 152 \\
c_{3} = -111 & c_{2} = 473 \\
c_{1} = -\num{10927270} & c_{0} = 105
\end{array}$
& $\begin{array}{@{}lll@{}}
c_{8} = -1.30 & c_{7} = 85.3 \\
c_{6} = -236 & c_{5} = 360 \\
c_{4} = -\num{328979} & c_{3} = 184 \\
c_{2} = -\num{6194947} & c_{1} = 113 \\
c_{0} = -874 &
\end{array}$
& $\begin{array}{@{}lll@{}}
c_{9} = -0.0535 & c_{8} = 2.79 \\
c_{7} = -53.1 & c_{6} = 364 \\
c_{5} = 150 & c_{4} = -416 \\
c_{3} = 290 & c_{2} = -972 \\
c_{1} = 1609 & c_{0} = -104
\end{array}$ \\
\midrule
Approximate Cubic According to Eq.
& $C_{p,\max} = 0.3926$
& $C_{p,\max} = 0.4453$
& $C_{p,\max} = 0.4729$ \\
\midrule
Exponential (Eq. )
& $K_{p} = 2.687,\beta = 2.201$
& $K_{p} = 12.88,\beta = 1.532$
& $K_{p} = 11.12,\beta = 1.564$ \\
\bottomrule
\end{tabularx}
\end{table*}
\end{document}
```
* in case, that you like to have table width equal `\textwidth` than rešlace
`\begin{tabularx}{0.85\textwidth}{...}`
width
`\begin{tabularx}{1\textwidth}{...}`
in above code i remove all not used packages and your definitions in preamble, which are not relevant for this table.
|
Actually, you don't need any multirow,and only 4 columns. Here is a much simpler code, with the first column 1/3 of the other columns width. Also, you should use `booktabs` with vertical rules: horizontal and vertical rules don't intersect properly. I replaced `\bottomrule` with `\Xhline` from `makecell. Last point: needless to load`amsmath`if you load`mathtools` – the latter does it for you.
\documentclass[]{IEEEtran}
```
% Floats
\usepackage{caption}
\captionsetup{justification = centering}
% Math
\usepackage{amssymb, amsfonts}
\usepackage[]{mathtools}
% Tables
\usepackage{ragged2e}
\usepackage{tabularx}
\newcolumntype{C}{ >{ \arraybackslash \Centering } X }
\renewcommand \tabularxcolumn [1] { >{ \centering } m{#1} }
\newcommand {\arraystretchdefaultl} {1.3}
\newcommand{\arraystretchdefault}{ \renewcommand {\arraystretch} {\arraystretchdefaultl} }
\arraystretchdefault
\newcommand {\scalelinespace} [1] {\rule{0pt}{#1\normalbaselineskip}}
\newlength{\tabcolsepdefaultl}
\setlength{\tabcolsepdefaultl}{2.12mm}
\newcommand{\tabcolsepdefault}{ \setlength{\tabcolsep}{\tabcolsepdefaultl} }
\tabcolsepdefault
\newlength{\arraycolsepdefaultl}
\setlength{\arraycolsepdefaultl}{2.12mm}
\newcommand{\arraycolsepdefault}{ \setlength{\arraycolsep}{\arraycolsepdefaultl} }
\arraycolsepdefault
\usepackage{booktabs}
\usepackage{multirow, makecell}
\begin{document}
\begin{table*}[h t p]
% Table options
% Caption
\caption{\Large \textbf{A table with multi-rows and multi columns}}
\label{table:fit_WT_par}
% Center the table
\centering
% Table contents
\begin{tabularx}{1\textwidth}{>{\hsize=0.4\hsize}C *{3}{|>{\hsize=1.2\hsize\arraybackslash}C}}
\toprule
\multicolumn{4}{c}{\textbf{WT Model}} \\
\hline
\textbf{Fit Type} & \textbf{GEV MP R} & \textbf{G58-850} & \textbf{E-92} \\
\hline
Polynomial Fit According to Eq. & \RaggedLeft $c_{7 }= -9.7, \; c_{6} = 531$, $c_{5} = -122, \; c_{4} = 152$, $c_{3} = -111, \; c_{2} = 473$, $c_{1} = -10927270, \; c_{0} = 105$ &
\justifying $c_{8} = -1.30, \; c_{7} = 85.3$, $c_{6} = -236, \; c_{5} = 360$, $c_{4} = -328979, \; c_{3} = 184$, $c_{2} = -6194947, \; c_{1} = 113$, $c_{0} = -874$ &
$c_{9} = -0.0535, \; c_{8} = 2.79$, $c_{7} = -53.1, \; c_{6} = 364$, $c_{5} = 150, \; c_{4} = -416$, $c_{3} = 290, \; c_{2} = -972$, $c_{1} = 1609, \; c_{0} = -104$ \\
\hline
Approximate Cubic According to Eq. & $C_{p, \, \max} = 0.3926$ & $C_{p, \,\max} = 0.4453$ & $C_{p, \, \max} = 0.4729$ \\
\hline
Exponential (Eq. ) & $K_{p} = 2.687, \; \beta = 2.201$ & $K_{p} = 12.88, \; \beta = 1.532$ & $K_{p} = 11.12, \; \beta = 1.564$ %
\\
\Xhline{0.8pt}
\end{tabularx}
\end{table*}
\end{document}
```
[](https://i.stack.imgur.com/M1nvl.png)
|
62,231,220
|
I have an HTML input on my page. The user is able to type text into it. When he types in a command, that I specified, and presses enter, the page outputs information into the `input.value`. If the user types in something random and confirms his input, the page just outputs: "Unknown command.", again into to `input.value`.
I made a striped down Fiddle here: [JSFiddle](https://jsfiddle.net/Simon_R/m1or79wn/)
**The Problem**:
When I type in: `test` and press enter, the value changes to: `This is kind of working…`. I know want to type in something new, but I first have to highlight, or delete the `This is kind of working…` text, which is really not intuitive.
Is there a way to change my script, so that when I'm in the input and I press any button, that is not button Nr.13 aka "Enter", the page just makes the value of the input, the button, that has been pressed? So that the user can just start typing in something new, after receiveing a value and doesn't have to delete the value that I put in there.
I tried adding an additional .onkeypress function, but it destroyed everything, so I didn't do it the right way.
This is my current JS:
```
var clInput = 0;
document.querySelector("#inputMain").onkeypress = function(e){
if (!e) e = window.event;
if (e.keyCode == '13'){
clInput = document.querySelector("#inputMain").value;
switch (clInput) {
case "test":
test();
break;
default:
document.querySelector("#inputMain").value = "Unknown command.";
}
return false;
}
}
function test() {
document.querySelector("#inputMain").value = "This is kind of working…";
}
```
HTML:
```
<input id="inputMain" name="inputMain" autofocus>
```
|
2020/06/06
|
[
"https://Stackoverflow.com/questions/62231220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13693217/"
] |
I have updated your code a bit to do exactly what you want. What was essentially done was to:
1. Keep track of when you pressed `13 - Enter`.
2. Then if `13 - Enter` was previously pressed, just make sure to clear the input.
You can check the demo here: <https://jsfiddle.net/nh6c7ugf/>
```
var clInput = 0; // Note: Ignore Upper- / Lower-Case in input?
var isEntered = false;
document.querySelector("#inputMain").onkeypress = function(e){
if (!e) e = window.event;
// clear the value
if (isEntered) {
isEntered = false;
document.querySelector("#inputMain").value = '';
}
if (e.keyCode == '13'){
clInput = document.querySelector("#inputMain").value;
isEntered = true;
switch (clInput) {
case "test":
test();
break;
default:
document.querySelector("#inputMain").value = "Unknown command.";
}
return false;
}
}
function test() {
document.querySelector("#inputMain").value = "This is kind of working…";
}
```
|
Sorry if I don't understand what you are trying to say
but if you want that the user can just start typing in something new, after receiving value and doesn't have to delete the value that you put in there.
you can do
```
function test() {
document.querySelector("#inputMain").value = "This is kind of working…";
document.querySelector("#inputMain").selct();
}
```
This will select all the text of the input field and when the user will type something the previous value of the field will be deleted
|
5,350,591
|
I have a simple code below:
```
class B;
class A{
B b;
};
class B{
public:
B(){
}
};
```
In class A's definition, I have a B-typed property. Using MS Visual Studio to compile, I've got the following error:
```
error C2079: 'A::b' uses undefined class 'B'
```
Due to some reasons, I can't put class B's definition before class A's one. Any idea?
|
2011/03/18
|
[
"https://Stackoverflow.com/questions/5350591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/197896/"
] |
The compiler is already telling you what's wrong : A has a member data b which is of an undefined type. Your forward declaration:
```
class B;
```
is just that : a declaration, not a definition. Since class A contains an instance of B directly (not just a pointer to B), the compiler needs to know the exact size of B : it needs its definition, not just a declaration, i.e. a promise that B will exist at some point.
The simplest thing to do here would be to reorder things this way:
```
class B{
public:
B(){
}
};
class A{
B b;
};
```
*Edit* : see also [this question](https://stackoverflow.com/questions/1410563/what-is-the-difference-between-a-definition-and-a-declaration) for the difference between declaration and definition.
*Further edit* : an alternative would be to change your member data to a pointer or a reference.
Do note that this isn't a trivial syntax change: it has implications on the life-cycle of your objects since the object pointed by A::b may then survive the destruction of A.
If what you want is composition (B is a part of A and dies with A), using a pointer will make your life harder with little benefits.
*More edits(!)* : just realized I misread the end of your question; what are the reasons preventing you from declaring B before A ?
If they cannot be worked around, you may have to go the pointer route. These reasons might be a sign that your objects are too tightly coupled though ! (perhaps B needs to be an inner class of A ? Or simply be merged into a single object ?)
|
```
class A;
class B {
A * getA();
};
class A {
B b;
};
```
This is the typical way to solve this. You *must* have B's definition in order to have a `B b;` member.
You need a forward declaration in order to declare a reference/pointer to B, you need the full definition in order to do anything else with B (such as defining a variable, calling a member function and so on)
|
5,350,591
|
I have a simple code below:
```
class B;
class A{
B b;
};
class B{
public:
B(){
}
};
```
In class A's definition, I have a B-typed property. Using MS Visual Studio to compile, I've got the following error:
```
error C2079: 'A::b' uses undefined class 'B'
```
Due to some reasons, I can't put class B's definition before class A's one. Any idea?
|
2011/03/18
|
[
"https://Stackoverflow.com/questions/5350591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/197896/"
] |
The compiler is already telling you what's wrong : A has a member data b which is of an undefined type. Your forward declaration:
```
class B;
```
is just that : a declaration, not a definition. Since class A contains an instance of B directly (not just a pointer to B), the compiler needs to know the exact size of B : it needs its definition, not just a declaration, i.e. a promise that B will exist at some point.
The simplest thing to do here would be to reorder things this way:
```
class B{
public:
B(){
}
};
class A{
B b;
};
```
*Edit* : see also [this question](https://stackoverflow.com/questions/1410563/what-is-the-difference-between-a-definition-and-a-declaration) for the difference between declaration and definition.
*Further edit* : an alternative would be to change your member data to a pointer or a reference.
Do note that this isn't a trivial syntax change: it has implications on the life-cycle of your objects since the object pointed by A::b may then survive the destruction of A.
If what you want is composition (B is a part of A and dies with A), using a pointer will make your life harder with little benefits.
*More edits(!)* : just realized I misread the end of your question; what are the reasons preventing you from declaring B before A ?
If they cannot be worked around, you may have to go the pointer route. These reasons might be a sign that your objects are too tightly coupled though ! (perhaps B needs to be an inner class of A ? Or simply be merged into a single object ?)
|
You can do what you wish if you change the reference to `b` into a pointer to `B`.
```
class A{
B* bPtr;
};
class B{
public:
B(){
}
};
```
In principle, you don't need an *explicit declaration* - that is, a *forward declaration* is all that is needed - when you don't need the actual size of the class, or access to the types and member functions inside the class.
In your original example, you are making a direct reference to `B`. As a result, the compiler needs to know everything about `B`, thus requiring an explicit declaration instead of a forward one.
By having your `A` class declaration using a pointer to `B`, then you can get away with a forward declaration.
**edit**
Some links might explain the concept for you:
<http://www.goingware.com/tips/parameters/notrequired.html>
<http://www-subatech.in2p3.fr/~photons/subatech/soft/carnac/CPP-INC-1.shtml>
<http://www.codeguru.com/forum/showthread.php?t=358333> (see post #2)
<http://en.wikipedia.org/wiki/Forward_declaration>
|
5,350,591
|
I have a simple code below:
```
class B;
class A{
B b;
};
class B{
public:
B(){
}
};
```
In class A's definition, I have a B-typed property. Using MS Visual Studio to compile, I've got the following error:
```
error C2079: 'A::b' uses undefined class 'B'
```
Due to some reasons, I can't put class B's definition before class A's one. Any idea?
|
2011/03/18
|
[
"https://Stackoverflow.com/questions/5350591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/197896/"
] |
The compiler is already telling you what's wrong : A has a member data b which is of an undefined type. Your forward declaration:
```
class B;
```
is just that : a declaration, not a definition. Since class A contains an instance of B directly (not just a pointer to B), the compiler needs to know the exact size of B : it needs its definition, not just a declaration, i.e. a promise that B will exist at some point.
The simplest thing to do here would be to reorder things this way:
```
class B{
public:
B(){
}
};
class A{
B b;
};
```
*Edit* : see also [this question](https://stackoverflow.com/questions/1410563/what-is-the-difference-between-a-definition-and-a-declaration) for the difference between declaration and definition.
*Further edit* : an alternative would be to change your member data to a pointer or a reference.
Do note that this isn't a trivial syntax change: it has implications on the life-cycle of your objects since the object pointed by A::b may then survive the destruction of A.
If what you want is composition (B is a part of A and dies with A), using a pointer will make your life harder with little benefits.
*More edits(!)* : just realized I misread the end of your question; what are the reasons preventing you from declaring B before A ?
If they cannot be worked around, you may have to go the pointer route. These reasons might be a sign that your objects are too tightly coupled though ! (perhaps B needs to be an inner class of A ? Or simply be merged into a single object ?)
|
C++ has the concept of an "incomplete" class and it is something you need to know.
Using an incomplete class allows you, in many situations, to use a class just knowing it is one, without knowing what is in it.
This enables the class detail to change later without requiring a recompile, thus it is a far weaker dependency in the coupling model.
You need a complete class to:
* Have an instance of one.
* Derive from it
* Call any method on it.
* delete a pointer to it.
You only need an incomplete class to:
* Hold a pointer or reference to it.
* Pass a pointer or reference to a function that takes a pointer or reference. (This can be a function that deletes the pointer, as long as it is fully defined at that point).
I think you only need an incomplete class to declare a function that returns one, and possibly to declare a function that takes one as a parameter, but at the time you define or call the function it needs to be complete, even if you don't use the return value.
|
47,213,127
|
I have a column 'Incident\_Time' representing time in a data frame in R.
when I call the str() function on the column it says something like this
>
> str(crime\_data$Incident\_Time)
>
>
> Factor w/ 1439 levels "00:01:00","00:02:00",..: 840 945 1140 981 1260 969 1020 840 980 765 ...
>
>
>
I want to convert this column into string type such that if the time is less than 12:00:00, it should get modified to the string "morning" , if time is between 12:00:00 and 6:00:00 , it is "daylight" and so on.
I typed the following commands:
```
time.tag <- chron(times=c("00:00:00", "06:00:00", "12:00:00", "18:00:00", "23:59:59"))
labels <- c("Early Morning", "Morning", "Evening", "Night")
crime_data$Incident_Time_Range <- cut(crime_data$Incident_Time, breaks = time.tag, labels, include.lowest = TRUE )
```
Then the following error occurred:
>
> Error in cut.default(crime\_data$Incident\_Time, breaks = time.tag, labels, :
> 'x' must be numeric
>
>
>
Please help me to identify the problem. Thank You.
|
2017/11/09
|
[
"https://Stackoverflow.com/questions/47213127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1496554/"
] |
Unverified as there is no sample data, but you shouldn't have your incident time as a factor. Convert to time:
```
crime_data$Incident_Time <- chron(times=as.character(crime_data$Incident_Time))
```
Then run your existing code
|
To provide a complete example.
**Example Data**
```
sampletime<-chron(times=as.character(as.ITime(Sys.time()+sample(86400,100))))
```
No modifications needed to code but it would not work until I converted `sampletime` to class `times` by using `chron`. I believe cut will not work if your data is not the same `class`.
```
cut(sampletime, breaks = time.tag, labels, include.lowest = TRUE )
[1] Early Morning Evening Evening Evening
[5] Morning Night Evening Night
[9] Night Morning Early Morning Early Morning
[13] Evening Early Morning Morning Early Morning
[17] Evening Morning Early Morning Evening
....
```
|
37,464,446
|
I have 4 divs and 4 images and each of them has an ID. I need to show another div when you hover the first div's image.
I wrote this code but only the first image with ID="insta2" and div ID="iinsta2" worked.
```
<style type="text/css">
#insta1{display:none}
#insta2{display:none}
#insta3{display:none}
#insta4{display:none}
#iinsta1:hover + #insta1 {
display: block;
}
#iinsta2:hover + #insta2 {
display: block;
}
#iinsta3:hover + #insta3 {
display: block;
}
#iinsta4:hover + #insta4 {
display: block;
}
</style>
```
And body:
```
<tr>
<td colspan="3" rowspan="2" style="text-align:center; width:30%">
<div id="insta1"><p> Hover 1 </p></div>
<img id="iinsta2" src="url" style="width:100% ; height:auto">
<div id="insta2"> <p> Hover </p></div>
</td>
<td colspan="4" style="text-align:center; width:40%">
<img id="iinsta1" src="url" style="width:100% ; height:auto">
</td>
<td colspan="3" rowspan="2" style="text-align:center; width:30%">
<div id="insta3"><p> Hover 3 </p></div>
<img id="iinsta3" src="url" style="width:100% ; height:auto">
<div id="insta4"> <p> Hover 4 </p> </div>
</td>
</tr>
<tr>
<td colspan="4" style="text-align:center; width:40%">
<img id="iinsta4" src="url" style="width:100% ; height:auto">
</td>
</tr>
```
|
2016/05/26
|
[
"https://Stackoverflow.com/questions/37464446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6383507/"
] |
Use this way:
```css
#insta1,
#insta2,
#insta3,
#insta4 {
display: none;
}
#iinsta1:hover + #insta1,
#iinsta2:hover + #insta2,
#iinsta3:hover + #insta3,
#iinsta4:hover + #insta4 {
display: block;
}
```
```html
<table>
<tr>
<td colspan="3" rowspan="2" style="text-align:center; width:30%">
<div id="insta1">
<p>Hover 1</p>
</div>
<img id="iinsta2" src="url" style="width:100% ; height:auto">
<div id="insta2">
<p>Hover</p>
</div>
</td>
<td colspan="4" style="text-align:center; width:40%">
<img id="iinsta1" src="url" style="width:100% ; height:auto">
</td>
<td colspan="3" rowspan="2" style="text-align:center; width:30%">
<img id="iinsta3" src="url" style="width:100% ; height:auto">
<div id="insta3">
<p>Hover 3</p>
</div>
</td>
</tr>
<tr>
<td colspan="4" style="text-align:center; width:40%">
<img id="iinsta4" src="url" style="width:100% ; height:auto">
<div id="insta4">
<p>Hover 4</p>
</div>
</td>
</tr>
</table>
```
The `+` object can be used only with siblings that are next. Also, I have reduced your CSS. Please use `absolute` positions for positioning the `:hover`s. And, if you wanna maintain the HTML layout, you need to use JavaScript for this.
|
```css
img ~ p {
visibility: hidden;
}
img:hover ~ p {
visibility: visible;
}
```
```html
<table border=1>
<tr>
<td>
<div class="item">
<h1>Hover 1</h1>
<img src="http://placekitten.com/100" />
<p>Hover</p>
</div>
</td>
<td>
<div class="item">
<h1>Hover 1</h1>
<img src="http://placekitten.com/100" />
<p>Hover</p>
</div>
</td>
<td>
<div class="item">
<h1>Hover 1</h1>
<img src="http://placekitten.com/100" />
<p>Hover</p>
</div>
</td>
<td>
<div class="item">
<h1>Hover 1</h1>
<img src="http://placekitten.com/100" />
<p>Hover</p>
</div>
</td>
</tr>
</table>
```
The example here seems complicated so I boiled it down to what I understood the question to be. I hope this helps. Feed back is welcome.
|
544
|
I'm making a mint chocolate stout. I've made it before; I added 1.5 ounces of fresh spearmint to the last 10 or 15 minutes of the boil. It turned out alright, but it's not as strong as I'd like. The obvious answer would be to add more mint. But before I make it again, I'd like to utilize your collective experience.
When is the best time to add mint without imparting off flavors?
Should I add it to secondary? (Last time I scooped it out before fermenting)
What type of mint would go best with the roasted malt notes?
|
2010/11/15
|
[
"https://homebrew.stackexchange.com/questions/544",
"https://homebrew.stackexchange.com",
"https://homebrew.stackexchange.com/users/12/"
] |
Adding mint during the boil is good, but the problem is that you'll lose a lot of the mint aroma during primary fermentation as the C02 carries it out the airlock.
The first thing that comes to mind would be to create a mint extract (soak the mint in vodka) and add that to your secondary. You can, of course, add the mint directly to the secondary, but you won't see as much flavor imparted as you would with an extract, and you'd need to remove it after a week or so before the leaves break down (resulting in potential grassy off-flavors).
Considering how well peppermint pairs with dark chocolate, I'd be inclined to use that over something like spearmint.
|
Have you considered making an extract from your mint using vodka? It would give you a lot of control over how minty your stout ends up. When you're ready to bottle you can take a small sample of the beer and add the mint extract until the flavor profile is what you're looking for. Then you just scale the amount up for the whole batch.
|
544
|
I'm making a mint chocolate stout. I've made it before; I added 1.5 ounces of fresh spearmint to the last 10 or 15 minutes of the boil. It turned out alright, but it's not as strong as I'd like. The obvious answer would be to add more mint. But before I make it again, I'd like to utilize your collective experience.
When is the best time to add mint without imparting off flavors?
Should I add it to secondary? (Last time I scooped it out before fermenting)
What type of mint would go best with the roasted malt notes?
|
2010/11/15
|
[
"https://homebrew.stackexchange.com/questions/544",
"https://homebrew.stackexchange.com",
"https://homebrew.stackexchange.com/users/12/"
] |
Have you considered making an extract from your mint using vodka? It would give you a lot of control over how minty your stout ends up. When you're ready to bottle you can take a small sample of the beer and add the mint extract until the flavor profile is what you're looking for. Then you just scale the amount up for the whole batch.
|
What about sanitizing it then muddling it, than add it to your bottling bucket and pour your fermented beer over it. Similar to using mint for drinks in a bar the oils will break down and stay in bottles, or you could boil the mint in your priming sugar for boiling and make a simple syrup.
|
544
|
I'm making a mint chocolate stout. I've made it before; I added 1.5 ounces of fresh spearmint to the last 10 or 15 minutes of the boil. It turned out alright, but it's not as strong as I'd like. The obvious answer would be to add more mint. But before I make it again, I'd like to utilize your collective experience.
When is the best time to add mint without imparting off flavors?
Should I add it to secondary? (Last time I scooped it out before fermenting)
What type of mint would go best with the roasted malt notes?
|
2010/11/15
|
[
"https://homebrew.stackexchange.com/questions/544",
"https://homebrew.stackexchange.com",
"https://homebrew.stackexchange.com/users/12/"
] |
Adding mint during the boil is good, but the problem is that you'll lose a lot of the mint aroma during primary fermentation as the C02 carries it out the airlock.
The first thing that comes to mind would be to create a mint extract (soak the mint in vodka) and add that to your secondary. You can, of course, add the mint directly to the secondary, but you won't see as much flavor imparted as you would with an extract, and you'd need to remove it after a week or so before the leaves break down (resulting in potential grassy off-flavors).
Considering how well peppermint pairs with dark chocolate, I'd be inclined to use that over something like spearmint.
|
What about sanitizing it then muddling it, than add it to your bottling bucket and pour your fermented beer over it. Similar to using mint for drinks in a bar the oils will break down and stay in bottles, or you could boil the mint in your priming sugar for boiling and make a simple syrup.
|
58,375,170
|
I'm very new to coding, and want the code to count the frequency of the words, but I am stopped because I'm unsure of how to remove duplicates.
```
txt = " remember all those walls we built remember those times"
words = txt.split()
for word in words:
print (word + " " + str(txt.count(word)))
import pandas as pd
my_table = pd.DataFrame()
for word in words:
tempdf = pd.DataFrame ({"word" : [word], "frequency" : [txt.count(word)]})
my_table = my_table.append(tempdf)
print(my_table)
```
|
2019/10/14
|
[
"https://Stackoverflow.com/questions/58375170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Your syntax error is due to a closing missing parentheses (`)`) for `print` on the line *prior to* `import pandas as pd`. This line should read:
```
print(word + " " + str(txt.count(word)))
```
As a general tip for syntax errors, first check the preceding line or previous function call for missing or extra parentheses.
|
You need to add an extra closing bracket in line 4,
and also add import pandas as pd in line 5 because you are using pd instead of pandas
|
58,375,170
|
I'm very new to coding, and want the code to count the frequency of the words, but I am stopped because I'm unsure of how to remove duplicates.
```
txt = " remember all those walls we built remember those times"
words = txt.split()
for word in words:
print (word + " " + str(txt.count(word)))
import pandas as pd
my_table = pd.DataFrame()
for word in words:
tempdf = pd.DataFrame ({"word" : [word], "frequency" : [txt.count(word)]})
my_table = my_table.append(tempdf)
print(my_table)
```
|
2019/10/14
|
[
"https://Stackoverflow.com/questions/58375170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
You need:
```
txt = " remember all those walls we built remember those times"
words = txt.split()
for word in words:
print(word + " " + str(txt.count(word)))
import pandas as pd
mytable = pd.DataFrame()
for word in words:
tempdf = pd.DataFrame ({"word" : [word], "frequency" : [txt.count(word)]})
mytable = mytable.append(tempdf)
print(mytable)
```
**or better with [`pd.concat`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html):**
```
import pandas as pd
txt = " remember all those walls we built remember those times"
words = txt.split()
for word in words:
print(word + " " + str(txt.count(word)) )
my_table=pd.concat([pd.DataFrame ({"word" : [word], "frequency" : [txt.count(word)]}) for word in words])
print(mytable)
```
---
keep in mind that you could also `update` the dictionary and then create the dataframe at the end
|
You need to add an extra closing bracket in line 4,
and also add import pandas as pd in line 5 because you are using pd instead of pandas
|
35,128,527
|
In Qt 4.8.5 32-bit and VS2010, I'm trying to create a Window as shown in this screenshot from QtDesigner:
[](https://i.stack.imgur.com/P1v02.png)
When I run the application, the widgets get laid down on top of each other :
[](https://i.stack.imgur.com/dfj0V.png)
In the Console, I see this :
[](https://i.stack.imgur.com/dMmXR.png)
Does anybody have any idea why this is happening?
Here is my code :
```
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(){
ui = new Ui::AView();
ui->setupUi(this);
}
~MainWindow();
...
private:
Ui::AView* ui;
}
```
|
2016/02/01
|
[
"https://Stackoverflow.com/questions/35128527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2394327/"
] |
The most clean and easy for understanding way would be to collect all tasks and run them directly on event. I just need to use invokeAll of ExecutorService. Following code sample can help:
```
public void handleSomeEvent(Event event) {
List<Task> tasksToRunOnEvent = getTasksToRunOnEvent(event);
List<Future<TaskResult> futures = executorService.invokeAll(tasksToRunOnEvent);
handleTaskResults(futures);
}
```
|
I took tvelykyy's advice and played around a little bit and came up with this impl:
```
public class EventBasedExecutor extends ScheduledThreadPoolExecutor implements EventBasedExecutorService {
private List<RunnableScheduledFuture<?>> workers = new ArrayList<>();
private int index;
public EventBasedExecutor(int corePoolSize) {
super(corePoolSize, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("message-sender-%d").build());
}
@Override
protected <V> RunnableScheduledFuture<V> decorateTask(Runnable runnable, RunnableScheduledFuture<V> task) {
if(!workers.contains(runnable)) {
workers.add(task);
}
return super.decorateTask(runnable, task);
}
@Override
public void executeEarly() {
if(index >= workers.size()) {
index = 0;
}
if(workers.size() == 0) {
return;
}
RunnableScheduledFuture<?> runnableScheduledFuture = workers.get(index);
index ++;
execute(runnableScheduledFuture);
}
}
```
A few words:
workers.contains(Runnable) is true, if you re-submit one RunnableScheduledFuture.
You have to submit it through execute to get it to run in the threadpool (rather than just call run on the runnable which will block the current thread).
I recommend the runnables to implement a safety guard so that they can't be executed twice at the same time (important for my usecase). So basically:
```
if( isrunning() ) return;
```
In decorateTask - you must re-decorate the runnable. This is because the implementation will take the wrapped runnable and re-schedule it, if it must. Since the old runnables are already scheduled, you don't want to reschedule them. So calling execute will run through the decoration and decorate the scheduled runnable (which will usually run every second or some) to be a non-repeatable runnable. This means, that your scheduled task can run once without being rescheduled, while still being available as a periodic runnable within the executor.
I hope this all makes sense :)
Artur
|
27,097,297
|
I'm trying to create a function to loop through some table rows but I need to use this.isempty instead of isempty. How do I access this inside of an each loop.
Code:
```
function checkValues(look) {
this.isempty = 1;
this.search = $(look).find("input").each(function(){
if ($.trim($(this).val())!="") {
this.isempty = 0;
}
});
return this.isempty;
}
```
Obviously the `this.isempty = 0;` will not work. How can I do this?
|
2014/11/24
|
[
"https://Stackoverflow.com/questions/27097297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4134359/"
] |
You can use a closure variable in this case to refer `isempty`
```
function checkValues(look) {
this.isempty = 1;
var self = this;
this.search = $(look).find("input").each(function () {
if ($.trim($(this).val()) != "") {
self.isempty = 0;
}
});
return this.isempty;
}
```
---
But a more appropriate way here is to use .filter() like
```
function checkValues(look) {
this.isempty = 1;
this.search = $(look).find("input").;
this.isempty = this.search.filter(function () {
return $.trim(this.value) != '';
}).length > 0;
return this.isempty;
}
```
|
Do you need to reference `this` because of a constraint in your code? Would the following work?
```
function checkValues(look) {
var isEmpty = 1;
$(look).find("input").each(function(){
if ($.trim($(this).val())!="") {
isEmpty = 0;
return false; // Breaks out of the loop for a little performance boost
}
});
return isEmpty;
}
```
|
17,167,168
|
I have some strange problem where all my string arrays has the same value in the List.
Here is my code:
```
List<string[]> map_data = new List<string[]>();
string[] map_data_array = new string[11];
for(int i = 0; i < 2000; i++)
{
map_data_array = PopulateDataFromFile(); // it returns different data every call
map_data.Add(map_data_array); // store to List
}
```
map\_data\_array has always different data, I've verified that by placing the break point there and I've checked it.
The problem is that `map_data` has the value of all elements the same. And this value is the data that comes from function `PopulateDataFromFile` when the i is 1999.
What I am doing wrong? :/
|
2013/06/18
|
[
"https://Stackoverflow.com/questions/17167168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1234373/"
] |
That only happens if you place the same array into the list. As you did not give the code to `PopulateDataFromFile` we can only guess what happens. Make sure that the function returns a seperate array created with `new` each time.
|
In the loop everytime you just change the address of map\_data\_array , so that's why always the value will get changed to the newer data obtained from the method call. Reinitialize the string array everytime will help. It should look something like this
```
for(int i = 0; i < 2000; i++)
{
string[] map_data_array = PopulateDataFromFile(); // it returns different data every call
map_data.Add(map_data_array); // store to List
}
```
or if its confusing for you can you make it simple by
```
for(int i = 0; i < 2000; i++)
{
map_data.Add(PopulateDataFromFile()); // store to List
}
```
|
17,167,168
|
I have some strange problem where all my string arrays has the same value in the List.
Here is my code:
```
List<string[]> map_data = new List<string[]>();
string[] map_data_array = new string[11];
for(int i = 0; i < 2000; i++)
{
map_data_array = PopulateDataFromFile(); // it returns different data every call
map_data.Add(map_data_array); // store to List
}
```
map\_data\_array has always different data, I've verified that by placing the break point there and I've checked it.
The problem is that `map_data` has the value of all elements the same. And this value is the data that comes from function `PopulateDataFromFile` when the i is 1999.
What I am doing wrong? :/
|
2013/06/18
|
[
"https://Stackoverflow.com/questions/17167168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1234373/"
] |
That only happens if you place the same array into the list. As you did not give the code to `PopulateDataFromFile` we can only guess what happens. Make sure that the function returns a seperate array created with `new` each time.
|
PopulateDataFromFile() is returning a String array with the same values.
|
17,167,168
|
I have some strange problem where all my string arrays has the same value in the List.
Here is my code:
```
List<string[]> map_data = new List<string[]>();
string[] map_data_array = new string[11];
for(int i = 0; i < 2000; i++)
{
map_data_array = PopulateDataFromFile(); // it returns different data every call
map_data.Add(map_data_array); // store to List
}
```
map\_data\_array has always different data, I've verified that by placing the break point there and I've checked it.
The problem is that `map_data` has the value of all elements the same. And this value is the data that comes from function `PopulateDataFromFile` when the i is 1999.
What I am doing wrong? :/
|
2013/06/18
|
[
"https://Stackoverflow.com/questions/17167168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1234373/"
] |
That only happens if you place the same array into the list. As you did not give the code to `PopulateDataFromFile` we can only guess what happens. Make sure that the function returns a seperate array created with `new` each time.
|
You need to process your data in chunks since `PopulateDataFromFile();` looks to be returning all of its data in one go (or as much as the array can fit). Using an extension method, you could do something like this: -
```
List<string[]> map_data = new List<string[]>();
foreach (var batch in PopulateDataFromFile().Batch(11))
{
map_data.Add((batch.ToArray());
}
```
Extension method: -
```
public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> items, int batchSize)
{
return items.Select((item, inx) => new { item, inx })
.GroupBy(x => x.inx / batchSize)
.Select(g => g.Select(x => x.item));
}
```
|
17,167,168
|
I have some strange problem where all my string arrays has the same value in the List.
Here is my code:
```
List<string[]> map_data = new List<string[]>();
string[] map_data_array = new string[11];
for(int i = 0; i < 2000; i++)
{
map_data_array = PopulateDataFromFile(); // it returns different data every call
map_data.Add(map_data_array); // store to List
}
```
map\_data\_array has always different data, I've verified that by placing the break point there and I've checked it.
The problem is that `map_data` has the value of all elements the same. And this value is the data that comes from function `PopulateDataFromFile` when the i is 1999.
What I am doing wrong? :/
|
2013/06/18
|
[
"https://Stackoverflow.com/questions/17167168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1234373/"
] |
PopulateDataFromFile() is returning a String array with the same values.
|
In the loop everytime you just change the address of map\_data\_array , so that's why always the value will get changed to the newer data obtained from the method call. Reinitialize the string array everytime will help. It should look something like this
```
for(int i = 0; i < 2000; i++)
{
string[] map_data_array = PopulateDataFromFile(); // it returns different data every call
map_data.Add(map_data_array); // store to List
}
```
or if its confusing for you can you make it simple by
```
for(int i = 0; i < 2000; i++)
{
map_data.Add(PopulateDataFromFile()); // store to List
}
```
|
17,167,168
|
I have some strange problem where all my string arrays has the same value in the List.
Here is my code:
```
List<string[]> map_data = new List<string[]>();
string[] map_data_array = new string[11];
for(int i = 0; i < 2000; i++)
{
map_data_array = PopulateDataFromFile(); // it returns different data every call
map_data.Add(map_data_array); // store to List
}
```
map\_data\_array has always different data, I've verified that by placing the break point there and I've checked it.
The problem is that `map_data` has the value of all elements the same. And this value is the data that comes from function `PopulateDataFromFile` when the i is 1999.
What I am doing wrong? :/
|
2013/06/18
|
[
"https://Stackoverflow.com/questions/17167168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1234373/"
] |
You need to process your data in chunks since `PopulateDataFromFile();` looks to be returning all of its data in one go (or as much as the array can fit). Using an extension method, you could do something like this: -
```
List<string[]> map_data = new List<string[]>();
foreach (var batch in PopulateDataFromFile().Batch(11))
{
map_data.Add((batch.ToArray());
}
```
Extension method: -
```
public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> items, int batchSize)
{
return items.Select((item, inx) => new { item, inx })
.GroupBy(x => x.inx / batchSize)
.Select(g => g.Select(x => x.item));
}
```
|
In the loop everytime you just change the address of map\_data\_array , so that's why always the value will get changed to the newer data obtained from the method call. Reinitialize the string array everytime will help. It should look something like this
```
for(int i = 0; i < 2000; i++)
{
string[] map_data_array = PopulateDataFromFile(); // it returns different data every call
map_data.Add(map_data_array); // store to List
}
```
or if its confusing for you can you make it simple by
```
for(int i = 0; i < 2000; i++)
{
map_data.Add(PopulateDataFromFile()); // store to List
}
```
|
17,167,168
|
I have some strange problem where all my string arrays has the same value in the List.
Here is my code:
```
List<string[]> map_data = new List<string[]>();
string[] map_data_array = new string[11];
for(int i = 0; i < 2000; i++)
{
map_data_array = PopulateDataFromFile(); // it returns different data every call
map_data.Add(map_data_array); // store to List
}
```
map\_data\_array has always different data, I've verified that by placing the break point there and I've checked it.
The problem is that `map_data` has the value of all elements the same. And this value is the data that comes from function `PopulateDataFromFile` when the i is 1999.
What I am doing wrong? :/
|
2013/06/18
|
[
"https://Stackoverflow.com/questions/17167168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1234373/"
] |
You need to process your data in chunks since `PopulateDataFromFile();` looks to be returning all of its data in one go (or as much as the array can fit). Using an extension method, you could do something like this: -
```
List<string[]> map_data = new List<string[]>();
foreach (var batch in PopulateDataFromFile().Batch(11))
{
map_data.Add((batch.ToArray());
}
```
Extension method: -
```
public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> items, int batchSize)
{
return items.Select((item, inx) => new { item, inx })
.GroupBy(x => x.inx / batchSize)
.Select(g => g.Select(x => x.item));
}
```
|
PopulateDataFromFile() is returning a String array with the same values.
|
28,976,763
|
i am having trouble with this problem i can not find the bug
i am storing strings form a file to a linked list.
lets say the file contains 5 strings
1. jack
2. juan
3. steven
4. mike
5. sam
---
the problem is that when i print the 5 node's linked list
it prints [sam] [sam] [sam] [sam] [sam] .
it prints the last string in all nodes
i am confused
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Node {
char * data;
struct Node *next;
};
struct Node *head;
void print() {
while (head != NULL) {
printf(" [%s] ", head->data);
head = head->next;
}
printf("\n");
}
void insertb(char *data) {
struct Node *temp;
temp = (struct Node*)malloc(sizeof(struct Node));
temp->next = NULL;
temp->data = data;
if (head == NULL) {
head = temp;
printf("%s\n", head->data);
} else {
temp->next = head;
head = temp;
printf("%s %s\n", temp->data, temp->next->data);
}
}
int main (int argc, char *argv[]) {
FILE *file = fopen(argv[1], "r");
head = NULL;
char data[10];
//int data;
while (fscanf(file, "%s",&data) != EOF) {
insertb(data);
// printf("%s\n", data);
}
print();
fclose(file);
return 0;
}
```
|
2015/03/11
|
[
"https://Stackoverflow.com/questions/28976763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3290636/"
] |
You have only a single buffer to store your strings, `data`. Its contents get overwritten with every call to fscanf.
Try `insertb(strdup(data));`.
|
you are setting the head to temp, which is the very last one every time you add some stuff into the list. In insertb function the else block is probably where you want to look for. Also it is considered to be a pretty bad idea to make global variables, hence it is very likely to change the content of the global variable, unintentionally and that can screw things over. I suggest you to look for pass by reference stuff in C also. I see that the other answer tells you to use strdup, maybe I am wrong too and I don't want to argue with that, but strdup duplicates the string. Instead of that I'd "re-initialize" the char array with
```
memset(buffer, 0, bufferLength);
```
and put manually a "\0" char at the end of the string to prevent saving rubbish in the buffer. Hope this helps.
|
28,937,273
|
I want to read all the files in a particular directory, and I want to read it one by one.
Here's what i've done so far. ls successfully get all the files from a specified directory, but could not give the file names to me one by one. It Echos the files one time only. I want to get it one by one because I need to do some parsing and use it somehwere.
```
#!/bin/sh
echo Content-type: application/json
echo ""
for output in "ls /home/myComputer/Desktop/*";
do
echo $output
done
```
|
2015/03/09
|
[
"https://Stackoverflow.com/questions/28937273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3714598/"
] |
You can do
```
for output in /home/myComputer/Desktop/*
do
echo $output
done
```
If there's any risk that `/home/myComputer/Desktop` is empty, please follow @JIDs advice in the comments below.
|
The next solution also works when the dir is empty.
```
ls /home/myComputer/Desktop/ 2>/dev/null |while read -r output; do
echo ${output}
done
```
This construction is nice to know, for when you want to split the input lines in some fields:
```
cat someFile | while read -r field1 field2 remainingfields; do
```
|
1,495,854
|
```
my $hash_ref = {
one => { val => 1, name => 'one' },
three => { val => 3, name => 'three'},
two => { val => 2, name => 'two' },
};
```
I would like to sort `$hash_ref` such that a foreach would order them by
```
$hash_ref->{$key}->{'val'}
one
two
three
```
Any suggestions?
|
2009/09/30
|
[
"https://Stackoverflow.com/questions/1495854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
`@sorted_list` is an array of references to the sorted hash elements:
```
@sorted_list = sort { $a->{'val'} <=> $b->{'val'} } values %{$unsorted_hash_ref};
```
You can use it like so:
```
#!/usr/bin/perl
my $hash_ref = {
one => { val => 1, name => 'one' },
three => { val => 3, name => 'three' },
two => { val => 2, name => 'two' },
};
foreach $elem ( sort { $a->{'val'} <=> $b->{'val'} } values %{$hash_ref} ) {
print "$elem->{'val'} : $elem->{'name'}\n";
}
```
Output:
```
1 : one
2 : two
3 : three
```
|
Hash tables don't have any specific order. However, you can sort the keys in an array and use that to iterate through the hash:
```
my $hash_ref = {
one => { val => 1, name => 'one'},
three => { val => 3, name => 'three'},
two => { val => 2, name => 'two'},
};
use strict;
use warnings;
use Lingua::EN::Words2Nums;
foreach my $key (sort { words2nums($a) <=> words2nums($b) } keys %$hash_ref)
{
# do something with $hash_ref->{$key}
print "processing key $key.\n";
}
```
You can define anything you like as a sort method; see [perldoc -f sort](http://perldoc.perl.org/functions/sort.html) for more details. Conversion from ordinal numerical text to arithmetic values is done with [Lingua::EN::Words2Nums](http://search.cpan.org/~joey/Lingua-EN-Words2Nums-0.15/Words2Nums.pm) (it does cardinal numbers too).
|
1,495,854
|
```
my $hash_ref = {
one => { val => 1, name => 'one' },
three => { val => 3, name => 'three'},
two => { val => 2, name => 'two' },
};
```
I would like to sort `$hash_ref` such that a foreach would order them by
```
$hash_ref->{$key}->{'val'}
one
two
three
```
Any suggestions?
|
2009/09/30
|
[
"https://Stackoverflow.com/questions/1495854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
`@sorted_list` is an array of references to the sorted hash elements:
```
@sorted_list = sort { $a->{'val'} <=> $b->{'val'} } values %{$unsorted_hash_ref};
```
You can use it like so:
```
#!/usr/bin/perl
my $hash_ref = {
one => { val => 1, name => 'one' },
three => { val => 3, name => 'three' },
two => { val => 2, name => 'two' },
};
foreach $elem ( sort { $a->{'val'} <=> $b->{'val'} } values %{$hash_ref} ) {
print "$elem->{'val'} : $elem->{'name'}\n";
}
```
Output:
```
1 : one
2 : two
3 : three
```
|
```
use strict;
use warnings;
my %hash_ref = (
one => { val => 1, name => 'one' },
three => { val => 3, name => 'three'},
two => { val => 2, name => 'two' },
);
foreach my $key(sort {$hash_ref{$a}{val} <=> $hash_ref{$b}{val}} keys %hash_ref) {
my $value = $hash_ref{$key}{val};
my $name = $hash_ref{$key}{name};
print "$name -> $value\n";
}
output:
one -> 1
two -> 2
three -> 3
```
|
1,495,854
|
```
my $hash_ref = {
one => { val => 1, name => 'one' },
three => { val => 3, name => 'three'},
two => { val => 2, name => 'two' },
};
```
I would like to sort `$hash_ref` such that a foreach would order them by
```
$hash_ref->{$key}->{'val'}
one
two
three
```
Any suggestions?
|
2009/09/30
|
[
"https://Stackoverflow.com/questions/1495854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
`@sorted_list` is an array of references to the sorted hash elements:
```
@sorted_list = sort { $a->{'val'} <=> $b->{'val'} } values %{$unsorted_hash_ref};
```
You can use it like so:
```
#!/usr/bin/perl
my $hash_ref = {
one => { val => 1, name => 'one' },
three => { val => 3, name => 'three' },
two => { val => 2, name => 'two' },
};
foreach $elem ( sort { $a->{'val'} <=> $b->{'val'} } values %{$hash_ref} ) {
print "$elem->{'val'} : $elem->{'name'}\n";
}
```
Output:
```
1 : one
2 : two
3 : three
```
|
```
#!/usr/bin/perl
my $hash_ref = (
one => {val => 1, name => "one"},
three => {val => 3, name => "three"},
two => {val => 2, name => 'two'},
);
foreach $elem( sort {$$hash_ref{$a}{val} <=> $$hash_ref{$b}{val}} keys %$hash_ref){
my $value = $hash_ref->{$elem}{val};
my $name = $hash_ref->{$elem}{name};
print "$name -> $value\n";
}
OutPut:
one -> 1
two -> 2
three -> 3
```
|
383,981
|
I have a file with many columns and some empty cells in different columns. I would like to replace the empty cells for NA only in the third column.
My file:
```
1 id1 info
2 otherinfo
3 id2
4 noinfo
5 id3
6 id4 info2
```
So the output should be:
```
1 id1 info
2 otherinfo
3 id2 NA
4 noinfo
5 id3 NA
6 id4 info2
```
I tried this command ([Replacing missing value blank space with zero](https://unix.stackexchange.com/questions/53448/replacing-missing-value-blank-space-with-zero)), but it replaced all empty cells.
Any suggestions?
|
2017/08/04
|
[
"https://unix.stackexchange.com/questions/383981",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/137472/"
] |
Short ***awk*** solution:
```
awk -F'[[:space:]]' '$2 && !$3{ $3="NA" }1' file
```
The output:
```
1 id1 info
2 otherinfo
3 id2 NA
4 noinfo
5 id3 NA
6 id4 info2
```
|
This `sed` works for me:
```
sed -E 's/(.*id[0-9]{1,}$)/\1 NA/'
```
Example:
```
sed -E 's/(.*id[0-9]{1,}$)/\1 NA/' NA.txt
1 id1 info
2 otherinfo
3 id2 NA
4 noinfo
5 id3 NA
6 id4 info2
```
Where `NA.txt` is this file:
```
cat NA.txt
1 id1 info
2 otherinfo
3 id2
4 noinfo
5 id3
6 id4 info2
```
|
383,981
|
I have a file with many columns and some empty cells in different columns. I would like to replace the empty cells for NA only in the third column.
My file:
```
1 id1 info
2 otherinfo
3 id2
4 noinfo
5 id3
6 id4 info2
```
So the output should be:
```
1 id1 info
2 otherinfo
3 id2 NA
4 noinfo
5 id3 NA
6 id4 info2
```
I tried this command ([Replacing missing value blank space with zero](https://unix.stackexchange.com/questions/53448/replacing-missing-value-blank-space-with-zero)), but it replaced all empty cells.
Any suggestions?
|
2017/08/04
|
[
"https://unix.stackexchange.com/questions/383981",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/137472/"
] |
If your file has fixed-width columns, you can parse them in GNU awk with `FIELDWIDTHS`, e.g.:
```
awk -v FIELDWIDTHS='1 1 3 1 99' -v OFS="" '!$5 { $5 = " NA" } 1' infile
```
Output:
```
1 id1 info
2 otherinfo
3 id2 NA
4 noinfo
5 id3 NA
6 id4 info2
```
|
This `sed` works for me:
```
sed -E 's/(.*id[0-9]{1,}$)/\1 NA/'
```
Example:
```
sed -E 's/(.*id[0-9]{1,}$)/\1 NA/' NA.txt
1 id1 info
2 otherinfo
3 id2 NA
4 noinfo
5 id3 NA
6 id4 info2
```
Where `NA.txt` is this file:
```
cat NA.txt
1 id1 info
2 otherinfo
3 id2
4 noinfo
5 id3
6 id4 info2
```
|
383,981
|
I have a file with many columns and some empty cells in different columns. I would like to replace the empty cells for NA only in the third column.
My file:
```
1 id1 info
2 otherinfo
3 id2
4 noinfo
5 id3
6 id4 info2
```
So the output should be:
```
1 id1 info
2 otherinfo
3 id2 NA
4 noinfo
5 id3 NA
6 id4 info2
```
I tried this command ([Replacing missing value blank space with zero](https://unix.stackexchange.com/questions/53448/replacing-missing-value-blank-space-with-zero)), but it replaced all empty cells.
Any suggestions?
|
2017/08/04
|
[
"https://unix.stackexchange.com/questions/383981",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/137472/"
] |
Short ***awk*** solution:
```
awk -F'[[:space:]]' '$2 && !$3{ $3="NA" }1' file
```
The output:
```
1 id1 info
2 otherinfo
3 id2 NA
4 noinfo
5 id3 NA
6 id4 info2
```
|
If your file has fixed-width columns, you can parse them in GNU awk with `FIELDWIDTHS`, e.g.:
```
awk -v FIELDWIDTHS='1 1 3 1 99' -v OFS="" '!$5 { $5 = " NA" } 1' infile
```
Output:
```
1 id1 info
2 otherinfo
3 id2 NA
4 noinfo
5 id3 NA
6 id4 info2
```
|
5,643,103
|
What's the best way to use ImageMagick in MonoTouch?
Adding the ImageMagickNET lib seems to produce errors during runtime, such as:
>
> Method
> 'Module:CrtImplementationDetails.DoDllLanguageSupportValidation
> ()' in assembly
> '/ImageMagickNET/bin/ReleaseQ8/ImageMagickNET.dll'
> contains native code that cannot be
> executed by Mono on this platform. The
> assembly was probably created using
> C++/CLI.
>
>
>
There are iPhone-specific binaries available, I suppose I have to link the whole library as described here:
<http://monotouch.net/Documentation/Binding_New_Objective-C_Types>
?
Thank you for your help :)
|
2011/04/13
|
[
"https://Stackoverflow.com/questions/5643103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/427221/"
] |
First, why this does not work.
Second, what you can do about it.
Why it does not work: The library that you are using is compiled with C++/CLI compiler against the Microsoft libraries.
All managed code that you use in MonoTouch must be compiled using MonoTouch's assemblies and tools, so the above wont work for two reasons: (a) Mono lacks a C++/CLI compiler and (b) even if that existed, you would have to reference the Mono asseblies
What can you do about it: You can build ImageMagic with Apple's C compiler, and then link the resulting code into your application:
<http://monotouch.net/Documentation/Linking_Native_Libraries>
Then for each ImageMagick method that you want to access, you need to wrap it using P/Invoke, a guide is available here:
<http://www.mono-project.com/Interop_with_Native_Libraries>
|
that error answers your question for you :
>
> in assembly '/ImageMagickNET/bin/ReleaseQ8/ImageMagickNET.dll' contains native code that
> cannot be executed by Mono on this
> platform.
>
>
>
A quick google tells me on [the imagemagick codeplex page](http://imagemagick.codeplex.com/)
that you're probably using what is called a 'wrapper'.
this means that the imagemagick code itself is still non-.NET imagemagick, which will never run on your iPhone.
|
59,795,747
|
Ok, I'm sorry, but I just cannot figure out how to do this... There are literally hundreds of "how do I validate my form in Angular" posts on here, but none of them **quite** fit what I'm trying to do, and I just cannot figure out how to make it work. So I'm asking this here. Forgive me if it's been asked before.
I'm using a reactive form in Angular 7.2.2. I'm returning a list of items from the server, and I'm dynamically creating an array of checkboxes -- one for each item. I want the user to be able to check one or more of those check-boxes -- but they must check **at least one** of the checkboxes, or the form should be invalid, and the submit button should be disabled.
(FYI, there are other FormControls -- either `<select>` or `<input type="text">` -- on my form that I have left out of this example. Those controls are not dynamically-created, so adding validators to them is trivial.)
Here's my component.html:
```
<form [formGroup]="myForm" (ngSubmit)="myFormSubmit()">
<div style="width: 100%; height: 160px; padding: 3px; overflow: auto;">
<label formArrayName="itemsToSelect" *ngFor="let item of myForm.controls.itemsToSelect.controls; let i = index" style="width: 85%; padding-left: 5px;">
<input type="checkbox" formControlName="{{i}}">
{{myListOfItems[i].item_id}}<br>
</label>
</div>
<input type="submit" [disable]="!this.myForm.valid">
</form>
```
And here's my component.ts
```
myListOfItems: any = [];
myForm = new FormGroup({
itemsToSelect: new FormArray([])
});
ngOnInit() {
this.myService.getMyItems()
.subscribe( (eventData) => {
myListOfItems = eventData;
myListOfItems.forEach((o, i) => {
const control = new FormControl(false); //false so the checkbox defaults to not-selected
(this.myForm.controls.itemsToSelect as FormArray).push(control);
});
});
}
myFormSubmit() {
//Do stuff here that assumes at least one checkbox is checked.
}
```
So... How do I get it so myForm.valid is false when all the checkboxes are blank, but true when one or more checkbox is checked? Any help would be appreciated. Thanks.
|
2020/01/17
|
[
"https://Stackoverflow.com/questions/59795747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2620218/"
] |
To get this:
```
[1, 2, 4, ...,26, etc]
```
without using `df.reset_index()` (ie; leaving the `DatetimeIndex` as is), why don't you iterate on the *Range* of the *Length* of the index itself:
```
range(df.index.shape[0])
```
and to get a list directly you may use *List Comprehension*:
```
[i for i in range(df.index.shape[0])]
```
You might also want to check [`df.index.get_loc()`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.get_loc.html), which returns the integer location of a specific requested index label.
```
unique_index = pd.Index(list('abc'))
unique_index.get_loc('b')
>>> 1
```
All of this is assuming you will be using this `list` for something other than direct DataFrame indexing of course. (Because obviously this won't work for that!)
|
You can get integer index from datetimeindex by
```py
import numpy as np
np.where(df.index.isin(df.index))
```
Output:
```bash
(array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
dtype=int64),)
```
|
3,458,503
|
I need text to fill a predefined area. I don't necessarily want the fonts to grow beyond a certain limit, but I would prefer that it at least shrinks if it doesn't fit in a certain area. (So to have an upperbound on the font size, and also a lowerbound, but take the upperbound as default and scale down when required.)
Is there any easy way to get something like that done easily?
|
2010/08/11
|
[
"https://Stackoverflow.com/questions/3458503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/136476/"
] |
I eventually ended up using the [fitText](http://www.jarvana.com/jarvana/view/com/lowagie/itext/2.1.2/itext-2.1.2-javadoc.jar!/com/lowagie/text/pdf/PdfSignatureAppearance.html#fitText%28com.lowagie.text.Font,%20java.lang.String,%20com.lowagie.text.Rectangle,%20float,%20int%29) operation on PdfSignatureAppearance, included in [iText](http://itextpdf.com/). That made it quite easy to get it done. It may not be perfect, but it's much better than not having anything at all.
```
public static final float calculateFontSize(String fontName, float maxFontsize, float width, float height, String text) {
Font font = FontFactory.getFont(fontName);
Rectangle rectangle = new Rectangle(width, height);
System.err.println("Calculating font size for " + width + " and " + height);
return PdfSignatureAppearance.fitText(font, text, rectangle, maxFontsize, PdfWriter.RUN_DIRECTION_LTR);
}
```
|
I would hand pick the font sizes you want to use to make sure they look good on the target output. No reason to stick to 3, use as many as you want. The rectangle passed into getFont() must have x an y both set to 0.
```
public class FontFactory {
private Font[] fonts;
public FontFactory() {
fonts = new Font[3];
// font[0] = largest font
// font[1] = middle font
// font[2] = smallest font
}
public Font getFont(String string, Graphics g, Rectangle rectangle) {
for (Font font : fonts) {
Rectangle2D bounds = g.getFontMetrics(font).getStringBounds(string, g);
if (rectangle.contains(bounds)) {
return font;
}
}
return fonts[fonts.length - 1];
}
}
```
|
44,197,910
|
List enumerators not working in case when they are put in a list. For example in case of two lists (two enumerators)
```
public void test()
{
var firstList = new List<int>() { 1, 2, 3 };
var secondList = new List<int>() { 4, 5, 6 };
var lists = new List<List<int>>();
lists.Add(firstList);
lists.Add(secondList);
// Not working
var iterators = lists.Select(x => x.GetEnumerator()).ToList();
iterators.ForEach(x => x.MoveNext());
iterators.ForEach(x => Console.WriteLine(x.Current));
// Working
var firstIterator = iterators[0];
var secondIterator = iterators[1];
firstIterator.MoveNext(); secondIterator.MoveNext();
Console.WriteLine(firstIterator.Current);
Console.WriteLine(secondIterator.Current);
}
```
the first part is not working and it prints `0 0`, while the second part is working and it prints `1 4`.
I don't understand what is mistake with the first part and how it can be solved.
|
2017/05/26
|
[
"https://Stackoverflow.com/questions/44197910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1765621/"
] |
This is because the [`List<T>.GetEnumerator`](https://msdn.microsoft.com/en-us/library/b0yss765(v=vs.110).aspx) method returns a [`List<T>.Enumerator`](https://msdn.microsoft.com/en-us/library/x854yt9s(v=vs.110).aspx) *mutable struct*.
When you assign it to a variable and call `MoveNext` and `Current`, it works. But when passed to delegate, it is passed by value, hence the delegate receives a copy so calling `MoveNext` has no effect of the original `struct` `Current`.
Just one of the side effects of the mutable structs.
If you change
```
x => x.GetEnumerator()
```
to
```
x => (IEnumerator<int>)x.GetEnumerator()
```
or
```
x => x.AsEnumerable().GetEnumerator()
```
both snippets will work because now the `iterators` will contain a boxed references of the returned structs.
|
Its because you run 2 separate `.ForEach()` in the not working part. Do both actions in 1 foreach (`MoveNext()`, then print). `MoveNext` will not be remembered in a `.Foreach()` for a good explaination: [Go to this answer](https://stackoverflow.com/a/44198312/2885376)
**This:**
```
iterators.ForEach(x => x.MoveNext());
iterators.ForEach(x => Console.WriteLine(x.Current));
```
**Becomes:**
```
iterators.ForEach(x => { x.MoveNext(); Console.WriteLine(x.Current); });
```
|
44,197,910
|
List enumerators not working in case when they are put in a list. For example in case of two lists (two enumerators)
```
public void test()
{
var firstList = new List<int>() { 1, 2, 3 };
var secondList = new List<int>() { 4, 5, 6 };
var lists = new List<List<int>>();
lists.Add(firstList);
lists.Add(secondList);
// Not working
var iterators = lists.Select(x => x.GetEnumerator()).ToList();
iterators.ForEach(x => x.MoveNext());
iterators.ForEach(x => Console.WriteLine(x.Current));
// Working
var firstIterator = iterators[0];
var secondIterator = iterators[1];
firstIterator.MoveNext(); secondIterator.MoveNext();
Console.WriteLine(firstIterator.Current);
Console.WriteLine(secondIterator.Current);
}
```
the first part is not working and it prints `0 0`, while the second part is working and it prints `1 4`.
I don't understand what is mistake with the first part and how it can be solved.
|
2017/05/26
|
[
"https://Stackoverflow.com/questions/44197910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1765621/"
] |
This is because the [`List<T>.GetEnumerator`](https://msdn.microsoft.com/en-us/library/b0yss765(v=vs.110).aspx) method returns a [`List<T>.Enumerator`](https://msdn.microsoft.com/en-us/library/x854yt9s(v=vs.110).aspx) *mutable struct*.
When you assign it to a variable and call `MoveNext` and `Current`, it works. But when passed to delegate, it is passed by value, hence the delegate receives a copy so calling `MoveNext` has no effect of the original `struct` `Current`.
Just one of the side effects of the mutable structs.
If you change
```
x => x.GetEnumerator()
```
to
```
x => (IEnumerator<int>)x.GetEnumerator()
```
or
```
x => x.AsEnumerable().GetEnumerator()
```
both snippets will work because now the `iterators` will contain a boxed references of the returned structs.
|
List's enumerator is implemented as a value type ([source code](https://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs,cf7f4095e4de7646)):
```
iterators[0].GetType().IsValueType // true
```
That means - iterators are passed by value when you are passing them to the methods (i.e. copy of iterator is passed instead of passing a reference to iterator instance). `ForEach` method simply executes an action in a loop:
```
iterators.ForEach(copy => copy.MoveNext());
```
Action delegate is a method, so you are passing a *copy* of each iterator to this method. So original iterators remain unchanged. And when you call `ForEach` second time, again, copies of original untouched iterators are passed there:
```
iterators.ForEach(newCopy => Console.WriteLine(newCopy.Current));
```
But original iterators are in the initial state (before the first item) that is why you see default values of integer type when you read `Current` value.
You can either work with single copy of iterator:
```
iterators.ForEach(copy => { copy.MoveNext(); Console.WriteLine(copy.Current); });
```
Or box value type to pass it by reference (note that type of `iterators` list will change):
```
var iterators = lists.Select(x => (IEnumerable<int>)x.GetEnumerator()).ToList();
```
|
7,586,764
|
We are multiple developers working on the same Xcode 4 iOS project. We are trying to commit to use Subversion but we keep getting conflicts with project.pbxproj when 2 developers add a new target or change the project structure.
What is the proper way to go about this issue?
|
2011/09/28
|
[
"https://Stackoverflow.com/questions/7586764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/969550/"
] |
About a week ago I revisited this problem and came up with a solution. The solution requires me to do a lot of manual width setting for the columns in this grid, and I consider that to be extremely sub-par in this day and age. Unfortunately, I have also continued to look for a more well-rounded solution native to the Android platform, but I have not turned anything up.
The following is the code to create this same grid, should any one following me need it. I will explain some of the more pertinent details below!
The layout: `grid.xml`:
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/lightGrey">
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginBottom="2dip"
android:layout_weight="1"
android:minHeight="100dip">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TableLayout
android:id="@+id/frozenTableHeader"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginTop="2dip"
android:layout_marginLeft="1dip"
android:stretchColumns="1"
/>
<qvtcapital.mobile.controls.ObservableHorizontalScrollView
android:id="@+id/contentTableHeaderHorizontalScrollView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/frozenTableHeader"
android:layout_marginTop="2dip"
android:layout_marginLeft="4dip"
android:layout_marginRight="1dip">
<TableLayout
android:id="@+id/contentTableHeader"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="1"/>
</qvtcapital.mobile.controls.ObservableHorizontalScrollView>
</LinearLayout>
<ScrollView
android:id="@+id/verticalScrollView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TableLayout
android:id="@+id/frozenTable"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginTop="2dip"
android:layout_marginLeft="1dip"
android:stretchColumns="1"
/>
<qvtcapital.mobile.controls.ObservableHorizontalScrollView
android:id="@+id/contentTableHorizontalScrollView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/frozenTable"
android:layout_marginTop="2dip"
android:layout_marginLeft="4dip"
android:layout_marginRight="1dip">
<TableLayout
android:id="@+id/contentTable"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="1"/>
</qvtcapital.mobile.controls.ObservableHorizontalScrollView>
</LinearLayout>
</ScrollView>
</TableLayout>
```
The activity: `Grid.java`:
```
public class ResultGrid extends Activity implements HorizontalScrollViewListener {
private TableLayout frozenHeaderTable;
private TableLayout contentHeaderTable;
private TableLayout frozenTable;
private TableLayout contentTable;
Typeface font;
float fontSize;
int cellWidthFactor;
ObservableHorizontalScrollView headerScrollView;
ObservableHorizontalScrollView contentScrollView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_grid);
font = Typeface.createFromAsset(getAssets(), "fonts/consola.ttf");
fontSize = 11; // Actually this is dynamic in my application, but that code is removed for clarity
final float scale = getBaseContext().getResources().getDisplayMetrics().density;
cellWidthFactor = (int) Math.ceil(fontSize * scale * (fontSize < 10 ? 0.9 : 0.7));
Button backButton = (Button)findViewById(R.id.backButton);
frozenTable = (TableLayout)findViewById(R.id.frozenTable);
contentTable = (TableLayout)findViewById(R.id.contentTable);
frozenHeaderTable = (TableLayout)findViewById(R.id.frozenTableHeader);
contentHeaderTable = (TableLayout)findViewById(R.id.contentTableHeader);
headerScrollView = (ObservableHorizontalScrollView) findViewById(R.id.contentTableHeaderHorizontalScrollView);
headerScrollView.setScrollViewListener(this);
contentScrollView = (ObservableHorizontalScrollView) findViewById(R.id.contentTableHorizontalScrollView);
contentScrollView.setScrollViewListener(this);
contentScrollView.setHorizontalScrollBarEnabled(false); // Only show the scroll bar on the header table (so that there aren't two)
backButton.setOnClickListener(backButtonClick);
InitializeInitialData();
}
protected void InitializeInitialData() {
ArrayList<String[]> content;
Bundle myBundle = getIntent().getExtras();
try {
content = (ArrayList<String[]>) myBundle.get("gridData");
} catch (Exception e) {
content = new ArrayList<String[]>();
content.add(new String[] {"Error", "There was an error parsing the result data, please try again"} );
e.printStackTrace();
}
PopulateMainTable(content);
}
protected void PopulateMainTable(ArrayList<String[]> content) {
frozenTable.setBackgroundResource(R.color.tableBorder);
contentTable.setBackgroundResource(R.color.tableBorder);
TableLayout.LayoutParams frozenRowParams = new TableLayout.LayoutParams(
TableLayout.LayoutParams.WRAP_CONTENT,
TableLayout.LayoutParams.WRAP_CONTENT);
frozenRowParams.setMargins(1, 1, 1, 1);
frozenRowParams.weight=1;
TableLayout.LayoutParams tableRowParams = new TableLayout.LayoutParams(
TableLayout.LayoutParams.WRAP_CONTENT,
TableLayout.LayoutParams.WRAP_CONTENT);
tableRowParams.setMargins(0, 1, 1, 1);
tableRowParams.weight=1;
TableRow frozenTableHeaderRow=null;
TableRow contentTableHeaderRow=null;
int maxFrozenChars = 0;
int[] maxContentChars = new int[content.get(0).length-1];
for (int i = 0; i < content.size(); i++){
TableRow frozenRow = new TableRow(this);
frozenRow.setLayoutParams(frozenRowParams);
frozenRow.setBackgroundResource(R.color.tableRows);
TextView frozenCell = new TextView(this);
frozenCell.setText(content.get(i)[0]);
frozenCell.setTextColor(Color.parseColor("#FF000000"));
frozenCell.setPadding(5, 0, 5, 0);
if (0 == i) { frozenCell.setTypeface(font, Typeface.BOLD);
} else { frozenCell.setTypeface(font, Typeface.NORMAL); }
frozenCell.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize);
frozenRow.addView(frozenCell);
if (content.get(i)[0].length() > maxFrozenChars) {
maxFrozenChars = content.get(i)[0].length();
}
// The rest of them
TableRow row = new TableRow(this);
row.setLayoutParams(tableRowParams);
row.setBackgroundResource(R.color.tableRows);
for (int j = 1; j < content.get(0).length; j++) {
TextView rowCell = new TextView(this);
rowCell.setText(content.get(i)[j]);
rowCell.setPadding(10, 0, 0, 0);
rowCell.setGravity(Gravity.RIGHT);
rowCell.setTextColor(Color.parseColor("#FF000000"));
if ( 0 == i) { rowCell.setTypeface(font, Typeface.BOLD);
} else { rowCell.setTypeface(font, Typeface.NORMAL); }
rowCell.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize);
row.addView(rowCell);
if (content.get(i)[j].length() > maxContentChars[j-1]) {
maxContentChars[j-1] = content.get(i)[j].length();
}
}
if (i==0) {
frozenTableHeaderRow=frozenRow;
contentTableHeaderRow=row;
frozenHeaderTable.addView(frozenRow);
contentHeaderTable.addView(row);
} else {
frozenTable.addView(frozenRow);
contentTable.addView(row);
}
}
setChildTextViewWidths(frozenTableHeaderRow, new int[]{maxFrozenChars});
setChildTextViewWidths(contentTableHeaderRow, maxContentChars);
for (int i = 0; i < contentTable.getChildCount(); i++) {
TableRow frozenRow = (TableRow) frozenTable.getChildAt(i);
setChildTextViewWidths(frozenRow, new int[]{maxFrozenChars});
TableRow row = (TableRow) contentTable.getChildAt(i);
setChildTextViewWidths(row, maxContentChars);
}
}
private void setChildTextViewWidths(TableRow row, int[] widths) {
if (null==row) {
return;
}
for (int i = 0; i < row.getChildCount(); i++) {
TextView cell = (TextView) row.getChildAt(i);
int replacementWidth =
widths[i] == 1
? (int) Math.ceil(widths[i] * cellWidthFactor * 2)
: widths[i] < 3
? (int) Math.ceil(widths[i] * cellWidthFactor * 1.7)
: widths[i] < 5
? (int) Math.ceil(widths[i] * cellWidthFactor * 1.2)
:widths[i] * cellWidthFactor;
cell.setMinimumWidth(replacementWidth);
cell.setMaxWidth(replacementWidth);
}
}
public void onScrollChanged(ObservableHorizontalScrollView scrollView, int x, int y, int oldX, int oldY) {
if (scrollView==headerScrollView) {
contentScrollView.scrollTo(x, y);
} else if (scrollView==contentScrollView) {
headerScrollView.scrollTo(x, y);
}
}
```
The scroll view listener (to hook the two up): `HorizontalScrollViewListener.java`:
```
public interface HorizontalScrollViewListener {
void onScrollChanged(ObservableHorizontalScrollView scrollView, int x, int y, int oldX, int oldY);
}
```
The ScrollView class that implements this listener: `ObservableHorizontalScrollView.java`:
```
public class ObservableHorizontalScrollView extends HorizontalScrollView {
private HorizontalScrollViewListener scrollViewListener=null;
public ObservableHorizontalScrollView(Context context) {
super(context);
}
public ObservableHorizontalScrollView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public ObservableHorizontalScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setScrollViewListener(HorizontalScrollViewListener scrollViewListener) {
this.scrollViewListener = scrollViewListener;
}
@Override
protected void onScrollChanged(int x, int y, int oldX, int oldY) {
super.onScrollChanged(x, y, oldX, oldY);
if (null!=scrollViewListener) {
scrollViewListener.onScrollChanged(this, x, y, oldX, oldY);
}
}
}
```
The really important part of this is sort of three-fold:
1. The ObservableHorizontalScrollView allows the header table and the content table to scroll in sync. Basically, this provides all of the horizontal motion for the grid.
2. The way in which they stay aligned is by detecting the largest string that will be in a column. This is done at the end of `PopulateMainTable()`. While we're going through each of the TextViews and adding them to the rows, you'll notice that there are two arrays `maxFrozenChars` and `maxContentChars` that keep track of what the largest string value we've seen is. At the end of `PopulateMainTable()` we loop through each of the rows and for each of the cells we set its min and max width based on the largest string we saw in that column. This is handled by `setChildTextViewWidths`.
3. The last item that makes this work is to use a monospaced font. You'll notice that in `onCreate` I am loading a consola.ttf font, and later applying it to each of the grid's TextViews that act as the cells in the grid. This allows us to be reasonably sure that the text will not be rendered larger than we have set the minimum and maximum width to in the prior step. I am doing a little bit of fanciness here, what with the whole cellWidthFactor and the maximum size of that column. This is really so that smaller strings will fit for sure, while we can minimize the white space for larger strings that are (for my system) not going to be all capital letters. If you ran in to trouble using this and you got strings that did not fit in the column size you set, this is where you would want to edit things. You would want to change the `replacementWidth` variable with some other formula for determining the cell width, such as `50 * widths[i]` which would be quite large! But would leave you with a good amount of whitespace in some columns. Basically, depending on what you plan on putting in your grid, this may need to be tweaked. Above is what worked for me.
I hope this helps someone else in the future!
|
Off the top of my head, this is how I would approach this:
1) Create an interface with one method that your Activity would implement to receive scroll coordinates and that your ScrollView can call back to when a scroll occurs:
```
public interface ScrollCallback {
public void scrollChanged(int newXPos, int newYPos);
}
```
2) Implement this in your activity to scroll the two constrained scrollviews to the position that the main scrollview just scrolled to:
```
@Override
public void scrollChanged(int newXPos, int newYPos) {
mVerticalScrollView.scrollTo(0, newYPos);
mHorizontalScrollView.scrollTo(newXPos, 0);
}
```
3) Subclass ScrollView to override the onScrollChanged() method, and add a method and member variable to call back to the activity:
```
private ScrollCallback mCallback;
//...
@Override
protected void onScrollChanged (int l, int t, int oldl, int oldt) {
mCallback.scrollChanged(l, t);
super.onScrollChanged(l, t, oldl, oldt);
}
public void setScrollCallback(ScrollCallback callback) {
mCallback = callback;
}
```
4) Replace the stock ScrollView in your XML with your new class and call `setScrollCallback(this)` in `onCreate()`.
|
7,586,764
|
We are multiple developers working on the same Xcode 4 iOS project. We are trying to commit to use Subversion but we keep getting conflicts with project.pbxproj when 2 developers add a new target or change the project structure.
What is the proper way to go about this issue?
|
2011/09/28
|
[
"https://Stackoverflow.com/questions/7586764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/969550/"
] |
[TableFixHeaders](https://github.com/InQBarna/TableFixHeaders) library might be useful for you in this case.
|
Off the top of my head, this is how I would approach this:
1) Create an interface with one method that your Activity would implement to receive scroll coordinates and that your ScrollView can call back to when a scroll occurs:
```
public interface ScrollCallback {
public void scrollChanged(int newXPos, int newYPos);
}
```
2) Implement this in your activity to scroll the two constrained scrollviews to the position that the main scrollview just scrolled to:
```
@Override
public void scrollChanged(int newXPos, int newYPos) {
mVerticalScrollView.scrollTo(0, newYPos);
mHorizontalScrollView.scrollTo(newXPos, 0);
}
```
3) Subclass ScrollView to override the onScrollChanged() method, and add a method and member variable to call back to the activity:
```
private ScrollCallback mCallback;
//...
@Override
protected void onScrollChanged (int l, int t, int oldl, int oldt) {
mCallback.scrollChanged(l, t);
super.onScrollChanged(l, t, oldl, oldt);
}
public void setScrollCallback(ScrollCallback callback) {
mCallback = callback;
}
```
4) Replace the stock ScrollView in your XML with your new class and call `setScrollCallback(this)` in `onCreate()`.
|
7,586,764
|
We are multiple developers working on the same Xcode 4 iOS project. We are trying to commit to use Subversion but we keep getting conflicts with project.pbxproj when 2 developers add a new target or change the project structure.
What is the proper way to go about this issue?
|
2011/09/28
|
[
"https://Stackoverflow.com/questions/7586764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/969550/"
] |
About a week ago I revisited this problem and came up with a solution. The solution requires me to do a lot of manual width setting for the columns in this grid, and I consider that to be extremely sub-par in this day and age. Unfortunately, I have also continued to look for a more well-rounded solution native to the Android platform, but I have not turned anything up.
The following is the code to create this same grid, should any one following me need it. I will explain some of the more pertinent details below!
The layout: `grid.xml`:
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/lightGrey">
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginBottom="2dip"
android:layout_weight="1"
android:minHeight="100dip">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TableLayout
android:id="@+id/frozenTableHeader"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginTop="2dip"
android:layout_marginLeft="1dip"
android:stretchColumns="1"
/>
<qvtcapital.mobile.controls.ObservableHorizontalScrollView
android:id="@+id/contentTableHeaderHorizontalScrollView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/frozenTableHeader"
android:layout_marginTop="2dip"
android:layout_marginLeft="4dip"
android:layout_marginRight="1dip">
<TableLayout
android:id="@+id/contentTableHeader"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="1"/>
</qvtcapital.mobile.controls.ObservableHorizontalScrollView>
</LinearLayout>
<ScrollView
android:id="@+id/verticalScrollView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TableLayout
android:id="@+id/frozenTable"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginTop="2dip"
android:layout_marginLeft="1dip"
android:stretchColumns="1"
/>
<qvtcapital.mobile.controls.ObservableHorizontalScrollView
android:id="@+id/contentTableHorizontalScrollView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/frozenTable"
android:layout_marginTop="2dip"
android:layout_marginLeft="4dip"
android:layout_marginRight="1dip">
<TableLayout
android:id="@+id/contentTable"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="1"/>
</qvtcapital.mobile.controls.ObservableHorizontalScrollView>
</LinearLayout>
</ScrollView>
</TableLayout>
```
The activity: `Grid.java`:
```
public class ResultGrid extends Activity implements HorizontalScrollViewListener {
private TableLayout frozenHeaderTable;
private TableLayout contentHeaderTable;
private TableLayout frozenTable;
private TableLayout contentTable;
Typeface font;
float fontSize;
int cellWidthFactor;
ObservableHorizontalScrollView headerScrollView;
ObservableHorizontalScrollView contentScrollView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_grid);
font = Typeface.createFromAsset(getAssets(), "fonts/consola.ttf");
fontSize = 11; // Actually this is dynamic in my application, but that code is removed for clarity
final float scale = getBaseContext().getResources().getDisplayMetrics().density;
cellWidthFactor = (int) Math.ceil(fontSize * scale * (fontSize < 10 ? 0.9 : 0.7));
Button backButton = (Button)findViewById(R.id.backButton);
frozenTable = (TableLayout)findViewById(R.id.frozenTable);
contentTable = (TableLayout)findViewById(R.id.contentTable);
frozenHeaderTable = (TableLayout)findViewById(R.id.frozenTableHeader);
contentHeaderTable = (TableLayout)findViewById(R.id.contentTableHeader);
headerScrollView = (ObservableHorizontalScrollView) findViewById(R.id.contentTableHeaderHorizontalScrollView);
headerScrollView.setScrollViewListener(this);
contentScrollView = (ObservableHorizontalScrollView) findViewById(R.id.contentTableHorizontalScrollView);
contentScrollView.setScrollViewListener(this);
contentScrollView.setHorizontalScrollBarEnabled(false); // Only show the scroll bar on the header table (so that there aren't two)
backButton.setOnClickListener(backButtonClick);
InitializeInitialData();
}
protected void InitializeInitialData() {
ArrayList<String[]> content;
Bundle myBundle = getIntent().getExtras();
try {
content = (ArrayList<String[]>) myBundle.get("gridData");
} catch (Exception e) {
content = new ArrayList<String[]>();
content.add(new String[] {"Error", "There was an error parsing the result data, please try again"} );
e.printStackTrace();
}
PopulateMainTable(content);
}
protected void PopulateMainTable(ArrayList<String[]> content) {
frozenTable.setBackgroundResource(R.color.tableBorder);
contentTable.setBackgroundResource(R.color.tableBorder);
TableLayout.LayoutParams frozenRowParams = new TableLayout.LayoutParams(
TableLayout.LayoutParams.WRAP_CONTENT,
TableLayout.LayoutParams.WRAP_CONTENT);
frozenRowParams.setMargins(1, 1, 1, 1);
frozenRowParams.weight=1;
TableLayout.LayoutParams tableRowParams = new TableLayout.LayoutParams(
TableLayout.LayoutParams.WRAP_CONTENT,
TableLayout.LayoutParams.WRAP_CONTENT);
tableRowParams.setMargins(0, 1, 1, 1);
tableRowParams.weight=1;
TableRow frozenTableHeaderRow=null;
TableRow contentTableHeaderRow=null;
int maxFrozenChars = 0;
int[] maxContentChars = new int[content.get(0).length-1];
for (int i = 0; i < content.size(); i++){
TableRow frozenRow = new TableRow(this);
frozenRow.setLayoutParams(frozenRowParams);
frozenRow.setBackgroundResource(R.color.tableRows);
TextView frozenCell = new TextView(this);
frozenCell.setText(content.get(i)[0]);
frozenCell.setTextColor(Color.parseColor("#FF000000"));
frozenCell.setPadding(5, 0, 5, 0);
if (0 == i) { frozenCell.setTypeface(font, Typeface.BOLD);
} else { frozenCell.setTypeface(font, Typeface.NORMAL); }
frozenCell.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize);
frozenRow.addView(frozenCell);
if (content.get(i)[0].length() > maxFrozenChars) {
maxFrozenChars = content.get(i)[0].length();
}
// The rest of them
TableRow row = new TableRow(this);
row.setLayoutParams(tableRowParams);
row.setBackgroundResource(R.color.tableRows);
for (int j = 1; j < content.get(0).length; j++) {
TextView rowCell = new TextView(this);
rowCell.setText(content.get(i)[j]);
rowCell.setPadding(10, 0, 0, 0);
rowCell.setGravity(Gravity.RIGHT);
rowCell.setTextColor(Color.parseColor("#FF000000"));
if ( 0 == i) { rowCell.setTypeface(font, Typeface.BOLD);
} else { rowCell.setTypeface(font, Typeface.NORMAL); }
rowCell.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize);
row.addView(rowCell);
if (content.get(i)[j].length() > maxContentChars[j-1]) {
maxContentChars[j-1] = content.get(i)[j].length();
}
}
if (i==0) {
frozenTableHeaderRow=frozenRow;
contentTableHeaderRow=row;
frozenHeaderTable.addView(frozenRow);
contentHeaderTable.addView(row);
} else {
frozenTable.addView(frozenRow);
contentTable.addView(row);
}
}
setChildTextViewWidths(frozenTableHeaderRow, new int[]{maxFrozenChars});
setChildTextViewWidths(contentTableHeaderRow, maxContentChars);
for (int i = 0; i < contentTable.getChildCount(); i++) {
TableRow frozenRow = (TableRow) frozenTable.getChildAt(i);
setChildTextViewWidths(frozenRow, new int[]{maxFrozenChars});
TableRow row = (TableRow) contentTable.getChildAt(i);
setChildTextViewWidths(row, maxContentChars);
}
}
private void setChildTextViewWidths(TableRow row, int[] widths) {
if (null==row) {
return;
}
for (int i = 0; i < row.getChildCount(); i++) {
TextView cell = (TextView) row.getChildAt(i);
int replacementWidth =
widths[i] == 1
? (int) Math.ceil(widths[i] * cellWidthFactor * 2)
: widths[i] < 3
? (int) Math.ceil(widths[i] * cellWidthFactor * 1.7)
: widths[i] < 5
? (int) Math.ceil(widths[i] * cellWidthFactor * 1.2)
:widths[i] * cellWidthFactor;
cell.setMinimumWidth(replacementWidth);
cell.setMaxWidth(replacementWidth);
}
}
public void onScrollChanged(ObservableHorizontalScrollView scrollView, int x, int y, int oldX, int oldY) {
if (scrollView==headerScrollView) {
contentScrollView.scrollTo(x, y);
} else if (scrollView==contentScrollView) {
headerScrollView.scrollTo(x, y);
}
}
```
The scroll view listener (to hook the two up): `HorizontalScrollViewListener.java`:
```
public interface HorizontalScrollViewListener {
void onScrollChanged(ObservableHorizontalScrollView scrollView, int x, int y, int oldX, int oldY);
}
```
The ScrollView class that implements this listener: `ObservableHorizontalScrollView.java`:
```
public class ObservableHorizontalScrollView extends HorizontalScrollView {
private HorizontalScrollViewListener scrollViewListener=null;
public ObservableHorizontalScrollView(Context context) {
super(context);
}
public ObservableHorizontalScrollView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public ObservableHorizontalScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setScrollViewListener(HorizontalScrollViewListener scrollViewListener) {
this.scrollViewListener = scrollViewListener;
}
@Override
protected void onScrollChanged(int x, int y, int oldX, int oldY) {
super.onScrollChanged(x, y, oldX, oldY);
if (null!=scrollViewListener) {
scrollViewListener.onScrollChanged(this, x, y, oldX, oldY);
}
}
}
```
The really important part of this is sort of three-fold:
1. The ObservableHorizontalScrollView allows the header table and the content table to scroll in sync. Basically, this provides all of the horizontal motion for the grid.
2. The way in which they stay aligned is by detecting the largest string that will be in a column. This is done at the end of `PopulateMainTable()`. While we're going through each of the TextViews and adding them to the rows, you'll notice that there are two arrays `maxFrozenChars` and `maxContentChars` that keep track of what the largest string value we've seen is. At the end of `PopulateMainTable()` we loop through each of the rows and for each of the cells we set its min and max width based on the largest string we saw in that column. This is handled by `setChildTextViewWidths`.
3. The last item that makes this work is to use a monospaced font. You'll notice that in `onCreate` I am loading a consola.ttf font, and later applying it to each of the grid's TextViews that act as the cells in the grid. This allows us to be reasonably sure that the text will not be rendered larger than we have set the minimum and maximum width to in the prior step. I am doing a little bit of fanciness here, what with the whole cellWidthFactor and the maximum size of that column. This is really so that smaller strings will fit for sure, while we can minimize the white space for larger strings that are (for my system) not going to be all capital letters. If you ran in to trouble using this and you got strings that did not fit in the column size you set, this is where you would want to edit things. You would want to change the `replacementWidth` variable with some other formula for determining the cell width, such as `50 * widths[i]` which would be quite large! But would leave you with a good amount of whitespace in some columns. Basically, depending on what you plan on putting in your grid, this may need to be tweaked. Above is what worked for me.
I hope this helps someone else in the future!
|
[TableFixHeaders](https://github.com/InQBarna/TableFixHeaders) library might be useful for you in this case.
|
25,319,322
|
I have a very unique problem which occurs only when font sizes dip below a certain level. Here is the code that I am working with which gives an example of what I'm trying to achieve:
```
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 18px;
height: 18px;
background-color: black;
border: 1px solid blue;
clear: both;
display: inline-block;
vertical-align: top;
color: red;
text-align: center;
font-size: 10px;
line-height: 18px;
}
</style>
<head>
<body>
<div>#</div><div>@</div><div>A</div><div>B</div><div>I</div><div>#</div><div>#</div><br><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
</body>
</html>
```
This yields exactly what I want it to - side by side divs with a single character inside each. If I try to scale this down, however, to a div size of 12x12 a gap appears in between each of the rows which I cannot afford to have. What tricks can I apply to get my desired output?
Here is what I mean by "scaling it down":
```
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 12px; /* change made here */
height: 12px; /* change made here */
background-color: black;
border: 1px solid blue;
clear: both;
display: inline-block;
vertical-align: top;
color: red;
text-align: center;
font-size: 10px;
line-height: 12px; /* change made here */
}
</style>
<head>
<body>
<div>#</div><div>@</div><div>A</div><div>B</div><div>I</div><div>#</div><div>#</div><br><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
</body>
</html>
```
|
2014/08/14
|
[
"https://Stackoverflow.com/questions/25319322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2543167/"
] |
I came up the following that works:
<http://jsfiddle.net/gfbxrgum/>
1. Wrap the rows in an element that will break. I just created a block level span that will clear both.
2. Float the divs and set clear to none.
CSS
```
div {
width: 12px; /* change made here */
height: 12px; /* change made here */
background-color: black;
border: 1px solid blue;
clear: none;
display: block;
float:left;
vertical-align: top;
color: red;
text-align: center;
font-size: 10px;
line-height: 12px; /* change made here */
}
span {
display:block;
clear:both;
}
```
HTML
```
<span><div>#</div><div>@</div><div>A</div><div>B</div><div>I</div><div>#</div><div>#</div></span><span><div></div><div></div><div></div><div></div><div></div><div></div><div></div></span>
```
|
Nothing wrong with your Style. You have a 'br' tag in between your Divs. Remove it and it'll work like a charm. :-D
If you still need to have a line break please refer to [this](https://stackoverflow.com/questions/13546227/is-there-a-way-to-have-a-line-break-between-divs) thread in SO
|
27,642,037
|
Haven't been able to solve this since my last go, but I restructured the code after this
<https://developers.facebook.com/blog/post/576/>
I can't trigger the re-request for accepting all the permissions (ignore the alert text content as that will change to tell the user about why the permission are needed)
Here's the sign in code
```
jQuery(function() {
$('body').prepend('<div id="fb-root"></div>');
return $.ajax({
url: "" + window.location.protocol + "//connect.facebook.net/en_US/all.js",
dataType: 'script',
cache: true
});
});
window.fbAsyncInit = function() {
return FB.init({
appId: '<%= ENV["FACEBOOK_KEY"] %>',
cookie: true
});
};
var permsNeeded = ["email", "user_birthday", "user_friends"];
var checkPermissions = function() {
var promptForPerms;
FB.api("/me/permissions", function(response) {
var i, permsArray, permsToPrompt;
permsArray = response.data[0];
permsToPrompt = [];
for (i in permsNeeded) {
if (permsArray[permsNeeded[i]] == null) {
permsToPrompt.push(permsNeeded[i]);
}
}
if (permsToPrompt.length > 0) {
alert("Need to re-prompt user for permissions: " + permsToPrompt.join(","));
promptForPerms(permsToPrompt);
} else {
alert("No need to prompt for any permissions");
}
});
promptForPerms = function(perms) {};
FB.login((function(response) {
console.log(response);
}), {
scope: perms.join(","),
auth_type: "rerequest"
});
$("#sign_in").click(function(e) {
e.preventDefault();
return FB.login((function(response) {
if (response.authResponse) {
checkPermissions();
}
}), {
scope: permsNeeded.join(',')
});
});
};
```
Any suggestions on what to modify or change? I'm totally stuck on what to do. Right now, nothing alerts regardless of what you deny or permit.
|
2014/12/24
|
[
"https://Stackoverflow.com/questions/27642037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2827338/"
] |
Seems like there are some bugs in your code. I highly recommend you to format and style your code properly.
I have fixed the bugs and you may refer to the revised code below.
Note that this is using facebook jssdk v2.2.
```
window.fbAsyncInit = function() {
FB.init({
appId : '960839450617376',
xfbml : true,
version : 'v2.2'
});
init();
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
function init() {
var permsNeeded = ["email", "user_birthday", "user_friends"];
var checkPermissions = function() {
var promptForPerms;
FB.api("/me/permissions", function(response) {
var permsArray, permsToPrompt;
permsArray = response.data;
permsToPrompt = [];
console.log(JSON.stringify(permsArray));
for (var i = 0, ilen = permsArray.length; i < ilen; i++) {
console.log(permsArray[i].permission, permsArray[i].status);
if (permsNeeded.indexOf(permsArray[i].permission) != -1 && permsArray[i].status != 'granted') {
permsToPrompt.push(permsArray[i].permission);
}
}
console.log(permsToPrompt);
if (permsToPrompt.length > 0) {
alert("Need to re-prompt user for permissions: " + permsToPrompt.join(", ") + '.\nPlease try again and allow the permission mentioned.');
} else {
alert("No need to prompt for any permissions");
}
});
};
$("#sign_in").click(function(e) {
console.log('sign in');
e.preventDefault();
return FB.login(
function(response) {
if (response.authResponse) {
checkPermissions();
}
}, {
scope: permsNeeded.join(','),
return_scopes: true,
auth_type: 'rerequest'
}
);
});
}
```
As you can see I have changed `permsArray = response.data[0]; => permsArray = response.data;`
This is because when I request the list of permission I receive the following json example
```
{
data: [
{
"permission":"public_profile",
"status":"granted"
},
{
"permission":"email",
"status":"granted"
},
{
"permission":"user_birthday",
"status":"granted"
},
{
"permission":"user_friends",
"status":"granted"
}
]
}
```
I have also edited the loop to check which permission is denied.
Instead of reprompting login via code, we request user to click the sign in button again so that the login popup will be allowed (via click event).
I have also set `auth_type: 'rerequest'` as default for the login request since I do not see any prompt for permission if all permission is granted.
|
@Jeff Caspian
This is the exact right way to get user email address, thanks a lot I was nearly struck for 2 days.
Actually lot of them are reporting as bug to Facebook team that they are not able to get email address in fact me too.
```
FB.api("/me/permissions", function(response) {
}
```
This is the call which saved me thanks again.
|
12,540
|
I recently read an article entitled [how NAT works](http://computer.howstuffworks.com/nat.htm "How NAT works"). Some things still remain unclear to me. I would be thankful if someone could explain.
Below is the part of the article regarding DynamicNAT that is most confusing:
>
> A computer on the stub domain attempts to connect to a computer
> outside the network, such as a Web server.
>
>
> The router receives the packet from the computer on the stub domain.
> The router saves the computer's non-routable IP address to an address
> translation table. The router replaces the sending computer's
> non-routable IP address with the first available IP address out of the
> range of unique IP addresses. The translation table now has a mapping
> of the computer's non-routable IP address matched with the one of the
> unique IP addresses.
>
>
> When a packet comes back from the destination computer, the router
> checks the destination address on the packet. It then looks in the
> address translation table to see which computer on the stub domain the
> packet belongs to.
>
>
>
1) How does NAT know that the packet "comes back" to destination computer?
2) What if other computers in the LAN are connected to the same server? How does the NAT know which packet should "come back" where?
3) Does the packet header modification allow to perform an Internet attack, in which the "source IP" is replaced with the victim's IP, and the answering server will flood victim with unwanted packets?
I guess multiple attackers would need to be involved...
4) Is StaticNAT equivalent to the PortForwarding of all ports?
|
2014/10/17
|
[
"https://networkengineering.stackexchange.com/questions/12540",
"https://networkengineering.stackexchange.com",
"https://networkengineering.stackexchange.com/users/9952/"
] |
There is a general misconception between [NAT](http://en.wikipedia.org/wiki/Network_address_translation) (Network address translation) and PAT (Port Address Translation), which is what we mostly use in our home routers.
**NAT**
Let's assume we have a network with the following topology:
*Private\_Network* <-------> *Router* <-------> *The\_Internet*
The interface of the *Router* that is connected to the *Private\_Network* has [a private IP address](http://en.wikipedia.org/wiki/Private_network), i.e. one that is not unique in *The\_Internet*. On the other hand, in the case of **NAT**, *Router* has **multiple** interfaces connected to *The\_Internet*. Each interface has a unique IP address in *The\_Internet*. Now let's assume that *Host\_A* and *Host\_B* are in the *Private\_Network* and they both want to access *Website\_X* in *The\_Internet* at the same time. The IPs and the ports of *Host\_A*'s packet will be:
Source IP: *Host\_A*'s private IP
Source Port: A port on *Host\_A*
Destination IP: *Website\_X*'s public/unique IP
Destination Port: A port where *Website\_X*'s server is listening to
and in the same way for a packet coming from *Host\_B*.
If the Source IP is left unchanged, then *Website\_X* will reply to an IP address that is private, i.e. not unique, and therefore the packet will never be able to find it's way back. In order to solve that problem, the *Router* checks whether one of his unique IP addresses connected to *The\_Internet* is not used. If that is the case, it does the following mapping:
*Host\_A*'s private IP ======= *Router's\_unique\_IP\_K*
and now the packet that started from *Host\_A* going to *Website\_X* and is now leaving the interface of the *Router* connected to *The\_Internet* will have the form:
Source IP: *Router's\_unique\_IP\_K*
Source Port: A port on *Host\_A*
Destination IP: *Website\_X*'s public/unique IP
Destination Port: A port where *Website\_X*'s server is listening to
Thus you can understand that there is an one-to-one association from private IPs to public IPs. Therefore when a packet arrives from *Website\_X* to the *Router*, this association is checked and the destination IP address is changed back to the private one and delivered successfully to the right host.
As you can see, this method is quite simple, but it has one big disadvantage: each private host has to have a unique IP address reserved, which is expensive, thus we select to have fewer unique IP addresses than hosts in the private network. Therefore if all the private hosts attempt to access *The\_Internet* at the same time, only a subset of them, equal to the number of the available public IP addresses that the *Router* has, will have access and the rest will be denied.
In order to counter that we created **PAT**.
**PAT**
**PAT** is what the vast majority of our home routers is using. The basic limitation is that the *Router* has a single unique IP address with which it connects to *The\_Internet*, but we still want to allow multiple hosts from the private network to access *The\_Internet* at the same time.
The way we do that is "similar" to the way **NAT** does it with a key difference: instead of the *Router* holding a pool of IP address, it holds a pool of port numbers. More precisely, a packet arriving at the *Router* from *Host\_A* in the *Private\_Network* destined to *Website\_X* in *The\_Internet* will have the following format:
Source IP: *Host\_A*'s private IP
Source Port: A port on *Host\_A*
Destination IP: *Website\_X*'s public/unique IP
Destination Port: A port where *Website\_X*'s server is listening to
Now the *Router* will do two tasks:
1. It will change the Source IP to the *Router*'s unique public IP **AND**
2. It will change the Source Port to a port from a pool that the *Router* is maintaining and is not already used, e.g. *Port\_Z*
and now the packet that started from *Host\_A* going to *Website\_X* and is now leaving the interface of the *Router* connected to *The\_Internet* will have the form:
Source IP: *Router's\_unique\_IP\_K*
Source Port: *Port\_Z*
Destination IP: *Website\_X*'s public/unique IP
Destination Port: A port where *Website\_X*'s server is listening to
and the *Router* will keep the following mapping:
*Host\_A*'s private IP **AND** a port on *Host\_A* ======= *Port\_Z*
Why does this work?
Now when a packet comes back, the *Router* simply checks the destination port number and changes the destination IP address and the destination port number according to the pre-mentioned mapping and the packet gets delivered successfully.
What if I run multiple applications on the same Host?
Different applications will have different ports, by definition, thus they will mapped to a different port from the *Router*.
What if multiple Hosts attempt to access *The\_Internet* at the same time and they all use the same application?
Different Hosts will have different private IP addresses, by definition, thus they will mapped to a different port from the *Router*.
**PAT** is dangerously balancing in a grey space of cross-layer. Port numbers are part of the Transport Protocol while Routers are allowed to operate up to the Internet Protocol. So technically speaking is something that is not allowed by the protocols. Therefore there are, at least theoretically, potential dangers: the port pool is limited. Therefore if my private network consists of 1000 Hosts and each one is running port\_pool/10 applications, the mapping table at the router will run out of available entries and access to applications will be denied.
This answer greatly exceeded my intended length, but I hope it was helpful.
|
The router knows where packets belong because `The router saves ... an address translation table.` It remembers what inside-outside address translations it has made. As such, one inside address equals one outside address, and the out-on-the-internet destination is irrelevant. This, of course, ignores the firewall present in practically every NAT router, which tracks full connections:
```
(inside) src:ip+port,dst:ip+port <-> (outside) src:ip+port,dst:ip+port
```
NAT can change any combination of ip and/or port.
#3 is any entirely different subject: *spoofing*
#4 "Static NAT", or "1-to-1", is an address only map. So, port (and even protocol: tcp, udp, gre, etc.) is irrelevant.
|
74,215
|
I was cleaning my chainring, chain and cassette with vinegar,
to remove unwanted grease but suddenly after a few minutes it suddenly turned slightly orange. It spread all over my rear gears.
I got worried so I put light oil; it worked but still has some light rust on it.
What should I do?
|
2020/12/29
|
[
"https://bicycles.stackexchange.com/questions/74215",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/54430/"
] |
Hey I would not worry too much about it at this point. Chains, cassettes, and chain rings are wear and tear components so let the rest of the rust come off with wear/tear and proper cleaning in the future. If it really bugs you, you can use some steel wool, but I would not.
In the future it is much better to use a proper degreaser like Finish Line.
There are posts around about how to clean a chain and drive train.
**Below is an excerpt from one of those answers I wrote:**
Here is video from my YouTube channel of a quick drive service that I do every 100-200 miles depending on the conditions and lube used.
The steps I use when cleaning components are summarized as:
1. Shift Into the Big Chain Ring and Small Gear in the back
2. Degrease - Chain clean tools made by Park or Finish Line make things easier here.
3. Water Rinse Chain - Chain clean tools made by Park or Finish Line make things easier here.
4. Wipe Chain With Rag
5. Clean Drive Components (i.e. Cassette, Chain Ring, and Derailleur)
6. Clean Cassette (See Above) - Something like a rag wrapped around something thin and solid like a CD works well for me and is inexpensive. A example is shown here in this clip:
7. Wipe Chain With Rag
8. Lube Chain - Only 1 small drop of lube per link. Find the masterlink/quicklink on the chain and use that as a reference to make sure you only lube a link 1 time. Less is more here as unnecessary lube just flings off the chain onto your wheel or braking surfaces and attracts more dust. Some people like to wipe their chain after lubing it, but I have had good luck just sparingly applying the lube to begin with so that after the next step there is not much need to wipe any excess. However, again each person may have their own opinion or preference on the matter. I have had good experience with WD40 Wet Lube (Not regular WD40) and Finish Line Ceramic Wet Lube. I am sure each person will have their own preferences like people do when it comes to motor oil.
9. Shift through all gears and chainrings to spread the lube around.
You can spend more time cleaning components, by removing the wheel & cassette, but usually what is shown outlined above is sufficient to keep things clean for most people.
Hope that helps
|
The rust is only cosmetic surface rust. I would ignore it.
In future, don not use vinegar as it is quite acidic. A proper degreaser will clean the chain and running gear without causing rust.
Oiling the chain is essential after cleaning, mainly to provide lubrication, but also the oil prevents rust. It is best to use a proper bicycle chain lube, as (what I think of )
a light oil is too light to provide the lubrication needed (much better than nothing if its all you have available).
|
74,215
|
I was cleaning my chainring, chain and cassette with vinegar,
to remove unwanted grease but suddenly after a few minutes it suddenly turned slightly orange. It spread all over my rear gears.
I got worried so I put light oil; it worked but still has some light rust on it.
What should I do?
|
2020/12/29
|
[
"https://bicycles.stackexchange.com/questions/74215",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/54430/"
] |
The rust is only cosmetic surface rust. I would ignore it.
In future, don not use vinegar as it is quite acidic. A proper degreaser will clean the chain and running gear without causing rust.
Oiling the chain is essential after cleaning, mainly to provide lubrication, but also the oil prevents rust. It is best to use a proper bicycle chain lube, as (what I think of )
a light oil is too light to provide the lubrication needed (much better than nothing if its all you have available).
|
Just oil the chain & cassette , it has rusted the surface.If you really want to, you can just degrease the cassette and chain rings and sand/paint them again with some paint for a surface protectant/cosmetic finish.Any exposure to moisture/caustic agent/acid on bare metal will cause rust.
|
74,215
|
I was cleaning my chainring, chain and cassette with vinegar,
to remove unwanted grease but suddenly after a few minutes it suddenly turned slightly orange. It spread all over my rear gears.
I got worried so I put light oil; it worked but still has some light rust on it.
What should I do?
|
2020/12/29
|
[
"https://bicycles.stackexchange.com/questions/74215",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/54430/"
] |
The rust is only cosmetic surface rust. I would ignore it.
In future, don not use vinegar as it is quite acidic. A proper degreaser will clean the chain and running gear without causing rust.
Oiling the chain is essential after cleaning, mainly to provide lubrication, but also the oil prevents rust. It is best to use a proper bicycle chain lube, as (what I think of )
a light oil is too light to provide the lubrication needed (much better than nothing if its all you have available).
|
You don’t want rust on your drivetrain. And rust, in my experience, has an “infective” property, whereby it can seed more rust if moved from one area to another. If it were my bike, I’d buy some phosphoric acid rust remover (or similar) and clean the drivetrain (take the chain and cogs off) with it to remove all traces of rust. I hear vinegar can also work.
Once everything is shiny again, you can lubricate the drivetrain in the normal way. If you keep your drivetrain lubricated then rust should not continue to appear, as the lubricant will prevent the exposure of the bare metal to moisture and the oxygen in the air.
|
74,215
|
I was cleaning my chainring, chain and cassette with vinegar,
to remove unwanted grease but suddenly after a few minutes it suddenly turned slightly orange. It spread all over my rear gears.
I got worried so I put light oil; it worked but still has some light rust on it.
What should I do?
|
2020/12/29
|
[
"https://bicycles.stackexchange.com/questions/74215",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/54430/"
] |
Hey I would not worry too much about it at this point. Chains, cassettes, and chain rings are wear and tear components so let the rest of the rust come off with wear/tear and proper cleaning in the future. If it really bugs you, you can use some steel wool, but I would not.
In the future it is much better to use a proper degreaser like Finish Line.
There are posts around about how to clean a chain and drive train.
**Below is an excerpt from one of those answers I wrote:**
Here is video from my YouTube channel of a quick drive service that I do every 100-200 miles depending on the conditions and lube used.
The steps I use when cleaning components are summarized as:
1. Shift Into the Big Chain Ring and Small Gear in the back
2. Degrease - Chain clean tools made by Park or Finish Line make things easier here.
3. Water Rinse Chain - Chain clean tools made by Park or Finish Line make things easier here.
4. Wipe Chain With Rag
5. Clean Drive Components (i.e. Cassette, Chain Ring, and Derailleur)
6. Clean Cassette (See Above) - Something like a rag wrapped around something thin and solid like a CD works well for me and is inexpensive. A example is shown here in this clip:
7. Wipe Chain With Rag
8. Lube Chain - Only 1 small drop of lube per link. Find the masterlink/quicklink on the chain and use that as a reference to make sure you only lube a link 1 time. Less is more here as unnecessary lube just flings off the chain onto your wheel or braking surfaces and attracts more dust. Some people like to wipe their chain after lubing it, but I have had good luck just sparingly applying the lube to begin with so that after the next step there is not much need to wipe any excess. However, again each person may have their own opinion or preference on the matter. I have had good experience with WD40 Wet Lube (Not regular WD40) and Finish Line Ceramic Wet Lube. I am sure each person will have their own preferences like people do when it comes to motor oil.
9. Shift through all gears and chainrings to spread the lube around.
You can spend more time cleaning components, by removing the wheel & cassette, but usually what is shown outlined above is sufficient to keep things clean for most people.
Hope that helps
|
Just oil the chain & cassette , it has rusted the surface.If you really want to, you can just degrease the cassette and chain rings and sand/paint them again with some paint for a surface protectant/cosmetic finish.Any exposure to moisture/caustic agent/acid on bare metal will cause rust.
|
74,215
|
I was cleaning my chainring, chain and cassette with vinegar,
to remove unwanted grease but suddenly after a few minutes it suddenly turned slightly orange. It spread all over my rear gears.
I got worried so I put light oil; it worked but still has some light rust on it.
What should I do?
|
2020/12/29
|
[
"https://bicycles.stackexchange.com/questions/74215",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/54430/"
] |
Hey I would not worry too much about it at this point. Chains, cassettes, and chain rings are wear and tear components so let the rest of the rust come off with wear/tear and proper cleaning in the future. If it really bugs you, you can use some steel wool, but I would not.
In the future it is much better to use a proper degreaser like Finish Line.
There are posts around about how to clean a chain and drive train.
**Below is an excerpt from one of those answers I wrote:**
Here is video from my YouTube channel of a quick drive service that I do every 100-200 miles depending on the conditions and lube used.
The steps I use when cleaning components are summarized as:
1. Shift Into the Big Chain Ring and Small Gear in the back
2. Degrease - Chain clean tools made by Park or Finish Line make things easier here.
3. Water Rinse Chain - Chain clean tools made by Park or Finish Line make things easier here.
4. Wipe Chain With Rag
5. Clean Drive Components (i.e. Cassette, Chain Ring, and Derailleur)
6. Clean Cassette (See Above) - Something like a rag wrapped around something thin and solid like a CD works well for me and is inexpensive. A example is shown here in this clip:
7. Wipe Chain With Rag
8. Lube Chain - Only 1 small drop of lube per link. Find the masterlink/quicklink on the chain and use that as a reference to make sure you only lube a link 1 time. Less is more here as unnecessary lube just flings off the chain onto your wheel or braking surfaces and attracts more dust. Some people like to wipe their chain after lubing it, but I have had good luck just sparingly applying the lube to begin with so that after the next step there is not much need to wipe any excess. However, again each person may have their own opinion or preference on the matter. I have had good experience with WD40 Wet Lube (Not regular WD40) and Finish Line Ceramic Wet Lube. I am sure each person will have their own preferences like people do when it comes to motor oil.
9. Shift through all gears and chainrings to spread the lube around.
You can spend more time cleaning components, by removing the wheel & cassette, but usually what is shown outlined above is sufficient to keep things clean for most people.
Hope that helps
|
You don’t want rust on your drivetrain. And rust, in my experience, has an “infective” property, whereby it can seed more rust if moved from one area to another. If it were my bike, I’d buy some phosphoric acid rust remover (or similar) and clean the drivetrain (take the chain and cogs off) with it to remove all traces of rust. I hear vinegar can also work.
Once everything is shiny again, you can lubricate the drivetrain in the normal way. If you keep your drivetrain lubricated then rust should not continue to appear, as the lubricant will prevent the exposure of the bare metal to moisture and the oxygen in the air.
|
72,665,680
|
So I have a problem that `strcmp` not working even the string is same. The cmp between destination and source string is have same string, but when `strcmp` it, it not working. See the code for explanation:
```
# include <stdio.h>
# include <string.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "r");
char namalengkap[100], gender[100], charnamafile[50], tempat[50], temp[1000], tdeeprint[100], gendercheck;
int umur, tb, bb, x;
int cmp1, cmp2, cmp3, cmp4, cmp5, cmp6, check;
float tdeenum;
fscanf(fp, "Username : %s\nPassword : %s", tempat, temp);
fscanf(fp, "\n\n\n=============================DATA PRIBADI USER===============================\n");
fscanf(fp, "= Nama Lengkap : %52[^\n] =\n", namalengkap);
fscanf(fp, "= Jenis Kelamin : %52[^\n] =\n", gender);
fscanf(fp, "= Umur : %52d =\n", &umur);
fscanf(fp, "= Tinggi Badan (CM) : %52d =\n", &tb);
fscanf(fp, "= Berat Badan (KG) : %52d =\n", &bb);
fscanf(fp, "= Rutinitas Olahraga : %52[^\n] =\n", tdeeprint);
fscanf(fp, "=============================================================================\n");
cmp1 = strcmp(tdeeprint, "Jarang Berolahraga");
cmp2 = strcmp(tdeeprint, "1 Hingga 3 Hari Dalam Seminggu");
cmp3 = strcmp(tdeeprint, "3 Hingga 5 Hari Dalam Seminggu");
cmp4 = strcmp(tdeeprint, "6 Hingga 7 Hari Dalam Seminggu");
cmp5 = strcmp(tdeeprint, "Pekerjaan Fisik Berat Atau Olahraga 2x Dalam Sehari");
if (cmp1 == 0) {
tdeenum = 1.2;
printf("tde1work : %f\n", tdeenum);
} else
if (cmp2 == 0) {
tdeenum = 1.375;
printf("tde2work : %f\n", tdeenum);
} else
if (cmp3 == 0) {
tdeenum = 1.55;
printf("tde3work : %f\n", tdeenum);
} else
if (cmp4 == 0) {
tdeenum = 1.725;
printf("tde4work : %f\n", tdeenum);
} else
if (cmp5 == 0) {
tdeenum = 1.9;
printf("tde5work : %f\n", tdeenum);
}
printf("\nUsername : %s\n", tempat);
printf("\nPassword : %s\n", temp);
printf("\nName : %s\n", namalengkap);
printf("\nGender : %s\n", gender);
printf("\nUmur : %d\n", umur);
printf("\nTB : %d\n", tb);
printf("\nBB : %d\n", bb);
printf("\ntdeeprint : %s\n", tdeeprint);
printf("\ntdeepnum : %f\n", tdeenum);
fclose(fp);
return 0;
}
```
When I run it:
```
Username : hitunga
Password : 12345
Name : a
Gender : Perempuan
Umur : 30
TB : 155
BB : 50
tdeeprint : Jarang Berolahraga
tdeepnum : 0.000000
Process returned 0 (0x0) execution time : 0.043 s
Press any key to continue.
```
The **test.txt** file content:
```
Username : hitunga
Password : 12345
=============================DATA PRIBADI USER===============================
= Nama Lengkap : a =
= Jenis Kelamin : Perempuan =
= Umur : 30 =
= Tinggi Badan (CM) : 155 =
= Berat Badan (KG) : 50 =
= Rutinitas Olahraga : Jarang Berolahraga =
= TDEE : 1.200 =
=============================================================================
```
So what wrong on my code? I really confused why isn't working. It is literally same string comparison but not working. Thank you
**Edit:**
So I replace the cmp section with `fscanf`, but still not getting the number
```
fscanf(fp, "= TDEE : %52.3f =\n", &datusr.tdeenum);
```
|
2022/06/17
|
[
"https://Stackoverflow.com/questions/72665680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19326012/"
] |
If you change your `printf` statement to this, the problem will likely become clear to you:
```
printf("\ntdeeprint : '%s'\n",tdeeprint);
```
Output snippet:
```
tdeeprint : 'Jarang Berolahraga '
```
The same applies to `namalengkap` and `gender`. The `%52[^\n]` pattern includes all the space characters that follow what you want until you get to `=`, that's why it doesn't match the `Jarang Berolahraga`.
|
Regarding the last question, `fscanf(fp, "= TDEE : %52.3f =\n", &datusr.tdeenum)` fails after consuming the input up to `= TDEE :` because `%52.3f` is not a valid conversion specifier: there is no *precision* field in `scanf` conversions. You should just use `%52f` or simply `%f`.
Note that your parser is very brittle and you do not check the return values of these `fscanf()` calls. Any mismatch will cause the input stream to get out of sync with your code and subsequent calls to `fscanf()` will fail and leave the destination variables unchanged, hence uninitialized, thus causing undefined behavior when you later compare them and print them.
You should change your parsing method: a safer approach is to read the file one line at a time with `fgets()`, prepare the line for parsing ie: remove the trailing `=` and trailing spaces, use `sscanf()` to try and match the expected data and check the return value to detect and report invalid input.
Here is a modified version:
```
#include <errno.h>
#include <stdio.h>
#include <string.h>
// read the next non blank line from file fp, strip trailing spaces and =
char *nextline(FILE *fp, char *buf, size_t size, int c) {
for (;;) {
if (!fgets(buf, size, fp)) {
*buf = '\0';
return buf;
}
size_t len = strlen(buf);
while (len > 0 && (buf[len - 1] == '\n' || buf[len - 1] == ' ' || buf[len - 1] == c)) {
buf[--len] = '\0';
}
if (*buf)
return buf;
}
}
int main() {
FILE *fp = fopen("220618-test.txt", "r");
if (fp == NULL) {
fprintf(stderr, "cannot open test.txt: %s\n", strerror(errno));
return 1;
}
char tempat[50], temp[1000];
char namalengkap[100], gender[100], tdeeprint[100], ch[2];
int umur, tb, bb;
double tdeenum;
char buf[200];
if (sscanf(nextline(fp, buf, sizeof buf, 0), "Username : %49s", tempat) != 1
|| sscanf(nextline(fp, buf, sizeof buf, 0), "Password : %999s", temp) != 1
|| sscanf(nextline(fp, buf, sizeof buf, 0), "=============================DATA PRIBADI USER==============================%1[=]", ch) != 1
|| sscanf(nextline(fp, buf, sizeof buf, '='), "= Nama Lengkap : %99[^\n]", namalengkap) != 1
|| sscanf(nextline(fp, buf, sizeof buf, '='), "= Jenis Kelamin : %99[^\n]", gender) != 1
|| sscanf(nextline(fp, buf, sizeof buf, '='), "= Umur : %d", &umur) != 1
|| sscanf(nextline(fp, buf, sizeof buf, '='), "= Tinggi Badan (CM) : %d", &tb) != 1
|| sscanf(nextline(fp, buf, sizeof buf, '='), "= Berat Badan (KG) : %d", &bb) != 1
|| sscanf(nextline(fp, buf, sizeof buf, '='), "= Rutinitas Olahraga : %99[^\n]", tdeeprint) != 1
|| sscanf(nextline(fp, buf, sizeof buf, '='), "= TDEE : %lf", &tdeenum) != 1
|| sscanf(nextline(fp, buf, sizeof buf, 0), "============================================================================%1[=]", ch) != 1) {
fprintf(stderr, "invalid input: parse error at %s\n", buf);
return 1;
}
fclose(fp);
printf("Username : %s\n", tempat);
printf("Password : %s\n", temp);
printf("Name : %s\n", namalengkap);
printf("Gender : %s\n", gender);
printf("Umur : %d\n", umur);
printf("TB : %d\n", tb);
printf("BB : %d\n", bb);
printf("tdeeprint : %s\n", tdeeprint);
printf("tdeepnum : %f\n", tdeenum);
return 0;
}
```
Output:
```
Username : hitunga
Password : 12345
Name : a
Gender : Perempuan
Umur : 30
TB : 155
BB : 50
tdeeprint : Jarang Berolahraga
tdeepnum : 1.200000
```
|
53,464,314
|
[I asked the following question on the CS SE](https://cs.stackexchange.com/q/100175/26856):
>
> For example, in the proof of lemma 6.4.1 in the HoTT book, a function
> inductively defined over a function is simply applied on paths `loop`
> and `refl`, and then a path between `loop` and `refl` is used
> (presumably by congruence via `f`) to construct a path between `f loop` and `f refl`:
>
>
>
> >
> > Suppose that `loop = refl base`. [...] with `x : A` and `p : x = x`, there is a function `f : S1 → A` defined by `f(base) :≡ x` and
> > `f(loop) := p`, we have
> >
> >
> >
> > ```
> > p = f(loop) = f(refl base) = refl x.
> >
> > ```
> >
> >
>
>
> But in a cubical setting, things are not so clear-cut. `f(loop)` is
> not well-typed, only `f(loop i)` is, for some `i : I`. But then that
> above proof becomes
>
>
>
> ```
> p = <i> f (loop i) = <i> f (refl base i) = refl x
>
> ```
>
> but doesn't that need some kind of "interval extensionality" in the
> middle step? What exactly is the justification of the middle step in
> cubical type theory? I can see how to prove `∀ i → f (loop i) = f (refl base i)`, but how does one "lift" that to `<i> f (loop i) = <i> f (refl base i)`?
>
>
>
I haven't received a response there so I'm going to try here, with concrete Agda code to back it.
I am trying to turn the above proof into Cubical Agda as follows. First, given `p`, the definition of `f` is straightforward:
```
hyp : loop ≡ refl {x = base}
p : x ≡ x
f : S¹ → A
f base = x
f (loop i) = p i
```
We can prove *pointwise along `loop`* that `f (loop i) ≡ f (refl i)`:
```
proofAt_ : ∀ i → f (loop i) ≡ f base
proofAt i = cong (λ p → f (p i)) hyp
```
(to see why, here it is in more detail:
```
proofAt_ : ∀ i → f (loop i) ≡ f base
proofAt i = begin
f (loop i) ≡⟨ cong (λ p → f (p i)) hyp ⟩
f (refl {x = base} i) ≡⟨⟩
f base ∎
```
)
but if I try to prove it for the whole thing:
```
proof : p ≡ refl
proof = begin
(λ i → p i) ≡⟨⟩
(λ i → f (loop i)) ≡⟨ (λ i → proofAt i) ⟩
(λ i → f base) ≡⟨⟩
(λ i → refl {x = x} i) ∎
```
it fails, I would think because of the "interval extensionality" I am trying to use:
>
> Cannot instantiate the metavariable `_342` to solution `f (loop i) ≡ f base` since it contains the variable `i` which is not in scope of the
> metavariable or irrelevant in the metavariable but relevant in the
> solution
>
>
> when checking that the expression `proofAt i` has type `_A_342`
>
>
>
trying to eta-convert it to just `proofAt_` also fails, but for a different reason (and I think there is, in general, no eta conversion for paths):
```
proof : p ≡ refl
proof = begin
(λ i → p i) ≡⟨⟩
(λ i → f (loop i)) ≡⟨ proofAt_ ⟩
(λ i → f base) ≡⟨⟩
(λ i → refl {x = x} i) ∎
```
>
> `((i : I) → f (loop i) ≡ f base)` !=< `_344 ≡ _y_345` of type
> `;Agda.Primitive.Setω`
>
>
>
So, what is the correct CTT transliteration of the above HoTT proof?
|
2018/11/25
|
[
"https://Stackoverflow.com/questions/53464314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/477476/"
] |
>
> Is this the correct way to import the jars?
>
>
>
*Yes*, include the log4j in the `dependency` section of the child `pom.xml`.
```
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version> <!-- version is optional when using dependency management -->
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
```
---
Also, make sure to refer the `parent` from the child as well, include the following in child `pom.xml` for that:
```
<parent>
<artifactId>testing.parent</artifactId>
<groupId>testing.group</groupId>
<version>1.0</version>
</parent>
```
ensuring the similar reference in the parent `pom.xml` as
```
<modules>
<module>testing.child</module>
</modules>
```
|
If you add below part to child pom.xml file, you don't need to import lof4j dependency separately though child pom.xml.
```
<parent>
<artifactId>testing.parent</artifactId>
<groupId>testing.group</groupId>
<version>1.0</version>
</parent>
```
|
63,207,013
|
I am a beginner of pytorch ,when i read the source code of a project about mask rcnn .I don't konw from where can i get some information about some methods that i don't understand .The official documentation doesn't seem very detailed?
```
# load an instance segmentation model pre-trained pre-trained on COCO
model = torchvision.models.detection.maskrcnn_resnet50_fpn(pretrained=True)
# get number of input features for the classifier
in_features = model.roi_heads.box_predictor.cls_score.in_features
# replace the pre-trained head with a new one
model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)
```
Just like code above ,I could not get detailed information about the " roi\_head" attribute from [doc](https://pytorch.org/docs/stable/torchvision/models.html#object-detection-instance-segmentation-and-person-keypoint-detection) of model .From where i can learn about it?
|
2020/08/01
|
[
"https://Stackoverflow.com/questions/63207013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14013952/"
] |
For this sort of thing, I find it helps to *draw* the commits. Of course, since you can't find the exact commit, you'll be stuck with drawing some approximation—but maybe that will help you find the right commits.
>
> I have a `master` branch and a `topic` branch which diverged from `master` at some "last common ancestor" commit.
>
>
>
So, let's draw that, as a sort of rough sketch:
```
...--c1--c2--c3--c4--m1--...--mn <-- master
\
t1--...--tn <-- topic
```
where the `c` commits are common to both branches, the `m` commits are only on `master`, and the `t` commits are only on `topic`. Commit `c4` is the last common one.
>
> I rewrote history on my master branch using `git rebase`, but forgot, that this included the commit that was the "last common ancestor" with my `topic` branch. In other words, if I now `git log` the `master branch`, I can't find the commit ID anymore of the "last common ancestor" commit with `topic`.
>
>
>
Since rebase works by *copying* commits, then moving the branch name to point to the last-copied commit, let's draw that now, using `'` suffixes to show the copied commits:
```
c2'-c3'-c4'-m1'-...--mn' <-- master
/
...--c1--c2--c3--c4--m1--...--mn [abandoned]
\
t1--...--tn <-- topic
```
While you *can* use `git log` on `topic` to find commit `c4`, it's not actually *shared* with `master` any more.
>
> I assume the "last common ancestor" commit hasn't been garbage collected yet, since it is still referenced by the `topic` branch. But it isn't part of the `master` branch anymore.
>
>
>
That's exactly right: while `m1-...-mn` are "abandoned", `c4` *isn't*. (Note that the hash IDs of these commits are probably in at least two reflogs: the one for `master`, and the one for `HEAD`. These reflog entries will keep the commits alive until the reflog entries themselves expire.)
>
> What happens now, if I now try to merge `topic` with `master`?
>
>
>
The merge operation will find the first actually-common commit, which is now `c1`, and diff the contents of `c1` (its snapshot) with the contents of `mn` (tip of master) to see what you changed on `master`, then diff `c1` with `tn` to see what you changed on `topic`. It will then combine the two changes and, if that's successful, make a merge commit on its own:
```
c2'-c3'-c4'-m1'-...--mn'
/ \
...--c1--c2--c3--c4 M <-- master (HEAD)
\ /
t1--...--tn <-- topic
```
(The abandoned commits are still in there if they haven't been GC-ed, but they were in the way so I stopped drawing them.) A `git log` of `master` will now show the duplicated `c4`-and-`c4'` commits, `c3`-and-`c3'`, and so on.
To eliminate them, find `c4` and `c4'` by some process—e.g., manual `git log` and eyeballing, or using `git cherry`, or using `git log --left-right --cherry-mark topic...master`, or whatever you like. Once you know where `c4` and `c4'` are, you can use the command [Omer suggested](https://stackoverflow.com/a/63207182/1256452):
```
git checkout topic
git rebase --onto master <hash-of-c4>
```
(or even just put `topic` on the end of the `git rebase` command, but I prefer not to do that - it's confusing to start on `master` and end on `topic`...).
|
I suggest you re-base topic on top of the new master using the `--onto` flag. You'll have to specify the point `topic` diverged from master. Find the "last common ancestor", I'll call it `abcd`. Now do this:
`git rebase --onto master abcd`
EDIT: Just realized you said you can't find that commit. That's very weird. Try going to the latest commit on `topic` and then follow the parents until you find that commit. It has to be there somewhere. Try using `git rev-list --parents topic`
|
63,207,013
|
I am a beginner of pytorch ,when i read the source code of a project about mask rcnn .I don't konw from where can i get some information about some methods that i don't understand .The official documentation doesn't seem very detailed?
```
# load an instance segmentation model pre-trained pre-trained on COCO
model = torchvision.models.detection.maskrcnn_resnet50_fpn(pretrained=True)
# get number of input features for the classifier
in_features = model.roi_heads.box_predictor.cls_score.in_features
# replace the pre-trained head with a new one
model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)
```
Just like code above ,I could not get detailed information about the " roi\_head" attribute from [doc](https://pytorch.org/docs/stable/torchvision/models.html#object-detection-instance-segmentation-and-person-keypoint-detection) of model .From where i can learn about it?
|
2020/08/01
|
[
"https://Stackoverflow.com/questions/63207013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14013952/"
] |
I suggest you re-base topic on top of the new master using the `--onto` flag. You'll have to specify the point `topic` diverged from master. Find the "last common ancestor", I'll call it `abcd`. Now do this:
`git rebase --onto master abcd`
EDIT: Just realized you said you can't find that commit. That's very weird. Try going to the latest commit on `topic` and then follow the parents until you find that commit. It has to be there somewhere. Try using `git rev-list --parents topic`
|
I am sure torek's response will have all the gory details... here's my short answer: find both the new and the old Id of that revision that was the common ancestor.
```
git rebase --onto new-id old-id topic
```
That is to get the branch at the position where it *was*.... but could also run
```
git rebase --onto master old-id topic
```
To put it on top of the new master branch
|
63,207,013
|
I am a beginner of pytorch ,when i read the source code of a project about mask rcnn .I don't konw from where can i get some information about some methods that i don't understand .The official documentation doesn't seem very detailed?
```
# load an instance segmentation model pre-trained pre-trained on COCO
model = torchvision.models.detection.maskrcnn_resnet50_fpn(pretrained=True)
# get number of input features for the classifier
in_features = model.roi_heads.box_predictor.cls_score.in_features
# replace the pre-trained head with a new one
model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)
```
Just like code above ,I could not get detailed information about the " roi\_head" attribute from [doc](https://pytorch.org/docs/stable/torchvision/models.html#object-detection-instance-segmentation-and-person-keypoint-detection) of model .From where i can learn about it?
|
2020/08/01
|
[
"https://Stackoverflow.com/questions/63207013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14013952/"
] |
For this sort of thing, I find it helps to *draw* the commits. Of course, since you can't find the exact commit, you'll be stuck with drawing some approximation—but maybe that will help you find the right commits.
>
> I have a `master` branch and a `topic` branch which diverged from `master` at some "last common ancestor" commit.
>
>
>
So, let's draw that, as a sort of rough sketch:
```
...--c1--c2--c3--c4--m1--...--mn <-- master
\
t1--...--tn <-- topic
```
where the `c` commits are common to both branches, the `m` commits are only on `master`, and the `t` commits are only on `topic`. Commit `c4` is the last common one.
>
> I rewrote history on my master branch using `git rebase`, but forgot, that this included the commit that was the "last common ancestor" with my `topic` branch. In other words, if I now `git log` the `master branch`, I can't find the commit ID anymore of the "last common ancestor" commit with `topic`.
>
>
>
Since rebase works by *copying* commits, then moving the branch name to point to the last-copied commit, let's draw that now, using `'` suffixes to show the copied commits:
```
c2'-c3'-c4'-m1'-...--mn' <-- master
/
...--c1--c2--c3--c4--m1--...--mn [abandoned]
\
t1--...--tn <-- topic
```
While you *can* use `git log` on `topic` to find commit `c4`, it's not actually *shared* with `master` any more.
>
> I assume the "last common ancestor" commit hasn't been garbage collected yet, since it is still referenced by the `topic` branch. But it isn't part of the `master` branch anymore.
>
>
>
That's exactly right: while `m1-...-mn` are "abandoned", `c4` *isn't*. (Note that the hash IDs of these commits are probably in at least two reflogs: the one for `master`, and the one for `HEAD`. These reflog entries will keep the commits alive until the reflog entries themselves expire.)
>
> What happens now, if I now try to merge `topic` with `master`?
>
>
>
The merge operation will find the first actually-common commit, which is now `c1`, and diff the contents of `c1` (its snapshot) with the contents of `mn` (tip of master) to see what you changed on `master`, then diff `c1` with `tn` to see what you changed on `topic`. It will then combine the two changes and, if that's successful, make a merge commit on its own:
```
c2'-c3'-c4'-m1'-...--mn'
/ \
...--c1--c2--c3--c4 M <-- master (HEAD)
\ /
t1--...--tn <-- topic
```
(The abandoned commits are still in there if they haven't been GC-ed, but they were in the way so I stopped drawing them.) A `git log` of `master` will now show the duplicated `c4`-and-`c4'` commits, `c3`-and-`c3'`, and so on.
To eliminate them, find `c4` and `c4'` by some process—e.g., manual `git log` and eyeballing, or using `git cherry`, or using `git log --left-right --cherry-mark topic...master`, or whatever you like. Once you know where `c4` and `c4'` are, you can use the command [Omer suggested](https://stackoverflow.com/a/63207182/1256452):
```
git checkout topic
git rebase --onto master <hash-of-c4>
```
(or even just put `topic` on the end of the `git rebase` command, but I prefer not to do that - it's confusing to start on `master` and end on `topic`...).
|
I am sure torek's response will have all the gory details... here's my short answer: find both the new and the old Id of that revision that was the common ancestor.
```
git rebase --onto new-id old-id topic
```
That is to get the branch at the position where it *was*.... but could also run
```
git rebase --onto master old-id topic
```
To put it on top of the new master branch
|
10,772,177
|
On iOS, if a view has several layers, then can the `drawRect` method just choose any one layer to display, and 1 second later, choose another layer to display, to achieve an animation effect?
Right now, I have several layers, but I don't think they are the view's layers (they are just individual layers which are not sublayers of parent layer), as I just created them using
```
CGLayerCreateWithContext(context, self.view.bounds.size, NULL);
```
and in `drawRect`, I use
```
CGContextDrawLayerAtPoint(context, self.bounds.origin, layer1);
```
to draw the layer onto the view... it works, but isn't this like drawing a layer onto a layer (drawing a layer onto the view's layer)? Isn't there a faster way, which is to tell the the view to use `layer1` or `layer2`, kind of like
```
self.layer = layer1;
```
but it can't because `layer` is read only. Can this be achieved?
|
2012/05/27
|
[
"https://Stackoverflow.com/questions/10772177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/325419/"
] |
If you know that the checkboxes are all on a form:
```
var list = new List<CheckBox>();
foreach(var control in this.Controls)
{
var checkBox = control as CheckBox;
if(checkBox != null)
{
list.Add(checkBox);
}
}
var checkBoxArray = list.ToArray();
```
If you don't know where the controls are then you will have to search for them.
BTW: The code above uses WinForms. If you are using WPF, Silverlight, Metro,... the container will be named differently.
|
You can't do new and then
```
checkboxarray = new CheckBox[] { txtChckBx0, ....}
```
it's two different ways to define an array.
you need to do:
```
CheckBox[] checkboxarray = { txtChckBx0, ....};
```
If you want it to work.
Good luck.
|
10,772,177
|
On iOS, if a view has several layers, then can the `drawRect` method just choose any one layer to display, and 1 second later, choose another layer to display, to achieve an animation effect?
Right now, I have several layers, but I don't think they are the view's layers (they are just individual layers which are not sublayers of parent layer), as I just created them using
```
CGLayerCreateWithContext(context, self.view.bounds.size, NULL);
```
and in `drawRect`, I use
```
CGContextDrawLayerAtPoint(context, self.bounds.origin, layer1);
```
to draw the layer onto the view... it works, but isn't this like drawing a layer onto a layer (drawing a layer onto the view's layer)? Isn't there a faster way, which is to tell the the view to use `layer1` or `layer2`, kind of like
```
self.layer = layer1;
```
but it can't because `layer` is read only. Can this be achieved?
|
2012/05/27
|
[
"https://Stackoverflow.com/questions/10772177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/325419/"
] |
If you know that the checkboxes are all on a form:
```
var list = new List<CheckBox>();
foreach(var control in this.Controls)
{
var checkBox = control as CheckBox;
if(checkBox != null)
{
list.Add(checkBox);
}
}
var checkBoxArray = list.ToArray();
```
If you don't know where the controls are then you will have to search for them.
BTW: The code above uses WinForms. If you are using WPF, Silverlight, Metro,... the container will be named differently.
|
In WinForm
```
List<CheckBox> checkBox = new List<CheckBox>();
// Adding checkboxes for testing...
for (int i = 0; i <= 80; i++)
{
var cbox = new CheckBox();
cbox.Name = "txtChckBx"+ i.ToString();
checkBox.Add(cbox);
Controls.Add(cbox);
}
List<CheckBox> checkBoxfound = new List<CheckBox>();
// loop though all the controls
foreach (var item in Controls)
{
// filter for checkboxes and name should start with "txtChckBx"
if (item is CheckBox && ((CheckBox)item).Name.StartsWith("txtChckBx", StringComparison.OrdinalIgnoreCase))
{
checkBoxfound.Add((CheckBox)item);
}
}
```
|
68,740
|
How I should check if a program is a virus in VMware? Some programs I do need admin ability to install and it makes sense. But how do I know if it's doing more than I want? Some thoughts are:
* How many processes open when I launch the application
* What is added to the startup tab in msconfig
* If any services are added.
That's pretty much all my ideas. Even if it does something I recognize I wouldn't know if it's necessary or not. What are some rule of thumb?
-Edit- What about registries, can I use that information to help? Maybe have a scanner tell me if the application I just used has messed with sections (like bootup) it shouldn't have?
|
2009/11/10
|
[
"https://superuser.com/questions/68740",
"https://superuser.com",
"https://superuser.com/users/-1/"
] |
Wireshark to monitor traffic, Process Explorer to monitor file and registry changes. Keep a "known good" snapshot to boot into every time to reduce possible contamination. Don't give it an internet connection if you don't have to.
|
Along the lines of your analysis (though, it's always safer to check where you downloaded it from and use local antivirus software),
1. Check for what network communications it attempts.
It's always fairly easy to enumerate what network activity is likely from the program description.
You can use the Sysinternals [TCPView](http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx) to follow it or just do frequent `netstat`.
Some Host antivirus/firewall tools also allow configuring a block for a process.
* Most malware focuses on 'corrupting' other applications on your system.
This means, just following the newly installed application will not be sufficient.
You need a way to detect when it starts playing with other executable files in your systems too.
|
68,740
|
How I should check if a program is a virus in VMware? Some programs I do need admin ability to install and it makes sense. But how do I know if it's doing more than I want? Some thoughts are:
* How many processes open when I launch the application
* What is added to the startup tab in msconfig
* If any services are added.
That's pretty much all my ideas. Even if it does something I recognize I wouldn't know if it's necessary or not. What are some rule of thumb?
-Edit- What about registries, can I use that information to help? Maybe have a scanner tell me if the application I just used has messed with sections (like bootup) it shouldn't have?
|
2009/11/10
|
[
"https://superuser.com/questions/68740",
"https://superuser.com",
"https://superuser.com/users/-1/"
] |
Run an outgoing firewall that prompts for new connections.
If the software attempts to make many outbound connections then it might be up to no good. A lot of software will check for updates either on initial start up or periodically, so you'll have to let the first one through. Don't check the "remember my answer for this application" option (one should exist) so you can see when the next time it "calls home".
This will also alert you to outgoing connection attempts from software you haven't directly launched - another sign that you've got some malware installed.
|
Along the lines of your analysis (though, it's always safer to check where you downloaded it from and use local antivirus software),
1. Check for what network communications it attempts.
It's always fairly easy to enumerate what network activity is likely from the program description.
You can use the Sysinternals [TCPView](http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx) to follow it or just do frequent `netstat`.
Some Host antivirus/firewall tools also allow configuring a block for a process.
* Most malware focuses on 'corrupting' other applications on your system.
This means, just following the newly installed application will not be sufficient.
You need a way to detect when it starts playing with other executable files in your systems too.
|
68,740
|
How I should check if a program is a virus in VMware? Some programs I do need admin ability to install and it makes sense. But how do I know if it's doing more than I want? Some thoughts are:
* How many processes open when I launch the application
* What is added to the startup tab in msconfig
* If any services are added.
That's pretty much all my ideas. Even if it does something I recognize I wouldn't know if it's necessary or not. What are some rule of thumb?
-Edit- What about registries, can I use that information to help? Maybe have a scanner tell me if the application I just used has messed with sections (like bootup) it shouldn't have?
|
2009/11/10
|
[
"https://superuser.com/questions/68740",
"https://superuser.com",
"https://superuser.com/users/-1/"
] |
Run an outgoing firewall that prompts for new connections.
If the software attempts to make many outbound connections then it might be up to no good. A lot of software will check for updates either on initial start up or periodically, so you'll have to let the first one through. Don't check the "remember my answer for this application" option (one should exist) so you can see when the next time it "calls home".
This will also alert you to outgoing connection attempts from software you haven't directly launched - another sign that you've got some malware installed.
|
Wireshark to monitor traffic, Process Explorer to monitor file and registry changes. Keep a "known good" snapshot to boot into every time to reduce possible contamination. Don't give it an internet connection if you don't have to.
|
42,826,388
|
I have time from epochs timestamps
I use `data.Time_req = pd.to_datetime(data.Time_req)`
But I get UTC time, I need +5:30 from the given time. How do I tell pandas to use `'IST'` timezone or just `5hrs 30 mins` further to the time it currently shows me. eg. `7 hrs` should become `12:30 hrs` and so on.
|
2017/03/16
|
[
"https://Stackoverflow.com/questions/42826388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1977867/"
] |
You can use [`tz_localize`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.tz_localize.html) to set the timezone to `UTC`/+0000, and then [`tz_convert`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.tz_convert.html) to add the timezone you want:
```
start = pd.to_datetime('2015-02-24')
rng = pd.date_range(start, periods=10)
df = pd.DataFrame({'Date': rng, 'a': range(10)})
df.Date = df.Date.dt.tz_localize('UTC').dt.tz_convert('Asia/Kolkata')
print (df)
Date a
0 2015-02-24 05:30:00+05:30 0
1 2015-02-25 05:30:00+05:30 1
2 2015-02-26 05:30:00+05:30 2
3 2015-02-27 05:30:00+05:30 3
4 2015-02-28 05:30:00+05:30 4
5 2015-03-01 05:30:00+05:30 5
6 2015-03-02 05:30:00+05:30 6
7 2015-03-03 05:30:00+05:30 7
8 2015-03-04 05:30:00+05:30 8
9 2015-03-05 05:30:00+05:30 9
```
[Working with time zones](http://pandas.pydata.org/pandas-docs/stable/timeseries.html#working-with-time-zones).
If need add `Timedelta` only:
```
df.Date = df.Date + pd.Timedelta('05:30:00')
print (df)
Date a
0 2015-02-24 05:30:00 0
1 2015-02-25 05:30:00 1
2 2015-02-26 05:30:00 2
3 2015-02-27 05:30:00 3
4 2015-02-28 05:30:00 4
5 2015-03-01 05:30:00 5
6 2015-03-02 05:30:00 6
7 2015-03-03 05:30:00 7
8 2015-03-04 05:30:00 8
9 2015-03-05 05:30:00 9
```
**NOTE:** Adding `Timedelta` will change the epoch timestamp associated with the `datetime` object. This may not be desired for many applications.
|
### From unix epoch timestamps
```
timestamps = [1656285319, 1656285336, 1656285424]
pd.to_datetime(timestamps, unit='s', utc=True).map(lambda x: x.tz_convert('Asia/Kolkata'))
```
outputs:
```
DatetimeIndex(['2022-06-27 04:45:19+05:30', '2022-06-27 04:45:36+05:30',
'2022-06-27 04:47:04+05:30'],
dtype='datetime64[ns, Asia/Kolkata]', freq=None)
```
#### All timezones
```
import pytz
pytz.all_timezones
```
[full list here](https://gist.github.com/eusoubrasileiro/2a442218ecf634ed5b5919a9783ddb7d)
|
42,826,388
|
I have time from epochs timestamps
I use `data.Time_req = pd.to_datetime(data.Time_req)`
But I get UTC time, I need +5:30 from the given time. How do I tell pandas to use `'IST'` timezone or just `5hrs 30 mins` further to the time it currently shows me. eg. `7 hrs` should become `12:30 hrs` and so on.
|
2017/03/16
|
[
"https://Stackoverflow.com/questions/42826388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1977867/"
] |
You can use [`tz_localize`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.tz_localize.html) to set the timezone to `UTC`/+0000, and then [`tz_convert`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.tz_convert.html) to add the timezone you want:
```
start = pd.to_datetime('2015-02-24')
rng = pd.date_range(start, periods=10)
df = pd.DataFrame({'Date': rng, 'a': range(10)})
df.Date = df.Date.dt.tz_localize('UTC').dt.tz_convert('Asia/Kolkata')
print (df)
Date a
0 2015-02-24 05:30:00+05:30 0
1 2015-02-25 05:30:00+05:30 1
2 2015-02-26 05:30:00+05:30 2
3 2015-02-27 05:30:00+05:30 3
4 2015-02-28 05:30:00+05:30 4
5 2015-03-01 05:30:00+05:30 5
6 2015-03-02 05:30:00+05:30 6
7 2015-03-03 05:30:00+05:30 7
8 2015-03-04 05:30:00+05:30 8
9 2015-03-05 05:30:00+05:30 9
```
[Working with time zones](http://pandas.pydata.org/pandas-docs/stable/timeseries.html#working-with-time-zones).
If need add `Timedelta` only:
```
df.Date = df.Date + pd.Timedelta('05:30:00')
print (df)
Date a
0 2015-02-24 05:30:00 0
1 2015-02-25 05:30:00 1
2 2015-02-26 05:30:00 2
3 2015-02-27 05:30:00 3
4 2015-02-28 05:30:00 4
5 2015-03-01 05:30:00 5
6 2015-03-02 05:30:00 6
7 2015-03-03 05:30:00 7
8 2015-03-04 05:30:00 8
9 2015-03-05 05:30:00 9
```
**NOTE:** Adding `Timedelta` will change the epoch timestamp associated with the `datetime` object. This may not be desired for many applications.
|
The following worked for me:
```
df['Local_Time'] = pd.to_datetime(df,unit='s', utc=True)\
.map(lambda x: x.tz_convert('America/Chicago'))
```
[This is the list of the name of timezones in pytz.](https://gist.github.com/heyalexej/8bf688fd67d7199be4a1682b3eec7568)
Hope this helps someone!
|
42,826,388
|
I have time from epochs timestamps
I use `data.Time_req = pd.to_datetime(data.Time_req)`
But I get UTC time, I need +5:30 from the given time. How do I tell pandas to use `'IST'` timezone or just `5hrs 30 mins` further to the time it currently shows me. eg. `7 hrs` should become `12:30 hrs` and so on.
|
2017/03/16
|
[
"https://Stackoverflow.com/questions/42826388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1977867/"
] |
### From unix epoch timestamps
```
timestamps = [1656285319, 1656285336, 1656285424]
pd.to_datetime(timestamps, unit='s', utc=True).map(lambda x: x.tz_convert('Asia/Kolkata'))
```
outputs:
```
DatetimeIndex(['2022-06-27 04:45:19+05:30', '2022-06-27 04:45:36+05:30',
'2022-06-27 04:47:04+05:30'],
dtype='datetime64[ns, Asia/Kolkata]', freq=None)
```
#### All timezones
```
import pytz
pytz.all_timezones
```
[full list here](https://gist.github.com/eusoubrasileiro/2a442218ecf634ed5b5919a9783ddb7d)
|
The following worked for me:
```
df['Local_Time'] = pd.to_datetime(df,unit='s', utc=True)\
.map(lambda x: x.tz_convert('America/Chicago'))
```
[This is the list of the name of timezones in pytz.](https://gist.github.com/heyalexej/8bf688fd67d7199be4a1682b3eec7568)
Hope this helps someone!
|
1,329,260
|
Can you compare two large exponential numbers, like $5^{44}$ and $4^{53}$ without taking their logs?
|
2015/06/17
|
[
"https://math.stackexchange.com/questions/1329260",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/223077/"
] |
One approach is to figure that, roughly, $2^{10} \approx 10^3$, and $5^9 \approx 2,000,000 = 2 \cdot 10^6$.
Then,
\begin{align}
4^{53} &= (2^2)^{53} \\
&= 2^{106} \\
&= 2^{100} \cdot 2^6 \\
&= (2^{10})^{10} \cdot 2^6 \\
&\approx (10^3)^{10} \cdot 2^6 \\
&= 10^{30} \cdot 2^6
\end{align}
By way of comparison,
\begin{align}
5^{44} &= 5^{45} \div 5 \\
&= (5^9)^5 \div 5 \\
&\approx (2 \cdot 10^6)^5 \div 5 \\
&= 2^5 \cdot (10^6)^5 \div 5 \\
&= 10^{30} \cdot (2^5 \div 5).
\end{align}
Now, $2^6 > 2^5 \div 5$, so one might suppose $4^{53} > 5^{44}$.
|
I'll interpret the actual question as "without using a calculator?" since I assume that's your objection to using logs.
What I know about $5$ and $4$ is that $5^3 = 125$ is pretty close to but a bit smaller than $2^7 = 128$. That tells me that $\log\_2 5 \le\frac{7}{3}$, hence that
$$\log\_2 5^{44} \le \frac{308}{3} < 103$$
while $\log\_2 4^{53} = 106$. So $4^{53}$ is bigger. Of course I could rephrase this argument without using logs by exponentiating everything but what's the point?
A calculator will verify that $\frac{7}{3}$ is in fact a [convergent](http://mathworld.wolfram.com/Convergent.html) of $\log\_2 5$, whose continued fraction approximation begins $2 + \frac{1}{3 + \frac{1}{9 + \dots}}$. So the above is a pretty close approximation; in fact the true value of $\log\_2 5^{44}$ is $102.164 \dots$.
|
1,329,260
|
Can you compare two large exponential numbers, like $5^{44}$ and $4^{53}$ without taking their logs?
|
2015/06/17
|
[
"https://math.stackexchange.com/questions/1329260",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/223077/"
] |
$$5^{44}<5^{45}=(5^3)^{15}=125^{15}<128^{15}=(256/2)^{15}=4^{60}/2^{15}<4^{53}$$ (because $2^{15}>2^{14}=4^{7}$)
|
One approach is to figure that, roughly, $2^{10} \approx 10^3$, and $5^9 \approx 2,000,000 = 2 \cdot 10^6$.
Then,
\begin{align}
4^{53} &= (2^2)^{53} \\
&= 2^{106} \\
&= 2^{100} \cdot 2^6 \\
&= (2^{10})^{10} \cdot 2^6 \\
&\approx (10^3)^{10} \cdot 2^6 \\
&= 10^{30} \cdot 2^6
\end{align}
By way of comparison,
\begin{align}
5^{44} &= 5^{45} \div 5 \\
&= (5^9)^5 \div 5 \\
&\approx (2 \cdot 10^6)^5 \div 5 \\
&= 2^5 \cdot (10^6)^5 \div 5 \\
&= 10^{30} \cdot (2^5 \div 5).
\end{align}
Now, $2^6 > 2^5 \div 5$, so one might suppose $4^{53} > 5^{44}$.
|
1,329,260
|
Can you compare two large exponential numbers, like $5^{44}$ and $4^{53}$ without taking their logs?
|
2015/06/17
|
[
"https://math.stackexchange.com/questions/1329260",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/223077/"
] |
One approach is to figure that, roughly, $2^{10} \approx 10^3$, and $5^9 \approx 2,000,000 = 2 \cdot 10^6$.
Then,
\begin{align}
4^{53} &= (2^2)^{53} \\
&= 2^{106} \\
&= 2^{100} \cdot 2^6 \\
&= (2^{10})^{10} \cdot 2^6 \\
&\approx (10^3)^{10} \cdot 2^6 \\
&= 10^{30} \cdot 2^6
\end{align}
By way of comparison,
\begin{align}
5^{44} &= 5^{45} \div 5 \\
&= (5^9)^5 \div 5 \\
&\approx (2 \cdot 10^6)^5 \div 5 \\
&= 2^5 \cdot (10^6)^5 \div 5 \\
&= 10^{30} \cdot (2^5 \div 5).
\end{align}
Now, $2^6 > 2^5 \div 5$, so one might suppose $4^{53} > 5^{44}$.
|
[Binomial expansion](https://en.wikipedia.org/wiki/Binomial_theorem) can help.
$$ (x+y) = \sum\_{k=0}^n\frac{n!}{k!(n-k)!}x^{n-k}y^k $$
In this case, x = 4, y = 1, which simplifies
For massive expansion like you have, you really only need to look at the first few terms (although with a low x and a big exponent, extra terms are advised. In this case:
$$ (4+1)^{44} \sim 4^{44} + 44\times4^{43} + \frac{44\times43}{2} \times 4^{42} + \frac{44\times43\times42}{6}\times 4^{41} + \frac{44\times43\times42\times41}{24}\times4^{40} + \frac{44\times43\times42\times41\times40}{120}\times4^{39} + \frac{44\times43\times42\times41\times40\times39}{720}\times4^{38} + \frac{44\times43\times42\times41\times40\times39\times38}{5040}\times4^{37} + \frac{44\times43\times42\times41\times40\times39\times38\times37}{40320}\times4^{36} + \frac{44\times43\times42\times41\times40\times39\times38\times37\times36}{362880}\times4^{35} + \frac{44\times43\times42\times41\times40\times39\times38\times37\times36\times35}{3628800}\times4^{34}$$
As the 4 terms get smaller, their relevance begin to diminish, and you can start to see the real relevance. So, $5^{44}$ is about $(1 + 11 + 50 + 170 + 416 + 833 + 1388 + 1984 + 2480 + 2755 + 2755 + ...) \times 4^{44} $ for that $5^{44}$. Adding them up, you see since $4^{53}/4^{44} = {4}^9 = 262144 $, which is WAY bigger than even a bunch of 2755s put together that $4^{53}$ is bigger.
|
1,329,260
|
Can you compare two large exponential numbers, like $5^{44}$ and $4^{53}$ without taking their logs?
|
2015/06/17
|
[
"https://math.stackexchange.com/questions/1329260",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/223077/"
] |
Using a GCD-like approach, start by dividing out the "smaller" term:
$${5^{44}\over 4^{44}}=\left(\frac54\right)^{44}\\
{4^{53}\over 4^{44}}=4^9$$
Now the new "smaller" term is $\frac54$:
$${\left(\frac54\right)^{44}\over \left(\frac54\right)^{18}}=\left(\frac54\right)^{26}\\
{4^9\over \left(\frac54\right)^{18}}=\left(\frac85\right)^{18}\\
\left(\frac54\right)^{8}\text{ vs }\left(\frac{32}{25}\right)^{18}$$
By inspection, $\frac{32}{25}\ge\frac54$, and as the exponent on $\frac{32}{25}$ is also greater, it is the greater quantity. It is from the $4^{53}$ term, and therefore this is the greater original quantity.
|
One approach is to figure that, roughly, $2^{10} \approx 10^3$, and $5^9 \approx 2,000,000 = 2 \cdot 10^6$.
Then,
\begin{align}
4^{53} &= (2^2)^{53} \\
&= 2^{106} \\
&= 2^{100} \cdot 2^6 \\
&= (2^{10})^{10} \cdot 2^6 \\
&\approx (10^3)^{10} \cdot 2^6 \\
&= 10^{30} \cdot 2^6
\end{align}
By way of comparison,
\begin{align}
5^{44} &= 5^{45} \div 5 \\
&= (5^9)^5 \div 5 \\
&\approx (2 \cdot 10^6)^5 \div 5 \\
&= 2^5 \cdot (10^6)^5 \div 5 \\
&= 10^{30} \cdot (2^5 \div 5).
\end{align}
Now, $2^6 > 2^5 \div 5$, so one might suppose $4^{53} > 5^{44}$.
|
1,329,260
|
Can you compare two large exponential numbers, like $5^{44}$ and $4^{53}$ without taking their logs?
|
2015/06/17
|
[
"https://math.stackexchange.com/questions/1329260",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/223077/"
] |
$$5^{44}<5^{45}=(5^3)^{15}=125^{15}<128^{15}=(256/2)^{15}=4^{60}/2^{15}<4^{53}$$ (because $2^{15}>2^{14}=4^{7}$)
|
I'll interpret the actual question as "without using a calculator?" since I assume that's your objection to using logs.
What I know about $5$ and $4$ is that $5^3 = 125$ is pretty close to but a bit smaller than $2^7 = 128$. That tells me that $\log\_2 5 \le\frac{7}{3}$, hence that
$$\log\_2 5^{44} \le \frac{308}{3} < 103$$
while $\log\_2 4^{53} = 106$. So $4^{53}$ is bigger. Of course I could rephrase this argument without using logs by exponentiating everything but what's the point?
A calculator will verify that $\frac{7}{3}$ is in fact a [convergent](http://mathworld.wolfram.com/Convergent.html) of $\log\_2 5$, whose continued fraction approximation begins $2 + \frac{1}{3 + \frac{1}{9 + \dots}}$. So the above is a pretty close approximation; in fact the true value of $\log\_2 5^{44}$ is $102.164 \dots$.
|
1,329,260
|
Can you compare two large exponential numbers, like $5^{44}$ and $4^{53}$ without taking their logs?
|
2015/06/17
|
[
"https://math.stackexchange.com/questions/1329260",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/223077/"
] |
Using a GCD-like approach, start by dividing out the "smaller" term:
$${5^{44}\over 4^{44}}=\left(\frac54\right)^{44}\\
{4^{53}\over 4^{44}}=4^9$$
Now the new "smaller" term is $\frac54$:
$${\left(\frac54\right)^{44}\over \left(\frac54\right)^{18}}=\left(\frac54\right)^{26}\\
{4^9\over \left(\frac54\right)^{18}}=\left(\frac85\right)^{18}\\
\left(\frac54\right)^{8}\text{ vs }\left(\frac{32}{25}\right)^{18}$$
By inspection, $\frac{32}{25}\ge\frac54$, and as the exponent on $\frac{32}{25}$ is also greater, it is the greater quantity. It is from the $4^{53}$ term, and therefore this is the greater original quantity.
|
I'll interpret the actual question as "without using a calculator?" since I assume that's your objection to using logs.
What I know about $5$ and $4$ is that $5^3 = 125$ is pretty close to but a bit smaller than $2^7 = 128$. That tells me that $\log\_2 5 \le\frac{7}{3}$, hence that
$$\log\_2 5^{44} \le \frac{308}{3} < 103$$
while $\log\_2 4^{53} = 106$. So $4^{53}$ is bigger. Of course I could rephrase this argument without using logs by exponentiating everything but what's the point?
A calculator will verify that $\frac{7}{3}$ is in fact a [convergent](http://mathworld.wolfram.com/Convergent.html) of $\log\_2 5$, whose continued fraction approximation begins $2 + \frac{1}{3 + \frac{1}{9 + \dots}}$. So the above is a pretty close approximation; in fact the true value of $\log\_2 5^{44}$ is $102.164 \dots$.
|
1,329,260
|
Can you compare two large exponential numbers, like $5^{44}$ and $4^{53}$ without taking their logs?
|
2015/06/17
|
[
"https://math.stackexchange.com/questions/1329260",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/223077/"
] |
$$5^{44}<5^{45}=(5^3)^{15}=125^{15}<128^{15}=(256/2)^{15}=4^{60}/2^{15}<4^{53}$$ (because $2^{15}>2^{14}=4^{7}$)
|
[Binomial expansion](https://en.wikipedia.org/wiki/Binomial_theorem) can help.
$$ (x+y) = \sum\_{k=0}^n\frac{n!}{k!(n-k)!}x^{n-k}y^k $$
In this case, x = 4, y = 1, which simplifies
For massive expansion like you have, you really only need to look at the first few terms (although with a low x and a big exponent, extra terms are advised. In this case:
$$ (4+1)^{44} \sim 4^{44} + 44\times4^{43} + \frac{44\times43}{2} \times 4^{42} + \frac{44\times43\times42}{6}\times 4^{41} + \frac{44\times43\times42\times41}{24}\times4^{40} + \frac{44\times43\times42\times41\times40}{120}\times4^{39} + \frac{44\times43\times42\times41\times40\times39}{720}\times4^{38} + \frac{44\times43\times42\times41\times40\times39\times38}{5040}\times4^{37} + \frac{44\times43\times42\times41\times40\times39\times38\times37}{40320}\times4^{36} + \frac{44\times43\times42\times41\times40\times39\times38\times37\times36}{362880}\times4^{35} + \frac{44\times43\times42\times41\times40\times39\times38\times37\times36\times35}{3628800}\times4^{34}$$
As the 4 terms get smaller, their relevance begin to diminish, and you can start to see the real relevance. So, $5^{44}$ is about $(1 + 11 + 50 + 170 + 416 + 833 + 1388 + 1984 + 2480 + 2755 + 2755 + ...) \times 4^{44} $ for that $5^{44}$. Adding them up, you see since $4^{53}/4^{44} = {4}^9 = 262144 $, which is WAY bigger than even a bunch of 2755s put together that $4^{53}$ is bigger.
|
1,329,260
|
Can you compare two large exponential numbers, like $5^{44}$ and $4^{53}$ without taking their logs?
|
2015/06/17
|
[
"https://math.stackexchange.com/questions/1329260",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/223077/"
] |
Using a GCD-like approach, start by dividing out the "smaller" term:
$${5^{44}\over 4^{44}}=\left(\frac54\right)^{44}\\
{4^{53}\over 4^{44}}=4^9$$
Now the new "smaller" term is $\frac54$:
$${\left(\frac54\right)^{44}\over \left(\frac54\right)^{18}}=\left(\frac54\right)^{26}\\
{4^9\over \left(\frac54\right)^{18}}=\left(\frac85\right)^{18}\\
\left(\frac54\right)^{8}\text{ vs }\left(\frac{32}{25}\right)^{18}$$
By inspection, $\frac{32}{25}\ge\frac54$, and as the exponent on $\frac{32}{25}$ is also greater, it is the greater quantity. It is from the $4^{53}$ term, and therefore this is the greater original quantity.
|
[Binomial expansion](https://en.wikipedia.org/wiki/Binomial_theorem) can help.
$$ (x+y) = \sum\_{k=0}^n\frac{n!}{k!(n-k)!}x^{n-k}y^k $$
In this case, x = 4, y = 1, which simplifies
For massive expansion like you have, you really only need to look at the first few terms (although with a low x and a big exponent, extra terms are advised. In this case:
$$ (4+1)^{44} \sim 4^{44} + 44\times4^{43} + \frac{44\times43}{2} \times 4^{42} + \frac{44\times43\times42}{6}\times 4^{41} + \frac{44\times43\times42\times41}{24}\times4^{40} + \frac{44\times43\times42\times41\times40}{120}\times4^{39} + \frac{44\times43\times42\times41\times40\times39}{720}\times4^{38} + \frac{44\times43\times42\times41\times40\times39\times38}{5040}\times4^{37} + \frac{44\times43\times42\times41\times40\times39\times38\times37}{40320}\times4^{36} + \frac{44\times43\times42\times41\times40\times39\times38\times37\times36}{362880}\times4^{35} + \frac{44\times43\times42\times41\times40\times39\times38\times37\times36\times35}{3628800}\times4^{34}$$
As the 4 terms get smaller, their relevance begin to diminish, and you can start to see the real relevance. So, $5^{44}$ is about $(1 + 11 + 50 + 170 + 416 + 833 + 1388 + 1984 + 2480 + 2755 + 2755 + ...) \times 4^{44} $ for that $5^{44}$. Adding them up, you see since $4^{53}/4^{44} = {4}^9 = 262144 $, which is WAY bigger than even a bunch of 2755s put together that $4^{53}$ is bigger.
|
70,625,715
|
Is there a module in python to get integers from string in given range (with limit/restriction) ?
It can be useful to make code cleaner.
```
def get_int_from_str(string: str, low_boundary: int = 0, high_boundary: int = 100) -> int | bool: # (or False directly)
try:
number = int("".join(filter(str.isdigit, string)))
if low_boundary < number < high_boundary:
return number
else:
return False
except ValueError: # Empty message or out of limit
return False
```
Usage:
```
...
if not amount := get_int_from_str(string=input(), low_boundary = 10, high_boundary = 20)
...
...
```
|
2022/01/07
|
[
"https://Stackoverflow.com/questions/70625715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14190526/"
] |
Don't fight exceptions. If you can't parse a string as an integer, let the `ValueError` be raised. If the number is out of range, raise a different `ValueError`. Otherwise, return a value that is *guaranteed* to be in the requested range.
```
def get_int_from_str(string: str, low_boundary: int = 0, high_boundary: int = 100) -> int:
x = int(str) # May raise
if x < low_boundary or x > high_boundary:
raise ValueError(f"Value '{x}' is out of range {low_boundary}-{high_boundary}")
return x
```
The caller knows better than your function what to do if the string cannot produce an in-range integer, and raising an exception *forces* them to consider the worst-case scenario, rather than letting them assume the function worked and encountering an error later.
---
As a conventional alternative, you can return `None` to indicate the lack of a suitable `int` value. Unlike `False`, `None` cannot be confused with `0`, but it can still be ignored altogether to cause problems later. (And `None` by itself doesn't tell you if the string wasn't parseable or if the parsed number was simply out of range.)
```
def get_int_from_str(string: str, low_boundary: int = 0, high_boundary: int = 100) -> Optional[int]:
try:
x = int(str)
except ValueError:
return None
if x < low_boundary or x > high_boundary:
return None
return x
```
or, to avoid repeating the `return None` statement:
```
def get_int_from_str(string: str, low_boundary: int = 0, high_boundary: int = 100) -> Optional[int]:
try:
x = int(str)
if x < low_boundary or x > high_boundary:
raise ValueError
except ValueError:
return None
return x
```
|
```
def get_int_from_str(string: str, low_boundary: int = 0, high_boundary: int = 100) -> int | False:
number = "".join(filter(str.isdigit, string))
if number:
number = int(number)
if low_boundary < number < high_boundary:
return number
return False
```
Note: Using not operator with the output of the function does not distinguish between `False` and `0` as `not False` and `not 0` will evaluate to `True`. Here you can differentiate by checking the output with `amount is not False` condition.
|
15,623,951
|
Yes, I have read the EXCELLENT explanations that there are at Stackoverflow about the NPE, and I have understood what they meant. Yet, I found (I think I found) an issue about this NPE in one of the sample exercises on that textbook, that in fact, I used at Harvard long long time ago.
It is about the reference variable String line = null; as the explanations say, no object has been created while it is later on tried to be used as such (so I think), more precisely is tried to be accesed when line = inputStream.nextLine( );. Here is the code and the question is how to fix that. I have tried instantianting an object but...not worked.
```
package test;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.FileOutputStream;
public class Test
{
public static void main(String[] args) {
Scanner inputStream = null;
PrintWriter outputStream = null;
try {
inputStream = new Scanner(new FileInputStream("original.txt"));
outputStream = new PrintWriter(
new FileOutputStream("numbered.txt"));
} catch (FileNotFoundException e) {
System.out.println("Problem opening files.");
System.exit(0);
}
String line = null;
int count = 0;
while (inputStream.hasNextLine()) {
line = inputStream.nextLine();
count++;
outputStream.println(count + " " + line.toString());
}
inputStream.close();
outputStream.close();
}
}
```
And yes, I tried to run it. I copied and pasted the code on a newly created project on Netbeans 7.3
|
2013/03/25
|
[
"https://Stackoverflow.com/questions/15623951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1961282/"
] |
Following code works for me.
Setting autofocus (preview class):
```
Parameters params = camera.getParameters();
params.setFocusMode(Parameters.FOCUS_MODE_AUTO);
//some more settings
camera.setParameters(params);
```
Call camera for shot a picture in case that autofocus is ready (activity class):
```
public void butClick(View v){
preview.camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
if(success){
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
}
});
}
```
Get picture (activity class):
```
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
//do something
}
};
```
|
you can try code:
```
ShutterCallback _pfnShutterCallback = new ShutterCallback() {
@Override
public void onShutter() {
// TODO Auto-generated method stub
}
};
PictureCallback _pfnRawPictureCallback = new PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
}
};
private AutoFocusCallback _pfnAutoFocusCallback = new AutoFocusCallback() {
@Override
public void onAutoFocus(boolean success, Camera camera) {
// TODO Auto-generated method stub
camera.autoFocus(null);
camera.takePicture(_pfnShutterCallback, _pfnRawPictureCallback,
mPicture);
}
};
private PictureCallback mPicture = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
new SavePhotoTask().execute(data);
camera.startPreview();
}
};
class SavePhotoTask extends AsyncTask<byte[], String, String> {
// Process save file image
}
```
call capture : `mCamera.autoFocus(autoFocusCallback);`
You can refer at:
<http://android-er.blogspot.com/2011/01/start-camera-auto-focusing-autofocus.html>
|
15,623,951
|
Yes, I have read the EXCELLENT explanations that there are at Stackoverflow about the NPE, and I have understood what they meant. Yet, I found (I think I found) an issue about this NPE in one of the sample exercises on that textbook, that in fact, I used at Harvard long long time ago.
It is about the reference variable String line = null; as the explanations say, no object has been created while it is later on tried to be used as such (so I think), more precisely is tried to be accesed when line = inputStream.nextLine( );. Here is the code and the question is how to fix that. I have tried instantianting an object but...not worked.
```
package test;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.FileOutputStream;
public class Test
{
public static void main(String[] args) {
Scanner inputStream = null;
PrintWriter outputStream = null;
try {
inputStream = new Scanner(new FileInputStream("original.txt"));
outputStream = new PrintWriter(
new FileOutputStream("numbered.txt"));
} catch (FileNotFoundException e) {
System.out.println("Problem opening files.");
System.exit(0);
}
String line = null;
int count = 0;
while (inputStream.hasNextLine()) {
line = inputStream.nextLine();
count++;
outputStream.println(count + " " + line.toString());
}
inputStream.close();
outputStream.close();
}
}
```
And yes, I tried to run it. I copied and pasted the code on a newly created project on Netbeans 7.3
|
2013/03/25
|
[
"https://Stackoverflow.com/questions/15623951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1961282/"
] |
For me this worked a treat:
```
//set camera to continually auto-focus
Camera.Parameters params = c.getParameters();
//*EDIT*//params.setFocusMode("continuous-picture");
//It is better to use defined constraints as opposed to String, thanks to AbdelHady
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
c.setParameters(params);
```
|
Looks like you should [continuous autofocus](http://developer.android.com/reference/android/hardware/Camera.Parameters.html#FOCUS_MODE_CONTINUOUS_VIDEO) as is discussed here.
There is a [question here](https://stackoverflow.com/questions/5878042/android-camera-autofocus-on-demand) that you can reference.
|
15,623,951
|
Yes, I have read the EXCELLENT explanations that there are at Stackoverflow about the NPE, and I have understood what they meant. Yet, I found (I think I found) an issue about this NPE in one of the sample exercises on that textbook, that in fact, I used at Harvard long long time ago.
It is about the reference variable String line = null; as the explanations say, no object has been created while it is later on tried to be used as such (so I think), more precisely is tried to be accesed when line = inputStream.nextLine( );. Here is the code and the question is how to fix that. I have tried instantianting an object but...not worked.
```
package test;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.FileOutputStream;
public class Test
{
public static void main(String[] args) {
Scanner inputStream = null;
PrintWriter outputStream = null;
try {
inputStream = new Scanner(new FileInputStream("original.txt"));
outputStream = new PrintWriter(
new FileOutputStream("numbered.txt"));
} catch (FileNotFoundException e) {
System.out.println("Problem opening files.");
System.exit(0);
}
String line = null;
int count = 0;
while (inputStream.hasNextLine()) {
line = inputStream.nextLine();
count++;
outputStream.println(count + " " + line.toString());
}
inputStream.close();
outputStream.close();
}
}
```
And yes, I tried to run it. I copied and pasted the code on a newly created project on Netbeans 7.3
|
2013/03/25
|
[
"https://Stackoverflow.com/questions/15623951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1961282/"
] |
Looks like you should [continuous autofocus](http://developer.android.com/reference/android/hardware/Camera.Parameters.html#FOCUS_MODE_CONTINUOUS_VIDEO) as is discussed here.
There is a [question here](https://stackoverflow.com/questions/5878042/android-camera-autofocus-on-demand) that you can reference.
|
you can try code:
```
ShutterCallback _pfnShutterCallback = new ShutterCallback() {
@Override
public void onShutter() {
// TODO Auto-generated method stub
}
};
PictureCallback _pfnRawPictureCallback = new PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
}
};
private AutoFocusCallback _pfnAutoFocusCallback = new AutoFocusCallback() {
@Override
public void onAutoFocus(boolean success, Camera camera) {
// TODO Auto-generated method stub
camera.autoFocus(null);
camera.takePicture(_pfnShutterCallback, _pfnRawPictureCallback,
mPicture);
}
};
private PictureCallback mPicture = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
new SavePhotoTask().execute(data);
camera.startPreview();
}
};
class SavePhotoTask extends AsyncTask<byte[], String, String> {
// Process save file image
}
```
call capture : `mCamera.autoFocus(autoFocusCallback);`
You can refer at:
<http://android-er.blogspot.com/2011/01/start-camera-auto-focusing-autofocus.html>
|
15,623,951
|
Yes, I have read the EXCELLENT explanations that there are at Stackoverflow about the NPE, and I have understood what they meant. Yet, I found (I think I found) an issue about this NPE in one of the sample exercises on that textbook, that in fact, I used at Harvard long long time ago.
It is about the reference variable String line = null; as the explanations say, no object has been created while it is later on tried to be used as such (so I think), more precisely is tried to be accesed when line = inputStream.nextLine( );. Here is the code and the question is how to fix that. I have tried instantianting an object but...not worked.
```
package test;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.FileOutputStream;
public class Test
{
public static void main(String[] args) {
Scanner inputStream = null;
PrintWriter outputStream = null;
try {
inputStream = new Scanner(new FileInputStream("original.txt"));
outputStream = new PrintWriter(
new FileOutputStream("numbered.txt"));
} catch (FileNotFoundException e) {
System.out.println("Problem opening files.");
System.exit(0);
}
String line = null;
int count = 0;
while (inputStream.hasNextLine()) {
line = inputStream.nextLine();
count++;
outputStream.println(count + " " + line.toString());
}
inputStream.close();
outputStream.close();
}
}
```
And yes, I tried to run it. I copied and pasted the code on a newly created project on Netbeans 7.3
|
2013/03/25
|
[
"https://Stackoverflow.com/questions/15623951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1961282/"
] |
Try to use `Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO` or `Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE`.
See below:
```
Camera.Parameters params = camera.getParameters();
if (params.getSupportedFocusModes().contains(
Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
}
camera.setParameters(params);
```
It's important to test whether the phone is supporting your chosen mode before attempting to use it, otherwise `setParameters()` will throw a runtime exception.
(Edit code now working properly)
|
you can try code:
```
ShutterCallback _pfnShutterCallback = new ShutterCallback() {
@Override
public void onShutter() {
// TODO Auto-generated method stub
}
};
PictureCallback _pfnRawPictureCallback = new PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
}
};
private AutoFocusCallback _pfnAutoFocusCallback = new AutoFocusCallback() {
@Override
public void onAutoFocus(boolean success, Camera camera) {
// TODO Auto-generated method stub
camera.autoFocus(null);
camera.takePicture(_pfnShutterCallback, _pfnRawPictureCallback,
mPicture);
}
};
private PictureCallback mPicture = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
new SavePhotoTask().execute(data);
camera.startPreview();
}
};
class SavePhotoTask extends AsyncTask<byte[], String, String> {
// Process save file image
}
```
call capture : `mCamera.autoFocus(autoFocusCallback);`
You can refer at:
<http://android-er.blogspot.com/2011/01/start-camera-auto-focusing-autofocus.html>
|
15,623,951
|
Yes, I have read the EXCELLENT explanations that there are at Stackoverflow about the NPE, and I have understood what they meant. Yet, I found (I think I found) an issue about this NPE in one of the sample exercises on that textbook, that in fact, I used at Harvard long long time ago.
It is about the reference variable String line = null; as the explanations say, no object has been created while it is later on tried to be used as such (so I think), more precisely is tried to be accesed when line = inputStream.nextLine( );. Here is the code and the question is how to fix that. I have tried instantianting an object but...not worked.
```
package test;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.FileOutputStream;
public class Test
{
public static void main(String[] args) {
Scanner inputStream = null;
PrintWriter outputStream = null;
try {
inputStream = new Scanner(new FileInputStream("original.txt"));
outputStream = new PrintWriter(
new FileOutputStream("numbered.txt"));
} catch (FileNotFoundException e) {
System.out.println("Problem opening files.");
System.exit(0);
}
String line = null;
int count = 0;
while (inputStream.hasNextLine()) {
line = inputStream.nextLine();
count++;
outputStream.println(count + " " + line.toString());
}
inputStream.close();
outputStream.close();
}
}
```
And yes, I tried to run it. I copied and pasted the code on a newly created project on Netbeans 7.3
|
2013/03/25
|
[
"https://Stackoverflow.com/questions/15623951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1961282/"
] |
This works perfectly for preview callback:
```
Camera.Parameters parameters = camera.getParameters();
if (parameters.getSupportedFocusModes().contains(
Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
}
camera.setParameters(parameters);
```
|
you can try code:
```
ShutterCallback _pfnShutterCallback = new ShutterCallback() {
@Override
public void onShutter() {
// TODO Auto-generated method stub
}
};
PictureCallback _pfnRawPictureCallback = new PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
}
};
private AutoFocusCallback _pfnAutoFocusCallback = new AutoFocusCallback() {
@Override
public void onAutoFocus(boolean success, Camera camera) {
// TODO Auto-generated method stub
camera.autoFocus(null);
camera.takePicture(_pfnShutterCallback, _pfnRawPictureCallback,
mPicture);
}
};
private PictureCallback mPicture = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
new SavePhotoTask().execute(data);
camera.startPreview();
}
};
class SavePhotoTask extends AsyncTask<byte[], String, String> {
// Process save file image
}
```
call capture : `mCamera.autoFocus(autoFocusCallback);`
You can refer at:
<http://android-er.blogspot.com/2011/01/start-camera-auto-focusing-autofocus.html>
|
15,623,951
|
Yes, I have read the EXCELLENT explanations that there are at Stackoverflow about the NPE, and I have understood what they meant. Yet, I found (I think I found) an issue about this NPE in one of the sample exercises on that textbook, that in fact, I used at Harvard long long time ago.
It is about the reference variable String line = null; as the explanations say, no object has been created while it is later on tried to be used as such (so I think), more precisely is tried to be accesed when line = inputStream.nextLine( );. Here is the code and the question is how to fix that. I have tried instantianting an object but...not worked.
```
package test;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.FileOutputStream;
public class Test
{
public static void main(String[] args) {
Scanner inputStream = null;
PrintWriter outputStream = null;
try {
inputStream = new Scanner(new FileInputStream("original.txt"));
outputStream = new PrintWriter(
new FileOutputStream("numbered.txt"));
} catch (FileNotFoundException e) {
System.out.println("Problem opening files.");
System.exit(0);
}
String line = null;
int count = 0;
while (inputStream.hasNextLine()) {
line = inputStream.nextLine();
count++;
outputStream.println(count + " " + line.toString());
}
inputStream.close();
outputStream.close();
}
}
```
And yes, I tried to run it. I copied and pasted the code on a newly created project on Netbeans 7.3
|
2013/03/25
|
[
"https://Stackoverflow.com/questions/15623951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1961282/"
] |
Following code works for me.
Setting autofocus (preview class):
```
Parameters params = camera.getParameters();
params.setFocusMode(Parameters.FOCUS_MODE_AUTO);
//some more settings
camera.setParameters(params);
```
Call camera for shot a picture in case that autofocus is ready (activity class):
```
public void butClick(View v){
preview.camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
if(success){
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
}
});
}
```
Get picture (activity class):
```
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
//do something
}
};
```
|
This works perfectly for preview callback:
```
Camera.Parameters parameters = camera.getParameters();
if (parameters.getSupportedFocusModes().contains(
Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
}
camera.setParameters(parameters);
```
|
15,623,951
|
Yes, I have read the EXCELLENT explanations that there are at Stackoverflow about the NPE, and I have understood what they meant. Yet, I found (I think I found) an issue about this NPE in one of the sample exercises on that textbook, that in fact, I used at Harvard long long time ago.
It is about the reference variable String line = null; as the explanations say, no object has been created while it is later on tried to be used as such (so I think), more precisely is tried to be accesed when line = inputStream.nextLine( );. Here is the code and the question is how to fix that. I have tried instantianting an object but...not worked.
```
package test;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.FileOutputStream;
public class Test
{
public static void main(String[] args) {
Scanner inputStream = null;
PrintWriter outputStream = null;
try {
inputStream = new Scanner(new FileInputStream("original.txt"));
outputStream = new PrintWriter(
new FileOutputStream("numbered.txt"));
} catch (FileNotFoundException e) {
System.out.println("Problem opening files.");
System.exit(0);
}
String line = null;
int count = 0;
while (inputStream.hasNextLine()) {
line = inputStream.nextLine();
count++;
outputStream.println(count + " " + line.toString());
}
inputStream.close();
outputStream.close();
}
}
```
And yes, I tried to run it. I copied and pasted the code on a newly created project on Netbeans 7.3
|
2013/03/25
|
[
"https://Stackoverflow.com/questions/15623951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1961282/"
] |
Try to use `Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO` or `Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE`.
See below:
```
Camera.Parameters params = camera.getParameters();
if (params.getSupportedFocusModes().contains(
Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
}
camera.setParameters(params);
```
It's important to test whether the phone is supporting your chosen mode before attempting to use it, otherwise `setParameters()` will throw a runtime exception.
(Edit code now working properly)
|
This works perfectly for preview callback:
```
Camera.Parameters parameters = camera.getParameters();
if (parameters.getSupportedFocusModes().contains(
Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
}
camera.setParameters(parameters);
```
|
15,623,951
|
Yes, I have read the EXCELLENT explanations that there are at Stackoverflow about the NPE, and I have understood what they meant. Yet, I found (I think I found) an issue about this NPE in one of the sample exercises on that textbook, that in fact, I used at Harvard long long time ago.
It is about the reference variable String line = null; as the explanations say, no object has been created while it is later on tried to be used as such (so I think), more precisely is tried to be accesed when line = inputStream.nextLine( );. Here is the code and the question is how to fix that. I have tried instantianting an object but...not worked.
```
package test;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.FileOutputStream;
public class Test
{
public static void main(String[] args) {
Scanner inputStream = null;
PrintWriter outputStream = null;
try {
inputStream = new Scanner(new FileInputStream("original.txt"));
outputStream = new PrintWriter(
new FileOutputStream("numbered.txt"));
} catch (FileNotFoundException e) {
System.out.println("Problem opening files.");
System.exit(0);
}
String line = null;
int count = 0;
while (inputStream.hasNextLine()) {
line = inputStream.nextLine();
count++;
outputStream.println(count + " " + line.toString());
}
inputStream.close();
outputStream.close();
}
}
```
And yes, I tried to run it. I copied and pasted the code on a newly created project on Netbeans 7.3
|
2013/03/25
|
[
"https://Stackoverflow.com/questions/15623951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1961282/"
] |
Looks like you should [continuous autofocus](http://developer.android.com/reference/android/hardware/Camera.Parameters.html#FOCUS_MODE_CONTINUOUS_VIDEO) as is discussed here.
There is a [question here](https://stackoverflow.com/questions/5878042/android-camera-autofocus-on-demand) that you can reference.
|
This works perfectly for preview callback:
```
Camera.Parameters parameters = camera.getParameters();
if (parameters.getSupportedFocusModes().contains(
Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
}
camera.setParameters(parameters);
```
|
15,623,951
|
Yes, I have read the EXCELLENT explanations that there are at Stackoverflow about the NPE, and I have understood what they meant. Yet, I found (I think I found) an issue about this NPE in one of the sample exercises on that textbook, that in fact, I used at Harvard long long time ago.
It is about the reference variable String line = null; as the explanations say, no object has been created while it is later on tried to be used as such (so I think), more precisely is tried to be accesed when line = inputStream.nextLine( );. Here is the code and the question is how to fix that. I have tried instantianting an object but...not worked.
```
package test;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.FileOutputStream;
public class Test
{
public static void main(String[] args) {
Scanner inputStream = null;
PrintWriter outputStream = null;
try {
inputStream = new Scanner(new FileInputStream("original.txt"));
outputStream = new PrintWriter(
new FileOutputStream("numbered.txt"));
} catch (FileNotFoundException e) {
System.out.println("Problem opening files.");
System.exit(0);
}
String line = null;
int count = 0;
while (inputStream.hasNextLine()) {
line = inputStream.nextLine();
count++;
outputStream.println(count + " " + line.toString());
}
inputStream.close();
outputStream.close();
}
}
```
And yes, I tried to run it. I copied and pasted the code on a newly created project on Netbeans 7.3
|
2013/03/25
|
[
"https://Stackoverflow.com/questions/15623951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1961282/"
] |
For me this worked a treat:
```
//set camera to continually auto-focus
Camera.Parameters params = c.getParameters();
//*EDIT*//params.setFocusMode("continuous-picture");
//It is better to use defined constraints as opposed to String, thanks to AbdelHady
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
c.setParameters(params);
```
|
Try to use `Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO` or `Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE`.
See below:
```
Camera.Parameters params = camera.getParameters();
if (params.getSupportedFocusModes().contains(
Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
}
camera.setParameters(params);
```
It's important to test whether the phone is supporting your chosen mode before attempting to use it, otherwise `setParameters()` will throw a runtime exception.
(Edit code now working properly)
|
15,623,951
|
Yes, I have read the EXCELLENT explanations that there are at Stackoverflow about the NPE, and I have understood what they meant. Yet, I found (I think I found) an issue about this NPE in one of the sample exercises on that textbook, that in fact, I used at Harvard long long time ago.
It is about the reference variable String line = null; as the explanations say, no object has been created while it is later on tried to be used as such (so I think), more precisely is tried to be accesed when line = inputStream.nextLine( );. Here is the code and the question is how to fix that. I have tried instantianting an object but...not worked.
```
package test;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.FileOutputStream;
public class Test
{
public static void main(String[] args) {
Scanner inputStream = null;
PrintWriter outputStream = null;
try {
inputStream = new Scanner(new FileInputStream("original.txt"));
outputStream = new PrintWriter(
new FileOutputStream("numbered.txt"));
} catch (FileNotFoundException e) {
System.out.println("Problem opening files.");
System.exit(0);
}
String line = null;
int count = 0;
while (inputStream.hasNextLine()) {
line = inputStream.nextLine();
count++;
outputStream.println(count + " " + line.toString());
}
inputStream.close();
outputStream.close();
}
}
```
And yes, I tried to run it. I copied and pasted the code on a newly created project on Netbeans 7.3
|
2013/03/25
|
[
"https://Stackoverflow.com/questions/15623951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1961282/"
] |
Following code works for me.
Setting autofocus (preview class):
```
Parameters params = camera.getParameters();
params.setFocusMode(Parameters.FOCUS_MODE_AUTO);
//some more settings
camera.setParameters(params);
```
Call camera for shot a picture in case that autofocus is ready (activity class):
```
public void butClick(View v){
preview.camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
if(success){
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
}
});
}
```
Get picture (activity class):
```
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
//do something
}
};
```
|
Looks like you should [continuous autofocus](http://developer.android.com/reference/android/hardware/Camera.Parameters.html#FOCUS_MODE_CONTINUOUS_VIDEO) as is discussed here.
There is a [question here](https://stackoverflow.com/questions/5878042/android-camera-autofocus-on-demand) that you can reference.
|
17,632,914
|
Hi I'm having trouble understanding why this isn't working
```
if(Long.parseLong(morse) == 4545454545){
System.out.println("2");
}
```
Where morse is just a String of numbers. The problem is it says Integer number too large: 4545454545, but I'm sure a Long can be much longer than that.
|
2013/07/13
|
[
"https://Stackoverflow.com/questions/17632914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2579707/"
] |
You need to use `4545454545l` or `4545454545L` to qualify it as `long`. Be default , `4545454545` is an `int` literal and `4545454545` is out of range of `int`.
*It is recommended to use uppercase alphabet `L` to avoid confusion , as `l` and `1` looks pretty similar*
You can do :
```
if(Long.valueOf(4545454545l).equals(Long.parseLong(morse)) ){
System.out.println("2");
}
```
OR
```
if(Long.parseLong(morse) == 4545454545l){
System.out.println("2");
}
```
As per [JLS 3.10.1](http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.1):
>
> An integer literal is of type long if it is suffixed with **an ASCII letter L or l (ell)**; otherwise it is of type int (§4.2.1).
>
>
>
|
You need to use `4545454545L` or `4545454545l` to qualify it as long.
|
17,632,914
|
Hi I'm having trouble understanding why this isn't working
```
if(Long.parseLong(morse) == 4545454545){
System.out.println("2");
}
```
Where morse is just a String of numbers. The problem is it says Integer number too large: 4545454545, but I'm sure a Long can be much longer than that.
|
2013/07/13
|
[
"https://Stackoverflow.com/questions/17632914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2579707/"
] |
You need to use `4545454545l` or `4545454545L` to qualify it as `long`. Be default , `4545454545` is an `int` literal and `4545454545` is out of range of `int`.
*It is recommended to use uppercase alphabet `L` to avoid confusion , as `l` and `1` looks pretty similar*
You can do :
```
if(Long.valueOf(4545454545l).equals(Long.parseLong(morse)) ){
System.out.println("2");
}
```
OR
```
if(Long.parseLong(morse) == 4545454545l){
System.out.println("2");
}
```
As per [JLS 3.10.1](http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.1):
>
> An integer literal is of type long if it is suffixed with **an ASCII letter L or l (ell)**; otherwise it is of type int (§4.2.1).
>
>
>
|
If your integer value is larger than `2147483647`, as your literal is then you need to use a long literal:
`4545454545L`
...note the `L` at the end, which is the difference between a long and an int literal. A lower case `l` works too, but is less readable as it's easily confused with a 1 (not a great thing when you're dealing with a number!)
|
58,083,876
|
I have previous implementation of AIDL for IPC in android. I want to add new method as this aidl has multiple implementation in client class and I don't want to implement for all classes.. I want to use default method just like its supported in Java 8.
|
2019/09/24
|
[
"https://Stackoverflow.com/questions/58083876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7887831/"
] |
The `default` keyword should be available in any `interface` description, even if generated from `AIDL`. This will not be backwards compatible with Java 7, so it might require `minSdkVersion 26` and:
```
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
```
|
Use it who is stopping you?
Inside interface you can write your code like below:
```
default void show() {
System.out.println("Default method here");
}
```
|
1,556
|
I have installed Chromium on my Raspberry Pi (running Raspian) with `sudo apt-get install chromium-browser` and I followed the instructions from this site to attempt to get flash player running: <http://linuxologist.com/01general/howto-chromium-browser-on-linux-with-flash/>
ie I just downloaded `libflashplayer.so`, placed it in `/usr/lib/` then make a symlink to it in `/usr/lib/chromium/plugins/`. then i open Chromium like so:
```
chromium --enable-plugins --enable-greasemonkey --enable-user-scripts --enable-extensions
```
from the command line. However, flash player is still not recognised. The version of flash player I downloaded was from softpedia in tar, which i had to untar.
Has anyone managed to get this working? If so, then what extra steps were required?
**Update**
[Alex](https://raspberrypi.stackexchange.com/users/86/alex-chamberlain) requested I run `file`, so here it is:
```
$ file /usr/lib/libflashplayer.so
libflashplayer.so: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked, stripped
```
|
2012/08/12
|
[
"https://raspberrypi.stackexchange.com/questions/1556",
"https://raspberrypi.stackexchange.com",
"https://raspberrypi.stackexchange.com/users/1111/"
] |
I think Adobe did not release any flash plugin of ARM Linux.
<http://get.adobe.com/flashplayer/otherversions/>
I don't know where do you get the "libflashplayer.so", but i guess it is X86 or X64 version.
|
Possible solution,install [android](http://www.raspberrypi.org/archives/1700) on a chrooted environment. That way android can play flash because of the [google chrome support](http://www.mobilemag.com/2012/02/07/google-chrome-arrives-for-android-ics-4-0/) and the [flash plugin](http://www.anandtech.com/show/5250/adobe-updates-flash-111-for-android-40) . Still a long way until android hits the raspberry pi.
Alternatives to Flash(If your only using it for video play back)
[VLC](http://www.videolan.org/vlc/)(My favourite choice)
```
#Arch Linux
pacman -S vlc
#Debian
apt-get install vlc
```
Install this [plugin](https://chrome.google.com/webstore/detail/jldiailifbdkepgpcojllmkbakleicab) .
Then open VLC goto Tools > Preferences (Click All) > Interfaces > Main interface > Check Web and save. Restart and your done!
**OR**
```
vlc -I http
```
[Lightroom](http://lightspark.github.com/)
|
1,556
|
I have installed Chromium on my Raspberry Pi (running Raspian) with `sudo apt-get install chromium-browser` and I followed the instructions from this site to attempt to get flash player running: <http://linuxologist.com/01general/howto-chromium-browser-on-linux-with-flash/>
ie I just downloaded `libflashplayer.so`, placed it in `/usr/lib/` then make a symlink to it in `/usr/lib/chromium/plugins/`. then i open Chromium like so:
```
chromium --enable-plugins --enable-greasemonkey --enable-user-scripts --enable-extensions
```
from the command line. However, flash player is still not recognised. The version of flash player I downloaded was from softpedia in tar, which i had to untar.
Has anyone managed to get this working? If so, then what extra steps were required?
**Update**
[Alex](https://raspberrypi.stackexchange.com/users/86/alex-chamberlain) requested I run `file`, so here it is:
```
$ file /usr/lib/libflashplayer.so
libflashplayer.so: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked, stripped
```
|
2012/08/12
|
[
"https://raspberrypi.stackexchange.com/questions/1556",
"https://raspberrypi.stackexchange.com",
"https://raspberrypi.stackexchange.com/users/1111/"
] |
ARM vs x86
==========
Intel processors used by desktops are 32/64-bit architectures, generally known as x86 and x86\_64.
ARM processors, which is used by the Raspberry Pi, also use a 32-bit architecture, but it is incompatible with x86. Therefore, x86 libraries will not run on the Raspberry Pi.
How do I know you have an x86 library?
--------------------------------------
I asked you to run
```
file /usr/lib/libflashplayer.so
```
which output
```
libflashplayer.so: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked, stripped
```
`Intel 80386` tells us it was compiled for x86.
Do Adobe release an ARM version of Flash?
-----------------------------------------
Yes and no. There are versions available for a lot of Mobile platforms, but I believe it is being deprecated (*citation needed*) and I haven't seen it available for ARM Linux. (*citation needed*)
|
Gnash
=====
>
> Gnash is a free SWF movie player. It is available as a stand-alone application or as a plugin for several popular web browsers. It supports playing media from a disk or streaming over a network connection. Some popular video sharing sites like YouTube are supported on a wide variety of devices from embedded ones to modern desktops.
>
>
>
Installation
------------
Gnash should be in the distributions' repositories.
**Debian**
```
$ sudo apt-get install gnash
```
**Arch**
```
$ sudo pacman -Sy gnash
```
Configuration
-------------
It should Just Work, but I haven't tried it yet. Will do soon.
### References
1. [Gnash User Manual](http://www.gnu.org/software/gnash/manual/gnashuser.html)
|
1,556
|
I have installed Chromium on my Raspberry Pi (running Raspian) with `sudo apt-get install chromium-browser` and I followed the instructions from this site to attempt to get flash player running: <http://linuxologist.com/01general/howto-chromium-browser-on-linux-with-flash/>
ie I just downloaded `libflashplayer.so`, placed it in `/usr/lib/` then make a symlink to it in `/usr/lib/chromium/plugins/`. then i open Chromium like so:
```
chromium --enable-plugins --enable-greasemonkey --enable-user-scripts --enable-extensions
```
from the command line. However, flash player is still not recognised. The version of flash player I downloaded was from softpedia in tar, which i had to untar.
Has anyone managed to get this working? If so, then what extra steps were required?
**Update**
[Alex](https://raspberrypi.stackexchange.com/users/86/alex-chamberlain) requested I run `file`, so here it is:
```
$ file /usr/lib/libflashplayer.so
libflashplayer.so: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked, stripped
```
|
2012/08/12
|
[
"https://raspberrypi.stackexchange.com/questions/1556",
"https://raspberrypi.stackexchange.com",
"https://raspberrypi.stackexchange.com/users/1111/"
] |
Gnash
=====
>
> Gnash is a free SWF movie player. It is available as a stand-alone application or as a plugin for several popular web browsers. It supports playing media from a disk or streaming over a network connection. Some popular video sharing sites like YouTube are supported on a wide variety of devices from embedded ones to modern desktops.
>
>
>
Installation
------------
Gnash should be in the distributions' repositories.
**Debian**
```
$ sudo apt-get install gnash
```
**Arch**
```
$ sudo pacman -Sy gnash
```
Configuration
-------------
It should Just Work, but I haven't tried it yet. Will do soon.
### References
1. [Gnash User Manual](http://www.gnu.org/software/gnash/manual/gnashuser.html)
|
Possible solution,install [android](http://www.raspberrypi.org/archives/1700) on a chrooted environment. That way android can play flash because of the [google chrome support](http://www.mobilemag.com/2012/02/07/google-chrome-arrives-for-android-ics-4-0/) and the [flash plugin](http://www.anandtech.com/show/5250/adobe-updates-flash-111-for-android-40) . Still a long way until android hits the raspberry pi.
Alternatives to Flash(If your only using it for video play back)
[VLC](http://www.videolan.org/vlc/)(My favourite choice)
```
#Arch Linux
pacman -S vlc
#Debian
apt-get install vlc
```
Install this [plugin](https://chrome.google.com/webstore/detail/jldiailifbdkepgpcojllmkbakleicab) .
Then open VLC goto Tools > Preferences (Click All) > Interfaces > Main interface > Check Web and save. Restart and your done!
**OR**
```
vlc -I http
```
[Lightroom](http://lightspark.github.com/)
|
1,556
|
I have installed Chromium on my Raspberry Pi (running Raspian) with `sudo apt-get install chromium-browser` and I followed the instructions from this site to attempt to get flash player running: <http://linuxologist.com/01general/howto-chromium-browser-on-linux-with-flash/>
ie I just downloaded `libflashplayer.so`, placed it in `/usr/lib/` then make a symlink to it in `/usr/lib/chromium/plugins/`. then i open Chromium like so:
```
chromium --enable-plugins --enable-greasemonkey --enable-user-scripts --enable-extensions
```
from the command line. However, flash player is still not recognised. The version of flash player I downloaded was from softpedia in tar, which i had to untar.
Has anyone managed to get this working? If so, then what extra steps were required?
**Update**
[Alex](https://raspberrypi.stackexchange.com/users/86/alex-chamberlain) requested I run `file`, so here it is:
```
$ file /usr/lib/libflashplayer.so
libflashplayer.so: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked, stripped
```
|
2012/08/12
|
[
"https://raspberrypi.stackexchange.com/questions/1556",
"https://raspberrypi.stackexchange.com",
"https://raspberrypi.stackexchange.com/users/1111/"
] |
OS maemo/meego(based on debain) supports flash player on nokia n900(with ARM Cortex A8) microB Browser(based on Mozilla Firefox):
<http://natisbad.org/N900/n900-commented-hardware-specs.html>
maemo download link:
<http://tablets-dev.nokia.com/>
next link is needed to generate IMEI for N900 to download image files:
\*ttp://www.nokiaport.de/tacdatabase/index.php?s=imeitools&lng=
i hope this info can help the raspberry pi community
thanks for reply if there is a chance to get it run on raspberry
|
Are you using Google Chrome? I think that's short for Chronium. If so, I read that Google Chrome cannot run correctly on an ARM processor. Hope this helps.
Try finding a different browser, use Epiphany or your pre-installed browser, or find another one using
>
> sudo apt-get install
>
>
>
|
1,556
|
I have installed Chromium on my Raspberry Pi (running Raspian) with `sudo apt-get install chromium-browser` and I followed the instructions from this site to attempt to get flash player running: <http://linuxologist.com/01general/howto-chromium-browser-on-linux-with-flash/>
ie I just downloaded `libflashplayer.so`, placed it in `/usr/lib/` then make a symlink to it in `/usr/lib/chromium/plugins/`. then i open Chromium like so:
```
chromium --enable-plugins --enable-greasemonkey --enable-user-scripts --enable-extensions
```
from the command line. However, flash player is still not recognised. The version of flash player I downloaded was from softpedia in tar, which i had to untar.
Has anyone managed to get this working? If so, then what extra steps were required?
**Update**
[Alex](https://raspberrypi.stackexchange.com/users/86/alex-chamberlain) requested I run `file`, so here it is:
```
$ file /usr/lib/libflashplayer.so
libflashplayer.so: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked, stripped
```
|
2012/08/12
|
[
"https://raspberrypi.stackexchange.com/questions/1556",
"https://raspberrypi.stackexchange.com",
"https://raspberrypi.stackexchange.com/users/1111/"
] |
Possible solution,install [android](http://www.raspberrypi.org/archives/1700) on a chrooted environment. That way android can play flash because of the [google chrome support](http://www.mobilemag.com/2012/02/07/google-chrome-arrives-for-android-ics-4-0/) and the [flash plugin](http://www.anandtech.com/show/5250/adobe-updates-flash-111-for-android-40) . Still a long way until android hits the raspberry pi.
Alternatives to Flash(If your only using it for video play back)
[VLC](http://www.videolan.org/vlc/)(My favourite choice)
```
#Arch Linux
pacman -S vlc
#Debian
apt-get install vlc
```
Install this [plugin](https://chrome.google.com/webstore/detail/jldiailifbdkepgpcojllmkbakleicab) .
Then open VLC goto Tools > Preferences (Click All) > Interfaces > Main interface > Check Web and save. Restart and your done!
**OR**
```
vlc -I http
```
[Lightroom](http://lightspark.github.com/)
|
Are you using Google Chrome? I think that's short for Chronium. If so, I read that Google Chrome cannot run correctly on an ARM processor. Hope this helps.
Try finding a different browser, use Epiphany or your pre-installed browser, or find another one using
>
> sudo apt-get install
>
>
>
|
1,556
|
I have installed Chromium on my Raspberry Pi (running Raspian) with `sudo apt-get install chromium-browser` and I followed the instructions from this site to attempt to get flash player running: <http://linuxologist.com/01general/howto-chromium-browser-on-linux-with-flash/>
ie I just downloaded `libflashplayer.so`, placed it in `/usr/lib/` then make a symlink to it in `/usr/lib/chromium/plugins/`. then i open Chromium like so:
```
chromium --enable-plugins --enable-greasemonkey --enable-user-scripts --enable-extensions
```
from the command line. However, flash player is still not recognised. The version of flash player I downloaded was from softpedia in tar, which i had to untar.
Has anyone managed to get this working? If so, then what extra steps were required?
**Update**
[Alex](https://raspberrypi.stackexchange.com/users/86/alex-chamberlain) requested I run `file`, so here it is:
```
$ file /usr/lib/libflashplayer.so
libflashplayer.so: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked, stripped
```
|
2012/08/12
|
[
"https://raspberrypi.stackexchange.com/questions/1556",
"https://raspberrypi.stackexchange.com",
"https://raspberrypi.stackexchange.com/users/1111/"
] |
ARM vs x86
==========
Intel processors used by desktops are 32/64-bit architectures, generally known as x86 and x86\_64.
ARM processors, which is used by the Raspberry Pi, also use a 32-bit architecture, but it is incompatible with x86. Therefore, x86 libraries will not run on the Raspberry Pi.
How do I know you have an x86 library?
--------------------------------------
I asked you to run
```
file /usr/lib/libflashplayer.so
```
which output
```
libflashplayer.so: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked, stripped
```
`Intel 80386` tells us it was compiled for x86.
Do Adobe release an ARM version of Flash?
-----------------------------------------
Yes and no. There are versions available for a lot of Mobile platforms, but I believe it is being deprecated (*citation needed*) and I haven't seen it available for ARM Linux. (*citation needed*)
|
OS maemo/meego(based on debain) supports flash player on nokia n900(with ARM Cortex A8) microB Browser(based on Mozilla Firefox):
<http://natisbad.org/N900/n900-commented-hardware-specs.html>
maemo download link:
<http://tablets-dev.nokia.com/>
next link is needed to generate IMEI for N900 to download image files:
\*ttp://www.nokiaport.de/tacdatabase/index.php?s=imeitools&lng=
i hope this info can help the raspberry pi community
thanks for reply if there is a chance to get it run on raspberry
|
1,556
|
I have installed Chromium on my Raspberry Pi (running Raspian) with `sudo apt-get install chromium-browser` and I followed the instructions from this site to attempt to get flash player running: <http://linuxologist.com/01general/howto-chromium-browser-on-linux-with-flash/>
ie I just downloaded `libflashplayer.so`, placed it in `/usr/lib/` then make a symlink to it in `/usr/lib/chromium/plugins/`. then i open Chromium like so:
```
chromium --enable-plugins --enable-greasemonkey --enable-user-scripts --enable-extensions
```
from the command line. However, flash player is still not recognised. The version of flash player I downloaded was from softpedia in tar, which i had to untar.
Has anyone managed to get this working? If so, then what extra steps were required?
**Update**
[Alex](https://raspberrypi.stackexchange.com/users/86/alex-chamberlain) requested I run `file`, so here it is:
```
$ file /usr/lib/libflashplayer.so
libflashplayer.so: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked, stripped
```
|
2012/08/12
|
[
"https://raspberrypi.stackexchange.com/questions/1556",
"https://raspberrypi.stackexchange.com",
"https://raspberrypi.stackexchange.com/users/1111/"
] |
ARM vs x86
==========
Intel processors used by desktops are 32/64-bit architectures, generally known as x86 and x86\_64.
ARM processors, which is used by the Raspberry Pi, also use a 32-bit architecture, but it is incompatible with x86. Therefore, x86 libraries will not run on the Raspberry Pi.
How do I know you have an x86 library?
--------------------------------------
I asked you to run
```
file /usr/lib/libflashplayer.so
```
which output
```
libflashplayer.so: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked, stripped
```
`Intel 80386` tells us it was compiled for x86.
Do Adobe release an ARM version of Flash?
-----------------------------------------
Yes and no. There are versions available for a lot of Mobile platforms, but I believe it is being deprecated (*citation needed*) and I haven't seen it available for ARM Linux. (*citation needed*)
|
I think Adobe did not release any flash plugin of ARM Linux.
<http://get.adobe.com/flashplayer/otherversions/>
I don't know where do you get the "libflashplayer.so", but i guess it is X86 or X64 version.
|
1,556
|
I have installed Chromium on my Raspberry Pi (running Raspian) with `sudo apt-get install chromium-browser` and I followed the instructions from this site to attempt to get flash player running: <http://linuxologist.com/01general/howto-chromium-browser-on-linux-with-flash/>
ie I just downloaded `libflashplayer.so`, placed it in `/usr/lib/` then make a symlink to it in `/usr/lib/chromium/plugins/`. then i open Chromium like so:
```
chromium --enable-plugins --enable-greasemonkey --enable-user-scripts --enable-extensions
```
from the command line. However, flash player is still not recognised. The version of flash player I downloaded was from softpedia in tar, which i had to untar.
Has anyone managed to get this working? If so, then what extra steps were required?
**Update**
[Alex](https://raspberrypi.stackexchange.com/users/86/alex-chamberlain) requested I run `file`, so here it is:
```
$ file /usr/lib/libflashplayer.so
libflashplayer.so: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked, stripped
```
|
2012/08/12
|
[
"https://raspberrypi.stackexchange.com/questions/1556",
"https://raspberrypi.stackexchange.com",
"https://raspberrypi.stackexchange.com/users/1111/"
] |
I think Adobe did not release any flash plugin of ARM Linux.
<http://get.adobe.com/flashplayer/otherversions/>
I don't know where do you get the "libflashplayer.so", but i guess it is X86 or X64 version.
|
Are you using Google Chrome? I think that's short for Chronium. If so, I read that Google Chrome cannot run correctly on an ARM processor. Hope this helps.
Try finding a different browser, use Epiphany or your pre-installed browser, or find another one using
>
> sudo apt-get install
>
>
>
|
1,556
|
I have installed Chromium on my Raspberry Pi (running Raspian) with `sudo apt-get install chromium-browser` and I followed the instructions from this site to attempt to get flash player running: <http://linuxologist.com/01general/howto-chromium-browser-on-linux-with-flash/>
ie I just downloaded `libflashplayer.so`, placed it in `/usr/lib/` then make a symlink to it in `/usr/lib/chromium/plugins/`. then i open Chromium like so:
```
chromium --enable-plugins --enable-greasemonkey --enable-user-scripts --enable-extensions
```
from the command line. However, flash player is still not recognised. The version of flash player I downloaded was from softpedia in tar, which i had to untar.
Has anyone managed to get this working? If so, then what extra steps were required?
**Update**
[Alex](https://raspberrypi.stackexchange.com/users/86/alex-chamberlain) requested I run `file`, so here it is:
```
$ file /usr/lib/libflashplayer.so
libflashplayer.so: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked, stripped
```
|
2012/08/12
|
[
"https://raspberrypi.stackexchange.com/questions/1556",
"https://raspberrypi.stackexchange.com",
"https://raspberrypi.stackexchange.com/users/1111/"
] |
Gnash
=====
>
> Gnash is a free SWF movie player. It is available as a stand-alone application or as a plugin for several popular web browsers. It supports playing media from a disk or streaming over a network connection. Some popular video sharing sites like YouTube are supported on a wide variety of devices from embedded ones to modern desktops.
>
>
>
Installation
------------
Gnash should be in the distributions' repositories.
**Debian**
```
$ sudo apt-get install gnash
```
**Arch**
```
$ sudo pacman -Sy gnash
```
Configuration
-------------
It should Just Work, but I haven't tried it yet. Will do soon.
### References
1. [Gnash User Manual](http://www.gnu.org/software/gnash/manual/gnashuser.html)
|
OS maemo/meego(based on debain) supports flash player on nokia n900(with ARM Cortex A8) microB Browser(based on Mozilla Firefox):
<http://natisbad.org/N900/n900-commented-hardware-specs.html>
maemo download link:
<http://tablets-dev.nokia.com/>
next link is needed to generate IMEI for N900 to download image files:
\*ttp://www.nokiaport.de/tacdatabase/index.php?s=imeitools&lng=
i hope this info can help the raspberry pi community
thanks for reply if there is a chance to get it run on raspberry
|
1,556
|
I have installed Chromium on my Raspberry Pi (running Raspian) with `sudo apt-get install chromium-browser` and I followed the instructions from this site to attempt to get flash player running: <http://linuxologist.com/01general/howto-chromium-browser-on-linux-with-flash/>
ie I just downloaded `libflashplayer.so`, placed it in `/usr/lib/` then make a symlink to it in `/usr/lib/chromium/plugins/`. then i open Chromium like so:
```
chromium --enable-plugins --enable-greasemonkey --enable-user-scripts --enable-extensions
```
from the command line. However, flash player is still not recognised. The version of flash player I downloaded was from softpedia in tar, which i had to untar.
Has anyone managed to get this working? If so, then what extra steps were required?
**Update**
[Alex](https://raspberrypi.stackexchange.com/users/86/alex-chamberlain) requested I run `file`, so here it is:
```
$ file /usr/lib/libflashplayer.so
libflashplayer.so: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked, stripped
```
|
2012/08/12
|
[
"https://raspberrypi.stackexchange.com/questions/1556",
"https://raspberrypi.stackexchange.com",
"https://raspberrypi.stackexchange.com/users/1111/"
] |
ARM vs x86
==========
Intel processors used by desktops are 32/64-bit architectures, generally known as x86 and x86\_64.
ARM processors, which is used by the Raspberry Pi, also use a 32-bit architecture, but it is incompatible with x86. Therefore, x86 libraries will not run on the Raspberry Pi.
How do I know you have an x86 library?
--------------------------------------
I asked you to run
```
file /usr/lib/libflashplayer.so
```
which output
```
libflashplayer.so: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked, stripped
```
`Intel 80386` tells us it was compiled for x86.
Do Adobe release an ARM version of Flash?
-----------------------------------------
Yes and no. There are versions available for a lot of Mobile platforms, but I believe it is being deprecated (*citation needed*) and I haven't seen it available for ARM Linux. (*citation needed*)
|
Are you using Google Chrome? I think that's short for Chronium. If so, I read that Google Chrome cannot run correctly on an ARM processor. Hope this helps.
Try finding a different browser, use Epiphany or your pre-installed browser, or find another one using
>
> sudo apt-get install
>
>
>
|
30,230,857
|
I am looking for a Date Picker control to choose a date between 10'000 B.C. till today (2015). Can I use the `UIDatePicker` for that ( I didn't find any information with [UIDatePicker](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIDatePicker_Class/index.html#//apple_ref/occ/instp/UIDatePicker/minimumDate) ?
I mean does it allow a date range of 12015 years ? Or is there another way to achieve this with standard controls ? or Do I have to create my own control ?
|
2015/05/14
|
[
"https://Stackoverflow.com/questions/30230857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1344545/"
] |
The OLEDB provider may not properly installed. What you chose is the SQL Server native client. Do you have SSMS installed on server? This should come with sql native client OLE DB.
|
I would like to share an experience when I faced following error
>
> Cannot create an instance of OLE DB provider "xxx.YYYY" for linked server "test". Error 7302.
>
>
>
I observed this message from a failed SQL Server job. On analysis it is found that `Allow Inprocess` was not enabled for the `provider`. When this is enabled, everything worked fine for me.
**Server Objects --> Linked Servers --> Providers**
Also refer following
1. ["Cannot create an instance of OLE DB provider" error as Windows Authentication user](https://stackoverflow.com/questions/14499977/cannot-create-an-instance-of-ole-db-provider-error-as-windows-authentication-u)
2. [Linked Server Properties (Provider Options Page)](https://technet.microsoft.com/en-us/library/ms188095(v=sql.105).aspx)
3. [Configuring OLE DB Providers for Distributed Queries](https://technet.microsoft.com/en-us/library/ms190918(v=sql.105).aspx)
|
180,842
|
I don't understand what do 'snapped forward' 'bounded off' mean in context?
>
> The breath whistled out of Jock Danby's throat, and he stopped in mid-charge as though hit in the chest with a double charge of buck-shot. His head and arms **snapped forward**, nerveless as a straw-man, and he flew backwards, crashing into the unbaked brick wall of the hut and beginning to slide down onto his knees. Zouga **bounded off** the tabletop. His left arm was numb to the fingertips from the unexpected blow, but he was light on his feet as a dancer, and the quick rush of cold anger armed and strengthened him.
>
>
>
I can not understand exactly what it means. I feel difficulty with these verbs with propositions like 'bind off' and 'snap forward'. Could you explain they meanings in context and other examples?
|
2018/09/26
|
[
"https://ell.stackexchange.com/questions/180842",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/80300/"
] |
Both of these may be found in the dictionary:
>
> [**snap**](https://en.oxforddictionaries.com/definition/snap) (v): 1.2 [with complement or adverbial] *Move or alter with a brisk movement and typically a sharp sound.*
>
>
> [**bound**](https://en.oxforddictionaries.com/definition/bound) (v): 1.1 (of an object) *rebound from a surface.*
>
>
>
So "to snap forward" means to move sharply or suddenly, in the "forward" direction. If someone is struck in the chest, it's not unusual for their arms to "snap forward" as their torso moves backwards.
"Bound off" is another way to say "rebound" or "bounce" off of something. In this case Zouga struck the tabletop but bounced off with little damage from the impact.
|
"Snap" is a sudden movement. "Forward" means that the movement was to (his) front. The implication is that the rest of him was stopped in its movement by something, but his extremities kept on going.
"Bounded" means "jumped" or "leapt". "Off" is a preposition meaning "away from on". He was on the table and he jumped so that he was no longer on it. "Bounded" has a connotation of jumping with enthusiasm (like a dog chasing something), and it sounds a bit like "bounce"; this fits with "light on his feet as a dancer".
|
180,842
|
I don't understand what do 'snapped forward' 'bounded off' mean in context?
>
> The breath whistled out of Jock Danby's throat, and he stopped in mid-charge as though hit in the chest with a double charge of buck-shot. His head and arms **snapped forward**, nerveless as a straw-man, and he flew backwards, crashing into the unbaked brick wall of the hut and beginning to slide down onto his knees. Zouga **bounded off** the tabletop. His left arm was numb to the fingertips from the unexpected blow, but he was light on his feet as a dancer, and the quick rush of cold anger armed and strengthened him.
>
>
>
I can not understand exactly what it means. I feel difficulty with these verbs with propositions like 'bind off' and 'snap forward'. Could you explain they meanings in context and other examples?
|
2018/09/26
|
[
"https://ell.stackexchange.com/questions/180842",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/80300/"
] |
Something hit the character and caused his arms and head to snap back.
[arms, head, legs,] + snap: an **involuntary sharp movement** of the head or arms etc.
Like (for the head) when you are in a car crash.
snap forward or back[ward].
bound ***off of table***: to jump off it, to get off the table in one movement
bound ***out of a room***: to leave a room quickly with long strides; to run out of it.
|
"Snap" is a sudden movement. "Forward" means that the movement was to (his) front. The implication is that the rest of him was stopped in its movement by something, but his extremities kept on going.
"Bounded" means "jumped" or "leapt". "Off" is a preposition meaning "away from on". He was on the table and he jumped so that he was no longer on it. "Bounded" has a connotation of jumping with enthusiasm (like a dog chasing something), and it sounds a bit like "bounce"; this fits with "light on his feet as a dancer".
|
180,842
|
I don't understand what do 'snapped forward' 'bounded off' mean in context?
>
> The breath whistled out of Jock Danby's throat, and he stopped in mid-charge as though hit in the chest with a double charge of buck-shot. His head and arms **snapped forward**, nerveless as a straw-man, and he flew backwards, crashing into the unbaked brick wall of the hut and beginning to slide down onto his knees. Zouga **bounded off** the tabletop. His left arm was numb to the fingertips from the unexpected blow, but he was light on his feet as a dancer, and the quick rush of cold anger armed and strengthened him.
>
>
>
I can not understand exactly what it means. I feel difficulty with these verbs with propositions like 'bind off' and 'snap forward'. Could you explain they meanings in context and other examples?
|
2018/09/26
|
[
"https://ell.stackexchange.com/questions/180842",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/80300/"
] |
Both of these may be found in the dictionary:
>
> [**snap**](https://en.oxforddictionaries.com/definition/snap) (v): 1.2 [with complement or adverbial] *Move or alter with a brisk movement and typically a sharp sound.*
>
>
> [**bound**](https://en.oxforddictionaries.com/definition/bound) (v): 1.1 (of an object) *rebound from a surface.*
>
>
>
So "to snap forward" means to move sharply or suddenly, in the "forward" direction. If someone is struck in the chest, it's not unusual for their arms to "snap forward" as their torso moves backwards.
"Bound off" is another way to say "rebound" or "bounce" off of something. In this case Zouga struck the tabletop but bounced off with little damage from the impact.
|
Something hit the character and caused his arms and head to snap back.
[arms, head, legs,] + snap: an **involuntary sharp movement** of the head or arms etc.
Like (for the head) when you are in a car crash.
snap forward or back[ward].
bound ***off of table***: to jump off it, to get off the table in one movement
bound ***out of a room***: to leave a room quickly with long strides; to run out of it.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.