qid
int64 1
74.7M
| question
stringlengths 0
70k
| date
stringlengths 10
10
| metadata
list | response
stringlengths 0
115k
|
---|---|---|---|---|
293,557 |
When ever I open terminal it goes to a "git" window and git is running in my activity monitor and about 80% of the cpu.
When ever I force quit it in the activity monitor, it just pop's back up in there. I've even relaunched finder and restarted my computer and git is still in the terminal and activity monitor, it seem unquittable.
How do I stop git running?
|
2011/06/06
|
[
"https://superuser.com/questions/293557",
"https://superuser.com",
"https://superuser.com/users/-1/"
] |
AFAIK git does none of these things - I suspect you got yourself a Trojan / Virus.
Some things to check:
* what is the output of ps auxw|grep -i git? What's the path returned for git?
* can you remove the git executable / remove the executable bit?
|
64,657,822 |
I'm new to Python. After a couple days researching and trying things out, I've landed on a decent solution for creating a list of timestamps, for each hour, between two dates.
**Example:**
```
import datetime
from datetime import datetime, timedelta
timestamp_format = '%Y-%m-%dT%H:%M:%S%z'
earliest_ts_str = '2020-10-01T15:00:00Z'
earliest_ts_obj = datetime.strptime(earliest_ts_str, timestamp_format)
latest_ts_str = '2020-10-02T00:00:00Z'
latest_ts_obj = datetime.strptime(latest_ts_str, timestamp_format)
num_days = latest_ts_obj - earliest_ts_obj
num_hours = int(round(num_days.total_seconds() / 3600,0))
ts_raw = []
for ts in range(num_hours):
ts_raw.append(latest_ts_obj - timedelta(hours = ts + 1))
dates_formatted = [d.strftime('%Y-%m-%dT%H:%M:%SZ') for d in ts_raw]
# Need timestamps in ascending order
dates_formatted.reverse()
dates_formatted
```
**Which results in:**
```
['2020-10-01T00:00:00Z',
'2020-10-01T01:00:00Z',
'2020-10-01T02:00:00Z',
'2020-10-01T03:00:00Z',
'2020-10-01T04:00:00Z',
'2020-10-01T05:00:00Z',
'2020-10-01T06:00:00Z',
'2020-10-01T07:00:00Z',
'2020-10-01T08:00:00Z',
'2020-10-01T09:00:00Z',
'2020-10-01T10:00:00Z',
'2020-10-01T11:00:00Z',
'2020-10-01T12:00:00Z',
'2020-10-01T13:00:00Z',
'2020-10-01T14:00:00Z',
'2020-10-01T15:00:00Z',
'2020-10-01T16:00:00Z',
'2020-10-01T17:00:00Z',
'2020-10-01T18:00:00Z',
'2020-10-01T19:00:00Z',
'2020-10-01T20:00:00Z',
'2020-10-01T21:00:00Z',
'2020-10-01T22:00:00Z',
'2020-10-01T23:00:00Z']
```
**Problem:**
* If I change `earliest_ts_str` to include **minutes**, say `earliest_ts_str = '2020-10-01T19:45:00Z'`, the resulting list does **not** increment the minute intervals accordingly.
**Results:**
```
['2020-10-01T20:00:00Z',
'2020-10-01T21:00:00Z',
'2020-10-01T22:00:00Z',
'2020-10-01T23:00:00Z']
```
**I need it to be:**
```
['2020-10-01T20:45:00Z',
'2020-10-01T21:45:00Z',
'2020-10-01T22:45:00Z',
'2020-10-01T23:45:00Z']
```
Feels like the problem is in the `num_days` and `num_hours` calculation, but I can't see how to fix it.
Ideas?
|
2020/11/03
|
[
"https://Stackoverflow.com/questions/64657822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5976033/"
] |
```
import datetime
from datetime import datetime, timedelta
timestamp_format = '%Y-%m-%dT%H:%M:%S%z'
earliest_ts_str = '2020-10-01T00:00:00Z'
ts_obj = datetime.strptime(earliest_ts_str, timestamp_format)
latest_ts_str = '2020-10-02T00:00:00Z'
latest_ts_obj = datetime.strptime(latest_ts_str, timestamp_format)
ts_raw = []
while ts_obj <= latest_ts_obj:
ts_raw.append(ts_obj)
ts_obj += timedelta(hours=1)
dates_formatted = [d.strftime('%Y-%m-%dT%H:%M:%SZ') for d in ts_raw]
print(dates_formatted)
```
EDIT:
Here is example with [Maya](https://pypi.org/project/maya/)
```
import maya
earliest_ts_str = '2020-10-01T00:00:00Z'
latest_ts_str = '2020-10-02T00:00:00Z'
start = maya.MayaDT.from_iso8601(earliest_ts_str)
end = maya.MayaDT.from_iso8601(latest_ts_str)
# end is not included, so we add 1 second
my_range = maya.intervals(start=start, end=end.add(seconds=1), interval=60*60)
dates_formatted = [d.iso8601() for d in my_range]
print(dates_formatted)
```
Both output
```
['2020-10-01T00:00:00Z',
'2020-10-01T01:00:00Z',
... some left out ...
'2020-10-01T23:00:00Z',
'2020-10-02T00:00:00Z']
```
|
12,028,594 |
I am trying to insert `≤` and `≥` into a symbol table where the column is of type `nvarchar`.
Is this possible or are these symbols not allowed in SQL Server?
|
2012/08/19
|
[
"https://Stackoverflow.com/questions/12028594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1610304/"
] |
To make it work, **prefix the string with `N`**
```sql
create table symboltable
(
val nvarchar(10)
)
insert into symboltable values(N'≥')
select *
from symboltable
```

**Further Reading**:
* [You must precede all Unicode strings with a prefix N when you deal with Unicode string constants in SQL Server](https://web.archive.org/web/20150114081311/http://support.microsoft.com:80/kb/239530/en-us "ARCHIVE of http://support.microsoft.com/kb/239530/en-us")
* [Why do some SQL strings have an 'N' prefix?](https://web.archive.org/web/20150208024547/http://databases.aspfaq.com/general/why-do-some-sql-strings-have-an-n-prefix.html "ARCHIVE of http://databases.aspfaq.com/general/why-do-some-sql-strings-have-an-n-prefix.html")
|
605,587 |
I am using a WSL, ubuntu on windows 10 and I want to set permissions like below but I am receiving an error.
Why? How do I fix it?
```
ubuntu-user@LAPTOP:~$ chmod 400 .ssh/MyKey.pem
chmod: changing permissions of '.ssh/MyKey.pem': Operation not permitted
```
|
2020/08/21
|
[
"https://unix.stackexchange.com/questions/605587",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/429104/"
] |
You can just use these commands in only one session, every time when you open terminal, you have to enter again. I solved my issue with this way.
```
sudo umount /mnt/c
sudo mount -t drvfs C: /mnt/c -o metadata
chmod 400 [fileName] or chmod 700 [fileName]
```
Reference:
<https://stackoverflow.com/questions/46610256/chmod-wsl-bash-doesnt-work>
|
201,822 |
I added a custom mass action to the shipments grid for sending multiple tracking emails at once and the collection part is throwing an error, because I must be missing something.
For reference, I looked at the `Magento\Cms\Controller\Adminhtml\Page\MassDisable` class.
So I came up with this:
`/app/code/PerunPro/DPD/Controller/Adminhtml/Shipment/MassSendTracking.php`
```
<?php
namespace PerunPro\DPD\Controller\Adminhtml\Shipment;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use Magento\Sales\Api\ShipmentManagementInterface;
use Magento\Sales\Model\ResourceModel\Order\Shipment\CollectionFactory;
use Magento\Ui\Component\MassAction\Filter;
class MassSendTracking extends \Magento\Backend\App\Action
{
/**
* Authorization level of a basic admin session
*
* @see _isAllowed()
*/
const ADMIN_RESOURCE = 'Magento_Sales::shipment';
/**
* @var Filter
*/
protected $filter;
/**
* @var CollectionFactory
*/
protected $collectionFactory;
protected $shipmentManagement;
public function __construct(
Context $context,
Filter $filter,
CollectionFactory $collectionFactory,
ShipmentManagementInterface $shipmentManagement
) {
$this->filter = $filter;
$this->collectionFactory = $collectionFactory;
$this->shipmentManagement = $shipmentManagement;
parent::__construct($context);
}
public function execute()
{
$collection = $this->filter->getCollection($this->collectionFactory->create());
// Do stuff
/** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
return $resultRedirect->setPath('*/*/');
}
}
```
When I submit the request, I get the following error:
>
> Fatal error: Uncaught TypeError: Argument 2 passed to
> Magento\Framework\View\Element\UiComponentFactory::argumentsResolver()
> must be of the type array, null given, called in
> /var/www/magento/v2\_2/vendor/magento/framework/View/Element/UiComponentFactory.php
> on line 198 and defined in
> /var/www/magento/v2\_2/vendor/magento/framework/View/Element/UiComponentFactory.php
> on line 164
>
>
>
I am guessing I am missing some stuff in di.xml, because `Magento\Sales\Model\ResourceModel\Order\Shipment\CollectionFactory` does not exist, but so doesn't `Magento\Cms\Model\ResourceModel\Page\CollectionFactory` which is in Page\MassDisable.
The CMS di.xml has this about it:
```
<type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
<arguments>
<argument name="collections" xsi:type="array">
<item name="cms_page_listing_data_source" xsi:type="string">Magento\Cms\Model\ResourceModel\Page\Grid\Collection</item>
<item name="cms_block_listing_data_source" xsi:type="string">Magento\Cms\Model\ResourceModel\Block\Grid\Collection</item>
</argument>
</arguments>
</type>
```
So I tried with with a wild guess in my own di.xml:
```
<type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
<arguments>
<argument name="collections" xsi:type="array">
<item name="sales_order_shipment_grid_data_source" xsi:type="string">Magento\Sales\Model\ResourceModel\Order\Shipment\Grid\Collection</item>
</argument>
</arguments>
</type>
```
Which of course has no effect :) Please help.
My module.xml sequence, I thought it would mean it also loads the XML grid info but clearly it doesn't
```
<sequence>
<module name="Magento_Sales"/>
<module name="Magento_Shipping"/>
</sequence>
```
|
2017/11/16
|
[
"https://magento.stackexchange.com/questions/201822",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/13685/"
] |
I figured it out... Since I wanted to continue on this and tried to debug it, I noticed that today it works.
While I was working on other stuff, I ran the `setup:di:compile` command several times in CLI. I think this is what was missing from the above. Also, the stuff in di.xml is not needed.
|
1,600,964 |
I have read in a paper that there is a formula as follows:
$$\prod\_{k=0}^{n-1} \left(x^2-2x\cos\left(\alpha+\frac{2k\pi}{n}\right)+1\right)=x^{2n}-2x^n\cos(n\alpha)+1.$$
In the paper they said that we can find such formula in ''Table of integrals, series and products'' by Gradshteyn and Ryzhik, and indeed I found it there with a reference to another book called ''Summation of Series'' by Jolley. In the latter book unfortunately I couldn't find the formula. So I do not know what to do. Can someone give me a proof of the above formula, or any other reference where the proof exists? Thanks for any help!
|
2016/01/05
|
[
"https://math.stackexchange.com/questions/1600964",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/154060/"
] |
Best done by passing to the complex plane in my opinion. Note the following:
$(x-e^{i\theta})(x-e^{-i\theta})=x^2-2x \cos\theta +1$
Try using this and pushing factors around on the left hand side a bit to try get closer to the right hand side.
---
We can use this to factor each expression on the left-hand side as $(x-e^{i(\alpha+2k\pi/n)})(x-e^{-i(\alpha+2k\pi/n)})$
So, our proof now relies on showing that:
$\prod\_{k=0}^{n-1}(x-e^{i(\alpha+2k\pi/n)})(x-e^{-i(\alpha+2k\pi/n)})=(x^n-e^{in\alpha})(x^n-e^{-in\alpha})$
This is very close to a factorisation of $x^n-1$ involving roots of unity, $\prod\_{k=0}^{n-1}(x-e^{2k\pi i/n})=x^n-1$. Let's split it into two parts:
$A(x)=\prod\_{k=0}^{n-1}(x-e^{i(\alpha+2k\pi/n)})$
$B(x)=\prod\_{k=0}^{n-1}(x-e^{-i(\alpha+2k\pi/n)})$
Substituting $x=te^{i\alpha}$ and $x=te^{-i\alpha}$ respectively, we quickly see:
$A(te^{i\alpha})=\prod\_{k=0}^{n-1}(te^{i\alpha}-e^{i(\alpha+2k\pi/n)})=e^{in\alpha}\prod\_{k=0}^{n-1}(t-e^{2k\pi i/n)})=e^{in\alpha}(t^n-1)$
$B(te^{-i\alpha})=\prod\_{k=0}^{n-1}(te^{-i\alpha}-e^{-i(\alpha+2k\pi/n)})=e^{-in\alpha}\prod\_{k=0}^{n-1}(t-e^{2k\pi i/n)})=e^{-in\alpha}(t^n-1)$
Moving back to the expressions in terms of $x$, this gives us $A(x)=x^n-e^{in\alpha}$ and $B(x)=x^n-e^{-in\alpha}$, and by applying the formula from the very start, we arrive at the desired identity.
|
5,048,852 |
How can I use [`JFreeChart`](http://www.jfree.org/jfreechart/) to display just the most recent data in a continually updated time series?
Addenda: A complete, working example that incorporates the accepted answer is shown [here](https://stackoverflow.com/a/5048863/230513). See also this [variation](https://stackoverflow.com/a/15521956/230513) having two series. See also this [*Q&A*](https://stackoverflow.com/q/31902373/230513) regarding `setTimeBase()`.
|
2011/02/19
|
[
"https://Stackoverflow.com/questions/5048852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230513/"
] |
The [`JFreeChart`](http://www.jfree.org/jfreechart/) class [`DynamicTimeSeriesCollection`](http://www.jfree.org/jfreechart/api/javadoc/org/jfree/data/time/DynamicTimeSeriesCollection.html) is a good choice.
Addendum: As noted by @Bahadır, the last point of the series was persistently zero. @Don helpfully suggests advancing the time and *then* appending the data.
```
dataset.advanceTime();
dataset.appendData(newData);
```

```
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.Timer;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.time.DynamicTimeSeriesCollection;
import org.jfree.data.time.Second;
import org.jfree.data.xy.XYDataset;
import org.jfree.chart.ui.ApplicationFrame;
import org.jfree.chart.ui.UIUtils;
/**
* @see http://stackoverflow.com/a/15521956/230513
* @see http://stackoverflow.com/questions/5048852
*/
public class DTSCTest extends ApplicationFrame {
private static final String TITLE = "Dynamic Series";
private static final String START = "Start";
private static final String STOP = "Stop";
private static final float MINMAX = 100;
private static final int COUNT = 2 * 60;
private static final int FAST = 100;
private static final int SLOW = FAST * 5;
private static final Random random = new Random();
private Timer timer;
public DTSCTest(final String title) {
super(title);
final DynamicTimeSeriesCollection dataset =
new DynamicTimeSeriesCollection(1, COUNT, new Second());
dataset.setTimeBase(new Second(0, 0, 0, 1, 1, 2011));
dataset.addSeries(gaussianData(), 0, "Gaussian data");
JFreeChart chart = createChart(dataset);
final JButton run = new JButton(STOP);
run.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (STOP.equals(cmd)) {
timer.stop();
run.setText(START);
} else {
timer.start();
run.setText(STOP);
}
}
});
final JComboBox combo = new JComboBox();
combo.addItem("Fast");
combo.addItem("Slow");
combo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if ("Fast".equals(combo.getSelectedItem())) {
timer.setDelay(FAST);
} else {
timer.setDelay(SLOW);
}
}
});
this.add(new ChartPanel(chart) {
@Override
public Dimension getPreferredSize() {
return new Dimension(640, 480);
}
}, BorderLayout.CENTER);
JPanel btnPanel = new JPanel(new FlowLayout());
btnPanel.add(run);
btnPanel.add(combo);
this.add(btnPanel, BorderLayout.SOUTH);
timer = new Timer(FAST, new ActionListener() {
float[] newData = new float[1];
@Override
public void actionPerformed(ActionEvent e) {
newData[0] = randomValue();
dataset.advanceTime();
dataset.appendData(newData);
}
});
}
private float randomValue() {
return (float) (random.nextGaussian() * MINMAX / 3);
}
private float[] gaussianData() {
float[] a = new float[COUNT];
for (int i = 0; i < a.length; i++) {
a[i] = randomValue();
}
return a;
}
private JFreeChart createChart(final XYDataset dataset) {
final JFreeChart result = ChartFactory.createTimeSeriesChart(
TITLE, "hh:mm:ss", "milliVolts", dataset, true, true, false);
final XYPlot plot = result.getXYPlot();
ValueAxis domain = plot.getDomainAxis();
domain.setAutoRange(true);
ValueAxis range = plot.getRangeAxis();
range.setRange(-MINMAX, MINMAX);
return result;
}
public void start() {
timer.start();
}
public static void main(final String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
DTSCTest demo = new DTSCTest(TITLE);
demo.pack();
UIUtils.centerFrameOnScreen(demo);
demo.setVisible(true);
demo.start();
}
});
}
}
```
|
6,715,025 |
I have a JS regexp.
```
var t1 = str.match(/\[h1\]/g).length;
```
If `str` contains the word `[h1]` it works fine else it shows an error!
How to solve the problem?
|
2011/07/16
|
[
"https://Stackoverflow.com/questions/6715025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/683233/"
] |
```
var t1 = (str.match(/\[h1\]/g)||[]).length;
```
|
26,494 |
En general los nombres españoles de los animales que han vivido desde antiguo en Europa provienen de las palabras latinas correspondientes. Es el caso de las vacas, gatos, cabras, ovejas, serpientes, caballos, burros, etc., que son etimológicamente derivados del latín.
No es el caso del [**zorro**](http://dle.rae.es/?id=cVU9wGT), que según el DRAE proviene del portugués:
>
> Del port. *zorro* 'holgazán', der. de *zorrar* 'arrastrar'; cf. occit. *mandra* 'zorra'; propiamente 'mandria, holgazán'.
>
>
>
Pues me parece raro que no se use (o no exista) alguna denominación derivada de "vulpes", que era la palabra latina con que se designaba este animalito. Y de hecho tampoco se usa en catalán (*guineu*), gallego (*raposo*), francés (*renard*), occitano (*guèine, mandra, rainal*) ni portugués (*raposa*).
¿Por qué será que, a diferencia del resto de los animales, se ha preferido un juego de palabras ("holgazán") en vez de continuar usando una palabra ya existente ("vulpes")? Y eso con el agregado de que el juego de palabras se tomó de un tercer idioma, el portugués. Es rebuscado.
|
2018/06/04
|
[
"https://spanish.stackexchange.com/questions/26494",
"https://spanish.stackexchange.com",
"https://spanish.stackexchange.com/users/6915/"
] |
La razón es así: muchos nombres de animales solían ser palabras tabú. La gente tenía miedo de llamar a los animales salvajes y destructivos por sus nombres "reales" y los sustituían por otros que existían, incluyendo el zorro:
* [OUP blog: *‘Vulpes vulpes,’ or foxes have holes.* Part 1](https://blog.oup.com/2016/03/animal-name-origins-taboo-words-noa-fox-etymology/), [Part 2](https://blog.oup.com/2016/03/fox-etymology-word-origin/), Anatoly Liberman
>
> Our ancient ancestors were [so worried about bears, they didn't even want to name them because they feared [the bears] might overhear and come after them.](https://xkcd.com/2381/) So they came up with this word — this is up in Northern Europe — bruin, meaning "the brown one" as a euphemism, and then bruin segued into bear. We know the euphemism, but we don't know what word it replaced, so bear is the oldest-known euphemism.
>
>
> * [Euphemania: Our Love Affair with Euphemisms](https://content.time.com/time/arts/article/0,8599,2041313,00.html)
>
>
>
No obstante, sí hay un cognado en castellano de *vulpes*:
>
> [**vulpeja**](http://dle.rae.es/?id=c5nldWp)
>
> Del lat. *vulpecŭla*, dim. de *vulpes* 'raposa'.
>
>
> 1. `f.` [zorra](http://dle.rae.es/?id=cVU9wGT) (‖ mamífero).
>
>
>
y un latinismo culto [del siglo XVIII](https://books.google.com/ngrams/graph?content=vulp%C3%A9cula&year_start=1500&year_end=2000&corpus=21&smoothing=3) de la misma raíz:
>
> [**vulpécula**](http://dle.rae.es/?id=c5lHtJH)
>
> Del lat. *vulpecŭla*, dim. de *vulpes* 'raposa'.
>
>
> 1. `f.` [vulpeja.](http://dle.rae.es/?id=c5nldWp)
>
>
>
---
Como notas, en muchos de los idiomas romances de Francia e Iberia se usan eufemismos o préstamos de otros idiomas para su(s) palabra(s) para *zorro*:
1. De origen incierto - zorro (esp)
2. [Del lat. *mamphur*](http://www.dom-en-ligne.de/dom.php?lhid=4scE0AMIfH8bxAc7zBoRIy) - mandra (occ)
3. a) [Del germànic **wihsela**](http://dcvb.iec.cat/results.asp?word=guilla) - guilla (cat)
b) [Del germànic **Winald** / **Winihild**](http://dcvb.iec.cat/results.asp?word=guineu) - guineu (cat), guèine (occ)
4. Del lat. *rapum* 'nabo' - rabosa (esp. ant.), raposo (esp), raposo (gal), raposa (pt), raposu, rapiegu (ast), rabosa, raboso (arg), rabosa (cat)
5. [Roman de Renart](https://es.wikipedia.org/wiki/Roman_de_Renart) - renard (fr), r'nard (norman), rinåd, rnåd (walloon), rainal, rainald, [rainard](https://www.youtube.com/watch?v=Ywj0K-oRc5A) (occ), ~~renard~~ (cat), renar, ראפוזה, רינאר (ladino)
Sin embargo (unos dialectos de) gallego y occitano sí todavía usan una palabra derivada de *vulpes*, como la mayoría de los idiomas romances del este de Francia:
6. a) From Latin vulpēs - golpe (gal), ~~volp~~ (cat), vop (occ), volp (lombard), bolp, bolpe, volp, volpe (venetian), bolp, volp (friulian), volp (ladin), vulp, vualp, vuolp, uolp, golp, gualp (romansch), bualp, vualp (dalmatian), bulpo (istriot), volpe (it), vórpa, vorpe (neapolitan), vurpi, jurpi, gurpi, vulpi (sicilian), volpe (corsican), grupi, gurpe (sard), vulpi, vulpe (aromanian)
Y los **diminutivos** de *vulpes* en muchas de las lenguas galo-ibéricas parecen haber sobrevivido ilesos:
6. b) [](https://i.stack.imgur.com/bRa1o.png)
---
**Nota:** la etimología de *zorro* provista en el DLE es poco fiable:
>
> "The initial attestations of Sp. *zorro/zorra* 'fox' are from the mid fifteenth century and appear almost exclusively in the feminine, employed in *cancionero* poetry, with reference to idle, immoral women (cf. mod. *zorra* 'prostitute'). […] DCECH may well be right in stating that *zorro/zorra* secondarily became a euphemistic designation for the dreaded fox (cf. *raposo* so used). […] The late initial documentation of *zorro* leads to the question [of] whether this word goes back to early Roman Spain or whether it is a later borrowing from Basque, a derivation, as noted above, challenged by Trask (1997: 421). Far from convincing is the unprovable hypothesis in DCECH that *zorro* goes back to a verb *zorrar* (whose authenticity I have been unable to verify), allegedly on onomatopoeic origin."
>
>
>
>
> * *A History of the Spanish Lexicon: A Linguistic Perspective,* 2012 (p. 39)
>
>
>
|
692,883 |
So I have a group of nginx server:
```
[nginx_internal_servers]
n01.local
n02.local
n03.local
```
And I have a pre deploy task to run. I'm running in `serial:1` mode, and I only want this pre deploy task to run on everyone other than me.
Currently my task looks like this, which runs on all nginx servers perfectly:
```
pre_tasks:
- name: Take service out of nginx upstream pools
local_action: command {{ playbook_dir }}/scripts/nginx-upstream-management.sh -s {{ item[0] }} -r {{ item[2] }} -g {{ item[1] }}
with_nested:
- groups['nginx_internal_servers']
- services_endpoints.keys()
- ansible_all_ipv4_addresses|last
```
Any ideas how to exclude the current node from the list `groups['nginx_internal_servers']`?
|
2015/05/18
|
[
"https://serverfault.com/questions/692883",
"https://serverfault.com",
"https://serverfault.com/users/25999/"
] |
Got it! Use a when :)
```
pre_tasks:
- name: Take service out of nginx upstream pools
local_action: command {{ playbook_dir }}/scripts/nginx-upstream-management.sh -s {{ item[0] }} -r {{ item[2] }} -g {{ item[1] }}
with_nested:
- groups['nginx_internal_servers']
- services_endpoints.keys()
- ansible_all_ipv4_addresses|last
when: item[0] != inventory_hostname
```
|
62,286,219 |
It can be using find, ls or stat
```
find /opt/sas/data/vaa_oadm/sasdata -type f -name '*.sas7bdat'
```
Expected output:
```
/path/of/file/file1.sas7bdat 10GB 10Jan2020 01Jan2019
/path/of/file/on/server/file2.sas7bdat 10MB 15Jan2020 08Dec2019
```
|
2020/06/09
|
[
"https://Stackoverflow.com/questions/62286219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/933047/"
] |
Use [splice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice):
```
fruits.splice(3, 1, 'coconut')
```
The arguments are:
1. start at index
2. delete count
3. replace with (optional)
|
45,835,185 |
My company is planning to introduce an user login with higher security requirements for the Service Tools in our machines (used for the maintenance). Up to now we used to login with a simple PW which is gradually known by everyone.
The new authentication method should require a 2FA. Every service technican is equipped with a smart phone so I thought of the following authentication process:
The phone number of the service technicans will be registered on a server (independent of the machine) and they will be able to request the code only via this phone maybe in combination with the serial number of the machine. The code will be sent automatically on the requester’s smart phone. With this code the service technican is able to login at the machine and he has access to the service tools.
My problem is: I hear a lot about Identity Management and frameworks as well as public / private key methods.
The sticking point is that our machines are running offline. So the first requirement is that we are able to manage the service technicans (add / delete permissions for service technicans) on the server (Name, ID, etc.) so they can request a code (2FA) and the second is that they can login at the machine even though the machine is offline.
How can I manage that the Login at the machine is decoupled of the identity managemend on the server side? Is there an easier way to do a login at a offline machine with higher security?
|
2017/08/23
|
[
"https://Stackoverflow.com/questions/45835185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8504966/"
] |
[`toString()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toString) does not accept any arguments, and cannot be used like this. I would recommend using [moment.js](https://momentjs.com/).
For example:
```js
var formatted = moment(1502722800000).format('YYYY/MM/DD h:mm');
console.log('formatted date '+formatted);
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
```
If you wish to work with timezones, you can also add [Moment Timezones](https://momentjs.com/timezone/).
|
31,433,824 |
I am trying to create a pl/sql function (my first take at pl/sql functions) that converts base 10 number to base 26 string (my base 26 will be A..Z).
```
create or replace function generateId(numericId IN NUMBER) RETURN VARCHAR2 AS
declare
type array_t is varray(26) of CHAR;
char_array array_t := array_t('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
res varchar2(3);
targetBase INTEGER := char_array.count;
begin
LOOP
res = char_array[REMAINDER(numericId, targetBase)] + result;
numericId = numericId / targetBase;
EXIT WHEN (numericId = 0);
RETURN res;
end;
```
The error I am getting is:
```
Error(2,1): PLS-00103: Encountered the symbol "DECLARE" when expecting one of the following: begin function pragma procedure subtype type <an identifier> <a double-quoted delimited-identifier> current cursor delete exists prior external language The symbol "begin" was substituted for "DECLARE" to continue.
```
My guess is I'm sticking declaration into a wrong place but I can't figure out where it should go.
|
2015/07/15
|
[
"https://Stackoverflow.com/questions/31433824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/151200/"
] |
You have too many syntax errors in the code.
1. Assignment in oracle is done using := and not =
2. Array indexes are referred using () not []
3. You cannot assign values to IN variables `numericId = numericId / targetBase`
4. Check the syntax for [loop statement](http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/controlstatements.htm#LNPLS402) - you are missing end loop
5. To get array count use COUNT()
And as the comments suggest
6. Remove Declare
|
44,185,844 |
The AWS [EC2 Security Groups documentation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html?icmpid=docs_ec2_console) mentions that "Security groups for EC2-VPC have additional capabilities that aren't supported by security groups for EC2-Classic" but the Security Groups dashboard does not provide any information on the "capabilities" of attributes of Security Groups that allow me to distinguish what kind of Security Group I'm looking at or what it is attached to, so that, for example I can't figure out whether I can consolidate Security Groups and share them across EC2 instances (for easier management):
1. How do I determine whether a given Security Group is appropriate for a given instance?
2. How do I determine whether what instances a Security Group is associated with (I see how to do the inverse in the Instances console)?
|
2017/05/25
|
[
"https://Stackoverflow.com/questions/44185844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/656912/"
] |
>
> Security groups for EC2-VPC have additional capabilities that aren't
> supported by security groups for EC2-Classic
>
>
>
This is only relevant if you have an AWS account that actually supports EC2 classic. If the account is less than a few years old you do not have support for EC2 classic. Security groups worked differently in EC2 classic as it was an entirely flat network. With the creation of VPCs security groups are now segregated by VPC.
>
> 1. How do I determine whether a given Security Group is appropriate for a
> given instance?
>
>
>
This is entirely up to you and what is on the instance. Security groups are a generic concept and can be applied to any instance. For example, if the instance is running something that needs to contact DynamoDB then you need to have a security group for that instance that supports that interaction. Likewise, if you have an instance that is running a webserver you might want a security group that exposes port 80.
>
> 2. How do I determine whether what instances a Security Group is associated with (I see how to do the inverse in the Instances
> console)?
>
>
>
This is can be quite daunting to accomplish via the GUI depending on the number of instances even assuming if you only want to look at EC2 groups and not something like RDS as well. It is most easily accomplished using the CLI and a command like:
```
$ aws ec2 describe-instances --output text | grep sg-{Some id}
```
|
55,500,208 |
I'm quite new to Python and I'm encountering a problem.
I have a dataframe where one of the columns is the departure time of flights. These hours are given in the following format : 1100.0, 525.0, 1640.0, etc.
This is a pandas series which I want to transform into a datetime series such as : `S = [11.00, 5.25, 16.40,...]`
What I have tried already :
* Transforming my objects into string :
```
S = [str(x) for x in S]
```
* Using datetime.strptime :
```
S = [datetime.strptime(x,'%H%M.%S') for x in S]
```
But since they are not all the same format it doesn't work
* Using parser from dateutil :
```
S = [parser.parse(x) for x in S]
```
I got the error :
```
'Unknown string format'
```
* Using the panda datetime :
```
S= pd.to_datetime(S)
```
Doesn't give me the expected result
Thanks for your answers !
|
2019/04/03
|
[
"https://Stackoverflow.com/questions/55500208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11306888/"
] |
Since it's a columns within a dataframe (A `series`), keep it that way while transforming should work just fine.
```
S = [1100.0, 525.0, 1640.0]
se = pd.Series(S) # Your column
# se:
0 1100.0
1 525.0
2 1640.0
dtype: float64
setime = se.astype(int).astype(str).apply(lambda x: x[:-2] + ":" + x[-2:])
```
This transform the floats to correctly formatted strings:
```
0 11:00
1 5:25
2 16:40
dtype: object
```
And then you can simply do:
```
df["your_new_col"] = pd.to_datetime(setime)
```
|
15,083 |
When I was being ordained in the Baptist Church, I was asked to write out a statement of faith. The point was to outline one's theology, but many of you know me well enough to know by now that I can't take everything seriously.
So, when it came time to discuss "sacrements" in the Baptist church, I said:
>
> "Baptists have three sacrements - communion, marriage, and potluck."
>
>
>
I was only half joking. Fairly central to the stereotype of the Baptist church is the potluck dinner. Episcopalians have the sacred rite of Coffee Hour. And, apparently Catholics have the Church Dinner thing going on too. In short, it seems like food is a central part of many churches.
I seem to remember something about "love feasts" somewhere in Scripture - but how is it that the humble potluck has had such a wide influence on church life?
|
2013/03/19
|
[
"https://christianity.stackexchange.com/questions/15083",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/1039/"
] |
A "potluck", in this context, is nothing more than a meal shared among members of a Church after a service. There's no doctrinal or ritual significance to it, as you know, and it's not ordained. it's simply sharing a meal amongst our Church family.
Jesus often ate with His disciples, so an argument could be made that Christians can trace it there. You could use the miraculous feeding of the multitudes, I suppose. However...
I'm sure the practice of eating after a service or worship, people bringing food, sharing time and a meal together far predates even New testament times. You could probably, if you liked, trace it right back to Adam and Eve eating of the fruit of the Garden (even if only allegorically, as many would interpret that book.) You may as well ask "When did the institution of greeting a brother in Christ" or "shaking hands after the second Hymn get it's start"
The answer is, of course, back at the beginning. It's just what families do. Our Church family, our co-workers, our biological family, or in-laws. We just enjoy spending time with those we care about.
More here: <http://www.fbcbennington.org/sermonsjhh/2011/7/15/in-search-of-the-new-testament-potluck-acts-237-47.html>
Excerpt:
>
> On this final day of VBS, the adults and the children are exploring
> Acts 2:37-47. Right in the midst of these essentials of the Church’s
> identity, we learn that we are not the first believers to connect
> “food” to the Christian faith. Indeed, the first churches learned
> that “breaking bread together” gave them as much a sense of identity
> as did the teaching, the praying, and the sharing with one another.
> Being together at table is essential to church as any prayer, hymn, or
> sermon.
>
>
> When you think back over your life, do you remember a good meal at
> church? I think of the dinner rolls of Anna Brown, a dedicated lay
> woman who had a kind word literally for every person around the table
> (a feat among Kansas Baptists, who are better known for having
> opinions on just about everything and everybody). I recall the
> skilled cooking of Orman Halderman, who learned to cook during his
> WWII service years, able to rally a fine meal every month out of a
> volunteer group of men trying to cook, without Orman’s leadership
> otherwise would have brought new meaning to the phrase “green eggs and
> ham”. I recollect the kindness shown by the search committee when
> coming to visit First Baptist, Bennington, five years ago. You heard
> that Kerry was a vegetarian and made especial effort to offer a meal
> sensitive to her dietary convictions. That meant a lot. And later
> this morning, we will make our way down the hall for the meal that
> will recall the words of an old hymn: “feed me till I want no more.”
>
>
> If you were to claim that “food” is somehow secondary to “church”, I
> would disagree gladly. Without meals together, we forget skills and
> values that worship cannot impart to us. In the pews, there’s a
> formalism that the supper bell sets aside. At table, we get to know
> the person beside us in the pews. (A good suggestion for potluck:
> Sit down by somebody later today that you have not connected with in a
> spell. Breaking bread together is a great icebreaker for churches to
> get to know one another. Better yet, find somebody you cannot recall
> getting to know yet. It may be a little uneasy at first, but
> remember, the person across from you is a fellow congregant. You have
> “First Baptist” in common!)
>
>
>
|
45,724,051 |
I have looked at the questions regarding this error, and have not found a solution.
I have a highlight directive, and I take an input `index`. This directive works when I declare it in the module I'm using it in. But I want to use it in several modules, So I removed the declaration, and put it inside of my root module that imports the errors. That is when I get the error:
```
Error: Template parse errors:
Can't bind to 'index' since it isn't a known property of 'div'. ("
<div class="read row"
appListHighlight
[ERROR ->][index]="index"
>
<div class="col"></div>
"): ng:///NetworkModule/DnsComponent.html@15:20
```
My directive:
```
import { Directive, Input, Renderer2, ElementRef, HostBinding, OnInit } from '@angular/core';
@Directive({
selector: '[appListHighlight]'
})
export class ListHighlightDirective implements OnInit{
@HostBinding('style.backgroundColor') backgroundColor = 'transparent';
@Input() index: string;
constructor() {}
ngOnInit() {
console.log('APP', this.index);
if (+this.index % 2 === 0) {
this.backgroundColor = 'rgba(128, 128, 128, 0.08)'
}
}
}
```
my html:
```
<div class="read row"
appListHighlight
[index]="index"
>
```
the html is part of a component inside my network module, which is imported into my root module like so
```
import { ListHighlightDirective } from './shared/list-highlight.directive';
import { NetworkModule } from './network/network.module';
declarations: [
AppComponent,
ListHighlightDirective
],
```
So what is happening? why does this work when the directive is imported to my networkModule, but not my root module? doesn't the root module compile everything in the app that it imports so all the imports are included?
--------------------\_\_\_\_\_\_UPDATE\_\_\_\_\_------------------------
I created a shared module, and imported it, but i'm getting the same error. my module looks like this:
```
import { ListHighlightDirective } from './list-highlight.directive';
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
@NgModule({
declarations: [
ListHighlightDirective
],
imports: [
CommonModule
]
})
export class SharedModule { }
```
|
2017/08/16
|
[
"https://Stackoverflow.com/questions/45724051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7385011/"
] |
An Angular module defines the template resolution environment for the template associated with every declared component. That means that when a component's template is parsed, it looks to THAT component's Angular module to find all of the referenced components, directives, and pipes.
A more common practice for something like this is to add the `appListHighlight` to a Shared module and then import that Shared module into your network module.
I have a youtube video about these concepts here: <https://www.youtube.com/watch?v=ntJ-P-Cvo7o&t=6s>
Or you can read more about this here: <https://angular.io/guide/ngmodule-faq>
In the picture below, I do something similar with the StarComponent, which is a nested component that turns a number into rating stars. You can use this same technique for your directive.
[](https://i.stack.imgur.com/pNrep.png)
|
9,684,218 |
My project is on the basis of multi-tenant.
I have multiple clients (companies) and each client has multiple users.
Each client has their own database, so during user authentication, I discover the name of associated database for that user.
The structure of each database is identical... only the data is different.
So that we can keep the different database for the different company, that will not going to mix in data in database.
The number of clients (and therefor the number of databases) is unknown when the application is written, so it is not possible to include all the connections in the bootstrap script.
Now, what I want to do is, dynamically alter the DB connection that is in the bootstrap or have the ability to dynamically create a new connection for the user signing in. Is there a simple solution for this in Yii and still use AR , query builder ?
The same question was asked on yii forum that still not answered clearly,....
you can find this question here [Yii dynamic dabatabase connection](http://www.yiiframework.com/forum/index.php?/topic/5385-dynamic-db-connection/)
|
2012/03/13
|
[
"https://Stackoverflow.com/questions/9684218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889944/"
] |
I'd do the same as qiang posted on the forum. You need a list of db connections and a property of the logged in user at `Yii::app()->user` that tells you which connection to use (I name it `connectionId` for my example).
You then overide `getDbConnection()` in a ActiveRecord base class:
```
public function getDbConnection()
{
if(self::$db!==null)
return self::$db;
else
{
// list of connections is an array of CDbConnection configurations indexed by connectionId
$listOfConnections=/* to be loaded somehow */;
// create DB connection based on your spec here:
self::$db=new CDbConnection($listOfConnections[Yii::app()->user->connectionId]);
self::$db->active=true;
return self::$db;
}
}
```
|
42,911,898 |
I have a start on looping through dynamically-created Checkboxes:
```
For Each cntrl As Control In Me.Controls
If TypeOf cntrl Is CheckBox Then
If (cntrl As CheckBox).Checked Then
'Do Something
End If
End If
Next
```
...but I don't know what I need instead of this line:
```
If (cntrl As CheckBox).Checked Then
```
...which was just a guess and which does not compile.
|
2017/03/20
|
[
"https://Stackoverflow.com/questions/42911898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/875317/"
] |
I think what you want to do is :
```
If DirectCast(cntrl, CheckBox).Checked = True Then
```
|
33,430,675 |
I am trying to implement the concept of `ConnectionPooling` in `Oracle` using `Jetty` server. I have tried the following that I saw on a tutorial. It is working if I deploy using `Tomcat` server, but `Jetty` seems to be giving me an unusual `error`. Details are below -
I have a class called `TestServlet.java` defined as -
```
import java.io.IOException;
import java.sql.*;
import javax.naming.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.sql.DataSource;
@SuppressWarnings("serial")
@WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
public TestServlet() throws ServletException{
System.out.println("Constructor");
init();
}
public DataSource dataSource;
private Connection con;
private Statement statement;
public void init() throws ServletException {
System.out.println("inside init method");
try {
// Get DataSource
Context initContext = new InitialContext();
System.out.println("Before envcontext");
Context envContext = (Context)initContext.lookup("java:comp/env");
System.out.println("After envcontext");
dataSource = (DataSource)envContext.lookup("jdbc/DSTest");
System.out.println(dataSource.toString());
} catch (NamingException e) {
System.out.println("Exception in try");
e.printStackTrace();
}
}
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("Request: "+req+"\tResponse: "+resp);
int i=0;
ResultSet resultSet = null;
try {
// Get Connection and Statement
con = dataSource.getConnection();
statement = con.createStatement();
String query = "SELECT * FROM USER";
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
++i;
System.out.println(i+":\nID:"+resultSet.getString("ID") +"\nEmail:"+ resultSet.getString("UEMAIL") +"\nPassword:" + resultSet.getString("PASSWORD")+"\nFlag:"+resultSet.getShort("FLAG")
+"\n");
}
} catch (SQLException e) {
System.out.println("EXCEPTIOn");
e.printStackTrace();
}finally {
try { if(null!=resultSet)resultSet.close();} catch (SQLException e)
{e.printStackTrace();System.out.println("1");}
try { if(null!=statement)statement.close();} catch (SQLException e)
{e.printStackTrace();System.out.println("2");}
try { if(null!=con)con.close();} catch (SQLException e)
{e.printStackTrace();System.out.println("3");}
}
}
```
}
And my `Jetty-web.xml` is as -
```
<?xml version="1.0" encoding="UTF-8"?>
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
<New id="DSTest" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg>java:comp/env</Arg>
<Arg>jdbc/DSTest</Arg>
<Arg>
<New class="org.apache.commons.dbcp.BasicDataSource">
<Set name="driverClassName">oracle.jdbc.OracleDriver</Set>
<Set name="url">ConnectionUrl</Set>
<Set name="username">app_user</Set>
<Set name="password">abcd</Set>
</New>
</Arg>
</New>
</Configure>
```
When I run the `servlet` class I get an error that says -
```
java.lang.NoClassDefFoundError: org/apache/commons/pool/impl/GenericObjectPool
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2658)
at java.lang.Class.getConstructors(Class.java:1638)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.newObj(XmlConfiguration.java:748)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.itemValue(XmlConfiguration.java:1078)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.value(XmlConfiguration.java:993)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.newObj(XmlConfiguration.java:741)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.configure(XmlConfiguration.java:383)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.configure(XmlConfiguration.java:317)
at org.eclipse.jetty.xml.XmlConfiguration.configure(XmlConfiguration.java:276)
at org.eclipse.jetty.webapp.JettyWebXmlConfiguration.configure(JettyWebXmlConfiguration.java:100)
at org.eclipse.jetty.webapp.WebAppContext.configure(WebAppContext.java:427)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1207)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:610)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:453)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:89)
at org.eclipse.jetty.server.Server.doStart(Server.java:262)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
at runjettyrun.Bootstrap.main(Bootstrap.java:80)
Caused by:
java.lang.ClassNotFoundException: org.apache.commons.pool.impl.GenericObjectPool
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:415)
at runjettyrun.ProjectClassLoader.loadClass(ProjectClassLoader.java:92)
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2658)
at java.lang.Class.getConstructors(Class.java:1638)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.newObj(XmlConfiguration.java:748)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.itemValue(XmlConfiguration.java:1078)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.value(XmlConfiguration.java:993)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.newObj(XmlConfiguration.java:741)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.configure(XmlConfiguration.java:383)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.configure(XmlConfiguration.java:317)
at org.eclipse.jetty.xml.XmlConfiguration.configure(XmlConfiguration.java:276)
at org.eclipse.jetty.webapp.JettyWebXmlConfiguration.configure(JettyWebXmlConfiguration.java:100)
at org.eclipse.jetty.webapp.WebAppContext.configure(WebAppContext.java:427)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1207)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:610)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:453)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:89)
at org.eclipse.jetty.server.Server.doStart(Server.java:262)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
at runjettyrun.Bootstrap.main(Bootstrap.java:80)
2015-10-30 14:22:51.172:INFO:oejs.AbstractConnector:Started [email protected]:8081 STARTING
2015-10-30 14:22:51.172:WARN:oejuc.AbstractLifeCycle:FAILED org.eclipse.jetty.server.Server@7857fe2: java.lang.NoClassDefFoundError: org/apache/commons/pool/impl/GenericObjectPool
java.lang.NoClassDefFoundError: org/apache/commons/pool/impl/GenericObjectPool
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2658)
at java.lang.Class.getConstructors(Class.java:1638)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.newObj(XmlConfiguration.java:748)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.itemValue(XmlConfiguration.java:1078)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.value(XmlConfiguration.java:993)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.newObj(XmlConfiguration.java:741)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.configure(XmlConfiguration.java:383)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.configure(XmlConfiguration.java:317)
at org.eclipse.jetty.xml.XmlConfiguration.configure(XmlConfiguration.java:276)
at org.eclipse.jetty.webapp.JettyWebXmlConfiguration.configure(JettyWebXmlConfiguration.java:100)
at org.eclipse.jetty.webapp.WebAppContext.configure(WebAppContext.java:427)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1207)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:610)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:453)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:89)
at org.eclipse.jetty.server.Server.doStart(Server.java:262)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
at runjettyrun.Bootstrap.main(Bootstrap.java:80)
Caused by:
java.lang.ClassNotFoundException: org.apache.commons.pool.impl.GenericObjectPool
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:415)
at runjettyrun.ProjectClassLoader.loadClass(ProjectClassLoader.java:92)
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2658)
at java.lang.Class.getConstructors(Class.java:1638)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.newObj(XmlConfiguration.java:748)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.itemValue(XmlConfiguration.java:1078)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.value(XmlConfiguration.java:993)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.newObj(XmlConfiguration.java:741)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.configure(XmlConfiguration.java:383)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.configure(XmlConfiguration.java:317)
at org.eclipse.jetty.xml.XmlConfiguration.configure(XmlConfiguration.java:276)
at org.eclipse.jetty.webapp.JettyWebXmlConfiguration.configure(JettyWebXmlConfiguration.java:100)
at org.eclipse.jetty.webapp.WebAppContext.configure(WebAppContext.java:427)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1207)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:610)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:453)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:89)
at org.eclipse.jetty.server.Server.doStart(Server.java:262)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
at runjettyrun.Bootstrap.main(Bootstrap.java:80)
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/pool/impl/GenericObjectPool
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2658)
at java.lang.Class.getConstructors(Class.java:1638)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.newObj(XmlConfiguration.java:748)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.itemValue(XmlConfiguration.java:1078)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.value(XmlConfiguration.java:993)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.newObj(XmlConfiguration.java:741)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.configure(XmlConfiguration.java:383)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.configure(XmlConfiguration.java:317)
at org.eclipse.jetty.xml.XmlConfiguration.configure(XmlConfiguration.java:276)
at org.eclipse.jetty.webapp.JettyWebXmlConfiguration.configure(JettyWebXmlConfiguration.java:100)
at org.eclipse.jetty.webapp.WebAppContext.configure(WebAppContext.java:427)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1207)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:610)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:453)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:89)
at org.eclipse.jetty.server.Server.doStart(Server.java:262)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
at runjettyrun.Bootstrap.main(Bootstrap.java:80)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.pool.impl.GenericObjectPool
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:415)
at runjettyrun.ProjectClassLoader.loadClass(ProjectClassLoader.java:92)
... 20 more
```
I have added the `commons-dbcp-1.4.jar` to my `WEB-INF/lib` folder in eclipse after looking at other stackoverflow threads. Even after doing that, I am getting the same error when I deploy on `Jetty`.
I am using `jetty` server version 8 integrated with `eclipse luna` 4.4.1.
Any help much appreciated.
|
2015/10/30
|
[
"https://Stackoverflow.com/questions/33430675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5213618/"
] |
You have 3 ways to do it:
1. If you are using maven or gradle in your project simply add commons-pool dependency to your pom.xml or build.gradle file (recommended way)
2. If you are not using one of the mentioned tools place correct jar in the WEB-INF/lib directory
3. The last one is to place jar in ${jettyHome}/lib directory
Make sure that you are using correct version of the commons-pool for your current commons-dbcp implementation
|
21,275,802 |
I have Three managed bean: One session scoped (S) and Two view scoped (A,B).
I want to use A's functionality in both S and B.
but the problem is that injecting view scoped bean in session scoped one is impossible.
```
The scope of the object referenced by expression #{a}, view, is shorter than the referring managed beans (s) scope of session
```
I don't want to duplicate A's functionality.
any idea?
|
2014/01/22
|
[
"https://Stackoverflow.com/questions/21275802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1395863/"
] |
This just indicates a design problem in your model. This suggests that view scoped bean class A is having "too much" code logic and that its code should be refactored into a different, reusable class which in turn can be used by both session scoped bean class S and view scoped bean class A. [Law of Demeter](http://en.wikipedia.org/wiki/Law_of_Demeter) and such. Perhaps it represents business service code which actually needs to be in an EJB?
In any case, you *could* achieve the requirement by passing view scoped bean A as method argument of an action method of session scoped bean S.
```
<h:commandXxx ... action="#{sessionScopedBean.doSomething(viewScopedBean)}" />
```
But this is also a design smell. You need to make absolutely sure that you choose the right scope for the data/state the bean holds. See also [How to choose the right bean scope?](https://stackoverflow.com/questions/7031885/how-to-choose-the-right-bean-scope)
|
35,601,279 |
The padding-top in nav a doesn't fit
I want to have this
[](https://i.stack.imgur.com/6U8ds.png)
but I actually get this
[](https://i.stack.imgur.com/LPagb.png)
here is my html and css code
```css
body{
background-image: url('img/bg.png');
color:#000305;
font-size:87.5%;
font-family:Arial, 'Licida Sans Unicode';
text-align:left;
}
a{
text-decoration:none;
}
a:link, a:visited{
}
a:hover, a:active{
}
.body{
clear:both;
margin: 0 auto;
width:70%;
}
.mainHeader img{
width:30%;
height:auto;
margin:2% 0;
}
.mainHeader nav{
background-color: #666;
height: 40px;
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
}
.mainHeader nav ul{
list-style:none;
margin:0 auto;
}
.mainHeader nav ul li{
float : left;
display:inline;
}
.mainHeader nav a:link, .mainHeader nav a:visited{
color: #FFF;
display:inlin-block;
padding:10px 25px;
height:20px;
}
.mainHeader nav a:hover, .mainHeader nav a:active,
.mainHeader nav .active a:link, .mainHeader nav .active a:visited{
background-color:#CF5C3F;
text-shadow:none;
}
.mainHeader nav ul li a{
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
}
```
```html
<header class="mainHeader">
<img src="img/css.jpg" />
<nav>
<ul>
<li class="active"><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Porfolio</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
</header>
```
Why is it so?
|
2016/02/24
|
[
"https://Stackoverflow.com/questions/35601279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5974205/"
] |
Change your `.mainHeader nav ul li` to `display: block`. You also had a typo in your child anchor tags which should have read `display: inline-block;`. I've added comments of what I've changed.
```css
body{
background-image: url('img/bg.png');
color:#000305;
font-size:87.5%;
font-family:Arial, 'Licida Sans Unicode';
text-align:left;
}
a{
text-decoration:none;
}
a:link, a:visited{}
a:hover, a:active{}
.body{
clear:both;
margin: 0 auto;
width:70%;
}
.mainHeader img{
width:30%;
height:auto;
margin:2% 0;
}
.mainHeader nav{
background-color: #666;
height: 40px;
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
}
.mainHeader nav ul{
list-style:none;
margin:0 auto;
}
.mainHeader nav ul li{
float : left;
display: block; /* I CHANGED THIS */
}
.mainHeader nav a:link, .mainHeader nav a:visited{
color: #FFF;
display:inline-block; /* I CHANGED THIS */
padding:10px 25px;
height:20px;
}
.mainHeader nav a:hover, .mainHeader nav a:active,
.mainHeader nav .active a:link, .mainHeader nav .active a:visited{
background-color:#CF5C3F;
text-shadow:none;
}
.mainHeader nav ul li a{
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
}
```
```html
<header class="mainHeader">
<img src="img/css.jpg" />
<nav>
<ul>
<li class="active"><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Porfolio</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
</header>
```
|
21,288,770 |
I have a project that requires me to add the values of multiple arrays, not necessarily all the same length.
I have 8 arrays that can be of varying lenght:
p1 = [1,5,6,8,3,8,]
p2 = [3,3,3,2,8,3,3,4]
p3 = [1,2,3,4,5,6,7,8,9]
p4 = [1,3,4,5,6,7,2,0,2,8,7]
and so on.
What I need to do is add the same key values together to make 1 'results' array, that would look something like:
results = [6, 13, 16, 19, 22, 24, 12, 12, 11, 8, 7]
I've found some code on Stackoverflow that does the job beautifully in most browsers, with the exception of IE8.
[Javascript merge 2 arrays and sum same key values](https://stackoverflow.com/questions/17115190/javascript-merge-2-arrays-and-sum-same-key-values)
Here is the code that works in most browsers:
```
var sums = {}; // will keep a map of number => sum
[p1, p2, p3, p4, p5, p6, p7, p8].forEach(function(array) {
//for each pair in that array
array.forEach(function(pair) {
// increase the appropriate sum
sums[pair[0]] = pair[1] + (sums[pair[0]] || 0);
});
});
// now transform the object sums back into an array of pairs, and put into array named 'results'...
var results = [];
for(var key in sums) {
results.push([key, sums[key]]);
}
```
The problem (I think) is that IE8 doesn't support forEach. Is there a way to do this without using forEach, either with plain Javascript or jQuery?
|
2014/01/22
|
[
"https://Stackoverflow.com/questions/21288770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3224362/"
] |
You can use [System.arraycopy](http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#arraycopy%28java.lang.Object,%20int,%20java.lang.Object,%20int,%20int%29):
>
>
> ```
> public static void arraycopy(
> Object src, int srcPos, Object dest, int destPos, int length)
>
> ```
>
> Copies an array from the specified source array, beginning at the
> specified position, to the specified position of the destination
> array. A subsequence of array components are copied from the source
> array referenced by src to the destination array referenced by dest.
> The number of components copied is equal to the length argument. The
> components at positions `srcPos` through `srcPos+length-1` in the source
> array are copied into positions `destPos` through `destPos+length-1`,
> respectively, of the destination array.
>
>
>
Note that the documentation on the System class says (emphasis added):
>
> Among the facilities provided by the System class are standard input,
> standard output, and error output streams; access to externally
> defined properties and environment variables; a means of loading files
> and libraries; and a **utility method for quickly copying a portion of
> an array.**
>
>
>
Here's an exaple and its output:
```
import java.util.Arrays;
public class ArrayCopyDemo {
public static void main(String[] args) {
int[] bigger_array = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int[] smaller_array = { 1, 2, 3 };
// start copying from position 1 in source, and into
// position 3 of the destination, and copy 2 elements.
int srcPos = 1, destPos = 3, length = 2;
System.arraycopy(smaller_array, srcPos, bigger_array, destPos, length );
System.out.println( Arrays.toString( bigger_array ));
}
}
```
```none
[0, 0, 0, 2, 3, 0, 0, 0, 0]
```
To copy the entire array, just use `0` as `srcPos`, and `src.length` as `length` (where `src` is the source array; in this case, you'd use `smaller_array.length`).
|
56,662,793 |
I am new to C# need help to convert json Object to Array
convert this json
```
[
{
"Id": 1000,
"Name": "May",
"Address": "odyssey",
"Country": "USA",
"Phone": "12345"
}
]
```
To
```
var details = {1000,May,odyssey,USA,12345};
```
|
2019/06/19
|
[
"https://Stackoverflow.com/questions/56662793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11496451/"
] |
Use Newtonsoft.Json to deserialize JSON to a specified .net type. You can deserialize to a class too, see below:
```
public class Person
{
public int Id {get;set;}
public string Name {get;set;}
public string Address {get;set;}
public string Country {get;set;}
public string Phone {get;set;}
}
var details = JsonConvert.DeserializeObject<Person>(json);
```
|
38,854,265 |
I'm inserting a `{string, MyStruct}` object in to an unordered\_map, later iterating through the unordered\_map and choosing to erase the element. However, before erasing the element I have an assert which is showing the unordered\_map is empty.
This is my insert:
```
my_umap.insert(std::make_pair(key.toString(), my_struct));
```
The struct contains a member recording the time at which it was inserted. I then periodically check the map and remove elements which have been in the unordered\_map for too long:
```
for(auto it = my_umap.begin(); it != my_umap.end(); ++it){
MyStruct& myStruct = it->second;
const bool deleteEntry = myStruct.ts.IsElapsed(std::chrono::seconds(5));
if(deleteEntry){
const string& key = it->first; // Cannot access memory for 'key'
assert(my_umap.size() >= 1); // This is failing
my_umap.erase(key);
}
}
```
I am running the code in gdb and the assert fails. When I query the value of `key` it says
>
> cannot access memory
>
>
>
When I query the size of `my_umap` it says the size is zero.
How can the for loop detect an element if the size of the unordered\_map is zero? There are no other threads accessing this container. I thought `unordered_map::insert()` copies the object in to the container, so the original object being deleted shouldn't matter?
|
2016/08/09
|
[
"https://Stackoverflow.com/questions/38854265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/997112/"
] |
After you call `my_umap.erase(...)`, your iterator becomes invalid:
[cppreference.com](http://en.cppreference.com/w/cpp/container/unordered_map/erase) says:
>
> References and iterators to the erased elements are invalidated. Other iterators and references are not invalidated.
>
>
>
This means that once the item is erased, the iterators that pointed to it are no longer valid.
You've got a couple of options:
1. Use the iterator to erase, and use the return value of `erase()`
===================================================================
Since C++11, erasing by iterator will return an iterator pointing to the next item in the map. So you can use this to keep your iterator valid:
```
auto it = my_umap.begin();
while (it != my_umap.end()) {
MyStruct& myStruct = it->second;
const bool deleteEntry = myStruct.ts.IsElapsed(std::chrono::seconds(5));
if(deleteEntry){
assert(my_umap.size() >= 1);
it = my_umap.erase(it); // <-- Return value should be a valid iterator.
}
else{
++it; // Have to manually increment.
}
}
```
2. Store your iterators in a list object and erase after iteration.
===================================================================
Alternatively, you can store delete candidates in a list object (e.g. vector and delete them after your initial iteration:
```
std::vector<MapType::iterator> deleteCandidates;
for(auto it = my_umap.begin(); it != my_umap.end(); ++it){
MyStruct& myStruct = it->second;
const bool deleteEntry = myStruct.ts.IsElapsed(std::chrono::seconds(5));
if(deleteEntry)
deleteCandidates.push_back(it);
}
for (auto it : deleteCandidates) {
my_umap.erase(it);
}
```
---
As for why your assertion is failing, you're probably encountering undefined behaviour by accessing an invalid iterator, making your `for` loop believe that the map is still not empty (because `invalidIterator != my_umap.end()`).
|
183,850 |
It seems obvious to me that Epic Feats are imbalanced - that is to say, that there is a great disparity in the relative power of feats with comparable requirements - but a lot of this is made hard to quantify because feats that appear to be the most broken cannot easily be taken at level 21. After realising that, I turned my attention to the Epic Feats that obviously can be taken at level 21. Among these, [Multispell](https://www.d20srd.org/srd/epic/feats.htm#multispell) drew my attention. It reads:
>
> **Multispell [Epic]**
>
> **Prerequisites**
>
> Quicken Spell, ability to cast 9th-level arcane or divine spells.
>
> **Benefit**
>
> You may cast one additional quickened spell in a round.
>
> **Special**
>
> You can gain this feat multiple times. Its effects stack.
>
>
>
This seems easy to obtain at level 21 and obviously game-destroying, particularly when compared to other Epic Feats like [Polyglot](https://www.d20srd.org/srd/epic/feats.htm#polyglot) (there's a spell for that, and I think that you need to be past level 21 for this anyway?), [Armor Skin](https://www.d20srd.org/srd/epic/feats.htm#armorSkin) (oh wow, +1 AC!), and [Storm Of Throws](https://www.d20srd.org/srd/epic/feats.htm#stormOfThrows) (I don't even know why you'd want this). Am I correct in my assessment, or is there some balancing factor somewhere that makes this feat not as broken as it appears when compared to the other Epic Feats that can easily be taken at level 21?
|
2021/04/12
|
[
"https://rpg.stackexchange.com/questions/183850",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/53359/"
] |
Yes, Multispell is preposterously powerful.¹ Between all the pre-epic options for making metamagic cheaper, and the new epic options like Improved Spell Capacity, there is no real reason not to just cast all the spells you need every turn. Well before epic levels, the most important constraint on a character’s ability to accomplish their goals is not spell slots, but actions—Multispell effectively ends that. It’s effectively a free *time stop* every turn but without *time stop*’s limitations.
And yes, Armor Skin, Polyglot, and Storm of Throws are basically worthless. Armor Skin and Polyglot could easily be non-epic feats with no prerequisites and they still would almost never get taken, optimally. Storm of Throws is a more justifiable feat choice than Whirlwind Attack (much larger range than most creature’s reach, prerequisites are actually feats you’d want to take anyway), but that’s not saying much (both feats require you to get into and stay in a dangerous position, and spread damage around so you’re not eliminating threats, so it’s rare you would want to use either—too rare to be worth a feat). Of the three, Polyglot is probably the best, but it’d be a rare character who should want any of them even pre-epic.
But the real issue here is that talking about “balance” in epic is meaningless—it’s simply **not** balanced. Not even remotely. Epic Spellcasting can, with proper cheese, become the ability to snap your fingers and cast “solve the problem,” whatever the problem is. Even if you ban that—and you must, anyone with Epic Spellcasting is literally playing a different game from everyone without it—the epic options are just wildly out of sync with one another. Powerful metamagic effects, Multispell, Improved Spell Capacity—all these options are absurd. And on the martial side, you get crap like Epic Weapon Focus.
Pulling the lens even further back, though, talking about Epic Spellcasting is still perhaps missing the point—because high-level D&D 3.5e isn’t remotely balanced **either**. It’s not as though you *reach* 21st and the game breaks—it had already been broken for several levels before you reach that point. So *of course* anything building off of that foundation is just going to get worse and worse. Warriors at those levels can basically guarantee one-turn kills against anything they can reach—and they’re *weak* at those levels. Spellcasters are changing reality left and right, and are effectively (if not literally) untouchable because of all the layers of magical defenses they can have. It’s nearly impossible to overstate how powerful *gate* and *shapechange* are.
So yes, Multispell is ridiculous—but that’s par for the course. The simple fact is that the epic rules **do not work**. They aren’t balanced. The only way people can play at those levels is by effectively making up their own rules to replace the official ones. And that *can* work—after all, completely freeform games can work if you have a group that knows each other well and is mature enough to limit themselves appropriately—but the *Epic Level Handbook* isn’t helpful in achieving it.
1. Various supplements—first *Miniatures Handbook* and since then several others, including *Rules Compendium*—state that Quicken Spell uses a swift action. The *Player’s Handbook*, of course, does not say that, because swift actions don’t exist in the *Player’s Handbook*, and this has never been errata’d. See [this Q&A for more details on the problems with that](https://rpg.stackexchange.com/q/37466/4563). The *Epic Level Handbook*, like the *Player’s Handbook*, also pre-dates *Miniatures Handbook* and so doesn’t use swift actions, which means Multispell fails to explicitly remove the swift action requirement on Quicken Spell—as far as its concerned, Quicken Spell doesn’t have any such thing, it just has a 1/round limitation, which Multispell does remove. RAW, this would be a problem, except that RAW, the swift-action casting time of quickened spells is, itself, a problem. So there isn’t really a lot of merit to worrying about this technicality—either you incorporate swift actions into the rules for pre-*Miniatures Handbook* publications, or you don’t. (You should.) If you do, you have to update *Epic Level Handbook* too (at least, if you’re using it at all, which I’d argue you should not); if you don’t, there’s no problem. But you can’t go halfway, or rather, if you do, any nonsense that results is on you; that’s not RAW.
|
968,304 |
The problem i have is that my volume group size is much bigger than it possible could be.
I have a physical disk of 300Gb.
I initially created a volume group on sda1. The size below is showing correctly what i set it up to be (93.1Gb) I then extended vg1 onto sda4 - so the volume group size should be approx (93+176) 269Gb.
```
sudo lsblk
[sudo] password for production:
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sda 8:0 0 278.9G 0 disk
├─sda1 8:1 0 93.1G 0 part
│ ├─vg1-lv_root 252:0 0 4.7G 0 lvm /
│ ├─vg1-lv_usr 252:1 0 9.3G 0 lvm /usr
│ ├─vg1-lv_var 252:2 0 19.3G 0 lvm /var
│ ├─vg1-lv_home 252:3 0 9.3G 0 lvm /home
│ └─vg1-lv_tmp 252:4 0 4.7G 0 lvm /tmp
├─sda2 8:2 0 9.3G 0 part [SWAP]
├─sda3 8:3 0 477M 0 part /boot
└─sda4 8:4 0 176G 0 part
sdb 8:16 0 278.9G 0 disk
└─sdb1 8:17 0 278.9G 0 part /mnt/cassandra
sdc 8:32 0 278.9G 0 disk
└─sdc1 8:33 0 278.9G 0 part /mnt/disk3
sr0 11:0 1 1024M 0 rom
```
However, as we see below, its saying its 445Gb.
```
sudo vgdisplay
--- Volume group ---
VG Name vg1
System ID
Format lvm2
Metadata Areas 2
Metadata Sequence No 12
VG Access read/write
VG Status resizable
MAX LV 0
Cur LV 5
Open LV 5
Max PV 0
Cur PV 2
Act PV 2
VG Size 445.52 GiB
PE Size 4.00 MiB
Total PE 114053
Alloc PE / Size 12096 / 47.25 GiB
Free PE / Size 101957 / 398.27 GiB
VG UUID NQM1uq-XGDm-I893-rXQk-Ex8y-Dw7W-CI2HQk
```
Here is the output of 'fdisk /dev/sda'
```
Command (m for help): p
Disk /dev/sda: 278.9 GiB, 299439751168 bytes, 584843264 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xbd0bc5dd
Device Boot Start End Sectors Size Id Type
/dev/sda1 * 2048 195311615 195309568 93.1G 8e Linux LVM
/dev/sda2 565311488 584841215 19529728 9.3G 82 Linux swap / Solaris
/dev/sda3 195311616 196288511 976896 477M 83 Linux
/dev/sda4 196288512 565311487 369022976 176G 8e Linux LVM
```
sudo pvs
```
[sudo] password for production:
PV VG Fmt Attr PSize PFree
/dev/sda1 vg1 lvm2 a-- 269.56g 222.31g
/dev/sda4 vg1 lvm2 a-- 175.96g 175.96g
```
Ubuntu version
```
lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 16.04.3 LTS
Release: 16.04
Codename: xenial
```
What's the best method to fix this issue?
|
2017/10/23
|
[
"https://askubuntu.com/questions/968304",
"https://askubuntu.com",
"https://askubuntu.com/users/751054/"
] |
Well then, LVM has a wrong idea of the size of sda1. Try:
```
sudo pvresize /dev/sda1
```
|
55,436,373 |
trying to write a function that will calculate present value of list of cash flows. I know that numpy can do this very easily but for an assignment I have to write my own function for this :/.
Here are the three cash flows in a list as well as discount rate.
```
cfList = [20, 50, 90]
r = 0.05
```
Here's the function i've written so far. f = 0 because I want to start with the first cash flow (in this case 20). i = 1 because for the first flow its raised to the 1st power and the second flow (50) will be squared and so on.
```
def npv(cfList, r):
f = 0
i = 1
pv = cfList[f] / ((1 + r) ** i)
while i < len(cfList):
f += 1
i += 1
return pv
print(npv(cfList, r))
```
However, this output only gives me the PV of the first cashflow, and not the sum of all three from the list. If you can help i appreciate it so much thanks !
|
2019/03/30
|
[
"https://Stackoverflow.com/questions/55436373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11081052/"
] |
You need to sum the individual cashflows within your function and return that. At the moment you are returning the value of pv of the first cashflow as you have a return statement in your for loop.
Also, I think the way you check your while loop against `i` will mean that you'll miss the last payment value. Usually you don't need to instantiate counter variables yourself (see my examples below):
```
def npv(cfList, r):
f = 0
i = 1
pv = cfList[f] / ((1 + r) ** i) # <-- this needs to be in the loop
while i < len(cfList): # <-- i will break loop before last payment is calculated.
f += 1
i += 1
return pv # <-- this return here is the issue
print(npv(cfList, r))
```
NPV being the sum of PV of all future cashflows, that is what you need to calculate. E.g.:
```
def npv(cfList, r):
sum_pv = 0 # <-- variable used to sum result
for i, pmt in enumerate(cfList, start=1): # <-- use of enumerate allows you to do away with the counter variables.
sum_pv += pmt / ((1 + r) ** i) # <-- add pv of one of the cash flows to the sum variable
return sum_pv # <-- only return the sum after your loop has completed.
```
Always remember that a `return` statement in a for-loop will break out of the loop the first time the `return` is encountered.
An alternate implementation would be to yield individual PVs from a PV generator and sum the results:
```
def pv_gen(cfList, r):
for i, pmt in enumerate(cfList, start=1):
yield pmt / ((1 + r) ** i)
print(sum(pv_gen(cfList, r)))
```
|
72,484,151 |
**Update:**
Due to my own fault of not mentioning, that `tool` is created in a `v-for` loop during render, I couldn't apply the proposed answers although they might have been correct.
In the end I did a workaround by adding following `css sudo element` to the parent of the `select` element:
```
&::after {
position: absolute;
content: 'Paragraph';
margin-right: .83rem;
font-size: .83rem;
place-self: center;
}
```
and setting it to `display: none`, when an item is selected.
**Original Question:**
I'm creating a `select` element in `vue 3` with help of `v-for`:
```
<template>
<select v-model="tool.action" @change="selectType(tool.action)">
<option v-for="option in options" :key="option" :value="option.value">{{ option.text }}</option>
</select>
</template>
<script setup>
const options: [
{ text: 'Heading 1', value: 'h1' },
{ text: 'Heading 2', value: 'h2' },
{ text: 'Heading 3', value: 'h3' },
{ text: 'Paragraph', value: 'p' },
]
</script>
```
Now I want to set a `placeholder` text in the `select box` to `Paragraph`. Usually it would work like this:
```
<select>
<option value="p" selected>Paragraph</option>
</select>
```
but `v-for` removes the option of setting `selected` manually so how do I do it?
|
2022/06/03
|
[
"https://Stackoverflow.com/questions/72484151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7826511/"
] |
A `<select>`'s *placeholder* is usually disabled and not one of the available options. You can do that with an `<option>` *before* your `v-for` of selectable `<option>`s:
```html
<template>
<select v-model="tool.action" @change="selectType(tool.action)">
<option disabled value="">Placeholder Option</option>
<option v-for="option in options" :key="option" :value="option.value">{{ option.text }}</option>
</select>
</template>
```
[demo 1](https://stackblitz.com/edit/vue3-placeholder-in-select?file=src%2Fcomponents%2FMyOptions.vue)
If you actually want to set the `<select>`'s *initial value*, you could set the `<select>`'s model (i.e., `tool.action`) to the desired value:
```html
<script setup>
⋮
tool.action = 'p' // initialize to 'Paragraph' option's value
</script>
```
[demo 2](https://stackblitz.com/edit/vue3-initial-value-for-select?file=src%2Fcomponents%2FMyOptions.vue)
|
14,733,232 |
so i have this code that uploads an image and resize it, and saves both
```
if(isset($_POST['submit']))
{
$sql="SELECT MAX(event_id) AS event_id FROM evenimente";
//$result=mysql_query($sql);
$prefix=mysql_query($sql);
$file=$_FILES['image']['tmp_name'];
$file2=$_FILES['image']['tmp_name'];
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);
//
$sizes = array();
$sizes['100'] = 100;
list(,,$type) = getimagesize($_FILES['image']['tmp_name']);
$type = image_type_to_extension($type);
move_uploaded_file($_FILES['image']['tmp_name'], 'images/'.$prefix.$type);
$t = 'imagecreatefrom'.$type;
$t = str_replace('.','',$t);
$img = $t('images/'.$prefix.$type);
foreach($sizes as $k=>$v)
{
$width = imagesx( $img );
$height = imagesy( $img );
$new_width = $v;
$new_height = floor( $height * ( $v / $width ) );
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
imagealphablending( $tmp_img, false );
imagesavealpha( $tmp_img, true );
imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
$c = 'image'.$type;
$c = str_replace('.','',$c);
$c( $tmp_img, 'images/th/'.$prefix.$type );
}
$location="images/" . $prefix.$type;
$sql="INSERT INTO evenimente (event_data, event_datasf, event_titlu, event_detalii, event_poza) VALUES ('". $_POST['data'] ."', '". $_POST['datasf'] ."', '". $_POST['titlu'] ."', '". $_POST['detalii'] ."', '$location') ";
mysql_query($sql);
//$prefix =mysql_insert_id();
include 'include.html';
echo 'OK!!!<br /> Redirecting';
echo "<meta http-equiv='refresh' content='1;adauga_eveniment.php'>";
}
}
```
so the code "works"...i have this problem i need to save the images with `the event_id`. but i can't make `$prefix` memorize the max id from my database and i don't know why...
hope you understand.
I can't use `mysql_insert_id();` because the id is generated after the aql submission, and i need the prefix before that... and `MAX` doesn't work...
I'm using the `event_id` as primary key...
Cheers
|
2013/02/06
|
[
"https://Stackoverflow.com/questions/14733232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2022106/"
] |
Your syntax is correct: `SELECT MAX(event_id) AS event_id FROM evenimente`
The problem is that you want to know the event\_id *before* it exists in the table.
SUGGESTION:
1) "insert" the new row
2) "select"the resulting event\_id
3) "update" the row
ALSO:
You're using the old, deprecated mysql API. Please familiarize yourself with either/both of the new mysqli/PDO APIs. And please consider using [prepared statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). They're more efficient ... and they help mitigate the risks of SQL injection attacks.
|
67,762,165 |
How can I do something if a user who joined less than 2 weeks ago sends a message in chat that has the `test` word in it ?
The only thing i could find was `discord.Member.joined_at`..which doesn't help me very much, just shows the time they joined.
I cannot use it like `if userjoin < 20160m:`
maybe something like deducting the current date with member join date to get the difference..
```
newjoined_words = ["test", "test2"]
@bot.listen("on_message")
async def on_message(msg):
for word in newjoined_words:
if word in msg.content.lower() and msg.author.joindate < 2w:
await ctx.send("working")
```
\*I know this may be a stupid question, but i never worked with datetime.
|
2021/05/30
|
[
"https://Stackoverflow.com/questions/67762165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14612274/"
] |
I got some help on the CDK.dev slack channel. I had the wrong `version`. It should be 1.2.0, the version of the Helm Chart. 2.2.0 is the version of the Controller.
Here's an official example of how to do this from the `aws-samples` GitHub repo: <https://github.com/aws-samples/nexus-oss-on-aws/blob/d3a092d72041b65ca1c09d174818b513594d3e11/src/lib/sonatype-nexus3-stack.ts#L207-L242>
|
251,606 |
I have created the following workflow 2013 inside our sharepoint online site, the workflow will get executed when the item is created inside ListA:-
[](https://i.stack.imgur.com/7YxOS.png)
The workflow will do these 3 steps:-
1. Create a new item inside another list named CommentBox.
2. Delete the item which was just created inside ListA.
3. Send an email containing the url of the item Which was created inside the workflow, on CommentBox list.
now i am not sure if there is a way to get the URL (Display form URL) for the item which i created inside the workflow on CommentBox list?. now as shown in the above picture i tried to get the `Varialbe:create`, but this will actually send a number, which i think it is the GUID for the newly added item. but seems there is not a way to get the URL for the newly added item, also i am unable to manually build the url for the display form, as seems the display form will only accept the ID and not the GUID.
Also if i define the workflow to send an email on the CommentBox list(the list where the current workflow is adding the item), then the workflow will not get fired. I think the reason is that if a workflow initiate an action (create list item in my case), then this action will not cause additional workflow to be sent..
so can anyone adivce on this please? how i can get the url for the item which is created inside the workflow?
Thanks
|
2018/10/26
|
[
"https://sharepoint.stackexchange.com/questions/251606",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/84413/"
] |
You can get the ID of the new item by using a lookup to the "CommentBox" list and then build the URL yourself.
Try this:
1. Create variable of type "Number" named "Id"
[](https://i.stack.imgur.com/rfwRy.png)
2. Just after the action "Create item" put action "Set Workflow Variable".
[](https://i.stack.imgur.com/JeSE3.png)
3. Configure the action as below:
[](https://i.stack.imgur.com/mUyW7.png)
4. Now you can use the variable "Id" in your email body
[](https://i.stack.imgur.com/I8TCd.png)
|
2,739,753 |
As the title says I'm looking for a general solution to a Diophantine equation of the form:
>
> $y^2 = x^2 + kx - m$
>
>
>
Where $x$ and $y$ are both positive integers. I know that $k$ and $m$ will always be a multiple of 2 if that helps.
Here are a few examples that I solved through brute force.
>
> 1. $y^2 = x^2 + 30 x - 28$
>
> $x = 2$
>
> $y = 6$
> 2. $y^2 = x^2 + 474 x - 554$
>
> $x = 45$
>
> $y = 151$
> 3. $y^2 = x^2 + 1802 x - 3018$
>
> $x = 37$
>
> $y = 255$
>
>
>
I'm a bit of a dummy so a thorough explanation would be much appreciated. Thanks in advance!
|
2018/04/16
|
[
"https://math.stackexchange.com/questions/2739753",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/552760/"
] |
*Hint:* Write $k=2b$. Then $y^2 = (x+b)^2 -b^2 - m$ and so $m+b^2=(x+b)^2 -y^2$ is a difference of two squares. Now use this [well-known fact](https://math.stackexchange.com/a/547420/589), which is easy to prove:
>
> $N \in \mathbb Z$ is a difference of two squares iff $N$ is odd or a multiple of $4$.
>
>
>
To be [explicit](https://math.stackexchange.com/a/934145/589), if $N=uv$ with $u$ and $v$ of the same parity, then
$$
N=uv=\left(\dfrac{u+v}2\right)^2 - \left(\dfrac{u-v}2\right)^2
$$
Therefore, the general solution of $y^2 = x^2 + kx - m$ follows from factoring $N=m+(\frac k2)^2$ as two factors of the same parity and using the formula above to find $x+\frac k2$ and $y$.
Let's see how this works for your first example:
$m+b^2=28+15^2=253=11\cdot 23=17^2-6^2$. Therefore, $x+15=17, y=6$. This is the only solution.
|
57,653,910 |
I'm writing a web application using Angular.
Each time a user navigates to the site, the app must perform a few server calls *before* the app is ready.
I have tried to define a function that must be resolved in Routes:
```
{path: '', resolve: {data: AppService}, children: [
{path: 'home', component: HomeComponent},,
{path: 'faq', component: FaqComponent},
{path: 'about', component: AboutComponent},
{path: 'contact', component: ContactComponent},
]}
```
and in AppServices I have the following function:
```
resolve(): Promise<any> {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('RESOLVING');
resolve();
}, 5000);
})
}
```
This does not work: The page a user navigates to is displayed before `resolve` is called.
**Question:** How can I define a function that must be resolved before the app is ready? This function must be called regardless of a user is navigating to `/` or `/foo` `/foo/bar` and must only be called the first time the user navigates to the app.
|
2019/08/26
|
[
"https://Stackoverflow.com/questions/57653910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1581803/"
] |
Add to app providers:
```
{
provide: APP_INITIALIZER,
useFactory: startupServiceFactory,
deps: [ Session ],
multi: true,
},
```
where:
```
export function startupServiceFactory(startupService: Session): Function {
return () => startupService.initialize();
}
```
replace the startupService.initialize() to your method.
the deps contains any dependency your service has, can be omitted.
example:
```
async initialize(): Promise<any> {
try {
if (!environment.production) {
this.user = await this.service.init();
this.role = this.user.role;
this.lang = this.user.lang;
this.translate.use(this.user.lang);
this.registerLocale();
this.navigate();
return;
}
this.router.navigateByUrl('/');
} catch (err) {}
}
```
|
1,705,098 |
When using the function `imagepng()` in PHP, how can I make sure the images that I save are saved with a transparent background?
|
2009/11/10
|
[
"https://Stackoverflow.com/questions/1705098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/170365/"
] |
Simply do this:
```
imagealphablending($img, false);
imagesavealpha($img, true);
```
Before outputting. Make sure that all source files (if you used any) are set to PNG 32-bit with transparency - if not the output may differ with black background or transparency does not comply.
|
39,202 |
How to find roots of $X^5 - 1$? (Or any polynomial of that form where $X$ has an odd power.)
|
2011/05/15
|
[
"https://math.stackexchange.com/questions/39202",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/9094/"
] |
It is easy to write down the solution in trigonometric functions, namely, $x=e^{2\pi i n/5}$ for $n=0,\ldots, 4$.
Here is an algebraic solution. First factor the polynomial as $$x^5-1=(x-1)(x^4+x^3+x^2+x+1).$$
The first factor gives you the obvious solution $x=1$. To find other roots, we need to solve the equation
$$ x^4+x^3+x^2+x+1=0.$$
Divides both sides by $x^2$, and use the fact that $(x+\frac{1}{x})^2=x^2+2+\frac{1}{x^2}$, we get
$$ (x+\frac{1}{x})^2 +(x+\frac{1}{x})-1=0$$
Set $y=x+\frac{1}{x}$, and we get a quadratic equation
$$ y^2+y-1=0,$$
which one may easily solve using quadratic formulas. Once we have solved for $y=y\_0, y\_1$, the equation reduces into two other quadratic equations
$$ x+ \frac{1}{x}= y\_i, \qquad i=0, 1 $$
or equivalently,
$$ x^2-y\_i x+1=0.$$
We just apply the quadratic formula again.
|
261,168 |
There are many "how do I do X" questions in Stack Overflow. I'm not counting questions with no merit ("do this for me"), but actual, useful questions that show research by the poster.
When the answer is "this is not possible, because of so and so", should that be an answer or rather a comment? Is there a general rule, or does it rather depend on how complex it is to reach that conclusion?
This [bounty question for Android](https://stackoverflow.com/questions/24006749/android-how-to-figure-out-if-email-was-sent-by-checking-sent-items) is an example of what I mean (especially since the bounty *explicitly* asks for a working solution).
|
2014/06/20
|
[
"https://meta.stackoverflow.com/questions/261168",
"https://meta.stackoverflow.com",
"https://meta.stackoverflow.com/users/82788/"
] |
If you can *actually* demonstrate that something is *impossible* (as opposed to simply not knowing how to do it), then go ahead and post it as an answer. Doing things this way
1. Lets you provide proof of your claim (such as a quote from spec or documentation explicitly stating that what the asker wants is not allowed), or at least a thorough description of what you consider to be all the possible ways to approach the problem and why they all fail.
2. Exposes your claim to voting, letting future visitors see whether the community agrees with it.
This is surely better than making a claim with no or minimal substantiation in a comment where voting can't be used to express disagreement and the details of the claim cannot be argued over and amended.
Consider [these](https://stackoverflow.com/questions/16804576/is-there-any-way-to-remove-photo-tags-with-facebook-api/17381078#17381078) [answers](https://stackoverflow.com/a/13059497/1709587) of mine which claim (at great length) that what the question asker is requesting is impossible. It would plainly not have been more helpful for either the question asker or future visitors if I had only posted a short comment simply stating that the task was impossible without justification - why would anyone believe me if I won't show my working? An answer is often the only tool that gives you enough space to demonstrate that something cannot be done and thus prevent the question asker, or future visitors, from pointlessly reproducing your work pursuing the impossible.
Remaining silent for the sake of some vague idea that these aren't "answers" would probably have wasted dozens of man-hours of people futilely performing exactly the same tests as me, and helped nobody.
|
66,452,884 |
So I'm trying to train Keras model. There is high accuracy (I'm using f1score, but accuracy is also high) while training and validating. But when I'm trying to predict some dataset I'm getting lower accuracy. Even if I predict training set. So I guess it's not about overfitting problem. What then is the problem?
```
import matplotlib.pyplot as plt
skf = StratifiedKFold(n_splits=5)
for train_index, test_index in skf.split(X, y):
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
X_train,x_val,y_train,y_val = train_test_split(X_train, y_train, test_size=0.5,stratify = y_train)
y_train = encode(y_train)
y_val = encode(y_val)
model = Sequential()
model.add(Dense(50,input_dim=X_train.shape[1],activation='tanh'))
model.add(Dropout(0.5))
model.add(Dense(25,activation='tanh'))
model.add(Dropout(0.5))
model.add(Dense(10,activation='tanh'))
model.add(Dropout(0.5))
model.add(Dense(2, activation='softmax'))
opt = Adam(learning_rate=0.001)
model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['acc', ta.utils.metrics.f1score])
history = model.fit(X_train, y_train,
validation_data=(x_val, y_val),
epochs=5000,
verbose=0)
plt.plot(history.history['f1score'])
plt.plot(history.history['val_f1score'])
plt.title('model accuracy')
plt.ylabel('f1score')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
break
```
The result is [here](https://i.stack.imgur.com/AaVUB.png). As you can see results high at training and validation set.
And code for predict:
```
from sklearn.metrics import f1_score
y_pred = model.predict(x_train)
y_pred = decode(y_pred)
y_train_t = decode(y_train)
print(f1_score(y_train_t, y_pred))
```
The result is 0.64, that is less than expected 0.9.
My decode and encode:
```
def encode(y):
Y=np.zeros((y.shape[0],2))
for i in range(len(y)):
if y[i]==1:
Y[i][1]=1
else :
Y[i][0]=1
return Y
def decode(y):
Y=np.zeros((y.shape[0]))
for i in range(len(y)):
if np.argmax(y[i])==1:
Y[i]=1
else :
Y[i]=0
return Y
```
|
2021/03/03
|
[
"https://Stackoverflow.com/questions/66452884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10637002/"
] |
Since you use a last layer of
```
model.add(Dense(2, activation='softmax')
```
you should **not** use `loss='binary_crossentropy'` in `model.compile()`, but `loss='categorical_crossentropy'` instead.
Due to this mistake, the results shown during model fitting are probably wrong - the results returned by sklearn's `f1_score` are the real ones.
Irrelevant to your question (as I guess the follow-up one will be *how to improve it?*), we practically never use `activation='tanh'` for the hidden layers (try `relu` instead). Also, dropout should *not* be used by default (especially with such a high value of 0.5); comment-out all dropout layers and only add them back if your model overfits (using dropout when it is not needed is known to hurt performance).
|
13,577,798 |
How do I get values from a vector to be the values of the diagonal in a matrix? I'm using python.
|
2012/11/27
|
[
"https://Stackoverflow.com/questions/13577798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1855428/"
] |
Here is a list comprehension that will do it:
```
[[v[i] if i==j else 0 for i in range(len(v))] for j in range(len(v))]
```
|
15,826,095 |
Assuming a basic method:
```
std::string StringTest()
{
std::string hello_world("Testing...");
return std::move(hello_world);
}
```
How should I use the output:
Option A:
```
auto& string_test_output=StringTest();
```
Option B:
```
auto string_test_output=StringTest();
```
Is StringTest() a temporary value? If so, Option A would not be safe. If it's not a temporary value, I have a feeling that Option B would cause a copy.
I am still getting used to RValue references so returning by value is still very scary as I don't want copying to occur or run into unnecessary copying!
|
2013/04/05
|
[
"https://Stackoverflow.com/questions/15826095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/965619/"
] |
The best way to do it would be to change your method to this:
```
std::string StringTest()
{
std::string hello_world("Testing...");
return hello_world;
}
```
There is no need to tell the function that the returned object should be an rvalue, this comes automatically from the value being a temporary - that is, it is not bound to any name at the call site. As such, the initialized will value already be move-constructed (unless the temporary inside the function is elided entirely), with no need for you to manually express such an intention.
Also, since your return type is `std::string`, you will return by value, not by rvalue-reference, so there is no point to moving the return argument before returning. In fact, calling `std::move` will have no effect other than possibly tricking your compiler to perform an additional unnecessary move-constructor before returning your value. Such a trick serves no purpose other than making your code slightly more complex and possibly slower to run.
You also do want to return by value. One reason is because of [Return Value Optimization (RVO)](http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/ "Return Value Optimization"). Most compilers will do this, which means you're better off just returning a "copy" which gets elided than trying to be clever and returning a reference.
Even when RVO cannot be applied, returning it by rvalue-reference still does not change how it is returned. When the value is returned, since it is a temporary at the call site, the returned value will already be an rvalue which can be passed along by rvalue reference to whatever function needs it as an argument. For instance, if you use the return value to intialize a variable and the return value is not elided, the move constructor still be called if available. So, not much is lost by simply returning by value.
Given this, you should probably do one of these to catch the value:
```
auto string_test_output = StringTest();
std::string string_test_output = StringTest();
```
|
10,275,135 |
I'm trying to implement BigInt subtract one, and want to optimize my code. Right now I just iterate over the number string, e.g. "1241241291919191904124142398623500000000000000" and in order to subtract one, all the trailing zeroes need to be replaced with nines.
How would I do this with regex?
What is a smart way to use regex to implement the BigInt subtractOne(string) function? It has a couple special cases.
This is what I have so far to match the trailing zeroes:
```
m = re.search('(?<=[1-9])0+$', '91000')
```
|
2012/04/23
|
[
"https://Stackoverflow.com/questions/10275135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/818304/"
] |
Use a [lookahead assertion](http://www.regular-expressions.info/lookaround.html):
```
import re
s = "1241241291919191904124142398623500000000000000"
r = re.compile("""0 # Match 0
(?= # only if the following can be matched here:
0* # zero or more 0s
$ # until the end of the string.
) # End of lookahead assertion""", re.VERBOSE)
```
Now you can do
```
>>> r.sub("9", s)
'1241241291919191904124142398623599999999999999'
```
|
66,501,609 |
My parent component has a next button that should be disabled till a user enters a value in any one of the controls that the child control has. The child control has dropdown lists, a textbox, and a date calendar control. I was thinking of using an output emitter for each of these controls and the button would be enabled if any of the value changes. However, I don't think it'll be that straightforward and I'm wondering if there's an easier way.
Here is the less simplified code
Parent component's html:
```
<ng-container [ngSwitch]="activeLayout">
<ng-container *ngSwitchCase="repair">
<app-repair [functionTypeCode]="functionTypeCode"></app-repair>
</ng-container>
<ng-container *ngSwitchCase="confirm">
<app-confirm [actionSelected]="actionSelected" [functionTypeCode]="functionTypeCode">
</app-confirm>
</ng-container>
</ng-container>
<ng-container [ngSwitch]="activeLayout">
<ng-container *ngSwitchCase="repair">
<button class="btn btn-sm btn-outline-secondary" style="height: 34px" type="button">Next</button>
</ng-container>
</ng-container>
```
Child component's html:
```
<div class="row" *ngIf="showIfUnit()">
<div class="col">
<app-dropdown placeholderLabel="Find Country Code..." label="For Country Code"
[(selected)]="selectedCountryValue" [dropdownData]="countryList">
</app-dropdown>
</div>
</div>
<div class="row">
<div class="col">
<input matInput [(ngModel)]="selectedExec" name="exec" />
</div>
</div>
<div class="row">
<div class="col">
<mat-form-field>
<mat-label>Order Date</mat-label>
<input matInput [matDatepicker]="pickerOrderDate" [(ngModel)]="selectedOrderDate">
<mat-datepicker-toggle matSuffix [for]="pickerOrderDate"></mat-datepicker-toggle>
<mat-datepicker #pickerOrderDate appendTo="body"></mat-datepicker>
</mat-form-field>
</div>
</div>
```
So if a value isn't selected in the dropdown list or nothing is entered into the textbox or the date hasn't been picked from the calendar control, the button on the parent should be disabled. Once any of those are selected on the child component, the button should be enabled.
**EDIT: Added ng-containers**
Thanks!
|
2021/03/06
|
[
"https://Stackoverflow.com/questions/66501609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8233658/"
] |
I think I have a solution for you. You can achieve that by using `@Output() informParent = new EventEmitter();`. Here is my code and stackblitz link below=>
**Child HTML:**
```
<label>Combo From Child:</label>
<select
[(ngModel)]="temp" (ngModelChange)="ngChange($event)">
<option *ngFor="let item of countries"
[value]="item.id">{{item.name}}
</option>
</select>
```
**Parent HTML:**
```
<button [disabled]="isbuttonDisable">Parent From Button</button>
<br>
<child message="Message from parent to child" (informParent)="parentWillTakeAction($event)"></child>
```
**Child TS:**
```
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
temp:any;
@Input() message: string;
@Output() informParent = new EventEmitter();
countries = [{
id: 1, name: 'France', cities: ['Paris', 'Marseille', 'Nice']
},
{
id: 2, name: 'Germany', cities: ['Hamburg', 'Berlin', 'Munich']
},
{
id: 3, name: 'Italy', cities: ['Roma', 'Milan', 'Napoli']
},
];
ngChange($event){
console.log($event);
console.log(this.temp);
this.informParent.emit(this.countries.find(c=>c.id==this.temp));
}
}
```
**Parent TS:**
```
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
messageFromChild: string = '';
isbuttonDisable:boolean=true;
parentWillTakeAction(message){
this.messageFromChild = message.name+' was Selected.';
this.isbuttonDisable=false;
}
}
```
**Note:** Please check the [Stackblitz Link Demo](https://stackblitz.com/edit/angular-parent-to-child-communication-1l3bev?file=src%2Fapp%2Fapp.component.ts).
|
54,489,406 |
I want to find number of student taken classes of every subject semester wise.
Below is the query which gives right answer
```
select semester,subject,count(stdId)
from tblSubjectMaster
group by subject, semester
```
But I have tried also other query and It is giving different result. Query is
```
select semester,subject,count(stdId)
from tblSubjectMaster
group by subject and semester
```
what is the difference between , and and in group by?
|
2019/02/02
|
[
"https://Stackoverflow.com/questions/54489406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5202470/"
] |
Comma separates expressions. `group by subject, semester` is creating a separate group for each distinct pair of values. I think that's what you want.
The example using `AND` is only one boolean expression, with only two distinct groups, one for **true** and one for **false**. `AND` is a boolean operator. It evaluates its two operands and then gives the boolean conjunction between them.
So it evaluates both `subject` and `semester` as booleans only, and then if both are true, then the whole boolean expression is true. That's the way a boolean `AND` works.
MySQL treats booleans as the same thing as integer values 1 for true and 0 for false. So it will evaluate `subject` and `semester` as numbers. This may give unexpected results.
You should use the comma if you want to group by two columns.
|
63,478,519 |
The project is at this [Github Repository](https://github.com/samgermain/SealsSounds_ReactNative). The file with the code is at `components/Soundboard.js`
---
This code was working previously, but now it looks like the promise is running forever. It looks like neither the resolve function, nor the reject function are executing because if I uncomment all the commented lines below and call the function `askForPurchase()` the only things printed to the console are
* an object that looks like `"_40": 0, "_55": {"_40": 0, "_55": null, "_65": 0, "_72": null}, "_65": 3, "_72": null}` for the line `console.log(RNIap.getPurchaseHistory())`
* and then the word `end`.
The `buyProduct()` function also is no longer initializing an IAP.
```
const buyProduct = function(){
RNIap.requestPurchase("1985162691", false).then(purchase => {
store.dispatch(setPurchases(purchase))
await RNIap.finishTransaction(purchase, false) //developerPayloadAndroid?: string Should I use this argument? I don't get how to use it
}).catch((error) => {
console.log(error.message);
})
}
const askForPurchase = function(){
if (!store.getState().purchase){
//console.log(RNIap.getPurchaseHistory())
RNIap.getPurchaseHistory().then(purchase => {
//console.log(`test1`)
store.dispatch(setPurchases(purchase))
if (purchase.length == 0){
//console.log(`test if`)
buyProduct()
}else{
//console.log(`test else`)
RNIap.getAvailablePurchases()
}
}, reason => {
console.log(reason)
})
//console.log(`end`)
}
}
```
---
**EXTRA**
This code was working a few months ago and I even pulled a commit(*1b9cb81f229680e173ce910892dddedc632c1651, comment: "Made the seal pic more cartoony"*) from that time to test out. After pulling this commit, I deleted my node\_modules and pods, and cleaned my build folder, but the `askForPurchase()` and `buyProduct()` functions no longer work in that commit either.
I am testing this on a real iPhone SE running ios 13.6.1
---
I created a sandbox tester if you need to test it out, but I don't think you'll need it
```
email: [email protected]
pw: Somepassword1
```
|
2020/08/19
|
[
"https://Stackoverflow.com/questions/63478519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6331353/"
] |
hello @Sam problem is async await problem they are not able to get value because they are not waiting to get data before getting data its firing without data and it was returning promise so you have to use [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)
so your code be like
```
const buyProduct = async()=>{
await RNIap.requestPurchase("1985162691", false).then(purchase => {
store.dispatch(setPurchases(purchase))
await RNIap.finishTransaction(purchase, false) //developerPayloadAndroid?: string Should I use this argument? I don't get how to use it
}).catch((error) => {
console.log(error.message);
})}
const askForPurchase = async()=>{
if (!store.getState().purchase){
//console.log(await RNIap.getPurchaseHistory())
await RNIap.getPurchaseHistory().then(purchase => {
//console.log(`test1`)
store.dispatch(setPurchases(purchase))
if (purchase.length == 0){
//console.log(`test if`)
buyProduct()
}else{
//console.log(`test else`)
RNIap.getAvailablePurchases()
}
}, reason => {
console.log(reason)
})
//console.log(`end`)
}}
```
|
7,420,206 |
I remember someone telling me that the features of the [Easing](http://gsgd.co.uk/sandbox/jquery/easing/) plugin may now be included in the jQuery core, or in jQuery UI. Is that true? Is the plugin still needed if using the current version of jQuery?
|
2011/09/14
|
[
"https://Stackoverflow.com/questions/7420206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/770127/"
] |
There are only two easing modes included in the jQuery library. From the documentation:
>
> The only easing implementations in the jQuery library are the default,
> called `swing`, and one that progresses at a constant pace, called
> `linear`. More easing functions are available with the use of plug-ins, most notably
> [the jQuery UI suite](http://jqueryui.com/).
>
>
>
Source: <http://api.jquery.com/slideDown/>
Here is a [showcase of easing modes included in jQUery UI](http://jqueryui.com/demos/effect/#easing)
|
45,175,408 |
Can anyone explain how x^-1 is being executed in below code. I tried but no luck. I understood how x^1 is being executed.
```
#include <stdio.h>
int main(void)
{
int a=220, b=221, c=3;
printf("a^1= %d ,, a^-1= %d \n", a^1, a^-1);
printf("b^1= %d ,, b^-1= %d \n", b^1, b^-1);
printf("c^1= %d ,, c^-1= %d \n", c^1, c^-1);
return 0;
}
/* output: a^1= 221 ,, a^-1= -221
b^1= 220 ,, b^-1= -222
c^1= 2 ,, c^-1= -4 */
```
|
2017/07/18
|
[
"https://Stackoverflow.com/questions/45175408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7167267/"
] |
The `^` operator is the `XOR` or [exclusive-or](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) operator in C.
To make it simple, consider 8-bit signed values, using the typical [two's-complement encoding](https://en.wikipedia.org/wiki/Two%27s_complement). The `int` type will work in the same way.
```
Decimal Binary
1 00000001
-1 11111111
-------- XOR
-2 11111110
```
Note that the unary operator `-` has higher precedence that the `^` bitwise operator.
|
40,216,392 |
I have an private App that works great till I upgraded my phone to Android 7.
The issue is I need picker to choose only month and year (with no day).
On the old Android versions, I had this one:
[](https://i.stack.imgur.com/0mtEn.png)
but - after the upgrade, all I can choose is:
[](https://i.stack.imgur.com/bo3Fi.png)
Is there a way to set the picker in the app to be the old style, or any other idea to select only month and year?
I tried the theme style parameter on the constructor like this:
```
final Calendar c = Calendar.getInstance();
DatePickerDialog dpd = new DatePickerDialog(context, android.R.style.Theme_Holo_Dialog ,listener,
c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
```
But it did not helped either, I am getting same results (different theme):
[](https://i.stack.imgur.com/irzWK.png)
Why does it change in the first place without me as developer setting it to the new picker?
You can see the clean code here:
[GitHub DatePicker test](https://github.com/gabik/AndroidDatePickerTest)
|
2016/10/24
|
[
"https://Stackoverflow.com/questions/40216392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/408628/"
] |
Try this:-
```
DatePickerDialog datepickerdialog = new DatePickerDialog(getActivity(),
AlertDialog.THEME_HOLO_LIGHT,this,year,month,day);
datepickerdialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
// arg1 = year
// arg2 = month
// arg3 = day
}
};
```
|
848,357 |
I am doing manual layouting for my Cocoa application and at some point I need to figure out what the inner size of a NSView subclass is. (E.g. What is the height available for my child view inside of a NSBox?)
One of the reasons is that I am using a coordinate system with origin at the top-left and need to perform coordinate transformations.
I could not figure out a way to get this size so far and would be glad if somebody can give me a hint.
Another very interesting property I would like to know is the minimum size of a view.
|
2009/05/11
|
[
"https://Stackoverflow.com/questions/848357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/79204/"
] |
`-bounds` is the one you're looking for in most views. NSBox is a bit of a special case, however, since you want to look at the bounds of the box's content view, not the bounds of the box view itself (the box view includes the title, edges, etc.). Also, the bounds rect is always the real size of the box, while the frame rect can be modified relative to the bounds to apply transformations to the view's contents (such as squashing a 200x200 image into a 200x100 frame).
So, for most views you just use `[parentView bounds]`, and for NSBox you'll use `[[theBox contentView] bounds]`, and you'll use `[[theBox contentView] addSubview: myView]` rather than `[parentView addSubview: myView]` to add your content.
|
17,786,513 |
I have some code which strips out illegal characters from a user entered string upon the ON\_EN\_CHANGE call.
So need to correct the curser position if any are removed.
To do so I have been attempting to use GetSel to retrieve the position, then setsel to set it as below. f is another int variable.
```
m_ExportDirectory.GetWindowTextA(directory);
//characters removed here
if (rem > 0)
{
int j;
m_ExportDefaultName.GetSel(f, j);
m_ExportDirectory.SetWindowTextA(directory);
m_ExportDefaultName.SetSel(f-rem, f-rem);
}
```
But getsel always sets both f & j to 0. I have attempted moving its call to above the GetWindowText but with no change.
Am I doing something stupid? If not Any ideas?
Thanks
|
2013/07/22
|
[
"https://Stackoverflow.com/questions/17786513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2036256/"
] |
I think the problem is that `GetSel()` returns the *selection* start and end position. You get (0,0) because no text is selected by the user.
|
55,620,119 |
I'm trying to execute the query below but the problem is that it shows execute a bunch of nonsense what I want it to show those who are female dependent and there associated employee first name ....... where is my failing point + I have to use union operator
```
SELECT Dep_FName AS 'First name' ,Dep_LName AS 'Last name' ,Em_FName AS 'Employee"s First name'
FROM evnt_db.dependent,evnt_db.employee
where Dep_gender='F'
Union SELECT Dep_FName AS 'First name' ,Dep_LName AS 'Last name' ,Em_FName AS 'Employee"s First name'
FROM evnt_db.dependent as d,evnt_db.employee as e
where d.Emp_Id=e.Em_Id ;
```
|
2019/04/10
|
[
"https://Stackoverflow.com/questions/55620119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10484766/"
] |
Union only selects distinct values, so maybe it is filtering overlap out. Also I don't know why you need to use Union for this statement since you are selecting from the same table. You could just use an OR in the where of the first half of the query.
```
SELECT Dep_FName AS 'First name ',Dep_LName AS 'Last name '
FROM evnt_db.dependent
where Dep_gender='F' OR Relationship='Wife';
```
If you must use UNION, this should work. I think you query had something weird with the parenthesis. Also the column names have to be identical in a UNION statement. There was an extra space on `'Last name '` and not on the other `'Last name'`
```
SELECT Dep_FName AS 'First name ',Dep_LName AS 'Last name '
FROM evnt_db.dependent
where Dep_gender='F'
UNION
SELECT Dep_FName AS 'First name ',Dep_LName AS 'Last name '
FROM evnt_db.dependent
where Relationship='Wife';
```
If you want to get the duplicate records (prevent union from filtering duplicates), use `UNION ALL` instead of just `UNION`
|
69,275,040 |
I have 2 ArrayLists:
```
private List<Client> clientList = new ArrayList<Client>();
private List<Client> sortedClientList = new ArrayList<Client>();
```
I sort `clientList` like this:
```
clientList.sort(Comparator.comparing(Client::getScore));
```
What I want to do, is to "clone" all the content in the same order to the sortedClientList, but I'm doing something wrong.
I tried `sortedClientList.add(clientList.sort(Comparator...` and `sortedClientList.addAll(clientList.sort(Comparator...` however I get the error `The method add(Client) in the type List<Client> is not applicable for the arguments (void)`
My goal is to have a sorted list but in a separate object, thus `sortedClientList`
|
2021/09/21
|
[
"https://Stackoverflow.com/questions/69275040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11739100/"
] |
The method is of type `void` meaning it doesn't return an object and therefore you cannot pass it as it if were an object.
```
clientList.sort(...)
```
this method sorts the elements of the `clientList`, it does not create a copy of `clientList` with the elements sorted.
What you're looking for is to make a sorted copy of the `clientList`, a similar question is posed here: [Sorted copy construction for ArrayList](https://stackoverflow.com/questions/12726696/sorted-copy-construction-for-arraylist)
|
36,871,297 |
I am working on some image processing in my app. Taking live video and adding an image onto of it to use it as an overlay. Unfortunately this is taking massive amounts of CPU to do which is causing other parts of the program to slow down and not work as intended. Essentially I want to make the following code use the GPU instead of the CPU.
```
- (UIImage *)processUsingCoreImage:(CVPixelBufferRef)input {
CIImage *inputCIImage = [CIImage imageWithCVPixelBuffer:input];
// Use Core Graphics for this
UIImage * ghostImage = [self createPaddedGhostImageWithSize:CGSizeMake(1280, 720)];//[UIImage imageNamed:@"myImage"];
CIImage * ghostCIImage = [[CIImage alloc] initWithImage:ghostImage];
CIFilter * blendFilter = [CIFilter filterWithName:@"CISourceAtopCompositing"];
[blendFilter setValue:ghostCIImage forKeyPath:@"inputImage"];
[blendFilter setValue:inputCIImage forKeyPath:@"inputBackgroundImage"];
CIImage * blendOutput = [blendFilter outputImage];
EAGLContext *myEAGLContext = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
NSDictionary *contextOptions = @{ kCIContextWorkingColorSpace : [NSNull null] ,[NSNumber numberWithBool:NO]:kCIContextUseSoftwareRenderer};
CIContext *context = [CIContext contextWithEAGLContext:myEAGLContext options:contextOptions];
CGImageRef outputCGImage = [context createCGImage:blendOutput fromRect:[blendOutput extent]];
UIImage * outputImage = [UIImage imageWithCGImage:outputCGImage];
CGImageRelease(outputCGImage);
return outputImage;}
```
|
2016/04/26
|
[
"https://Stackoverflow.com/questions/36871297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2394443/"
] |
Suggestions in order:
1. do you really need to composite the two images? Is an `AVCaptureVideoPreviewLayer` with a `UIImageView` on top insufficient? You'd then just apply the current ghost transform to the image view (or its layer) and let the compositor glue the two together, for which it will use the GPU.
2. if not then first port of call should be CoreImage — it wraps up GPU image operations into a relatively easy Swift/Objective-C package. There is a simple composition filter so all you need to do is make the two things into `CIImage`s and use `-imageByApplyingTransform:` to adjust the ghost.
3. failing both of those, then you're looking at an OpenGL solution. You specifically want to use `CVOpenGLESTextureCache` to push core video frames to the GPU, and the ghost will simply permanently live there. Start from the [GLCameraRipple sample](https://developer.apple.com/library/ios/samplecode/GLCameraRipple/Introduction/Intro.html) as to that stuff, then look into `GLKBaseEffect` to save yourself from needing to know GLSL if you don't already. All you should need to do is package up some vertices and make a drawing call.
|
31,046,697 |
This is my first app using *Angularjs*.
I'm creating an app using **AngularJs** which brings tour details from API response. I have multiple controller, each controller has a different pages.
My problem is I have four links (links look like Spanish, France, India, America, etc.) on my each page footer. If I click on one of them, I should show respective API results on the main controller. Please look into the below diagram for understating pageflow.

Thank you in advance!!
|
2015/06/25
|
[
"https://Stackoverflow.com/questions/31046697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3598557/"
] |
I think your code is okay, I am also doing same and got to know from payu that **test** **merchant\_key** and **salt** is not working currently. Try for production mode.
If you want to load data from server use(postUrl):
```
post_Data = "hash="+PayMentGateWay.this.hash+"&key="+merchant_key+"&txnid="+PayMentGateWay.this.params.get("txnid")+"&amount="+PayMentGateWay.this.params.get("amount")+
"&productinfo="+PayMentGateWay.this.params.get("productinfo")+"&firstname="+PayMentGateWay.this.params.get("firstname")+
"&email="+PayMentGateWay.this.params.get("email")+"&phone="+PayMentGateWay.this.params.get("phone")+
"&surl="+PayMentGateWay.this.params.get("surl")+"&furl="+ PayMentGateWay.this.params.get("furl")+
"&service_provider="+ "payu_paisa";
webView.postUrl("https://secure.payu.in/_payment", EncodingUtils.getBytes(post_Data, "base64"));
```
I hope this help.
|
36,127,253 |
I am trying to train a new model with the Stanford CoreNLP implementation of the neural network parser of Chen and Manning (2014). During training, I use the `-devFile` option to do a UAS evaluation on the development set every 100 iterations. After a few thousand iterations I get a fairly good UAS (around 86 per cent). However, after the training is completed and I try to test it on the same development set, I get a UAS of around 15 per cent. I am using the English Universal Dependencies treebank.
Command line options for training:
```
java edu.stanford.nlp.parser.nndep.DependencyParser -trainFile ~/Datasets/universal-dependencies-1.2/UD_English/en-ud-train.conllu -devFile ~/Datasets/universal-dependencies-1.2/UD_English/en-ud-dev.conllu -embedFile path/to/wordvecs -embeddingSize 100 -model nndep.model.txt.gz -trainingThreads 2
```
Command line options for testing:
```
java edu.stanford.nlp.parser.nndep.DependencyParser -model nndep.model.txt.gz -testFile ~/Datasets/universal-dependencies-1.2/UD_English/en-ud-dev.conllu
```
When I use the provided UD model for English everything works fine, and I get a UAS of around 80 per cent on the development set. This leads me to believe that my trained model is subpar, and that I might have missed some needed step or option. But since the evaluation during training gives pretty good results, I am a bit confused. From my understanding there should not be that big of a difference between these two evaluations.
So, what might be the cause of the large discrepancy between the evaluation during training versus that at testing time?
|
2016/03/21
|
[
"https://Stackoverflow.com/questions/36127253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6082557/"
] |
Absolutely. If you look at the Thread.java class of the standard library, you'll see this line:
```
/* What will be run. */
private Runnable target;
```
<http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Thread.java#154>
|
14,383,039 |
Safari and Chrome can execute JavaScript via AppleScript
**Safari:**
```
tell application "Safari"
open location "http://example.com"
activate
do JavaScript "alert('example');" in current tab of first window
end tell
```
**Chrome:**
```
tell application "Google Chrome"
open location "http://example.com"
activate
execute front window's active tab javascript "alert('example');"
end tell
```
**Is there a way to do this in Firefox?**
*Note: Same question for Opera is here: [AppleScript - JavaScript execution on Opera](https://stackoverflow.com/questions/14383302/applescript-javascript-execution-on-opera)*
*I thought about asking them together, but I decided to ask two separate questions to be able to accept answers separately.*
|
2013/01/17
|
[
"https://Stackoverflow.com/questions/14383039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/624808/"
] |
If you use surf features, thats mean a float set off vector [128] or [64] depending of you surf configuration you will be set the neural net as follow
-Create a data base with models :
```
-bikes
-cars
-autobus
-truck
```
-Take diferents photos of each type of objects like 10 photos of diferents model off cars, 10 photos of diferents model off bikes 10 photos of differents model off truck... etc, to each photo off each object class extract its surf feature vectors.
-Each type of object will be represent one off class of object in the neural-net like this;
```
-car ;object class 1 =binary representaation in 4 bits= 0 0 0 1
-bikes ;obejct class 2 =binary representaation in 4 bits= 0 0 1 0
-truck ;obejct class 3 =binary representaation in 4 bits= 0 0 1 1
-ball ;obejct class 4 =binary representaation in 4 bits= 0 1 0 0
```
-Each bit in binary repesentacion will be correspond to one neuron in the output layer of the network and represent one class of object to be recognized
Now the configuration of neural network will be based on the size of the feature vector and the number of types of object that you wanna recognize in this way;
The Number of nuerons in the input-layer;64 or 128 depending of the size off surf feature vector that you configured and used
The number of nuerons in the output-layer in the neural-net will be the number of classes of objects that you wanna recognize in this example 4
The activation function neecesary to each neuron is the sigmoid or tanh function (<http://www.learnartificialneuralnetworks.com/>), beacause the surf features are represented by floats numbers, if you use freak fetaures or another binary local feature descriptor (Brisk, ORB, BRief ) then you will be use an binary activation function to each neuron like step function o sigm function
The algoritm used to train the network is the backpropagation
before continue you need set and prepare the data set to train the neural network
example
```
-all feature vector extracted from picture belong a car will be label or asociated to class 1
-all feature vector extracted from picture belong a bike will be label or asociated to class 2
-all feature vector extracted from picture belong a truk will be label or asociated to class 3
-all feature vector extracted from picture belong a ball will be label or asociated to class 4
```
to this example you will have 4 neurons in out-put layer and 128 0r 64 neurons of in input-layer.
-The output of neural net in recognittion mode will be the neuron that have the most hight value of this 4 nuerons.
its necesarry use normalization in the interval [0,1] to all features in the data set, before begin the training phase,because the out-put of the neural net is the probability that have the input vector to belong at one class of object in the data set.
the data set to train the network have to be split as follow:
```
-70% off the data used to train
-15% off the data used to validate the network arquitecture (number of neurons in the hidden layyer)
-15% off the data used to test the final network
```
when training the neural network, the stop criterion is recognittion rate,when its is near to 85-90%
why use neural net and not svm machines, svm machines work fine ,but it not can be make a the best separation class map in no linear classification problems like this or when you have lot of diferents objects classes or types of objects, this lack is aprecciate in the recognittion phase results
I recomended you read some about the neural network theory to understand how they work
<http://link.springer.com/chapter/10.1007%2F11578079_10>
opencv have machine learning class to neural nets mlp module
hope this can help you
|
154,340 |
How can I verify the property $x(t)\delta(t)=x(0)\delta(t)$ in Mathematica? I tried with:
```
In[5]:= x[t_] := t
In[6]:= x[t] DiracDelta[t] == x[0] DiracDelta[t]
Out[6]= t DiracDelta[t] == 0
```
I expect the output True.
Thank you in advance.
|
2017/08/23
|
[
"https://mathematica.stackexchange.com/questions/154340",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/42100/"
] |
As noted by Bob Hanlon in the comments, $\delta(t)$ is not defined outside of integrals, so it doesn't make any sense to ask the question whether $x(t)\delta(t)=x(0)\delta(t)$.
However, what you can do is verify that both expressions behave the same under the integral, i.e. that $\int f(t) g(t)\mathrm{d}t$ is the same for $f(t)=x(t)\delta(t)$ and $f(t)=x(0)\delta(t)$:
```
In[1]:= Integrate[x[t] DiracDelta[t] f[t], t] == Integrate[x[0] DiracDelta[t] f[t], t]
Out[1]:= True
```
Here, you don't need to define anything for `x[t]`, as this is true for all `x[t]`.
### Update 2
As noted in the comments, we should only consider definite integrals. This leads to the following definition of `GeneralizedEqual`:
```
GeneralizedEqual[f_, g_, t_, opts : OptionsPattern[]] :=
Integrate[h[t] f, {t, -Infinity, Infinity}, opts]
== Integrate[h[t] g, {t, -Infinity, Infinity}, opts]
```
With this definition, we can also prove the generalized version of the original equation (again, see comments), $\delta(t-T)x(t)"="\delta(t-T)x(T)$:
```
In[1]:= GeneralizedEqual[DiracDelta[t - T] f[t], DiracDelta[t - T] f[T], t]
Out[1]= ConditionalExpression[True, T \[Element] Reals]
```
### Update
To make it a bit nicer to look at, you can introduce a generalized version of `==`:
```
In[1]:= GeneralizedEqual[f_, g_, t_] := Integrate[h[t] f, t] == Integrate[h[t] g, t]
In[2]:= GeneralizedEqual[x[t] DiracDelta[t], x[0] DiracDelta[t], t]
Out[2]:= True
```
|
32,415,374 |
I need to split a tag that looks something like "B1/AHU/\_1/RoomTemp", "B1/AHU/\_1/109/Temp", so with a variable with a variable number of fields. I am interested in getting the last field, or sometimes the last but one. I was disappointed to find that negative indexes do not count from the right and allow me to select the last element of an array in Hive as they do in Python.
```
select tag,split(tag,'[/]')[ -1] from sensor
```
I was more surprised when this did not work either:
```
select tag,split(tag,'[/]')[ size(split(tag,'[\]'))-1 ] from sensor
```
Both times giving me an error along the lines of this:
```
FAILED: SemanticException 1:27 Non-constant expressions for array indexes not supported.
Error encountered near token '1'
```
So any ideas? I am kind of new to Hive. Regex's maybe? Or is there some syntactic sugar I am not aware of?
|
2015/09/05
|
[
"https://Stackoverflow.com/questions/32415374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3458744/"
] |
This question is getting a lot of views (over a thousand now), so I think it needs a proper answer. In the event I solved it with this:
```
select tag,reverse(split(reverse(tag),'[/]')[0]) from sensor
```
which is not actually stated in the other suggested answers - I got the idea from a suggestion in the comments.
This:
* reverses the string (so "abcd/efgh" is now "hgfe/dcba")
* splits it on "/" into an array (so we have "hgfe" and "dcba")
* extracts the first element (which is "hgfe")
* then finally re-reverses (giving us the desired "efgh")
Also note that the second-to-last element can be retrieved by substituting 1 for the 0, and so on for the others.
|
98,879 |
I'm trying to install my scanner "HP ScanJet 2400". I followed the recipe from here: <http://www.elcot.in/linuxdrivers_download.php>, However, it was not possible at all to detect it, when working in CentOS, Fermi & OSuSE OS.
Doess anyone have any suggestions on how to get this scanner working?
|
2013/11/05
|
[
"https://unix.stackexchange.com/questions/98879",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/-1/"
] |
Your example mixes single-quote and double quote. And find wants a pattern which matches the whole filename, so you want to begin/end the pattern with '\*'.
This will find all files that have the pattern you describe:
```
find yourpath -name "*[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*"
```
But if you want to use regextype, you need "posix-egrep", and note carefully that regex needs to match entire path,
```
find yourpath -regextype posix-egrep -regex ".*[0-9]{4}-[0-9]{2}-[0-9]{2}.*"
```
|
10,408,471 |
>
> **Possible Duplicate:**
>
> [Rotate Image .pbm Haskell](https://stackoverflow.com/questions/10407003/rotate-image-pbm-haskell)
>
>
>
i need help about a rotation matrix in haskell
i have 2 data type:
```
data RGBdata= RGB Int Int Int
data PBMfile= PBM Int Int [[RGBdata]]
```
and my function receive:
```
spin :: PBMfile -> PBMfile
spin (PBM x y l) = (PBM x y ((transpose . reverse) l))
```
where 'x' and 'y' is the number of colums and rows respectively (maybe can help to do the function).
for example:
```
(PBM 2 2 [[(RGB 0 255 255),(RGB 255 0 0)],[(RGB 255 255 255),(RGB 255 0 0)]])
```
I try rotate 90° to the left using combinations with reverse and transpose, but the image result is wrong.
i try
```
spin :: PBMfile -> PBMfile
spin (PBM x y l) = (PBM x y ((reverse . transpose) l))
```
and
```
spin :: PBMfile -> PBMfile
spin (PBM x y l) = (PBM x y ((transpose . reverse) l))
```
and
```
spin :: PBMfile -> PBMfile
spin (PBM x y l) = (PBM x y (((map reverse) . transpose) l))
```
to rotate the matrix but does not work.
the result is something like
<http://imageshack.us/photo/my-images/52/catmc.jpg/>
|
2012/05/02
|
[
"https://Stackoverflow.com/questions/10408471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/495943/"
] |
The transpose operation should happen before the reverse operation. Try
```
spin (PBM x y l) = (PBM y x ((reverse . transpose) l))
```
Also the dimensions of the rotated images are switched.
|
11,264 |
If I wanted to check how competitive it is to get into a school's PhD (or MS/PhD track) program, what should I look at? For undergraduate, I usually search for the incoming SAT/ACT scores and the acceptance rate, and I found that pretty reliable. Is there something like that for grad schools?
|
2013/07/20
|
[
"https://academia.stackexchange.com/questions/11264",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/7799/"
] |
I am not aware of any absolute measure for this. However, you can have a general idea by:
1. Some schools provide last year(s) statistics about their programs
(usually in the prospective student section). For example, program A
has attracted X number of applications and Y applications were
accepted.
2. Also, some programs have a fix limit (i.e. due to number of equipments available) for number of applications to be accepted.
3. Sometimes online admission results like the one in [Grad Cafe](http://thegradcafe.com/survey/index.php)
give you a sense on how strict the school is.
|
57,911,194 |
My navigation UL items are not being displayed inline with my website's logo: Is it possible of the logo size? I've tried adding the width property to the #logo but it wont react...
Picture of problem: <http://prntscr.com/p5aygy>
Logo properties: 496px x 109
**HTML**
```
<!--Navigation!!!-->
<nav>
<div id="logo"><img src="images/White.png"></div>
<label for="drop" class="toggle">Menu</label>
<input type="checkbox" id="drop"/>
<ul class="menu">
<li><a href="#">Home</a></li>
<li><a href="#">Pricing</a></li>
<li><a href="#">Faq</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
```
**CSS FILE**
```
nav {
margin: 0;
padding: 0;
background-color: black;
}
#logo {
display: block;
float: left;
padding: 10px 0 0 30px;
}
nav:after {
content: "";
display: table;
clear: both;
}
nav ul {
float: right;
list-style: none;
padding: 0;
margin: 0;
}
nav ul li {
display: inline-block;
float: left;
}
@media (max-width:768px) {
#logo {
display: block;
width:100%;
text-align: center;
float: none;
padding: 20px 0 10px;
}
nav ul li {
width: 100%;
}
.toggle + a, .menu {
display: none;
}
}```
```
|
2019/09/12
|
[
"https://Stackoverflow.com/questions/57911194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12053918/"
] |
remove `$scope` in the template. Try `changeSearchTo(searchname)` without the comma.
|
30,194,921 |
As per my understanding "ffprobe" will provide file related data in JSON format. So, I have installed the ffprobe in my Ubuntu machine but I don't know how to access the ffprobe JSON response using Java/Grails.
Expected response format:
```
{
"format": {
"filename": "/Users/karthick/Documents/videos/TestVideos/sample.ts",
"nb_streams": 2,
"nb_programs": 1,
"format_name": "mpegts",
"format_long_name": "MPEG-TS (MPEG-2 Transport Stream)",
"start_time": "1.430800",
"duration": "170.097489",
"size": "80425836",
"bit_rate": "3782576",
"probe_score": 100
}
}
```
This is my groovy code
```
def process = "ffprobe -v quiet -print_format json -show_format -show_streams HelloWorld.mpeg ".execute()
println "Found ${process.text}"
render process as JSON
```
I m able to get the process object and i m not able to get the json response
Should i want to convert the process object to json object?
OUTPUT:
Found java.lang.UNIXProcess@75566697
org.codehaus.groovy.grails.web.converters.exceptions.ConverterException: Error converting Bean with class java.lang.UNIXProcess
|
2015/05/12
|
[
"https://Stackoverflow.com/questions/30194921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3283008/"
] |
I assumed that `services.AddLogging();` was doing the right thing and registering `ILogger`. After looking at the source (<https://github.com/aspnet/Logging/blob/d874c5726e713d3eb34938f85faf7be61aae0f2a/src/Microsoft.Framework.Logging/LoggingServiceCollectionExtensions.cs>) I found that it's actually registering `ILogger<>`. Changing the signature of `ILogger` to `ILogger<HomeController>` makes the above example work.
```
public class HomeController :
Controller
{
ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
// ...
}
```
Thanks to @Steve for setting me on the right track to find this.
|
55,977,498 |
I have these following data.frames:
dt1
```
Id Mother Weight
1 elly 10
2 bina 20
3 sirce 30
4 tina 30
5 lina 40
```
and
dt2
```
Id Mother Weight sex
1 elly 10 M
2 bina 20 F
3 sirce 30 F
```
And I would like select rows from DT1 (ID) based in DT2 (ID), this way:
new.dt
```
Id Mother Weight sex
4 tina 30 NA
5 lina 40 NA
```
|
2019/05/03
|
[
"https://Stackoverflow.com/questions/55977498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11348734/"
] |
If it's already running, Flink's REST API will be listening on some port. You could use something like `curl server:8081` to see if it's available. If it's not running, curl will exit with a status of 7 to indicate that the connection was refused.
|
57,945,303 |
I'm simulating in a test the conversation between three actors (A, B, C)
```
A ---> MessageA2B ---> B ---> MessageB2C ---> C
```
When `MessageB2C` is successfully arrived to C then the acknowledgement is sent back to the origin.
```
C --> MessageB2C_Ack --> B --> MessageA2B_Ack --> A
```
The only peculiarity of this conversation is the message `MessageB2C`.
`MessageB2C` is sent at least every 50 ms until C does not answer with its acknowledgement.
I've implemented this simple conversation with scala testkit framework, but the test fail in a particular situation.
<https://github.com/freedev/reactive-akka-testkit>
When ActorB retries to send MessageB2C more then once time, then is unable to receive the answers from ActorC. And the reply from ActorC to ActorB goes to deadLetters.
```scala
test("expectNoMessage-case: actorB retries MessageB2C every 50 milliseconds") {
val actorA = TestProbe()
val actorC = TestProbe()
val actorB = system.actorOf(ActorB.props(Props(classOf[TestRefWrappingActor], actorC)), "step1-case2-primary")
actorA.send(actorB, MessageA2B())
actorA.expectNoMessage(100.milliseconds)
actorC.expectMsg(MessageB2C())
// Retries form above
actorC.expectMsg(200.milliseconds, MessageB2C())
// Never reach this point with 100 ms frequency
actorC.expectMsg(200.milliseconds, MessageB2C())
actorA.expectNoMessage(100.milliseconds)
actorC.reply(MessageB2C_Ack())
// Never reach this point with MessageB2C 50 ms frequency
actorA.expectMsg(MessageA2B_Ack())
}
```
This is the `ActorB` code:
```
class ActorB(actorCProps: Props) extends Actor {
import ActorB._
import context.dispatcher
val log = Logging(context.system, this)
val actorC = context.actorOf(actorCProps)
def retry(actorRef: ActorRef, message: Any, maxAttempts: Int, attempt: Int): Future[Any] = {
log.info("ActorB - sent message MessageB2C to ActorC " + actorC)
val future = Patterns.ask(actorRef, message, 50.millisecond) recover {
case e: AskTimeoutException =>
if (attempt <= maxAttempts) retry(actorRef, message, maxAttempts, attempt + 1)
else None
}
future
}
def receive = {
case r:MessageA2B => {
val client = context.sender()
implicit val timeout = Timeout(100.milliseconds)
implicit val scheduler=context.system.scheduler
val p = MessageB2C()
retry(actorC, p, 10) onSuccess({
case p: MessageB2C_Ack => {
client ! MessageA2B_Ack()
}
})
}
}
}
```
### Update
Strangely the test completes successfully commenting the line `actorA.expectNoMessage`
|
2019/09/15
|
[
"https://Stackoverflow.com/questions/57945303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/336827/"
] |
Tests like this can be flakey because they depend on exact timings of execution but actual execution can be affected by various factors including system load (and maybe cosmic rays). That said, I was able to get your test to pass with a couple of modifications to ActorB...
```
RetrySupport
.retry(() => {
log.info("ActorB - sent message MessageB2C to ActorC " + actorC)
Patterns.ask(actorC, p, 100.millisecond)
}, 10, 0.millisecond)
.onSuccess({
case p: MessageB2C_Ack => {
log.info(
"ActorB - Received MessageB2C_Ack so now sending an MessageA2B_Ack to client " + client
)
client ! MessageA2B_Ack()
}
})
```
The key to debugging the issue was to look at the timings of the log "ActorB - sent message MessageB2C to ActorC Actor". I was seeing times of around 250ms. The problem was the length of time you wait for your `ask` is added to the `delay` parameter of the `retry`. In order to wait 100ms between messages you should set the delay time to 0 and use the ask timeout to manage the retry scheduling.
|
11,255,118 |
I'm searching a method to close a specific window by the title.
I tried with `Process.GetProcessesByName`; but not is working by this case particulary.
I'm searching a method with APIs or similar (Not in C#, I see several code but not work fine in vb.net)
Thanks!
---
UPDATE
Thanks for the reply. But I'm still have a problem with the solution that you describe me below.
I'm have an only process that's control two windows. Then, if I close (or kill) the Window #2, instantly close the first one (See the image).
By this reason I think in using an API method from the begging.
I'm only want close the second window.

|
2012/06/29
|
[
"https://Stackoverflow.com/questions/11255118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/582614/"
] |
Try using something like this. using [`Process.MainWindowTitle`](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.mainwindowtitle) to get the Title Text and [`Process.CloseMainWindow`](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.closemainwindow) to close down the UI, its a little more graceful than killing the Process.
Note: Contains does a case-sensitive search
```
Imports System.Diagnostics
Module Module1
Sub Main()
Dim myProcesses() As Process = Process.GetProcesses
For Each p As Process In myProcesses
If p.MainWindowTitle.Contains("Notepad") Then
p.CloseMainWindow()
End If
Next
End Sub
End Module
```
---
As far as Win API functions try something like this. Be aware if you close the parent window you **will** close the children also.
```
Module Module1
Private Declare Auto Function FindWindowEx Lib "user32" (ByVal parentHandle As Integer, _
ByVal childAfter As Integer, _
ByVal lclassName As String, _
ByVal windowTitle As String) As Integer
Private Declare Auto Function PostMessage Lib "user32" (ByVal hwnd As Integer, _
ByVal message As UInteger, _
ByVal wParam As Integer, _
ByVal lParam As Integer) As Boolean
Dim WM_QUIT As UInteger = &H12
Dim WM_CLOSE As UInteger = &H10
Sub Main()
Dim handle As Integer = FindWindowEx(0, 0, Nothing, "YourFormsTitle")
PostMessage(handle, WM_CLOSE, 0, 0)
End Sub
End Module
```
|
26,999 |
Can I know a code for simple IR receiver. I using external trasmitter, and when the receiver (on arduino board) get the input (detect signal from transmitter), LED will be HIGH.
|
2016/08/03
|
[
"https://arduino.stackexchange.com/questions/26999",
"https://arduino.stackexchange.com",
"https://arduino.stackexchange.com/users/24310/"
] |
Here is a library that might be able to help you out: <https://github.com/cyborg5/IRLib/>. Also a specific example of controlling a server from a sony remote control. <https://github.com/cyborg5/IRLib/blob/master/examples/IRservo/IRservo.ino>
I am slightly confused on what you mean 'get input'. So I am assuming an input from a button. Here is some pseudo code compiled from the IRservo example that might point you in the right direction.
```
#include <IRLib.h>
#define MY_PROTOCOL SONY
#define BUTTON_0 0x90bca //LED ON
#define BUTTON_1 0x00bca //LED OFF
#define LED_PIN 13 //Pin to LED
IRrecv My_Receiver(11);//Receive on pin 11
IRdecode My_Decoder;
void setup() { //Code to run once
My_Receiver.No_Output();//Turn off any unused IR LED output circuit
My_Receiver.enableIRIn(); // Start the receiver
pinMode(LED_PIN, OUTPUT); //Set LED 13 to out
digitalWrite(LED_PIN, LOW); //Start off in the off position
}
void loop() { //Code that runs forever
if (My_Receiver.GetResults(&My_Decoder)) {
My_Decoder.decode(); //Convert the values into types
if(My_Decoder.decode_type==MY_PROTOCOL) { // Match the controller
switch(My_Decoder.value) {
case BUTTON_0: digitalWrite(LED_PIN, HIGH); break; //Turn the LED on
case BUTTON_1: digitalWrite(LED_PIN, LOW); break; //Turn the LED off
}
}
My_Receiver.resume(); //Wait for next input
}
}
```
This should theoretically work, but has never been tested. Now if you are just wanting any result to turn on the LED you might be able to do this
```
void loop() { //Code that runs forever
if (My_Receiver.GetResults(&My_Decoder)) {
My_Decoder.decode();
digitalWrite(LED_PIN, HIGH); //Turn the LED on
}
My_Receiver.resume(); //Wait for next input
}
```
**Edit:**
A sample from getting text (Different library) from the receiver and printing it to the Serial Monitor. Link to library: <https://github.com/z3t0/Arduino-IRremote>
```
#include <IRremote.h> //Link: https://github.com/z3t0/Arduino-IRremote
#define IR_PIN = 11; //The data pin to the IR recv
#define LED_DATA = 13; //Either the builtin LED or plug one in
IRrecv irrecv(IR_PIN); //Start recv obj
decode_results results;
void setup()
{
Serial.begin(9600); //Start Serial at 9600 baud
pinMode(LED_DATA, OUTPUT); //Set LED pin to out
digitalWrite(LED_DATA, LOW); //Start recv data view pin in low
irrecv.enableIRIn(); // Start the receiver
}
void loop() {
if (irrecv.decode(&results)) {
//We have recieved something... lets print it and turn on the LED
digitalWrite(LED_DATA, HIGH);
Serial.println(results.value, HEX); //Send line in ascii hex format
delay(200); //Make the LED visible
digitalWrite(LED_DATA, LOW); //Turn off data led
irrecv.resume(); // Receive the next value
}
}
```
**Edit #2**
Since an image has been provided I believe this is what you want. To turn the ir data into a visible light... To do that is a little more tricky in just doing code. Here's an example that doesn't require any external libraries and will do what you want.
```
#include <avr/interrupt.h>
#include <avr/io.h>
#define TIMER_RESET TCNT1 = 0
#define SAMPLE_SIZE 64
#defome LED_PIN 13
int IRpin = 2;
unsigned int TimerValue[SAMPLE_SIZE];
char direction[SAMPLE_SIZE];
byte change_count;
long time;
void setup() {
Serial.begin(115200);
Serial.println("Analyze IR Remote");
TCCR1A = 0x00; // COM1A1=0, COM1A0=0 => Disconnect Pin OC1 from Timer/Counter 1 -- PWM11=0,PWM10=0 => PWM Operation disabled
// ICNC1=0 => Capture Noise Canceler disabled -- ICES1=0 => Input Capture Edge Select (not used) -- CTC1=0 => Clear Timer/Counter 1 on Compare/Match
// CS12=0 CS11=1 CS10=1 => Set prescaler to clock/64
TCCR1B = 0x03; // 16MHz clock with prescaler means TCNT1 increments every 4uS
// ICIE1=0 => Timer/Counter 1, Input Capture Interrupt Enable -- OCIE1A=0 => Output Compare A Match Interrupt Enable -- OCIE1B=0 => Output Compare B Match Interrupt Enable
// TOIE1=0 => Timer 1 Overflow Interrupt Enable
TIMSK1 = 0x00;
pinMode(IRpin, INPUT);
pinMode(LED_PIN, OUTPUT);
}
void loop()
{
Serial.println("Waiting...");
change_count = 0;
while(digitalRead(IRpin) == HIGH) {}
TIMER_RESET;
TimerValue[change_count] = TCNT1;
direction[change_count++] = '0';
while (change_count < SAMPLE_SIZE) {
if (direction[change_count-1] == '0') {
while(digitalRead(IRpin) == LOW) {}
TimerValue[change_count] = TCNT1;
direction[change_count++] = '1';
digitalWrite(LED_PIN, LOW);
} else {
while(digitalRead(IRpin) == HIGH) {}
TimerValue[change_count] = TCNT1;
direction[change_count++] = '0';
digitalWrite(LED_PIN, HIGH);
}
}
Serial.println("Bit stream detected!");
change_count = 0;
time = (long) TimerValue[change_count] * 4;
digitalWrite(LED_PIN, LOW)
Serial.print(time);
Serial.print("\t");
Serial.println(direction[change_count++]);
while (change_count < SAMPLE_SIZE) {
time = (long) TimerValue[change_count] * 4;
Serial.print(time);
Serial.print("\t");
Serial.println(direction[change_count-1]);
Serial.print(time);
Serial.print("\t");
Serial.println(direction[change_count++]);
}
Serial.println("Bit stream end!");
delay(2000);
}
```
If you want a non code example check out the answer below. It is a great solution. Without needing any arduino.
best regards, David
|
49,792,210 |
How can I enforce user to enter only numbers using `p-chips` component?
I want to fill array of `numbers` from user input.
Is there any alternative way to achieve this other than `p-chips` component?
|
2018/04/12
|
[
"https://Stackoverflow.com/questions/49792210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1790632/"
] |
By using `p-chips` component, you can use `onAdd` method to check user input :
**HTML**
```
<p-chips [(ngModel)]="values" (onAdd)=checkInput($event)></p-chips>
```
**TS**
```
checkInput(event) {
this.errorMessage = ''; // reinitialize error message
if(!this.isInt(event.value)) {
this.errorMessage = event.value + ' is not an integer !'; // display error message
this.values.pop(); // remove last entry from values
}
}
```
See [Plunker](https://plnkr.co/edit/CojCsvLoQNgDFhoEZb1K?p=preview)
|
23,879,403 |
```
array = [
["sean", "started", "shift", "at", "10:30:00"],
["anna", "started", "shift", "at", "11:00:00"],
["sean", "started", "shift", "at", "10:41:45"],
["anna", "finished", "shift", "at", "11:30:00"],
["sean", "finished", "shift", "at", "10:48:45"],
["sean", "started", "shift", "at", "11:31:00"],
["sean", "finished", "shift", "at", "11:40:00"]
]
```
Few things to consider
1. if you look at sean's entries - there are 2 entries for 'start times' one at 10:30:00 and also at 10:41:45 . The system can record multiple 'start times' but only one 'Finished' time. The logic is to pair first 'started' & first 'finished' and combine them.
2. How to skip the duplicated 'start time' entries (such as Sean's) and get a desired output as below...
array = [
["sean", "started", "shift", "at", "10:30:00", "finished", "shift", "at", "10:48:45"],
["anna", "started", "shift", "at", "11:00:00", "finished", "shift", "at", "11:30:00"],
["sean", "started", "shift", "at", "11:31:00", "finished", "shift", "at", "11:40:00"]
]
Theres no easy way is it?
|
2014/05/27
|
[
"https://Stackoverflow.com/questions/23879403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3642990/"
] |
```
array.group_by(&:first).map do |person, events|
events.chunk { |_, event_type| event_type }.each_slice(2).map do |(_, (start, _)), (_, (finish, _))|
%W(#{p} started shift at #{start[4]} finished shift at #{finish[4]})
end
end
# => [
# => ["sean", "started", "shift", "at", "10:30:00", "finished", "shift", "at", "10:48:45"],
# => ["sean", "started", "shift", "at", "11:31:00", "finished", "shift", "at", "11:40:00"],
# => ["anna", "started", "shift", "at", "11:00:00", "finished", "shift", "at", "11:30:00"]
# => ]
```
|
5,118 |
From a paper via Schneier on Security's [Another AES Attack](http://www.schneier.com/blog/archives/2009/07/another_new_aes.html) (emphasis mine):
>
> In the case of AES-128, there is no known attack which is faster than the 2128 complexity of exhaustive search. However, **AES-192 and AES-256 were recently shown to be breakable by attacks which require 2176 and 2119 time, respectively**. While these complexities are much faster than exhaustive search, they are completely non-practical, and do not seem to pose any real threat to the security of AES-based systems.
>
>
> In this paper we describe several attacks which can break with practical complexity variants of AES-256 whose number of rounds are comparable to that of AES-128.
>
>
>
Is the implication here that AES-192 is stronger than AES-256? If so, in simple terms, how is that possible?
>
> The attack exploits the fact that the **key schedule for 256-bit version is pretty lousy -- something we pointed out in our 2000 paper -- but doesn't extend to AES with a 128-bit key.**
>
>
>
Again, in simple terms, what does that mean?
In practice, does this mean I should drop AES-256 in favor of its 128-bit counterpart, like Schneier recommends in the comments?
>
> That being said, the key schedule for AES-256 is very poor. **I would recommend that people use AES-128 and not AES-256.**
>
>
>
|
2012/10/19
|
[
"https://crypto.stackexchange.com/questions/5118",
"https://crypto.stackexchange.com",
"https://crypto.stackexchange.com/users/4127/"
] |
[AES](http://en.wikipedia.org/wiki/Advanced_Encryption_Standard) is an algorithm which is split into several internal *rounds*, and each round needs a specific 128-bit subkey (and an extra subkey is needed at the end). In an ideal world, the 11/13/15 subkeys would be generated from a strong, cryptographically secure PRNG, itself seeded with "the" key.
However, this world is not ideal, and the subkeys are generated through a process called the *key schedule*, which is very fast but not a decent PRNG at all; it is meant to offer sufficient security in the very specific context of producing subkeys for the AES only. The key schedule of AES was already known to be somewhat weak in some ways, allowing some exploitable structure to leak from one subkey to another, and this means [related-key attacks](http://en.wikipedia.org/wiki/Related-key_attack).
Related-key attacks are not a problem when the encryption algorithm is used for encryption, because they work only when the victim uses several distinct keys, such that the differences (bitwise XOR) between the keys are known to the attacker and follow a very definite pattern. This is not the kind of thing which often occurs in protocols where AES is used; correspondingly, resistance to related-key attacks was not a design criterion for the AES competition. Related-key attacks can be troublesome when we try to reuse the block cipher as a building block for something else, e.g. a hash function. In the formal land of academic cryptanalysis, related-key attacks still count as worthwhile results, despite their lack of applicability to most practical scenarios.
The key schedules for AES-128, AES-192 and AES-256 are necessarily distinct from each other, since they must work over master keys of distinct sizes and produce distinct numbers of subkeys. It turns out that the version of the key schedule for AES-128 seems quite stronger than the key schedule for AES-256 *when considering resistance to related-key attacks*. It is actually quite logical: to build a related-key attack, the cryptographer must have some fine control over the subkeys, preferably as independently from each other as possible. It seems natural that the longer the source master key, the more control over subkeys the cryptanalyst gets -- because the related-key attack model is a model where the attacker can somehow "choose" the keys (or at least the differences between the keys). In the extreme case of a 1408-bit master key which would simply be split into eleven 128-bit keys, the cryptanalyst would have all the independent control he could wish for. Therefore, an academic weakness relatively to related-key attacks should, generically, increase with the key size.
The apparent paradox of the decrease in academic security when the key size increases highlights the contrived nature of the related-key attack model.
|
2,214,066 |
I need to get all the `input` objects and manipulate the `onclick` param.
The following does the job for `<a>` links. Looking for something like this for `input` tags.
```js
for (var ls = document.links, numLinks = ls.length, i=0; i<numLinks; i++){
var link = unescape(ls[i].href);
link = link.replace(/\\'/ig,"#");
if(ls[i].href.indexOf("javascript:") == -1)
{
ls[i].href = "javascript:LoadExtern(\\""+link+"\\",\\"ControlPanelContent\\",true,true);";
}
}
```
|
2010/02/06
|
[
"https://Stackoverflow.com/questions/2214066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1567109/"
] |
*(See update at end of answer.)*
You can get a [`NodeList`](https://developer.mozilla.org/En/DOM/NodeList) of all of the `input` elements via `getElementsByTagName` ([DOM specification](http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-A6C9094), [MDC](https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName), [MSDN](http://msdn.microsoft.com/en-us/library/ms536439(VS.85).aspx)), then simply loop through it:
```
var inputs, index;
inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
// deal with inputs[index] element.
}
```
There I've used it on the `document`, which will search the entire document. It also exists on individual elements ([DOM specification](http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-1938918D)), allowing you to search only their descendants rather than the whole document, e.g.:
```
var container, inputs, index;
// Get the container element
container = document.getElementById('container');
// Find its child `input` elements
inputs = container.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
// deal with inputs[index] element.
}
```
...but you've said you don't want to use the parent `form`, so the first example is more applicable to your question (the second is just there for completeness, in case someone else finding this answer needs to know).
---
**Update**: `getElementsByTagName` is an absolutely fine way to do the above, but what if you want to do something slightly more complicated, like just finding all of the checkboxes instead of all of the `input` elements?
That's where the useful `querySelectorAll` comes in: It lets us get a list of elements that match **any CSS selector we want**. So for our checkboxes example:
```
var checkboxes = document.querySelectorAll("input[type=checkbox]");
```
You can also use it at the element level. For instance, if we have a `div` element in our `element` variable, we can find all of the `span`s with the class `foo` that are inside that `div` like this:
```
var fooSpans = element.querySelectorAll("span.foo");
```
`querySelectorAll` and its cousin `querySelector` (which just finds the *first* matching element instead of giving you a list) are supported by all modern browsers, and also IE8.
|
61,525,439 |
new to Access here so hoping someone could help me with this... I'm trying to import .CSV file to DB which works fine and all. The problem is that .CSV file will have various columns and might not be in the same sequence as set in DB tables. It looks like access is importing all columns in a row regardless of the column name.
Using this Do.Cmd below:
```
strPathFile = strPath & strFile
DoCmd.TransferText acImportDelim, "pimmig2", strTable, strPathFile, blnHasFieldNames
```
For example, table headers in Access:
```
Action, Type, Retek Hierarchy, ID, Name
```
.CSV file headers:
```
Action, Type, Banner, From Banner, Retek Hierarchy, Master Catalogue, ID
```
So what happens is that after the import, column 'From Banner' ends up in 'Retek Hierarchy' and all data in the table is scewd up...
I have set primary keys and all, have SPECS done so run out of options... :( help please...
|
2020/04/30
|
[
"https://Stackoverflow.com/questions/61525439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2344279/"
] |
A really easy way to deal with this?
Import into a temp table. So, you empty the table, (or drop it). Now import into this table.
You then fire up the query builder, and create a append query. The beauty of this approach is that not only can you setup field to field mapping, but you can EVEN do this if the field names are not exact matches. Once you create this append query with all of the field mapping?
Save that query.
So, now your steps are:
Import data to that table
Execute the append query.
And you can even add formatting, or cast of data types in that append query. So, you can map fields, and do so without having to write/type the fields in code.
So, you still have a wee bit of code, but the key concept of that append query will thus give you the ability to map columns from the import to the production table, and even give you the chance to map fields that don't even have the exact same name.
Thus, in theory, you can choose nice column names for your production data, and the import can have any field names you want. The append query can be created 100% with the query builder, and the welcome ability to choose which columns go to what production columns is all done by choosing the field mapping with combo boxes in the query builder.
The other nice ability of that temp table? Well, you can run some update query, or even some VBA looping code to clean up, or massage the data before you run that one append query to send data into the final production table. So, you not only get field mapping (wthout having to write code), but you also get a chance to clean up, or even remove bad rows of data before you send (append) the imported data to the actual production table.
|
2,828,629 |
Consider the profinite completion $\widehat{\Bbb Z}$ of the additive group of $\Bbb Z$.
>
> Is there a surjective group morphism $s : \widehat{\Bbb Z} \to \Bbb Z$ ?
> If so, can we moreover assume that $s \circ i = \rm{id}\_{\Bbb Z}$, where $i : \Bbb Z \to \widehat{\Bbb Z}$ is the canonical embedding?
>
>
>
Clearly, there is no continuous map $\widehat{\Bbb Z} \to \Bbb Z$, otherwise $\Bbb Z$ would be compact and discrete... ; so $s$ can't be continuous.
I also noticed that there is no surjective group morphism $\Bbb Z\_p \to \Bbb Z$ (i.e. $\Bbb Z$ is not a quotient of the $p$-adic integers), for any prime $p$, since the former is $q$-divisible for any prime $q \neq p$, while the latter is not.
Thank you!
|
2018/06/22
|
[
"https://math.stackexchange.com/questions/2828629",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/298680/"
] |
In fact it seems there are no nontrivial group homomorphisms $\widehat{\mathbb{Z}} \to \mathbb{Z}$.
First let's note that there are no nontrivial group homomorphisms $\mathbb{Z}\_{p} \to \mathbb{Z}$, since, as you say, the image of any such map must be $q$-divisible for $q \ne p$.
Write $\widehat{\mathbb{Z}} = \prod \mathbb{Z}\_{p} = \mathbb{Z}\_{2} \times \prod\_{p \ne 2} \mathbb{Z}\_{p}$. There are no nontrivial maps $\mathbb{Z}\_{2} \to \mathbb{Z}$ by the above, and there are no nontrivial maps $\prod\_{p \ne 2} \mathbb{Z}\_{p} \to \mathbb{Z}$, since $\prod\_{p \ne 2} \mathbb{Z}\_{p}$ is $2$-divisible.
|
29,929,411 |
Is there any way to disable pinch zoom in an [electron](http://electron.atom.io/) app?
I can't get it to work from inside the web-view with normal javascript methods as described here: <https://stackoverflow.com/a/23510108/665261>
It seems the `--disable-pinch` flag is [not supported by electron](https://github.com/atom/electron/blob/master/docs/api/chrome-command-line-switches.md).
I have experimented with various methods using:
1. `event.preventDefault()` on javascript `touchmove/mousemove` events
2. `meta viewport` tags in HTML
3. `-webkit-text-size-adjust` in CSS
4. flags/config for electron
Is there any method either for webkit in general, or [electron](http://electron.atom.io/) in particular?
|
2015/04/28
|
[
"https://Stackoverflow.com/questions/29929411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/665261/"
] |
**UPDATE 2:**
Use [webFrame.setZoomLevelLimits](https://github.com/atom/electron/blob/master/docs/api/web-frame.md#webframesetzoomlevellimitsminimumlevel-maximumlevel) (v0.31.1+) in **render process** ([Differences Between Main Process and Renderer Process](https://github.com/atom/electron/blob/master/docs/tutorial/quick-start.md#differences-between-main-process-and-renderer-process)). Because smart zoom on mac still work with document.addEventListener.
Example `require('electron').webFrame.setZoomLevelLimits(1, 1)`
---
**UPDATE:**
`deltaY` property for pinch zoom has `float` value, but normal scroll event return `int` value. Now solution has no problem with ctrl key.
**[Demo 2](http://output.jsbin.com/tehidu)**.
```
document.addEventListener('mousewheel', function(e) {
if(e.deltaY % 1 !== 0) {
e.preventDefault();
}
});
```
---
Using Chromium `monitorEvents(document)` I found that is responsible for this event `mousewheel`. I don't know, why `mousewheel` triggered with pinch zoom.
Next step, find difference between normal scroll and pinch zoom.
Pinch zoom has an attribute `e.ctrlKey = true`, and normal scroll event has `e.ctrlKey = false`. But if you hold down `ctrl` key and scroll a page, `e.ctrlKey` equal `true`.
I couldn't find a better solution. :(
**[Demo](http://output.jsbin.com/yosezo)**
```
document.addEventListener('mousewheel', function(e) {
if(e.ctrlKey) {
e.preventDefault();
}
});
```
|
60,577,675 |
I'm building an app with VueJS + Vuetify and using "v-autocomplete" as a multi-selection dropdown. However, I can't find a way to prevent the dropdown drawer from opening when I click to remove an item.
**Codepen example:** <https://codepen.io/rafacarneiro/pen/abOVEzw?editable=true&editors=101>
Code used when removing an item:
```js
<v-chip
v-bind="data.attrs"
:input-value="data.selected"
close
@click="data.select"
@click:close="remove(data.item)"
>
```
**Current behaviour:** when clicking on the "X" icon on a selected item, the item is removed, however, the dropdown drawer opens at the same time. I would like to prevent this behaviour when removing an item, but I've been struggling to find a way to do it.
|
2020/03/07
|
[
"https://Stackoverflow.com/questions/60577675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11852470/"
] |
Looks almost like a dup of: [How to stop select from opening when closing chip in vuetify?](https://stackoverflow.com/questions/53268291/how-to-stop-select-from-opening-when-closing-chip-in-vuetify)
If you remove the `filled` prop from the v-autocomplete it will work.
|
2,260,261 |
In this post
[A commutative ring $A$ is a field iff $A[x]$ is a PID](https://math.stackexchange.com/questions/356924/a-commutative-ring-a-is-a-field-iff-ax-is-a-pid)
It was proved that a commutative ring $A$ is a field iff $A[x]$ is a principal ideal domain. By this theorem, because $GF\_9$ is a finite field, then $GF\_9[x]$ must be a principal ideal domian. However in my midterm exam of cryptography. There is a problem said $GF\_9[x]$ is a principal ideal domain but not a field. Using the polynomial representation of $GF\_9$, we can view $GF\_9[x]$ as two variables polynomial in $\alpha$ and $x$ with coefficient belong to $GF\_3$.
My question is, how to prove that it is not a field?
Are there any necessary and sufficient condition to make it become a field?
|
2017/05/01
|
[
"https://math.stackexchange.com/questions/2260261",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/394129/"
] |
>
> My question is, how to prove that it is not a field?
>
>
>
You can observe that $x$ does not have an inverse. (Argue by degree, for example.)
>
> Are there any necessary and sufficient condition to make it become a field?
>
>
>
No. The indeterminate $x$ is never invertible in an ordinary polynomial ring over a field.
>
> It confused me that whether $GF\_9[x]$ is a principal ideal domain or not.
>
>
>
That example *requires* two free indeterminates. The point is that $x$ and $y$ cannot be multiples of a single element of $K[x,y]$. In your case, (with a single variable) the argument does not apply.
>
> Using the polynomial representation of $GF\_9$, we can view $GF\_9[x]$ as two variables polynomial in $α$ and $x$ with coefficient belong to $GF\_3$.
>
>
>
No, it is not a *full* polynomial ring of two variables. It is true that $GF\_9\cong GF\_3[\alpha]/p(\alpha)$ where $p(\alpha)$ is an irreducible quadratic over $GF\_3$, but that does not make the quotient "a polynomial ring." You are describing $GF\_3[x,\alpha]/(p(\alpha))$ which is a quotient of $GF\_3[x,\alpha]$, and does not fit that argument.
|
718,569 |
How do I do a search for any of the following:
Find folders that start with a space on linux and then remove any starting spaces so the folder can start with a letter or a number?
Find FILES that start with a space on linux and then remove any starting spaces so the files can start with a letter or a number?
|
2022/09/24
|
[
"https://unix.stackexchange.com/questions/718569",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/444473/"
] |
```bash
find . -depth -name ' *' -exec sh -c '
for pathname do
newname=${pathname##*/}
newname=${newname#"${newname%%[! ]*}"}
newpathname=${pathname%/*}/$newname
if [ -z "$newname" ] || [ -e "$newpathname" ]; then
continue
fi
mv -v "$pathname" "$newpathname"
done' sh {} +
```
The above finds any file or directory whose name starts with at least one space character in or below the current directory. It does this in a depth-first order (due to `-depth`) to avoid renaming directories that it hasn't yet processed the contents of; renaming a directory would otherwise cause `find` not to find it later, as it was renamed.
A short in-line shell script is called for batches of names that start with a space. The script iterates over the given pathnames and starts by extracting the actual name from the end of the current pathname into the variable `newname`. It does this using the standard parameter substitution, `${pathname##*/}`, removing everything to the last `/` in the string (the longest prefix matching `*/`), leaving the final pathname component. This is essentially the same as `"$(basename "$pathname")"` in this case.
We then need to trim off the spaces guaranteed to exist at the start of the string in `$newname`. We do this by first removing everything but the spaces with `${newname%%[! ]*}` (the longest suffix matching `[! ]*`, i.e. from the first non-space character onwards), and then removing the result of that from the start of the `$newname` string with `${newname#"${newname%%[! ]*}"}`.
The destination path in the `mv` command is made up of the directory path of `$pathname` concatenated by a slash and the new name, i.e. `${pathname%/*}/$newname`, which is essentially the same as `"$(dirname "$pathname")/$newname"`.
The code detects name collisions and silently skips the processing of names that would collide. It also skips names that collapse to empty strings. This is what the `if` statement before `mv` does. If you want to bring these names to the user's attention, then do so before `continue`.
**Test run on a *copy* of your backed-up data.**
Test-running the code above:
```bash
$ tree -Q
"."
|-- " dir0"
| |-- " o dir1"
| | |-- " otherfile"
| | `-- "dir2"
| | |-- " dir3"
| | `-- " moar"
| `-- "file"
`-- "script"
4 directories, 4 files
```
```bash
$ sh script
./ dir0/ o dir1/dir2/ moar -> ./ dir0/ o dir1/dir2/moar
./ dir0/ o dir1/dir2/ dir3 -> ./ dir0/ o dir1/dir2/dir3
./ dir0/ o dir1/ otherfile -> ./ dir0/ o dir1/otherfile
./ dir0/ o dir1 -> ./ dir0/o dir1
./ dir0 -> ./dir0
```
Notice how it starts at the bottom of the directory hierarchy. If it had tried renaming `dir0` first, it would have failed to enter it later to rename the other directories and files.
```bash
$ tree -Q
"."
|-- "dir0"
| |-- "file"
| `-- "o dir1"
| |-- "dir2"
| | |-- "dir3"
| | `-- "moar"
| `-- "otherfile"
`-- "script"
4 directories, 4 files
```
|
12,296,676 |
I try to setup git user access between machine A and B by ssh without password input.
While finished these steps:
```
/*
* suppose A stands for 192.168.16.14
* and then B stands for machine ip 192.168.16.160
*/
```
### [In Machine A]
```
git@A:~/.ssh$ ssh-keygen -t rsa
git@A:~/.ssh$ cp id_rsa.pub /tmp/lzq.rsa.git.pub
git@A:~/.ssh$ exit
root@A:~# scp /tmp/lzq.rsa.git.pub 192.168.16.160:/tmp
```
[OK]
```
/*
* thus [OK] means machine A root user can login B
by root user with ssh access without password,
* and B also can do right things in respectively.
*/
```
### [In Machine B]
```
git@B:~/.ssh$ ssh-keygen -t rsa
git@B:~/.ssh$ cp id_rsa.pub /tmp/zz.rsa.git.pub
git@B:~/.ssh$ exit
root@B:~# scp /tmp/zz.rsa.git.pub 192.168.16.14:/tmp
```
[OK]
### [In Machine A]
```
git@A:~/.ssh$ cp /tmp/zz.rsa.git.pub ./
git@A:~/.ssh$ cat id_rsa.pub >> authorized_keys
git@A:~/.ssh$ cat zz.rsa.git.pub >> authorized_keys
git@A:~/.ssh$ sudo /etc/init.d/sshd restart
```
### [In Machine B]
```
git@B:~/.ssh$ cp /tmp/lzq.rsa.git.pub ./
git@B:~/.ssh$ cat id_rsa.pub >> authorized_keys
git@B:~/.ssh$ cat lzq.rsa.git.pub >> authorized_keys
git@B:~/.ssh$ sudo /etc/init.d/sshd restart
```
### [In Machine A]
```
git@A:~/$ ssh -vvv 192.168.16.14
Welcome to Ubuntu 12.04 LTS (GNU/Linux 3.2.0-27-generic x86_64)
* Documentation: https://help.ubuntu.com/
139 packages can be updated.
46 updates are security updates.
Last login: Thu Sep 6 11:05:28 2012 from 192.168.16.14
git@zzz-Inspiron-1545:
```
So:
```
/*
* we can use 'ssh 192.168.16.14' as git user in B, the log show as followings.
* note that 'lavande-G31M-ES2C' stands for A.
* the quote section record as file 'lzq-ssh-zz-success.txt'
*/
git@lavande-G31M-ES2C:~/.ssh$ ssh -vvv 192.168.16.160
OpenSSH_5.9p1Debian-5ubuntu1, OpenSSL 1.0.1 14 Mar 2012
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: ssh_connect: needpriv 0
debug1: Connecting to 192.168.16.160 [192.168.16.160] port 22.
debug1: Connection established.
debug3: Incorrect RSA1 identifier
debug3: Could not load "/home/git/.ssh/id_rsa" as a RSA1 public key
debug1: identity file /home/git/.ssh/id_rsa type 1
debug1: Checking blacklist file /usr/share/ssh/blacklist.RSA-2048
debug1: Checking blacklist file /etc/ssh/blacklist.RSA-2048
debug1: identity file /home/git/.ssh/id_rsa-cert type -1
debug1: identity file /home/git/.ssh/id_dsa type -1
debug1: identity file /home/git/.ssh/id_dsa-cert type -1
debug1: identity file /home/git/.ssh/id_ecdsa type -1
debug1: identity file /home/git/.ssh/id_ecdsa-cert type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.9p1 Debian-5ubuntu1
debug1: match: OpenSSH_5.9p1 Debian-5ubuntu1 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_5.9p1 Debian-5ubuntu1
debug2: fd 3 setting O_NONBLOCK
debug3: load_hostkeys: loading entries for host "192.168.16.160" from file "/home/git/.ssh/known_hosts"
debug3: load_hostkeys: found key type ECDSA in file /home/git/.ssh/known_hosts:1
debug3: load_hostkeys: loaded 1 keys
debug3: order_hostkeyalgs: prefer hostkeyalgs: [email protected],[email protected],[email protected],ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
debug1: SSH2_MSG_KEXINIT sent debug1: SSH2_MSG_KEXINIT received
debug2: kex_parse_kexinit:
ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: [email protected],[email protected],[email protected],ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,[email protected],[email protected],[email protected],[email protected],ssh-rsa,ssh-dss debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,[email protected]
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,[email protected]
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,[email protected],hmac-sha2-256,hmac-sha2-256-96,hmac-sha2-512,hmac-sha2-512-96,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,[email protected],hmac-sha2-256,hmac-sha2-256-96,hmac-sha2-512,hmac-sha2-512-96,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,[email protected],zlib
debug2: kex_parse_kexinit: none,[email protected],zlib
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: kex_parse_kexinit: ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: ssh-rsa,ssh-dss,ecdsa-sha2-nistp256
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,[email protected]
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,[email protected]
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,[email protected],hmac-sha2-256,hmac-sha2-256-96,hmac-sha2-512,hmac-sha2-512-96,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,[email protected],hmac-sha2-256,hmac-sha2-256-96,hmac-sha2-512,hmac-sha2-512-96,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,[email protected]
debug2: kex_parse_kexinit: none,[email protected]
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: mac_setup: found hmac-md5 debug1: kex: server->client aes128-ctr
hmac-md5 none
debug2: mac_setup: found hmac-md5
debug1: kex: client->server aes128-ctr hmac-md5 none
debug1: sending SSH2_MSG_KEX_ECDH_INIT
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ECDSA e0:29:49:e6:f0:8a:fd:59:da:03:aa:3b:e1:ea:e4:2b debug3: load_hostkeys: loading entries for host "192.168.16.160" from file "/home/git/.ssh/known_hosts" debug3: load_hostkeys: found key type ECDSA in file /home/git/.ssh/known_hosts:1
debug3: load_hostkeys: loaded 1 keys debug1: Host '192.168.16.160' is known and matches the ECDSA host key.
debug1: Found key in /home/git/.ssh/known_hosts:1
debug1: ssh_ecdsa_verify: signature correct
debug2: kex_derive_keys
debug2: set_newkeys: mode 1
debug1: SSH2_MSG_NEWKEYS sent
debug1:expecting SSH2_MSG_NEWKEYS debug2: set_newkeys: mode 0
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug2: service_accept:ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug2: key: /home/git/.ssh/id_rsa (0x7f06fdce77d0)
debug2: key: /home/git/.ssh/id_dsa ((nil))
debug2: key: /home/git/.ssh/id_ecdsa ((nil)) debug1: Authentications that can continue: publickey
debug3:start over, passed a different list publickey
debug3: preferred gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/git/.ssh/id_rsa
debug3: send_pubkey_test debug2: we sent a publickey packet, wait for reply
debug1: Server accepts key: pkalg ssh-rsa blen 279
debug2: input_userauth_pk_ok: fp 3e:89:13:95:e7:3e:73:60:fa:06:77:1b:e0:e0:0d:b3
debug3: sign_and_send_pubkey: RSA 3e:89:13:95:e7:3e:73:60:fa:06:77:1b:e0:e0:0d:b3
debug1: read PEM private key done: type RSA
debug1: Authentication succeeded (publickey). Authenticated to 192.168.16.160 ([192.168.16.160]:22).
debug1: channel 0: new [client-session]
debug3: ssh_session2_open:channel_new: 0
debug2: channel 0: send open
debug1: Requesting [email protected]
debug1: Entering interactive session.
debug2: callback start
debug2: client_session2_setup: id 0
debug2: fd 3 setting TCP_NODELAY
debug2: channel 0: request pty-req confirm 1
debug1: Sending environment.
debug3: Ignored env SHELL debug3: Ignored env TERM
debug3: Ignored env XDG_SESSION_COOKIE
debug3: Ignored env USER
debug3: Ignored env MAIL
debug3: Ignored env PATH
debug3: Ignored env PWD
debug1: Sending env LANG = en_US.UTF-8
debug2: channel 0: request env confirm 0
debug3: Ignored env SHLVL
debug3: Ignored env HOME
debug3: Ignored env LOGNAME
debug3: Ignored env DISPLAY
debug3: Ignored env XAUTHORITY
debug3: Ignored env COLORTERM
debug3: Ignored env OLDPWD
debug3: Ignored env _
debug2: channel 0: request shell confirm 1
debug2: callback done debug2: channel 0: open confirm rwindow 0 rmax 32768
debug2: channel_input_status_confirm: type 99 id 0
debug2: PTY allocation request accepted on channel 0
debug2: channel 0: rcvd adjust 2097152
debug2: channel_input_status_confirm: type 99 id 0
debug2: shell request accepted on channel 0 Welcome to Ubuntu 12.04 LTS (GNU/Linux 3.2.0-27-generic x86_64)
* Documentation: https://help.ubuntu.com/
139 packages can be updated. 46 updates are security updates.
Last login: Thu Sep 6 11:05:28 2012 from 192.168.16.14
git@zzz-Inspiron-1545:~$ debug2: client_check_window_change: changed
debug2: channel 0: request window-change confirm 0 debug2:
client_check_window_change: changed debug2: channel 0: request
window-change confirm 0 git@zzz-Inspiron-1545:~$
```
### [In Machine B]
```
[code]git@B:~/$ ssh -vvv 192.168.16.14[/code]
[email protected]'s password:
```
**Problem:**
```
/*
* "[email protected]'s password:", the result is not the same in respectively.
* log file as 'zz-ssh-lzq-err.txt'
*/
```
Show log file as the following(notes that '`zzz-Inspiron-1545`' stands for '`B`' ):
```
git@zzz-Inspiron-1545:~/.ssh$ ssh -vvv 192.168.16.14
OpenSSH_5.9p1 Debian-5ubuntu1, OpenSSL 1.0.1 14 Mar 2012
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: ssh_connect: needpriv 0
debug1: Connecting to 192.168.16.14 [192.168.16.14] port 22.
debug1: Connection established.
debug3: Incorrect RSA1 identifier
debug3: Could not load "/home/git/.ssh/id_rsa" as a RSA1 public key
debug1: identity file /home/git/.ssh/id_rsa type 1
debug1: Checking blacklist file /usr/share/ssh/blacklist.RSA-2048
debug1: Checking blacklist file /etc/ssh/blacklist.RSA-2048
debug1: identity file /home/git/.ssh/id_rsa-cert type -1
debug1: identity file /home/git/.ssh/id_dsa type -1
debug1: identity file /home/git/.ssh/id_dsa-cert type -1
debug1: identity file /home/git/.ssh/id_ecdsa type -1
debug1: identity file /home/git/.ssh/id_ecdsa-cert type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.9p1 Debian-5ubuntu1
debug1: match: OpenSSH_5.9p1 Debian-5ubuntu1 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_5.9p1 Debian-5ubuntu1
debug2: fd 3 setting O_NONBLOCK
debug3: load_hostkeys: loading entries for host "192.168.16.14" from file "/home/git/.ssh/known_hosts"
debug3: load_hostkeys: found key type ECDSA in file /home/git/.ssh/known_hosts:1
debug3: load_hostkeys: loaded 1 keys
debug3: order_hostkeyalgs: prefer hostkeyalgs: [email protected],[email protected],[email protected],ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug2: kex_parse_kexinit: ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: [email protected],[email protected],[email protected],ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,[email protected],[email protected],[email protected],[email protected],ssh-rsa,ssh-dss
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,[email protected]
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,[email protected]
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,[email protected],hmac-sha2-256,hmac-sha2-256-96,hmac-sha2-512,hmac-sha2-512-96,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,[email protected],hmac-sha2-256,hmac-sha2-256-96,hmac-sha2-512,hmac-sha2-512-96,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,[email protected],zlib
debug2: kex_parse_kexinit: none,[email protected],zlib
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: kex_parse_kexinit: ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: ssh-rsa,ssh-dss,ecdsa-sha2-nistp256
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,[email protected]
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,[email protected]
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,[email protected],hmac-sha2-256,hmac-sha2-256-96,hmac-sha2-512,hmac-sha2-512-96,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,[email protected],hmac-sha2-256,hmac-sha2-256-96,hmac-sha2-512,hmac-sha2-512-96,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,[email protected]
debug2: kex_parse_kexinit: none,[email protected]
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: mac_setup: found hmac-md5
debug1: kex: server->client aes128-ctr hmac-md5 none
debug2: mac_setup: found hmac-md5
debug1: kex: client->server aes128-ctr hmac-md5 none
debug1: sending SSH2_MSG_KEX_ECDH_INIT
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ECDSA 03:32:02:5b:ac:29:41:a3:dc:96:33:a5:f7:ae:22:3d
debug3: load_hostkeys: loading entries for host "192.168.16.14" from file "/home/git/.ssh/known_hosts"
debug3: load_hostkeys: found key type ECDSA in file /home/git/.ssh/known_hosts:1
debug3: load_hostkeys: loaded 1 keys
debug1: Host '192.168.16.14' is known and matches the ECDSA host key.
debug1: Found key in /home/git/.ssh/known_hosts:1
debug1: ssh_ecdsa_verify: signature correct
debug2: kex_derive_keys
debug2: set_newkeys: mode 1
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug2: set_newkeys: mode 0
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug2: key: /home/git/.ssh/id_rsa (0x7f514e700890)
debug2: key: /home/git/.ssh/id_dsa ((nil))
debug2: key: /home/git/.ssh/id_ecdsa ((nil))
debug1: Authentications that can continue: publickey,password
debug3: start over, passed a different list publickey,password
debug3: preferred gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/git/.ssh/id_rsa
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
debug1: Authentications that can continue: publickey,password
debug1: Trying private key: /home/git/.ssh/id_dsa
debug3: no such identity: /home/git/.ssh/id_dsa
debug1: Trying private key: /home/git/.ssh/id_ecdsa
debug3: no such identity: /home/git/.ssh/id_ecdsa
debug2: we did not send a packet, disable method
debug3: authmethod_lookup password
debug3: remaining preferred: ,password
debug3: authmethod_is_enabled password
debug1: Next authentication method: password
[email protected]'s password:
debug3: packet_send2: adding 64 (len 48 padlen 16 extra_pad 64)
debug2: we sent a password packet, wait for reply
Connection closed by 192.168.16.14
git@zzz-Inspiron-1545:~/.ssh$
```
Did you have caught this problem?
How would I do to slove the problem?
**Why cannot we login `A` by ssh access without password from `B` as a git user?**
|
2012/09/06
|
[
"https://Stackoverflow.com/questions/12296676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1651306/"
] |
I'm on WindowsXP, and I use `Ctrl` + `Alt` + `↓` to navigate through the messages in the Make window - does this do what you want?
One thing about that though, is that it is actually navigating though "messages" not just errors - so if you have a lot of warnings in your project, that could get in the way. I did just notice there's a "hide warnings" button though, so that could help.
|
48,532,977 |
I have a workflow where there are 2 signers, a client, and then a supervisor. I have it so that the client signs it, then the supervisor signs it. I now need my app, to get the signed document.
I have been reading some docusign API and some SO stuff and I see this [DocusignRest API](https://www.docusign.com/p/RESTAPIGuide/RESTAPIGuide.htm#Basic%20Scenarios/Retrieving%20Envelope%20and%20Documents.htm?Highlight=documents)
But that is after the envelope reaches completed status, I don't want to have to poll the envelope, is there a webhook or callback that I can call after ALL recipients have signed/
|
2018/01/31
|
[
"https://Stackoverflow.com/questions/48532977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1967416/"
] |
Yes, DocuSign has webhook called as DocuSign Connect. You can subscribed for the trigger events like envelope complete etc, once that event happens then DocuSign will push the XML message to you with the envelope details. You can read more related to DS here,
* [Custom Connect Configuration](https://www.docusign.com/supportdocs/ndse-admin-guide/Content/custom-connect-configuration.htm)
* [DS Support - Connect](https://support.docusign.com/guides/ndse-admin-guide-connect)
|
12,505,915 |
I have a view (called outPutView) that contains graphics, like uIImageViews and labels. I need to render an image of the outPutView and it's sub-views. I am using renderInContext:UIGraphicsGetCurrentContext() to do so. Works fine, except that I need to scale the views. I am using a transform on the outPutView. This successfully scales the view and it's sub-views, but the transform does not render. While the views are scaled onscreen. the final render displays the vies at their original size, while the render context is at the target size (here @2x iPhone view size).
Thanks for reading!!
```
[outPutView setTransform:CGAffineTransformMake(2, 0, 0, 2, 0, 0)];
CGSize renderSize = CGSizeMake(self.view.bounds.size.width*2, self.view.bounds.size.height*2);
UIGraphicsBeginImageContext(renderSize);
[[outPutView layer] renderInContext:UIGraphicsGetCurrentContext()];
renderedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
```
|
2012/09/20
|
[
"https://Stackoverflow.com/questions/12505915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1408546/"
] |
I've just made this work, although in the opposite direction (scaling down). Here's a summary of the relevant code:
```c
// destination size is half of self (self is a UIView)
float rescale = 0.5;
CGSize resize = CGSizeMake(self.width * rescale, self.height * rescale);
// make the destination context
UIGraphicsBeginImageContextWithOptions(resize, YES, 0);
// apply the scale to dest context
CGContextScaleCTM(UIGraphicsGetCurrentContext(), rescale, rescale);
// render self into dest context
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
// grab the resulting UIImage
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
```
To scale up instead of down, it should be fine to have `rescale = 2`.
|
51,728,082 |
I've been wrangling with this problem for over a week with little to no progress.
I've looked at
* [How to set selected value of jquery select2?](https://stackoverflow.com/questions/25187926/how-to-set-selected-value-of-jquery-select2)
* [Select2 doesn't work when embedded in a bootstrap modal](https://stackoverflow.com/questions/18487056/select2-doesnt-work-when-embedded-in-a-bootstrap-modal/19574076#19574076)
* [Populating dropdown with JSON result - Cascading DropDown using MVC3, JQuery, Ajax, JSON](https://stackoverflow.com/questions/14339089/populating-dropdown-with-json-result-cascading-dropdown-using-mvc3-jquery-aj)
* [Reset select2 value and show placeholder](https://stackoverflow.com/questions/17957040/reset-select2-value-and-show-placeholder)
* <https://github.com/select2/select2/issues/3057>
* <https://github.com/select2/select2/issues/1436>.
Finally, after looking at <https://select2.org/troubleshooting/common-problems>
I tried applying both the `dropdownParent: $('#myModal')` and the
```
// Do this before you initialize any of your modals
$.fn.modal.Constructor.prototype.enforceFocus = function() {};
```
Neither of these fixes worked so I'm really at my wits end and ready to give up on using the modal altogether. Basically I'm getting my data back from the server in a JSON object, then using that data to populate the modal. The populating is working correctly on all the elements (several of which are select / combo boxes) except the first combobox.
Thank you in advance for your help and sorry if the answer is posted elsewhere, but I can't find it.
Following is the pertinent code:
```
<!-- Modal to Add / Edit Delay parent div must have same id as value of the data-target attribute used to trigger the modal -->
<div class="modal fade" id="delayAddModal" tabindex="-1" role="dialog" aria-labelledby="delayAddLabel">
<div class="modal-dialog" role="document">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<!-- This "x" button is for dismissing the modal -->
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="delayAddLabel">Add Delay</h4>
</div>
<div class="modal-body">
<p id="testActualJobTaskIdFunction"></p>
@Html.Partial("_ActualTrainDelayAddEdit", Model.TrainDelay)
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<!-- call to js function-->
<button id="delayAddButton" type="button" class="btn btn-primary" data-title="Add Delay">Add Delay</button>
</div>
</div>
</div>
</div>
```
Partial view nested in the modal defined above (this has been trimmed down so that the elements that are updating correctly are missing). The subdivisionId is not updating correctly, however, locationId is (both are combo boxes):
```
@model ActualTrainDelayAddEditModel
<form name="delay-form" id="delay-form">
@Html.HiddenFor(m => m.ActualTrainDelayId, new { id = "ActualTrainDelayId" })
@Html.HiddenFor(m => m.ActualJobTaskId)
@*Original:*@
<div class="form-group">
<!-- Renders floating text ("Subdivision") above the select options -->
@Html.LabelFor(m => m.SubdivisionId, new { @class = "field-label always-visible" })
<!-- ID for select element -->
<!-- Renders select class="select" id="SubdivisionId" name="SubdivisionId"><option value="4429faa8-5ad4-4adf-adde-ec7cf88ed9e9" innerHTML "Caltrain"-->
@Html.DropDownListFor(m => m.SubdivisionId, Model.AvailableSubdivisions, new { @class = "select" })
@Html.ValidationMessageFor(m => m.SubdivisionId)
</div>
<!-- Location -->
<div class="form-group">
@Html.LabelFor(m => m.LocationId, new { @class = "field-label always-visible" })
<select id="LocationId" name="LocationId" class="select">
@foreach (var loc in Model.AvailableLocations)
{
<option value="@loc.Id" data-milepost="@loc.Milepost">@loc.Name</option>
}
</select>
@Html.ValidationMessageFor(m => m.LocationId)
</div>
</div>
```
jQuery function that is updating the modal with the data:
```
<script>
// Do this before you initialize any of your modals
$.fn.modal.Constructor.prototype.enforceFocus = function() {};
$("#delayAddModal")
.on("show.bs.modal",
function(event) {
var button = $(event.relatedTarget); // Button that triggered the modal
var modal = $(this);
var title = button.data('title'); // get New title from data-title attribute
var delId = button.data("guid");
var name = button.data("name");
var conditionalVariable = 1;
var updateButtonValue = "Save Edit";
//alert(title);
//$("#SubdivisionId").append("<option value='0'>--Select State--</option>");
//If add delay is clicked there will be no guid
if (delId == null) {
modal.find('.modal-title').text(title); // set title to Add Delay
modal.find('#delayAddButton').text("Add Delay"); // set button value to Add Delay
return;
}
modal.find('.modal-title').text(title); // set title to New title
modal.find('#delayAddButton').text(updateButtonValue); // set button value to Edit Delay
// var button = $(event.relatedTarget);
// var delId = button.data("guid");
// var name = button.data("name");
//var modal = $(this);
$.ajax({
type: "GET",
url: "@Url.Action("GetDelayDataForEditing")/" + "?delayId=" + delId,
dataType: 'json',
//data: delId,
success: function(data) {
modal.find('');
//$("#SubdivisionId").change(function () {
var sub = data.SubdivisionId;
//console.log("This is the subId: "+sub);
//changing the subdivision changes the locations available in the location box
$.getJSON('@Url.Action("LocationBySubdivisionList", "TrainActivity")?id=' + sub,
function(locs) {
// the stuff that needs to happen before the parent ajax completes needs to go in here
$('#IncidentNumber').val(data.IncidentNumber);
// alert("In the getJson function");
//$("select#SubdivisionId").empty();
$('select#SubdivisionId').val(data.SubdivisionId);
//$('#SubdivisionId').select2('data', data.SubdivisionId);
//$('select#SubdivisionId').select2('data', data.SubdivisionId);
//$('#SubdivisionId').select2('data', { id: 100, a_key: 'Lorem Ipsum' });
$("#SubdivisionId > [value=" + data.SubdivisionId + "]")
.insertBefore("#SubdivisionId > :first-child");
//$("#SubdivisionId").append(data.SubdivisionId);
$('#StartMilepost').val(data.StartMilepost);
$('#EndMilepost').val(data.EndMilepost);
var list = $('#LocationId');
list.find('option').remove();
$(locs).each(function(index, loc) {
list.append('<option value="' +
loc.Id +
'" data-milepost="' +
loc.Milepost +
'">' +
loc.Name +
'</option>');
});
$('select#LocationId').val(data.LocationId);
$("#LocationId > [value=" + data.LocationId + "]")
.insertBefore("#LocationId > :first-child");
//$("#LocationId").append(data.LocationId);
//nearestMilepost();
$('select#DelayTypeId').val(data.DelayTypeId);
$("#DelayTypeId > [value=" + data.DelayTypeId + "]")
.insertBefore("#DelayTypeId > :first-child");
//$("#DelayTypeId").append(data.DelayTypeId);
$('select#ThirdPartyResponsibleId').val(data.ThirdPartyResponsibleId);
$("#ThirdPartyResponsibleId > [value=" + data.ThirdPartyResponsibleId + "]")
.insertBefore("#ThirdPartyResponsibleId > :first-child");
$('#BeginDelayDateTime').val(parseHoursAndMinutes(data.BeginDelayDateTime));
$('#EndDelayDateTime').val(parseHoursAndMinutes(data.EndDelayDateTime));
$('#ResultingDelay').val(data.ResultingDelay);
$('#TimeInDelay').val(data.TimeInDelay);
if (data.IsServiceFailure) {
$('#IsServiceFailure').iCheck('check');
} else {
$('#IsServiceFailure').iCheck('uncheck');
}
if (data.IsResolved) {
$('#IsResolved').iCheck('check');
} else {
$('#IsResolved').iCheck('uncheck');
}
if (data.IsRootCauseDelay) {
$('#IsRootCauseDelay').iCheck('check');
} else {
$('#IsRootCauseDelay').iCheck('uncheck');
}
$('#Comment').val(data.Comment);
$('#SavedVisible').iCheck('uncheck');
$('#SaveNewComment').iCheck('uncheck');
$('#ActualTrainDelayId').val(data.ActualTrainDelayId);
//delayExists = true;
//$('button#delayAddButton').attr("id", delId);
});
alert("Success " +
"\nunparsed data: " +
data +
"\nStringified data: " +
JSON.stringify(data) +
//"\nNew JS date: " + newJavaScriptDate +
//"\nDate date: " + parsedBeginDateTime +
//"\nFormatted date: " + hoursAndMinutes +
//"\nDisplay time: " + timeToDisplay +
//"\nAJT id: " + data.ActualJobTaskId +
//"\nIncident Number: " + data.IncidentNumber +
"\nLocation ID: " +
data.LocationId +
"\nStart MP: " +
data.StartMilepost +
"\nEnd MP: " +
data.EndMilepost +
"\nDelay Type Id: " +
data.DelayTypeId +
"\nThird Party Resp: " +
data.ThirdPartyResponsibleId +
"\nSubdivision Id: " +
data.SubdivisionId +
"\nbegin Delay time: " +
data.BeginDelayDateTime +
"\nend Delay time: " +
data.EndDelayDateTime +
"\nresulting delay: " +
data.ResultingDelay +
"\ntime in delay: " +
data.TimeInDelay +
"\nis root cause: " +
data.IsRootCauseDelay +
"\nis resolved: " +
data.IsResolved +
"\nis service failure: " +
data.IsServiceFailure +
"\ncomment: " +
data.Comment
);
//$('#delays-grid').data('kendoGrid').dataSource.read();
//$("#delayAddModal").modal("hide");
},
error: function() { alert("error in Delay Edit"); }
});
//modal.find(".modal-body").text("Edit the Delay at " + name + " with id " + delId);
//modal.find(".modal-footer #delayEditButton").data("guid", delId);
});
</script>
```
|
2018/08/07
|
[
"https://Stackoverflow.com/questions/51728082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9221452/"
] |
Okay, I think I came up with a fix found here: <https://select2.org/programmatic-control/add-select-clear-items>
I edited my statement from:
```
$('select#SubdivisionId').val(data.SubdivisionId);
```
to:
```
$('select#SubdivisionId').val(data.SubdivisionId).trigger('change');
```
Sorry for any inconvenience. Hopefully this helps. Cheers.
|
12,084,994 |
I want to generate a certain number of divs using PHP with different ids, I know how to generate them for a set number, but how do I generate on click, with different ids? Also, if
I wanted to delete a div (and its corresponding id) how would I do that?
This is the code I have for generating (6) divs
```
$element = "<div></div>";
$count = 6;
foreach( range(1,$count) as $item){
echo $element;
}
```
I need something like the click() in jquery/javscript (but in PHP) to trigger div creation instead and I don't even know where to start.
|
2012/08/23
|
[
"https://Stackoverflow.com/questions/12084994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/625609/"
] |
In JavaScript you can do
```
function createDiv(id, parent)
{
var elem = document.createElement('div');
elem.id = id;
document.getElementById(parent).appendChild(elem);
}
createDiv(10, id-of-parent-elem-to-append-to);
```
where 10 will be the ID of the new element and you will have to supply the ID of the element to which the new DIV should be appended, as the 2nd argument
|
34,538,046 |
I am trying to make multiple API requests and I have to make the request in different functions that are within a class like so:
```
class exampleClass
{
function callFunction1 () {
// stuff that makes a call
return $json;
}
function printStuffOut() {
$jsonStuff = $this->callFunction1();
$$jsonStuff->{'result'}[0]->{'fieldName'};
}
function printStuffOut2() {
$jsonStuff = $this->callFunction1();
$jsonStuff->{'result'}[0]->{'fieldName'};
}
}
```
Am I making two separate API calls?
If I am, is there a way to store that API call information say in an array then use that array in all the other functions in my class?
|
2015/12/30
|
[
"https://Stackoverflow.com/questions/34538046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2769705/"
] |
Answer to first question: Yes you are, each time the method is called it executes all its definition again.
Answer to second question: Yes there is, so called member properties. You can read up about them in the PHP manual here: [PHP Manual: Properties](http://php.net/manual/en/language.oop5.properties.php)
|
14,625,601 |
This work is being done on a test virtualbox machine
In my /root dir, i have created the following:
"/root/foo"
"/root/bar"
"/root/i have multiple words"
Here is the (relevant)code I currently have
```
if [ ! -z "$BACKUP_EXCLUDE_LIST" ]
then
TEMPIFS=$IFS
IFS=:
for dir in $BACKUP_EXCLUDE_LIST
do
if [ -e "$3/$dir" ] # $3 is the backup source
then
BACKUP_EXCLUDE_PARAMS="$BACKUP_EXCLUDE_PARAMS --exclude='$dir'"
fi
done
IFS=$TEMPIFS
fi
tar $BACKUP_EXCLUDE_PARAMS -cpzf $BACKUP_PATH/$BACKUP_BASENAME.tar.gz -C $BACKUP_SOURCE_DIR $BACKUP_SOURCE_TARGET
```
This is what happens when I run my script with sh -x
```
+ IFS=:
+ [ -e /root/foo ]
+ BACKUP_EXCLUDE_PARAMS= --exclude='foo'
+ [ -e /root/bar ]
+ BACKUP_EXCLUDE_PARAMS= --exclude='foo' --exclude='bar'
+ [ -e /root/i have multiple words ]
+ BACKUP_EXCLUDE_PARAMS= --exclude='foo' --exclude='bar' --exclude='i have multiple words'
+ IFS=
# So far so good
+ tar --exclude='foo' --exclude='bar' --exclude='i have multiple words' -cpzf /backup/root/daily/root_20130131.071056.tar.gz -C / root
tar: have: Cannot stat: No such file or directory
tar: multiple: Cannot stat: No such file or directory
tar: words': Cannot stat: No such file or directory
tar: Exiting with failure status due to previous errors
# WHY? :(
```
The Check completes sucessfully, but the `--exclude='i have multiple words'` does not work.
Mind you that it DOES work when i type it in my shell, manually:
```
tar --exclude='i have multiple words' -cf /somefile.tar.gz /root
```
I know that this would work in bash when using arrays, but i want this to be POSIX.
Is there a solution to this?
|
2013/01/31
|
[
"https://Stackoverflow.com/questions/14625601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1213137/"
] |
Consider this scripts; ('with whitespace' and 'example.desktop' is sample files)
```
#!/bin/bash
arr=("with whitespace" "examples.desktop")
for file in ${arr[@]}
do
ls $file
done
```
This outputs as exactly as yours;
```
21:06 ~ $ bash test.sh
ls: cannot access with: No such file or directory
ls: cannot access whitespace: No such file or directory
examples.desktop
```
You can set IFS to '\n' character to escape white spaces on file names.
```
#!/bin/bash
arr=("with whitespace" "examples.desktop")
(IFS=$'\n';
for file in ${arr[@]}
do
ls $file
done
)
```
the output of the second version should be;
```
21:06 ~ $ bash test.sh
with whitespace
examples.desktop
```
|
360,492 |
An example is switching the main view according to the selected item in a [hamburger menu](https://en.wikipedia.org/wiki/Hamburger_button). Also sometimes it is just a small part of the GUI that changes according to the application state or according to user interaction with other parts of the GUI.
In WebForms days we used to create a tab control and hide the tab buttons bars and change the current tab page programmatically. Or stack the views on top of each other in design and in runtime hide all but one.
In WPF and MVVM I've seen people creating `DataTemplate` for each view, attach each to a view model and switch by changing the bound object to be of a different view model type and so the view changes.
I can see why that is a good idea for the hamburger menu views, but for some other cases, there are not necessarily a view model for each view. And in that case I'd like to escape having to create dummy view models for each view just to be able to switch between them rather than really having different types of data that I need to bind to each view.
Am I right to be concerned about this design detail?
Anyone had the same situation? What was the way you achieved the switch view effect?
In general, assuming there is no different type of data attached to each of the views to switch between, is it a correct practice to create view models just for something that is purely GUI? In other words, is view models more coupled to the data and what kind of data is available or to the GUI and the types of view we need to cover? And should we write the code for changing views on certain triggers in code behind in case we agreed that this is purely GUI and view models are not to be involved?
|
2017/11/09
|
[
"https://softwareengineering.stackexchange.com/questions/360492",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/286104/"
] |
In MVVM, the ViewModel contains the state of your UI. The View is merely a reflection of that state. This reflection of state is accomplished via databinding, converters, styles, etc.
I think what you want is a state variable on your ViewModel and have visibility of various UI bits bound to that state.
First, define a state enum and create a property on your VM:
```cs
enum ViewState
{
State1,
State2
}
class MyVM
{
public ViewState ViewState {get;set;}
}
```
Then in your view, you can hide/show UI elements using triggers:
```
<StackPanel>
<StackPanel.Style>
<Style TargetType="StackPanel">
<Setter Property="Visibility" Value="Collapsed" />
<Style.Triggers>
<DataTrigger Binding="{Binding Path=ViewState}" Value="{x:Static local:ViewState.State1}">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</StackPanel.Style>
</StackPanel>
```
|
32,105,989 |
I am trying to calculate the daily mode of this time series. In the example data below, I would like to see the mode of the `windDir.c` column per day.
Don't know how to use the `apply.daily()` wrapper given the fact there is no "colMode" argument. So, I tried using a custom function in `period.apply()`, but to no avail. The code I tried, along with the `dput` follows.
```
ep <- endpoints(wind.d,'days')
modefunc <- function(x) {
tabresult <- tabulate(x)
themode <- which(tabresult == max(tabresult))
if (sum(tabresult == max(tabresult))>1)
themode <- NA
return(themode)
}
period.apply(wind.d$windDir.c, INDEX=ep, FUN=function(x) mode(x))
```
Reproducible data:
```
wind.d <- structure(list(date = structure(c(1280635200, 1280635200, 1280635200,
1280635200, 1280635200, 1280635200, 1280635200, 1280721600, 1280721600,
1280721600, 1280721600, 1280721600, 1280721600, 1280721600, 1280808000,
1280808000, 1280808000, 1280808000, 1280808000, 1280808000), class = c("POSIXct",
"POSIXt"), tzone = ""), windDir.c = structure(c(4L, 3L, 3L, 4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 6L, 5L, 5L, 4L, 5L, 5L
), .Label = c("15", "45", "75", "105", "135", "165", "195", "225",
"255", "285", "315", "345"), class = "factor")), .Names = c("date",
"windDir.c"), class = "data.frame", row.names = c(NA, -20L))
```
|
2015/08/19
|
[
"https://Stackoverflow.com/questions/32105989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2263321/"
] |
You can refer to the element that handles the event with [`currentTarget`](https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget).
>
> Identifies the current target for the event, as the event traverses the DOM. It always refers to the element the event handler has been attached to as opposed to `event.target` which identifies the element on which the event occurred.
>
>
>
---
However, instead of relying on the browser to provide a global `event` object, I would pass it to the function:
```
onclick="doSomething(event)"
```
You can also refer to the element the handler is bound to with `this`:
```
onclick="doSomething(event, this)"
```
Of course please consider to [not use inline event handlers](https://stackoverflow.com/a/21975639/218196).
|
1,405,646 |
Can some one please help me to solve $\int\_{-1}^{2}\left \lfloor x \right \rfloor dx$ ?
|
2015/08/22
|
[
"https://math.stackexchange.com/questions/1405646",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/84605/"
] |
**Hint.** You may write your integral as
$$
\int\_{-1}^{2}[x]dx=\int\_{-1}^0[x]dx+\int\_0^1[x]dx+\int\_1^{2}[x]dx
$$ then it is easier to evaluate each part.
|
243,296 |
I'm trying to learn electronics and right now I'm reading the book *The Art of Electronics*.
I'm stuck on this chapter 2 on figure 2.10B.
1. In particular I'm simply confused with the lingo like "pulling" collector to the ground, R3 "hold off" Q3, what does the author really mean? If it is some sort of quantity like voltage or current, why doesn't the author just say something like "voltage/current increases/decreases to X"?
2. What is "sinks the current"?
3. The part where it says "make sure you understand why?" well, no kidding I don't understand... :( I've understood about NPN and PNP thing, like for example to get into saturation mode Vb > Ve and Vb > Vc (NPN) and stuff like that, but I still didn't get how R3 keeps Q3 off when Q2 is off?
Well, I used the SPICE simulator, the result is exactly as the book says, but
I don't understand why. Many book reviews seems to state the book is great for beginners, but it just skims through so fast on the foundations part.
Here is the text:
>
> Figure 2.10B shows how to do that: NPN switch Q2 accepts the “logic-level” input of 0 V or +3 V, pulling its collector load to ground accordingly.
> When Q2 is cut off, R3 holds Q3 off; when Q2 is saturated
> (by a +3 V input), R2 sinks base current from Q3 to bring it
> into saturation.
> The “divider” formed by R2 R3 may be confusing: R3's
> job is to keep Q3 off when Q2 is off; and when Q2 pulls
> its collector low, most of its collector current comes from
> Q3's base (because only ∼0.6 mA of the 4.4 mA collector
> current comes from R3 – make sure you understand why).
> That is, R3 does not have much effect on Q3's saturation.
> Another way to say it is that the divider would sit at about
> +11.6 V (rather than +14.4 V), were it not for Q3's base–
> emitter diode, which consequently gets most of Q2's collector current. In any case, the value of R3 is not critical and could be made larger; the tradeoff is slower turn-off of Q3, owing to capacitive effects.
>
>
>

|
2016/06/28
|
[
"https://electronics.stackexchange.com/questions/243296",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/114815/"
] |
1)
* When Q2 is on, it has very low Vce, 'pulling' the collector of Q2 to near ground.
* When Q2 is off, R3 holds Q3 in an "off" state, because it causes the base voltage of Q3 to be almost identical to the emitter of Q3. When Vbe < 0.7V the transistor will be OFF
* OFF = no current
2)
Which current? Q2 sinks current from R3 when it's on. The "Load" sinks current from Q3. It's a resistor or a light bulb or something.
3)
When Vbe is less than the cutoff voltage, the transistor will be off.
It's not the most easy to read passage in the book, but you should be able to get through it by tracing currents and voltages on your own, matching up what he's saying with what you see.
|
14,341,241 |
i have an aspx, aspx.cs file, in the aspx file i m using javascript functions,
in the javascript code i use the getter (<%=getSize%>) method defined in the aspx.cs file,
but the page returns: "The Controls collection cannot be modified because the control contains code blocks" why?
```
<!-- language-all:lang-js -->
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="uploadFile.aspx.cs"
Inherits="UploadControl_CustomProgressPanel" Title="Untitled Page" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Untitled Page</title>
<script language="javascript" type="text/javascript">
var size = <%=getSize%>;
var id= 0;
function ProgressBar()
{
if(document.getElementById("FileUpload1").value != "")
{
document.getElementById("divProgress").style.display = "block";
document.getElementById("divUpload").style.display = "block";
id = setInterval("progress()",20);
return true;
}
else
{
alert("Select a file to upload");
return false;
}
}
function progress()
{
//size = size + 1;
if(size > 299)
{
clearTimeout(id);
}
document.getElementById("divProgress").style.width = size + "pt";
document.getElementById("lblPercentage").firstChild.data = parseInt(size / 3) + "%";
}
```
aspx.cs file:
```
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
public partial class UploadControl_CustomProgressPanel : System.Web.UI.Page
{
protected int size = 2;
protected int getSize{ get { return this.size; }}
protected void Page_Load(object sender, EventArgs e)
{
string UpPath;
UpPath = "C:\\";
if (! Directory.Exists(UpPath))
{
Directory.CreateDirectory("C:\\");
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//StatusLabel.Text = "File scelto, Upload in corso..";
if(FileUpload1.HasFile)
{
try
{
string filePath = Request.PhysicalApplicationPath;
filePath += "classic/hub/csv/";
filePath += FileUpload1.FileName;
this.size = 50;
FileUpload1.SaveAs(filePath);
//StatusLabel.Text = "Upload status: File uploaded!";
Label1.Text = "Upload successfull!";
}
catch(Exception ex)
{
//StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}
```
|
2013/01/15
|
[
"https://Stackoverflow.com/questions/14341241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/448381/"
] |
You haven't posted the full HTML but try to move your script out of the `<head>` tag.
|
2,181,802 |
HI, I have a problem parsing a date in php using strptime() as my system is running windows. I've also try to parse the date using strtotime() but not luck either because I'm using euro date format.
This is the date format I'm using **30/11/2009 11:00 am** and I need to get the timestamp from it.
Any ideas how can I achieve this ??
|
2010/02/02
|
[
"https://Stackoverflow.com/questions/2181802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/111374/"
] |
```
$us = preg_replace('#^(\d+)/(\d+)/(\d+)\s([\d:]+)\s([a-zA-z]{0,2})$#','$3-$2-$1 $4 $5', $date);
$timestamp = strtotime($date);
```
|
11,337,041 |
Usually, `stdout` is line-buffered. In other words, as long as your `printf` argument ends with a newline, you can expect the line to be printed instantly. This does not appear to hold when using a pipe to redirect to `tee`.
I have a C++ program, `a`, that outputs strings, always `\n`-terminated, to `stdout`.
When it is run by itself (`./a`), everything prints correctly and at the right time, as expected. However, if I pipe it to `tee` (`./a | tee output.txt`), it doesn't print anything until it quits, which defeats the purpose of using `tee`.
I know that I could fix it by adding a `fflush(stdout)` after each printing operation in the C++ program. But is there a cleaner, easier way? Is there a command I can run, for example, that would force `stdout` to be line-buffered, even when using a pipe?
|
2012/07/05
|
[
"https://Stackoverflow.com/questions/11337041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/363078/"
] |
you can try `stdbuf`
```
$ stdbuf --output=L ./a | tee output.txt
```
(big) part of the man page:
```
-i, --input=MODE adjust standard input stream buffering
-o, --output=MODE adjust standard output stream buffering
-e, --error=MODE adjust standard error stream buffering
If MODE is 'L' the corresponding stream will be line buffered.
This option is invalid with standard input.
If MODE is '0' the corresponding stream will be unbuffered.
Otherwise MODE is a number which may be followed by one of the following:
KB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.
In this case the corresponding stream will be fully buffered with the buffer
size set to MODE bytes.
```
keep this in mind, though:
```
NOTE: If COMMAND adjusts the buffering of its standard streams ('tee' does
for e.g.) then that will override corresponding settings changed by 'stdbuf'.
Also some filters (like 'dd' and 'cat' etc.) dont use streams for I/O,
and are thus unaffected by 'stdbuf' settings.
```
you are not running `stdbuf` on `tee`, you're running it on `a`, so this shouldn't affect you, unless you set the buffering of `a`'s streams in `a`'s source.
Also, `stdbuf` is **not** POSIX, but part of GNU-coreutils.
|
71,142,888 |
Since today my Azure Devops pipeline fails on the VSBuild task while it worked fine a long time.
I have 40 errors like :
*##[error]BlazorClient\Components\AuditTrailList.razor.cs(17,19): Error CS0246: The type or namespace name 'ImportMessages' could not be found (are you missing a using directive or an assembly reference?)*
ImportMessages that is referred in the error is actually a blazor component though which is located in the same project and the same namespace as AuditTrailList..
If I look closer at the 40 errors, it is always on components referring to other components, cfr. screenshot.
[](https://i.stack.imgur.com/UXUM4.png)
This is my yaml file for the pipeline:
```
trigger:
branches:
include:
- develop
paths:
exclude:
- '**/azure-pipelines.yml'
pool:
vmImage: 'windows-2022'
variables:
solution: '**/*.sln'
buildPlatform: 'Any CPU'
buildConfiguration: 'Release'
JsLibDirectory: 'FundServices.BlazorClient/JsLib'
steps:
- task: UseDotNet@2
displayName: 'Use dotnet 6'
inputs:
version: '6.0.x'
- task: NuGetToolInstaller@1
- task: NuGetCommand@2
inputs:
command: 'restore'
restoreSolution: '**/*.sln'
feedsToUse: 'config'
nugetConfigPath: '.nuget\NuGet.Config'
externalFeedCredentials: 'Telerik Nuget'
- task: NodeTool@0
inputs:
versionSpec: '10.x'
displayName: 'Install Node.js'
- task: Npm@1
displayName: 'npm install'
inputs:
command: 'install'
workingDir: '$(JsLibDirectory)'
verbose: true
- script: |
npm run build
displayName: 'npm run build'
workingDirectory: '$(JsLibDirectory)'
- task: VSBuild@1
inputs:
solution: '$(solution)'
msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:DeployIisAppPath="Default Web Site"'
platform: '$(buildPlatform)'
configuration: '$(buildConfiguration)'
clean: true
msbuildArchitecture: 'x64'
- task: VSTest@2
inputs:
testSelector: 'testAssemblies'
testAssemblyVer2: |
**\*Tests.dll
!**\*TestAdapter.dll
!**\obj\**
!**\bin\**\ref\**
searchFolder: '$(System.DefaultWorkingDirectory)'
platform: '$(buildPlatform)'
configuration: '$(buildConfiguration)'
- task: DotNetCoreCLI@2
displayName: Publish
inputs:
command: publish
publishWebProjects: True
arguments: '--configuration $(BuildConfiguration) --output $(Build.artifactstagingdirectory)'
zipAfterPublish: True
# - task: ExtractFiles@1
# inputs:
# archiveFilePatterns: '$(Build.artifactstagingdirectory)/FundServices.BlazorClient.zip'
# destinationFolder: '$(Build.artifactstagingdirectory)/WorkingDirectory'
# cleanDestinationFolder: true
# overwriteExistingFiles: true
# - task: CopyFiles@2
# inputs:
# SourceFolder: '$(Build.artifactstagingdirectory)/WorkingDirectory/wwwroot'
# Contents: 'web.config'
# TargetFolder: '$(Build.artifactstagingdirectory)/WorkingDirectory'
# OverWrite: true
# - task: ArchiveFiles@2
# inputs:
# rootFolderOrFile: '$(Build.artifactstagingdirectory)/WorkingDirectory'
# includeRootFolder: false
# archiveType: 'zip'
# archiveFile: '$(Build.artifactstagingdirectory)/FundServices.BlazorClient.zip'
# replaceExistingArchive: true
- task: PublishBuildArtifacts@1
displayName: 'Publish WebApp'
inputs:
PathtoPublish: '$(Build.artifactstagingdirectory)/FundServices.BlazorClient.zip'
ArtifactName: 'WebApp'
publishLocation: 'Container'
condition: succeededOrFailed()
- task: PublishBuildArtifacts@1
displayName: 'Publish Api'
inputs:
PathtoPublish: '$(Build.artifactstagingdirectory)/FundServices.Api.zip'
ArtifactName: 'WebApi'
publishLocation: 'Container'
condition: succeededOrFailed()
- task: PublishBuildArtifacts@1
displayName: 'Publish WorkFlowScheduler'
inputs:
PathtoPublish: '$(Build.artifactstagingdirectory)/FundServices.WorkFlowScheduler.zip'
ArtifactName: 'WorkFlowScheduler'
publishLocation: 'Container'
condition: succeededOrFailed()
```
Thanks,
Tom
|
2022/02/16
|
[
"https://Stackoverflow.com/questions/71142888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1270097/"
] |
You could try to use the **singleton design pattern** for your specific problem
See this link: <https://www.gofpatterns.com/creational/patterns/singleton-pattern.php>
|
3,081 |
This has bugged me for some time.
Tycho Brahe's data on planetary observations, presumably, consisted of the direction in which a planet was observed at a given date and time, but **not** the distance to the planet. What techniques did Kepler use to add a depth dimension to these observations, to create the three-dimensional data that one can start studying to arrive at his three laws?
[Cross-posted from Physics Stack Exchange.](https://physics.stackexchange.com/questions/161333/how-did-kepler-infer-three-dimensional-positions-from-tycho-brahes-data)
|
2015/11/17
|
[
"https://hsm.stackexchange.com/questions/3081",
"https://hsm.stackexchange.com",
"https://hsm.stackexchange.com/users/272/"
] |
At the time of Kepler distances were not measured or observed directly. Or if measured, the results were completely wrong. All his laws are stated in terms of RATIOS of distances, and these ratios can be in principle measured from the geometry
of the situation. When you describe everything as seen from the Earth (as the ancients did), distances are completely irrelevant. But when one uses heliocentric system, all ratios of distances to the distance from Earth to Sun
can be obtained from angular observation.
Of course this is only the general principle. The details are MUCH more complicated.
EDIT. But the idea is the following: suppose for simplicity that everything happens in the same plane, and that the planets move on circles.
(This is actually a good approximation because the inclinations of the orbits are small and excentricities are also small. As seen from the Earth, the Sun rotates on a circle of radius $r$ uniformly, with center at the Earth. The planet rotates around the Sun on a circle of radius $R$, also uniformly. Suppose that at three different times you observe the direction on the planet, this essentially means that you measure two angles on your picture. And two other angles you know because you know the time of observations and Sun's rotation speed. From these angles by pure geometry you can find the ratio $r/R$. Just make a picture, and consider this a high school geometry exercise (of moderate difficulty). This was already known to Ptolemy, by the way.
These ratios were known to Kepler, and by playing with them he discovered his 3-d
law. But his greatest achievement is the FIRST law: he was able to derive from
the observations (of the same kind that I described) that the planets really
do not move on circles but on ellipses. How exactly he did this I cannot explain within the space allowed here:-) But his own explanation is available in English btw.
|
7,765 |
pretty much the title- version 0.4/loki
using either parallels 11 or 12, after i install parallels tools the cursor is invisible (I can still click things on the desktop)
Things i tried-
1. Reinstalling
2. Disable Vsync
3. Disable 3D acceleration
|
2016/09/13
|
[
"https://elementaryos.stackexchange.com/questions/7765",
"https://elementaryos.stackexchange.com",
"https://elementaryos.stackexchange.com/users/6295/"
] |
I had to set the Boot flags to this:
devices.usb.mouse=1
This fixed the problem for me.
|
17,427,087 |
I've recently read the [Single Pass Seed Selection Algorithm for k-Means](http://thescipub.com/pdf/10.3844/jcssp.2010.60.66) article, but not really understand the algorithm, which is:
1. Calculate distance matrix `Dist` in which `Dist (i,j)` represents distance from `i` to `j`
2. Find `Sumv` in which `Sumv (i)` is the sum of the distances from `i`th point to all other points.
3. Find the point `i` which is `min (Sumv)` and set `Index = i`
4. Add First to `C` as the first centroid
5. For each point `xi`, set `D (xi)` to be the distance between `xi` and the nearest point in `C`
6. Find `y` as the sum of distances of first `n/k` nearest points from the `Index`
7. Find the unique integer `i` so that `D(x1)^2+D(x2)^2+...+D(xi)^2 >= y > D(x1)^2+D(x2)^2+...+D(x(i-1))^2`
8. Add `xi` to `C`
9. Repeat steps 5-8 until `k` centers
Especially step 6, do we still use the same `Index` (same point) over and over or we use the newly added point from `C`? And about step 8, does `i` have to be larger than `1`?
|
2013/07/02
|
[
"https://Stackoverflow.com/questions/17427087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2542797/"
] |
Honestly, I wouldn't worry about understanding that paper - its not very good.
* The algorithm is poorly described.
* Its not actually a single pass, it needs do to n^2/2 pairwise computations + one additional pass through the data.
* They don't report the runtime of their seed selection scheme, probably because it is very bad doing O(n^2) work.
* They are evaluating on very simple data sets that don't have a lot of bad solutions for k-Means to fall into.
* One of their metrics of "better"ness is how many iterations it takes k-means to run given the seed selection. While it is an interesting metric, the small differences they report are meaningless (k-means++ seeding could be more iterations, but less work done per iteration), and they don't report the run time or which k-means algorithm they use.
You will get a lot more benefit from learning and understanding the k-means++ algorithm they are comparing against, and reading some of the history from that.
If you really want to understand what they are doing, I would brush up on your matlab and read their provided matlab code. But its not really worth it. If you look up the quantile seed selection algorithm, they are essentially doing something very similar. Instead of using the distance to the first seed to sort the points, they appear to be using the sum of pairwise distances (which means they don't need an initial seed, hence the unique solution).
|
5,540 |
Currently purchasing the required kit to start etching my own boards and have gotten to the etching solution stage. Ferric Chloride seems to be the standard for etching but I have also read about [Muriatic Acid + Hydrogen Peroxide ecthing](http://www.instructables.com/id/Stop-using-Ferric-Chloride-etchant!--A-better-etc/#step1), which apparently is better all round (both for the environment and my pocket).
Has anyone had any experience with this method of etching?
|
2010/10/24
|
[
"https://electronics.stackexchange.com/questions/5540",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/1333/"
] |
I've used the muriatic acid/hydrogen peroxide solution. It works great when it's fresh, but it does NOT keep for me. If I go back and use it a couple of weeks later, it just doesn't work. I haven't pursued proper disposal, yet, so I've accrued a bit of the stuff in mason jars (whose lids are rusting from the acid, by the way). Once I figure out how to get rid of the acid/peroxide mixture, I think I'm going to try FeCl.
|
104,825 |
I need a little help figuring out what's going on with an NPC's character controller. Here are the character controller settings for the NPC.
[](https://i.stack.imgur.com/rWTBX.png)
The problem I'm running into is that the NPC isn't walking up a slight gradient as it should; instead, it moves **through** the ground.
Below are the settings for the ground.
[](https://i.stack.imgur.com/Yn6wK.png)
The NPC isn't on the ground- it is a few units off. Any help is greatly appreciated.
Thanks in advance...
|
2015/07/29
|
[
"https://gamedev.stackexchange.com/questions/104825",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/17865/"
] |
The difference, based on the Minecraft wiki documentation, appears to be that [`.nbt` is a binary format for storing arbitrary tree data](http://minecraft.gamepedia.com/NBT_Format). The [Anvil format](http://minecraft.gamepedia.com/Anvil_file_format) a type of region format, specifically for storing chunks of a Minecraft world.
An Anvil file might *contain* NBT formatted blobs of data describing individual aspects of the region, but the Anvil file itself is more a container of `.nbt` (and possible other data) than a a singular `.nbt` itself, and consequently it's very possible the `NBTExplorer` explorer tool simply isn't designed to open that kind of file.
It's also possible that despite your assertion, the data is not "ok" and may be malformed in such a way that it's parseable as a `.nbt` alone but when put within the structure of the `.mca` file, it causes some checksum or something to fail.
|
12,535,828 |
I'm reading sms record from database and write them into text file. But it takes too much time 3 to 4 mins to read n write 3500 records. If records are much more than that it takes plenty of time which is not appreciable. My code is:
```
final Cursor cur1 = c.getContentResolver().query(Uri.parse("content://sms/"), null, null, null, "date ASC");
final int size = cur1.getCount();
final int sleeptimer = size;
final SMS [] sms = new SMS[size];
final String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator + "account.txt";
FileWriter fw = null;
try {
fw = new FileWriter(baseDir);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
final BufferedWriter writer = new BufferedWriter(fw);
Thread myThread = new Thread()
{
public void run()
{
try
{
int currentwait = 0;
int j=0;
while(currentwait < sleeptimer)
{
sleep(200);
currentwait+=200;
for(int i = 0 ; i < 200 ; i++)
{
if(!cur1.moveToNext())
{
break;
}
ContactInfo p = new ContactInfo();
String content = cur1.getString(cur1.getColumnIndex("body"));
String number = cur1.getString(cur1.getColumnIndex("address"));
long date = cur1.getLong(cur1.getColumnIndex("date"));
String protocol = cur1.getString(cur1.getColumnIndex("protocol"));
String name = p.getName(number, c);
String type = null;
Calendar cal=Calendar.getInstance();
cal.clear();
cal.setTimeInMillis(date);
String date_time=String.format("%1$te %1$tB %1$tY,%1$tI:%1$tM:%1$tS %1$Tp",cal);
if( protocol == null )
{
type = "Outbox";
}
else
type = "Inbox";
try{
writer.write("Type: " + type);
writer.newLine();
writer.write("Name: " + number+"<"+name+">");
writer.newLine();
writer.write("Date: " + date_time);
writer.newLine();
writer.write("Content: " + content);
writer.newLine();
writer.newLine();
} catch (IOException e) {
Log.i("INFO", e.getMessage().toString());
}
//Log.i("INFO", content+" "+j);
sms[j] = new SMS(type , name , number , date_time , content );
j++;
}
}
}
catch(Exception e)
{
}
finally{
try{
writer.flush();
writer.close();
}
catch (Exception e) {
}
uploadtoserver(baseDir);
}
}
};
myThread.start();
```
any idea to improve it ???thanks :)))
|
2012/09/21
|
[
"https://Stackoverflow.com/questions/12535828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1534018/"
] |
Just remove this line:
```
sleep(200);
```
|
55,660,237 |
Here's a sample dataframe:
```
df = pd.DataFrame([['A0000x', 'a'],
['B0010x', 'b'],
['C0020x', 'c'],
['D0040x', 'd']])
df.columns = ['num', 'let']
```
I would like to extract only the rows where the integer comprised of 3rd and 4th character in the `num` column is divisible by 2, for example.
So I need to check if `df['num'][2:4] % 2`
I got this far, but can't figure out how to convert it into an integer:
`df.index[df['num'].str[2:4] == '01']`
|
2019/04/12
|
[
"https://Stackoverflow.com/questions/55660237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4414359/"
] |
Use `astype` to convert the string column to int, then boolean index.
```
df['num'].str[2:4].astype(int)
0 0
1 1
2 2
3 4
Name: num, dtype: int64
```
```
df[df['num'].str[2:4].astype(int) % 2 == 0]
num let
0 A0000x a
2 C0020x c
3 D0040x d
```
|
42,775,004 |
For example, I have a markerdisplay.cpp file. The markerdisplay member function will look like the below code.
```
void MarkerDisplay::setMarkerStatus(MarkerID id, StatusLevel level, const std::string& text)
{
.....
}
```
Can I have a non-member function in the markerdisplay.cpp?
For example,
```
bool validateFloats(const visualization_msgs::Marker& msg)
{
...
}
```
The function validateFloats is not a member function, and I also don't declare it in the header file. I only use this function inside of the validateFloats.cpp file.
Someone told me this may cause some problems. Is that true?
|
2017/03/13
|
[
"https://Stackoverflow.com/questions/42775004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7705666/"
] |
If you don't need the function outside of the `.cpp`, it is sufficient to declare and define it in that file. Of course you will still have to declare it before first use, but that is the only "problem" I can think of.
It is rather a good idea *not* to declare the function in the header if not needed because you use up fewer "project-public" names and make it easier to find all uses of the function, thus making the code more maintainable.
If you don't declare the function in your header, you should make it `static`:
```
static bool validateFloats(const visualization_msgs::Marker& msg);
```
or put it in an anonymous namespace:
```
namespace {
bool validateFloats(const visualization_msgs::Marker& msg);
}
```
(preferred) to avoid accidental cross-translation-unit name clashes.
|
55,999,996 |
Updating elements inside an array is explained here:
<https://docs.mongodb.com/manual/reference/operator/update/set/#set-elements-in-arrays>
But in the docs seems the case missing where the array does not exists yet in the document. Example:
If have this document:
```
{
_id: 'some-id',
otherprops: 'value'
}
```
And I want it to become like this:
```
{
// ...
settings: {
friends: [
{
name: 'John Doe',
age: 28
}
]
}
// ...
}
```
In this situation I dont know if there is already a settings.friends array. So my query looks like this:
```
{
$set: {
'settings.friends.0.name': 'John Doe',
'settings.friends.0.age': 28
}
}
```
However the document results in like this:
```
{
// ...
settings: {
friends: {
0: {
name: 'John Doe',
age: 28
}
}
}
// ...
}
```
Is there a way to force mongodb to create an array instead of an object in my example **but with using dot notations only.**
|
2019/05/06
|
[
"https://Stackoverflow.com/questions/55999996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1216137/"
] |
>
> try this.
>
>
>
```
{
$addToSet: {
"settings.friends": [
{
name: 'John Doe',
age: 28
}
]
}
}
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.