INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How to limit the amount of method for a delegate?
I have a `delegate`,and i want it only can be register for 5 times. I know i can set the `delegate` `private` and write a `AddRegister()` method to control the amount of `registered` method. Have any other ideas ?
|
You can use `GetInvocationList` method on the delegate object and then call `Count` method on it. Something to the effect of the following
Mydel d1 = this.MyMethod;
int count = d1.GetInvocationList().Count();//Here count will be 1
Also I would prefer to have the registration combined with the above functionality in one place similar to the one you mentioned in your question. In this way you need not have to write the `count <= 5` condition wherever it is being registered. Hence it will be easier to maintain.
Hope this helps.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, .net, delegates"
}
|
Dart: Failed to load "test/xxx_test.dart": Instance of 'OutsideTestException'
When I try to run the following test:
import 'package:my_project/my_file.dart';
import 'package:test/test.dart';
void main() {
group('int extensions:', () {
expect(1.digits(), 1);
expect(10.digits(), 2);
expect(100.digits(), 3);
});
}
I get the following error message:
> Failed to load "test/my_file_test.dart": Instance of 'OutsideTestException'
The answer is probably obvious most people coming here now, but it took me a while to realize what was wrong. I'm adding my answer below for other people with the same problem.
|
You need to call `test` and not just `group`:
void main() {
group('int extensions:', () {
test('digits', () {
expect(1.digits(), 1);
expect(10.digits(), 2);
expect(100.digits(), 3);
});
});
}
|
stackexchange-stackoverflow
|
{
"answer_score": 13,
"question_score": 6,
"tags": "dart, testing"
}
|
How to get atomically incremented value in Firebase RTDB?
I am using increment() to atomically generate a sequence number for orders:
firebase.database.ServerValue.increment(1)
Now, I would like to show that sequence number as orderID to the users. With transaction, I will have that sequence number on the client already:
var seq;
ref.transaction(function(value) {
seq = (value || 0) + 1;
return seq;
});
With increment(), how do I do that? Should I make another round trip to the server using once() or listen to changes using on()?
|
In order to get the incremented value, you can indeed use either `once()` or `on()` to receive the updated the result. You do, in fact, have to read it back from the server to know for certain the new value.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "javascript, firebase realtime database"
}
|
Programmatically refresh/synchronize an IntelliJ IDEA project via a plugin
Is there a way to programmatically refresh/synchronize an IntelliJ IDEA project via a plugin?
I'm working on an IntelliJ IDEA plugin that creates a file within the active project. And I want to refresh/synchronize the project automatically via the plugin so that the user can see the changes immediately. Is this possible in IntelliJ IDEA?
|
After digging a bit more I came through the following solution and it worked.
public void actionPerformed(AnActionEvent e) {
// Create/Modify files
// Get the project from the ActionEvent
Project project = e.getData(PlatformDataKeys.PROJECT);
// Get the Base Dir and refresh with the following parameters
// 'asynchronous' set to false and 'recursive' set to true
project.getBaseDir().refresh(false,true);
}
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 3,
"tags": "java, intellij idea, intellij plugin, intellij 14"
}
|
How to prove $\frac{2^a+3}{2^a-9}$ is not a natural number
How can I prove that
$$\frac{2^a+3}{2^a-9}$$
for $a \in \mathbb N$ is never a natural number?
|
**Hint:** $$\frac{2^a+3}{2^a-9}=1+\frac{12}{2^a-9}$$
So $\frac{12}{2^a-9}$ must be a natural number as well.
|
stackexchange-math
|
{
"answer_score": 11,
"question_score": 2,
"tags": "elementary number theory, diophantine equations"
}
|
In Yii2, how can I exclude layout from rendering in a view file?
I have an admin login page that I want to render without the layout. How can I render a view in Yii2 without rendering the main layout?
|
This can be done using `renderPartial()` method.
You can get more from the official documentation. Here's a link-detail)!
|
stackexchange-stackoverflow
|
{
"answer_score": 32,
"question_score": 18,
"tags": "php, yii2"
}
|
SPI and word size - what happens with (say) 8 bit and 24 bit data from the same chip?
I have a chip to be read/written via SPI. Some of its registers are 8 bits, others 24 and 32. How does the SPI master (the MCU) handle these different data sizes?
|
It doesn't. It just works in whatever data size you tell it to.
Typically that is 8 bits, though some can work in 16 or 32 bits for increased efficiency.
To transfer 8 bits you lower SS, transfer 8 bits, then raise SS.
To transfer 24 bits you lower SS, transfer 8 bits, transfer another 8 bits, then yet another 8 bits, then finally raise SS.
!enter image description here
The entire transaction of 24 bits is just a series of 8 bit transfers framed by the SS pin being low.
What you then do with those three transferred values is entirely up to you.
|
stackexchange-electronics
|
{
"answer_score": 6,
"question_score": 3,
"tags": "spi"
}
|
Pandas: Selecting rows by condition on column and index
Assume we have the following dataframe:
d = {'col1': ['a1', 'b1', 'c1', 'a1'], 'col2': ['a2', 'b2', 'b2', 'c2'], 'year':[2011, 2011, 2012, 2012], 'rank':[1, 2, 1, 2]}
df = pd.DataFrame(data=d).set_index(['year', 'rank']).sort_index()
col1 col2
year rank
2011 1 a1 a2
2 b1 b2
2012 1 c1 b2
2 a1 c2
How can I select all columns where `col1 != 'a1'` or `year != 2011`?
If `year` wouldn't be an index, I could do this by
df[(df.col1 != 'a1') | (df.year != 2011)]
However, as year is an index, `df.year` would throw an AttributeError.
How can I formulate the condition for the index? Thanks in advance!
|
You can access the index by the method `df.index.get_level_values`, e.g. you can gain the searched result by
In [29]: df[(df.col1 != 'a1') | (df.index.get_level_values('year') != 2011)]
Out[29]:
col1 col2
year rank
2011 2 b1 b2
2012 1 c1 b2
2 a1 c2
**Some Sidenote:**
The comparison `df.index.get_level_values('year') != 2011` will be an numpy array, therefore we need to get the values from the `pd.Series` for comparing with `df.col1 != 'a1'` (in some older pandas versions you may have used to acess the values with `.values` or similar, because comparing of an series with index with some array was not possible. Howewer, at least with 0.24 and above this is not necessary anymore).
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "python, pandas, dataframe, select"
}
|
Battery Level Indicator
I am using 3 AA batteries of 1.5V each, to obtain a voltage of 4.5V which i am then reducing to 3.3V using a LDO. My current requirement is around 100mA.
I want a simple, **low** power dissipation circuit which would be connected to the arduino to monitor this battery level
Previously for one of my projects I have used a simple zener diode to monitor the battery level. However I didn't take into account the heat dissipation, reliability etc.
So, can I know what are the different types of options available? My main constraints are:- 1)Circuit should be simple 2)Low power dissipation
I am attaching the pics of my entire circuit and the zener circuit which i used before.[![Entire Circuit\[!\[\]\[1\]](
To provide a bit of background of the zener circuit, I first calibrate it for my application, then I am able to view the percentage of battery at the display.
|
setting the GPIO high turns on Q1 and Q2 presenting half the battery voltage to the analog input.
setting the GPIO it low turns off Q1 and Q2 avoiding unneeded drain on the battery.
!schematic
simulate this circuit - Schematic created using CircuitLab
|
stackexchange-electronics
|
{
"answer_score": 0,
"question_score": 1,
"tags": "arduino, power supply, voltage, batteries"
}
|
how to add classname to all elements starting with specific id?
Before you lash out on me, I know this question might be a possible duplicate. I tried every other post I found on stackoverflow and failed.
I want to add a class name to all elements in my html which start with 'subclass', followed by a single digit number(classid), followed by a random number. I dont exactly know how many elements are there as it is being generated dynamically with servlets.
Following is the code I tried to run:
<style>
.bold {
font-weight: bold;
}
</style>
<script>
function highlight(classid){
alert(classid);
$("p[id^='subclass'+classid]").addClass('bold');
alert('hello world');
}
</script>
<p id='subclass25'>Hello World </p>
I get the alert for classid but not the alert for 'hello world'. So I know for sure my JQuery is wrong....
|
You have missed the quotes which is the reason jquery selector is not getting created properly, see below
highlight('25');
function highlight(classid){
alert(classid);
$("p[id^='subclass" + classid + "']").addClass('bold');
alert('hello world');
}
.bold {
font-weight: bold;
}
<script src="
<p id='subclass25'>Hello World </p>
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "javascript, jquery, jquery selectors"
}
|
where are site features in sharepoint?
i want to add ASP.NET pages in sharepoint having the same theme, so i watched this video < however, i found that in the video, they added something through site features "sample feature custom application page" which i cant find on mine. on my site features there is only "team collaboration link" and nothing else. any idea y that? or to reach my main goal which is adding the asp.net page with the sharepoint theme?
|
You can wrap your custom page in a solution containing a feature. By doing that you can easily deploy your page to all front end web servers in the farm.
You can read more about SharePoint solutions here: < and <
But if your new to SharePoint i would recommend you to read Ted Pattisons book "Inside Windows SharePoint Services 3.0". It contains all you need to know to start building your own solutions.
Its also possible to add a feature without wraping it in a solution, you can do that by creating a folder in %commonprogramfiles%\Microsoft Shared\Web Server Extensions\12\TEMPLATE\Features\ containing your feature.xml and your custom page.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "asp.net, sharepoint"
}
|
Как исключить предупреждения, связанные со смешением http и https на сайте wordpress?
Есть сайт на WordPress, на котором имею предупреждения такого плана
> Mixed Content: The page at ' was loaded over HTTPS, but requested an insecure image ' This content should also be served over HTTPS.
Интересно, что показывает на места в хедере и футере, так где адрес задается переменной по такому принципу:
<link rel="shortcut icon" href="<?php echo $cs_theme_option['fav_icon']" ?>" />
Как можно от них избавиться?
|
Плагином < поменять в контенте протокол ссылок.
Если ссылки в файлах, то и в файлах изменить.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "php, wordpress, http, https"
}
|
Blender for Virtual Reality
How would you create a game with Blender that can be used by the HTC Vive? Is it even Possible? What are all of the steps for this to be possible?
|
Yes, here you go: Blender Room Scale VR Viewport on the HTC Vive
Source can be found here:
< <
For a real project you should consider using Unity3D and creating assets with Blender.
See also:
Blender VR \- <
|
stackexchange-blender
|
{
"answer_score": 5,
"question_score": 5,
"tags": "game engine"
}
|
Resources for IMO
I am seeking an online resource or any book where I can find the questions of International Mathematical Olympiad questions chapter wise eg Number Theory problems grouped together.
Like this site where we can get all the programming problems of SPOJ classified under different sections.
I have googled but didn't come across any such site. So I will greatly appreciate if anybody provides me some reference.
|
Art of Problem Solving
Also check their forum, they have lots of extra materials: Forum
|
stackexchange-math
|
{
"answer_score": 4,
"question_score": 2,
"tags": "reference request, soft question, big list, contest math, online resources"
}
|
Where condition in oracle request
I have a a date field who can be `null` in an Oracle Database.
I want to select the row with the highest date. But if there is only one row with a `null` date and I use the max clause it will be ignored.
SELECT val1, val2
from T_DER
WHERE DATE_AP = ( SELECT MAX (DATE_AP) FROM T_DER WHERE AE= 'XXX')
AND (AE= 'XXX');
so , in these cases :
* for AE = XXX => row 1 : DATE_AP = 01/01/2015 and row 2 : DATE_AP = 01/02/2016
* return row 2
* for AE = XXX => row 1 : DATE_AP = 01/01/2015 and row 2 : DATE_AP = null
* return row 1
* for AE = XXX => row 1 : DATE_AP = null
* return row 1
|
Use analytic functions:
SELECT t.*
FROM (SELECT t.*,
ROW_NUMBER() OVER (PARTITION BY AE ORDER BY DATE_AP DESC NULLS LAST) as seqnum
FROM T_DER t
WHERE AE = 'XXX'
) t
WHERE seqnum = 1;
`ROW_NUMBER()` is a window/analytic/ranking function, documented here. Basically, it assigns a sequential number to groups of rows, where the groups are defined by the `partition by` clause and the ordering within each group by `order by`.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "sql, database, oracle, select, null"
}
|
2014 Tax Fee For One Month Without Healthcare
Confirming that I understand this link correctly about paying taxes on every month I was uninsured, and that nothing has been changed in the last week.
I went one month without healthcare when changing jobs (they didn't cover until I had been employed for a full 30 days). My income at $300K means I pay $3000 a year for no coverage multiplied by 1/12, meaning that I owe $250 based on the below:
> If you’re uninsured for just part of the year, 1/12 of the yearly penalty applies to each month you’re uninsured.
Is am I correct, and to avoid this fee, do I have to temporarily sign up for coverage just for a month while waiting, or is there a way to negotiate this with an employer?
|
Generally you should have insurance all the time - you never know what may happen. When you leave your job, you have the option of continuing the plan you had with your employer under COBRA (you pay your own premiums) until the new employer's plan kicks in.
However, in case of a short gap of up to 2 months, there's an exemption from the penalty. Read here and see if it applies to you.
|
stackexchange-money
|
{
"answer_score": 2,
"question_score": 0,
"tags": "united states, taxes, healthcare"
}
|
Integral by method of residues
I want to integrate $\displaystyle \int_\gamma \frac{z}{(z-1)(z-2)}dz$ along the curve $\gamma(t)=2+\frac{1}{2}e^{it}$, with $t\in [0,2\pi]$
Can this be done by mean of residues? The curve is not closed, so I think it might be a problem. The fact that exercise was in a chapter calleed "Cauchy integral formula and residues" suggest that this theorems should be used to solve the integral
|
The curve _is_ closed. What made you think it is not?
You can compute is using Cauchy's integral formula:\begin{align}\int_\gamma\frac z{(z-1)(z-2)}\,\mathrm dz&=\int_\gamma\frac{\frac z{z-1}}{z-2}\,\mathrm dz\\\&=2\pi i\frac2{2-1}\\\&=4\pi i.\end{align}
|
stackexchange-math
|
{
"answer_score": 5,
"question_score": 2,
"tags": "complex analysis, residue calculus, complex integration, cauchy integral formula"
}
|
getCriteria not working as expected with boolean field types
I have a custom content table for an elementType. I have a few fields set up in my `Record` as boolean. The two fields are `approved` and `denied` I have to search the database where both fields are set to zero/false.
I can only get the values to show up in `$query->params` inside my `modifyElementsQuery()` method when I set `$criteria->approved/denied` to (string)"1". Setting these to true, false, or (string)"0" cause them to not show up in the `$query->params` list.
How do I work with a boolean field in this manner? I need `Where denied = '0'` to show up in the query when i set `$criteria->denied = false`
|
I believe this should work (not tested):
$criteria->setAttribute('denied', 'not 1');
As when using the `ElementCriteriaModel` in Twig, you can't directly check for "falsey" values.
|
stackexchange-craftcms
|
{
"answer_score": 1,
"question_score": 1,
"tags": "plugin development, database, elementcriteriamodel, elementtype"
}
|
Pack recommendations for running?
So I've been running to work as my form of commuting and I've been getting by with my Gregory Z45 internal-frame pack for carrying whatever I need for the day. What bothers me about this pack is that it seems to flop around quite a bit when running, which gets to be annoying over the course of the 6 miles to my office.
Ideally, I think I'm looking for something really simple and lightweight that would sit nicely between my shoulderblades while still being secured by some sort of a hip strap. I'd also love to be able to take such a pack out for some lightweight backpacking, so a frame isn't strictly necessary since I'd use a sleeping pad for some structure in this case.
Any recommendations?
|
I have had very good success with the Osprey Talon Series of packs. I personally own the 22 and the 44. Both are good packs that meet the requirements that you have outlined in your second paragraph.
|
stackexchange-outdoors
|
{
"answer_score": 4,
"question_score": 10,
"tags": "backpacks"
}
|
Why is $\frac{1}{x^{-1}}=x$?
I believe I get why $x^{-1}=\frac{1}{x}$ . Because if we would like our exponent rule ($\frac{x^n}{x^m}= x^{m-n}$) to be true for all values of $m$ and $n$ then $x^{-1}$ should be another way to write $\frac{1}{x}$ as [$\frac{x^1}{x^2}=x^{1-2}=x^{-1}=\frac{1}{x}$] even if multiplying a certain number by itself negative number of times makes no sense.
So I can see why $x^{-1}$ is just another way to write $\frac{1}{x}$ but I can't get how we've arrived that $\frac{1}{x^{-1}}$ is equal to $x$; I can't think of any way that will give us a negative power in the doninator in order to proof that $\frac{1}{x^{-1}}$=$x$, we can't subtract from the dominator's power even when we divide. We always end up subtracting from the numerator's power instead, example:
> $\frac{1}{x}÷\frac{1}{x^3}=\frac{1}{x}×x^3= \frac{x^3}{x}=x^{3-1}=x^2$
|
For a nonzero real number $x$, the reciprocal $\frac1x$ is the real number such that when multiplying with $x$, you get $1$. In other words, when $x\ne 0$, $\frac1x$ is the multiplicative inverse of $x$.
For $x\ne 0$, the negative exponential $x^{-1}$ is by definition $\frac1x$, and thus $$ x\cdot x^{-1}=x^{-1}\cdot x=1 $$ Therefore, $$ \frac{1}{x^{-1}}=x. $$
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 1,
"tags": "arithmetic, exponentiation"
}
|
Sum of fractions with square roots inequality
What is the greatest integer $n$ such that
$n \leq 1 + \frac{1}{\sqrt{2}} + \frac{1}{\sqrt{3}} + \ldots + \frac{1}{\sqrt{2014}}$?
|
For positive integer $k$, we have $$2\sqrt{k} < \sqrt{k+1} + \sqrt{k} < 2\sqrt{k+1}$$ Taking reciprocals and rationalising the middle term, we get $$\frac1{2\sqrt{k+1}}< \sqrt{k+1}-\sqrt k < \frac1{2\sqrt k}$$
The middle term telescopes and hence sums easily. Thus we can have tight bounds on both sides:
$$\sum_{k=1}^{2014}\frac1{\sqrt{k}} = 1+\sum_{k=1}^{2013}\frac1{\sqrt{k+1}} < 1+2\sum_{k=1}^{2013} (\sqrt{k+1}-\sqrt{k})= 2\sqrt{2014}-1 \approx 88.75$$ and
$$\sum_{k=1}^{2014} \frac1{\sqrt k} > 1+\frac1{\sqrt2}+2\sum_{k=3}^{2014}(\sqrt{k+1}-\sqrt{k}) = 2\sqrt{2015} - 2\sqrt3+1+\frac1{\sqrt2} \approx 88.02 $$
so you have your integer.
|
stackexchange-math
|
{
"answer_score": 5,
"question_score": 3,
"tags": "inequality, contest math"
}
|
Select DOM element by text from React component
I'm testing a react component and need to simulate a click on a specific element inside the component. I don't want to add `id` just for the sake of the test, is there a way to select this element by text?
const ReactTestUtils = require('react-test-utils');
const Sidebar = require('components/sidebar');
describe('clicking on More button', function() {
it('triggers analytics event', function() {
const component = renderComponent(<Sidebar policyPreferences={ this.policyPreferences } />);
const moreButton = component.getDOMElementByText('More'); // <- I need something like this
ReactTestUtils.Simulate.click(moreButton);
expect(analytics.track).toHaveBeenCalled();
}
}
|
The following function iterates through all elements until it finds one with the matching text:
function getElementByText(text){
var all = document.getElementsByTagName("*");
for (var i=0, max=all.length; i < max; i++) {
if (all[i].innerHTML == text){
return all[i];
}
}
return null;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "javascript, jquery, testing, reactjs, jasmine"
}
|
Core dumped while using vector<string>
So on Ubuntu I always get core dumped when trying to execute this function:
vector<string> inArray(vector<string> &array1, vector<string> &array2){
vector<string> result;
for(int i=0;i<array1.size();i++){
for(int j=0;j<array2.size();j++){
if(array1[i] == array2[j])result.push_back(array1[i]);
}
}
return result;
}
Can someone tell me what is wrong?
EDIT:
int main()
{
vector<string> arr1{"arp", "live", "strong"};
vector<string> arr2{"lively", "alive", "harp", "sharp", "armstrong"};
vector<string> result = inArray(arr1, arr2);
cout<<result[0];
cout<<result[1];
cout<<result[2];
return 0;
}
I was doing Kata on codewars.
|
Instead of printing result[0],result[1],result[2],first check the size of vector result and if it is '0' then return 0 or whatever is given and otherwise return result vector.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -4,
"tags": "c++, vector"
}
|
JavaScript Regex restrict _
This is my regex
`^(?![^a-z])(?!.*\.\.)[a-z0-9._]+([a-z])$`
**Rules**
* String should start and end with [a-z]
* double . in a row is not allowed
* double _ in a row is allowed ( should be not this is wrong)
* Allowed characters are [a-z0-9_.]
everything works as like what i want, but i cannot restrict 2 o more _ in a row it has same restrict for . but does not work for _
This is online editor: <
what is wrong ?
|
You can use this regex:
/^(?![^a-z])(?!.*([_.])\1)[\w.]*[a-z]$/gmi
RegEx Demo
**RegEx Breakup:**
* `^`: Start
* `(?![^a-z])`: Make sure first char is a letter
* `(?!.*([_.])\1)`: Make sure we don't have repeated underscore or dot
* `[\w.]*`: Match 0+ word characters or dot
* `[a-z]`: Match a letter in the end
* `$`: End
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "javascript, regex"
}
|
Batch finding and operation Display partially duplicate files
I have a question. Is it possibile in batch language to search and display files which first five letter in filename are the same.. This folder contains thousands of files. For example
22222rewrs344234w.mp3
22222asdqweavasd.mp3
234seqwe.mp3
32434.mp3
qwedasdasdasd.mp3
qwedasasdasd.mp3
11122asdas.mp3
11122asdasd.mp3
...
...
...
I need to display in cmd only names of files
22222rewrs344234w.mp3
22222asdqweavasd.mp3
11122asdas.mp3
11122asdasd.mp3
qwedasdasdasd.mp3
qwedasasdasd.mp3
Because the first five letter are the same.If the folder does not contain a 5 character duplicates it prints a message folder Could someone help me with this problem?
|
@echo off
setlocal EnableDelayedExpansion
rem Group files with same 5 chars prefix in name
for %%a in (*.*) do (
set "file=%%a"
for /F %%f in ("!file:~0,5!") do set "group[%%f]=!group[%%f]! %%a"
)
rem Show groups that have more than one name
for /F "tokens=2*" %%a in ('set group[') do (
if "%%b" neq "" echo Same prefix: %%a %%b
)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -2,
"tags": "batch file, cmd"
}
|
How to change Pagination.Item color inside the style property in 'react-bootstrap'?
style={{backgroundColor:'black'}}, color={...} and css styles don't work, color remains the same. All solutions are about css.
|
**You could do it by selecting the 'page-link' class inside each item**
Similar to this:
.page-item .page-link {
background: red;
}
Check this out:
.
Recently, Docker has been working on docker-app which allows you to share docker-compose.yml files using a registry server. This is a separate install, and currently experimental, so I wouldn't base a production environment on it, but may be useful for developers to try out. You can checkout the project here:
<
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "docker, docker compose, nexus"
}
|
Group by, pivot, count and sum in DF in R
I have a date frame with the fields PARTIDA (date), Operação (4 levels factor) and TT (numeric) .

df <-
tibble(
partida = c("date1", "date2", "date3", "date1", "date2"),
operacao = c("D", "J", "C", "D", "M"),
tt = c(1, 2, 3, 4, 5)
)
tt_sums <-
df %>%
group_by(partida) %>%
count(wt = tt)
operacao_counts <-
df %>%
group_by(partida, operacao) %>%
count() %>%
ungroup() %>%
spread(operacao, n) %>%
mutate_if(is.numeric, replace_na, 0)
final_df <-
operacao_counts %>%
left_join(tt_sums, by = "partida")
> final_df
# A tibble: 3 x 6
partida C D J M n
<chr> <dbl> <dbl> <dbl> <dbl> <dbl>
1 date1 0 2 0 0 5
2 date2 0 0 1 1 7
3 date3 1 0 0 0 3
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "r, dplyr"
}
|
Simple CSS Scale-Nine Layout
After all these years, I still haven't learned CSS layout, so bear with me. I'm trying to create a container with rounded corners that I generated in Photoshop. The background of the container is white, so I have eight images: top-left-corner, top, top-right-corner, right, bottom-right-corner, bottom, bottom-left-corner, and left.
The edges have a drop shadow around them so yes, I do need 8 sides. How would I lay this out in CSS? I tried and failed miserably to do it with a table + CSS. How would I do it using divs?
**EDIT:** Simply speaking, how would I lay something out like the pseudo code below
[IMG][IMG WIDTH="100%"][IMG]
If I write this in HTML, my images are split over three lines. How do I get it all to fit on one line?
|
Check out: Curvy Corners, it's a jQuery plugin that will look at your CSS and find any CSS3 properties for webkit: `-webkit-border-radius: 10px;` and make any corners with that CSS property round, in every browser.
I use it for IE and it works great! All you have to do is add the .js file to your directory and link it at the bottom of your HTML and it does all the work for you :)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "css, html"
}
|
how to programatically check for reader macros
I have a vector which can contain arbitrary data. I want to check of any of the element is a reader macro, how do I do that ?
`(is-reader-macro? #<DateTime 2012>) ;=> true`
Thanks, Murtaza
|
Once a string is `read` you cannot tell by the resulting data what the exact reader construct was that created it. The data item you just read is not a reader macro, it's just data.
In your specific example, what you've got is the printed representation of a jodatime DateTime object, which cannot be read - the `#< ... >` construct is meant to prevent that. The actual object that prints like that is just a jodatime DateTime object, not a reader macro.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "clojure"
}
|
Oracle SQL: Order By numerical and alphabetical order
I have a table called "countries" and a column named "val" that is VARCHAR2(2 CHAR). I have some problems with the order of the values from this column. I will not write all values(359) from "val" just a few for example:
'AD','EC','XX','1C','1D','MR','4R','1E','TO','SK'
And I want to order the values in numerical order and than in alphabetical order:
'1C','1D','1E','4R','AD','EC','MR','SK','TO','XX'.
I wrote something like this:
`SELECT val FROM countries ORDER BY CASE WHEN val LIKE '[1-9]%' THEN 0 ELSE 1 END ASC;` and everything works fine except that the first two values '1C' and '1D' are shown at the end of the table and not at the beginning. It's very strange. I have Oracle 12c. I need help !!
|
Don't use `LIKE`. If you only care about the first value, you can just use string comparisons:
ORDER BY (CASE WHEN SUBSTR(val, 1, 1) BETWEEN '0' AND '9'
THEN 0 ELSE 1
END) ASC,
val
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sql, oracle"
}
|
$\int_0^{\frac{\pi}{2}}(\sqrt{\tan x}+\sqrt{\cot x})\mathrm dx $
$$\int_0^{\frac{\pi}{2}}(\sqrt{\tan x}+\sqrt{\cot x})\mathrm dx $$ my attempt :multiply and divide the $\sqrt{\tan(x)}$ term by $\sec^2(x)$ and similarly the $\sqrt{\cot(x)}$ by $\csc^2(x)$ and say $\tan x=u^2$ and $\cot x=y^2$ so we get $$\int_0^\frac{{\pi}}{2} (\frac{2u^2}{1+u^4}\mathrm du- \frac{2y^2}{1+y^4}\mathrm dy)$$
which is $0$.
and that is obviously wrong I have seen this answer here that effectively uses the same sub I did , but in a different way. Hence the question.
> What am I doing wrong?
|
$$\int_0^{\frac{\pi}{2}}(\sqrt{\tan x}+\sqrt{\cot x})\mathrm dx=\int_0^{+\infty}\frac{2u^2}{1+u^4}\mathrm du+\int_{+\infty}^0\frac{-2y^2}{1+y^4}\mathrm dy.$$
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 1,
"tags": "calculus, integration, definite integrals"
}
|
PHP and Bcrypt
> **Possible Duplicate:**
> How do you use bcrypt for hashing passwords in PHP?
I am developing an API using PHP. My previous version of the API which I want to migrate from was build using Rails 3.
I have only one problem. The stored passwords for the users was encrypted with the below technique.
BCrypt::Engine.hash_secret(password, user.password_salt);
How can I do the same in PHP (Codeigniter) so that the users can continue using their old passwords?
Thankful for all help!
|
I think you can use the crypt function with the blowfish algorithm: <
Another option is to use mcrypt: <
Edit: example
Here's what I would do:
$hashedPassword = crypt('password', '$2a$11$abcd');
Use crypt like this:
hash = crypt(password, salt);
$hashedPassword should now contain the hash.
Basically in order to use the blow fish alogrithm, the salt needs to be in this format: $2a$[2 digit cost parameter]$[22 digit alphanumeric string]
To determine if you have blowfish on yours server:
if (CRYPT_BLOWFISH == 1) {
echo 'Blowfish: ' . crypt('rasmuslerdorf', '$2a$07$usesomesillystringforsalt$') . "\n";
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "ruby on rails, codeigniter, bcrypt"
}
|
Instantiate enum class
Consider I am having the following enum class,
public enum Sample {
READ,
WRITE
}
and in the following class I am trying to test the enum class,
public class SampleTest {
public static void main(String[] args) {
testEnumSample(Sample.READ);
}
public static void testEnumSample(Sample sample) {
System.out.println(sample);
}
}
Here I am specifying `Sample.READ` then passing it as the parameter to the method `testEnumSample`. Instead if we want to instantiate the enum class and pass it as parameter what we need to do?
|
> Here I need to specifying Sample.READ to pass it as parameter. Instead if we want to instantiate the enum class and pass it as parameter what we need to do?
What would "instantiate the enum class" even mean? The point of an enum is that there are a _fixed_ set of values - you can't create more later. If you want to do so, you shouldn't be using an enum.
There are other ways of getting enum values though. For example, you could get the first-declared value:
testEnumSample(Sample.values()[0]);
or perhaps pass in the name and use `Sample.valueOf`:
testEnumSample("READ");
...
Sample sample = Sample.valueOf(sampleName);
If you explained what you were trying to achieve, it would make it easier to help you.
|
stackexchange-stackoverflow
|
{
"answer_score": 39,
"question_score": 19,
"tags": "java, enums"
}
|
while文のブロックが一度も実行されない
print('')
n = 10
while n < 0: # n0
print(n)
n = n - 1
print('')
================================
================================
10
9
8
7
6
5
4
3
2
1
|
>
> ================================
>
>
> ================================
>
> 10
> 9
> 8
> 7
> 6
> 5
> 4
> 3
> 2
> 1
>
while n < 0: # n0
while n > 0: # n0
|
stackexchange-ja_stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "python"
}
|
CSS: Image width to resize and fit the browser width dynamically
I have made a code to resize and set the width of an image to that of the browser dynamically, so I have set the following code in css
max-width: 100%;
height: auto;
My challenge is that the image never resizes dynamically to occupy the entire screen width of the browser dynamically. Here is a Plnker I have made < What could be wrong.
|
Change `max-width` to `width`.
As should be obvious from the naming, `max-width` only acts as an upper limit. It does not make anything bigger, it merely downsizes things if they already are bigger than what you specify there.
Sample: <
HTML:
<img src=" alt="">
CSS:
img {
width: 100%;
height: auto;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "html, css"
}
|
equivalence relation and lexicographic order
This is a HW question
Let $A = \mathbb{Z}^+ \times \ \mathbb{Z}^ +$. Define $R$ on $A$ by $(x_1,x_2)R(y_1,y_2)$ iff $x_1+x_2=y_1+y_2$. Is $R$ an equivalence relation on A.
I dont think It is as simple as to show that the reflexive, symmetry and transitivity hold on $x_1+x_2=y_1+y_2$ for all $\mathbb{Z}^+$ but rather something do with lexicographic order (but i could be wrong).
I am mostly looking for a hint on how to proceed.
|
_Hint:_ (After you correct a probable typo in your definition,) the relation is of type $aRb\iff f(a)=f(b)$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "discrete mathematics"
}
|
Javascript Auto-Refresh Class Elements
Problem:
Values constantly change on db. Need to auto-reload certain elements values without reloading all page. Very similar to collective bidding pages as attached image.
!enter image description here
A simple page Dashboard type with three columns of grid organized data.
How can I effectively reload (AJAX CALL) certain class types, content?
Since these column values change as time goes from db, they have to auto refresh on time interval.
Code Sample:
<div class="autovalue">26</div>
<div class="autovalue">20</div>
<div class="autovalue">96</div>
Maybe Jquery has a method.
|
Set an interval function, i did this example using jQuery.
var intervalID = setInterval(function(){
$('.refreshClass').each(function(){
$(this).load(this.href);
})
}, 900);
In my example `<a href="url-to-get.php" class="refresh"></a>` will request the href attribute every 900ms and update the innerHtml.
For a better performance you can cache your selectors and use id instead of classes. :)
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "javascript, ajax, dom, jquery"
}
|
Add iPhone-detection to jQuery script
I've written a script in jQuery, which adds padding to an element when my website loads as a web app:
<script type='text/javascript'>
jQuery("div").ready(function(){
if (("standalone" in window.navigator) && window.navigator.standalone) {
jQuery(".menu-secondary").css("paddingTop", "20px");
};
});
</script>
I'd like to extend the script to only apply when the website is loaded as a web app on an iPhone or iPod.
I've tried the following with no luck:
<script type='text/javascript'>
jQuery("div").ready(function(){
if (("standalone" in window.navigator) && window.navigator.standalone) ||
((navigator.userAgent.match(/iphone|ipod/i))) {
jQuery(".menu-secondary").css("paddingTop", "20px");
};
});
</script>
Any help would be really appreciated!
|
window.navigator.userAgent.match("iPhone")
this returns an array you should check for null or length
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, jquery, ios, css"
}
|
memory limit opencpu / R
I've got a strange problem with opencpu. I'am setting up a webinterface to use xcms (R-package) and when reading an mzxml file with the webinterface I get the error : cannot allocate vector of size 207.2 Mb. This looks like an error from R, but if I open R on the server and try to open the file myself it works and R creates and object of 435Mb. Is there somewhere a memory limit set (apache, opencpu, R)? If I use ulimit -a the max memory size is set to unlimited.
Cheers, Rico
|
Yes, the OpenCPU cloud server sets a memory limit `RLIMIT_AS` on every request using the RAppArmor package. This is to prevent a single user from consuming all resources on a server. The default limit is 1GB per process. You can configure these limits by editing:
/etc/opencpu/server.conf
After editing the file, restart the server:
sudo service opencpu restart
For more information on rlimits, read the JSS paper on RAppArmor.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "r, apache, opencpu"
}
|
NSString isEqualToString: for \n
I have an Cocoa app that calls a web service. When I parse the response from the web service I am getting a \n as the last character in my foundCharacters delegate for the NSXMLParser for each element in the XML.
When I try to do the following:
if (![string isEqualToString:@"\n"])
The check will always fails to catch the newline. Anyone know a good way to string check a newline?
I also find it odd that each element would have a newline at the end of each value, even though I see no evidence of that in the output from the web service.
This is quite the problem for something that should be exceptionally easy to do.
|
I think this is just what you need?
text = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
|
stackexchange-stackoverflow
|
{
"answer_score": 20,
"question_score": 9,
"tags": "objective c, cocoa, nsstring, string comparison"
}
|
The usage of “toodle pip”
According to the Urban Dictionary:
> _to toodle pip a dear friend_ means _to say goodbye in a very friendly way._
How common is this expression? Can I use it without any fear to be misunderstood?
|
The expression was common among upper-class English people around 100 years ago but is now very much obsolete. If you use it now you run a severe risk of not being understood or of being considered foolish. The Urban Dictionary is a VERY BAD source of information for English learners.
|
stackexchange-ell
|
{
"answer_score": 5,
"question_score": 0,
"tags": "word usage, slang"
}
|
What do I need to do to get paid to Scheme?
I'm a big fan of functional programming in general, Schemes in particular, and PLT-Racket ideally. I am wondering what concrete steps are likely to get me into a position where coding Scheme (or some functional language) is the bulk of the work.
I'm actually quite interested in academia, but on the other hand, I don't feel like I necessarily have what it takes (at least not at the moment) to do a top-tier Ph.D in CS. I definitely would prefer to have some real-world experience putting complex systems together in Scheme either way. Does anyone have any advice for an aspiring Schemer?
|
Start writing some Scheme libraries, then blog about the libraries you've wrote, get noticed in the community.
This will always give you leverage when applying for a position, employers like to have some evidence of what you can do.
|
stackexchange-stackoverflow
|
{
"answer_score": 16,
"question_score": 13,
"tags": "functional programming, scheme, racket"
}
|
Jquery Ajax responce not working in safari..but other browser it is work fine..what is mistake here?
$.ajax({
url:'ajax.php?action=wordFind&word='+arrString,
cache: true,
type: "GET",
success:function(res){
if(res=="find") { }
}
});
|
$.ajax({
url:'ajax.php?action=wordFind&word='+arrString,
cache: true,
async:false,
dataType:html,//If the response is json replace it with "json"
type: "GET",
success:function(res){
console.log(res);//To check you are getting any reponse
if(res=="find")
{
//Do the stuff you want.
}
}
});
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -4,
"tags": "jquery, ajax"
}
|
UITableView not shown inside UIStackView
I have a `UIStackView` where it can show a label, image, table view or nothing based on user selection. Here is my current hierarchy for the dynamic view:
* UIStackView_Parent
* UILabel - some text, fixed view
* UIStackView_Child - this is the container that can show multiple things or nothing
* UIView - another fixed view
When I call `UIStackView_Child.addArrangedSubview(...)` with a label or image it works perfectly, but `addArrangedSubview(tableView)` does not show the table. I have `tableView.scrollEnabled = false` and set frame to fixed height based on number of cell and defined the table's `cellHeight`.
Any help would be much appreciated, thanks!
|
That's because stackview tries to compress content as much as possible. When you initally add a tableview, I'm assuming it has no content, so stackview compresses the width to 0 because it has nothing to show. You have to do one of two things:
After the table gets populated with data, you have to set the tableView's frame. I do this by calculating how big each cell is going to be. I know the width is going to be as big as the view that contains stackview. So it winds up being something like
let estimatedHeight = tableView.numberOfRows(inSection: 0) //You may need to modify as necessary
let width = parentView.frame.size.width
tableView.frame = CGRect(x: 0, y: 0, width: width, height: estimatedHeight)
Once you set the tableView's frame, stackview should automatically adjust.
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 6,
"tags": "ios, swift, uistackview"
}
|
Why does ObjectOutputStream write 14 bytes instead of 8 with DataOutputStream?
The same method (writeInt()) in ObjectOutputStream and DataOutputStream writes different data? Isn't it supposed to be equal for primitive types?
// Output: 14 bytes file
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("file_14bytes.bin"));
out.writeInt(1);
out.writeInt(2);
out.close();
// Output: 8 bytes file
DataOutputStream dout= new DataOutputStream(new FileOutputStream("file_8bytes.bin"));
dout.writeInt(3);
dout.writeInt(4);
dout.close();
For example, I wanted to send objects info on first connection using objectoutputstream's writeObject() method, and then send x, y floats in loop with OOS's writeInt().
|
ObjectOutputStream is designed to write objects and writes some meta data when writing any information including primitives.
Also OOS is buffered so you might not see all the bytes written immediately in the underlying stream.
Note: a writeInt uses 4 bytes with DataOutputStream.
> send x, y floats in loop with OOS's writeInt()
I suggest you use writeFloat(f) to write floats.
If you have an array of floats I suggest you use writeObject() e.g.
oos.writeObject(someShape);
oos.writeObject(floatArray);
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "java, networking, objectoutputstream, dataoutputstream"
}
|
Remove Filepath in GridFS
I am using the official c# driver for MongoDB and when I upload a file, the metadata contains the filename WITH the path, which is not what I would like:
var gfs = new MongoGridFS(database);
var gfsi = gfs.Upload("c:\a.pdf");
The resulting metadata is:
"_id" ...
"filename" : "c:\\a.pdf",
...
Is it possible to remove the path oder just write the filename?
|
The MongoGridFS class exposes multiple overloads for the Upload and Download methods, including one in which you can specify differing remote/local paths.
e.g.
var gfs = new MongoGridFS
gfs.Upload(@"c:\a.pdf", "a.pdf");
gfs.Download(@"c:\b.pdf", "a.pdf");
The filename for the GridFS object always refers to the remote filename you set here and the original filename would be otherwise lost.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "c#, mongodb, gridfs"
}
|
Neural Network example in .NET
Any good tutorial with source that will demonstrate how to develop neural network (step bay step for dummies ;-))
|
Here is good example: Brainnet 1 - A Neural Netwok Project - With Illustration And Code - Learn Neural Network Programming Step By Step And Develop a Simple Handwriting Detection System that will demonstrate some practical uses of neural network programming.
|
stackexchange-stackoverflow
|
{
"answer_score": 15,
"question_score": 47,
"tags": ".net, artificial intelligence, neural network"
}
|
How do I convert image frames into a video using ffmpeg?
I have a bunch of individual frames and I was wondering if I could use something like FFMpeg to convert it to an mp4? Here is what all my files look like
They start off `exportsequence_` then a string of numbers in order of frame. The video is in 30 fps and I believe it to be around 12 or so minutes. Is there a command I can use to do this?
|
Use the image demuxer:
ffmpeg -framerate 30 -i exportsequence_%10d.jpg output.foo
If the files do not start with `exportsequence_0000000001.jpg` then add the `-start_number` input option.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "video, ffmpeg"
}
|
Sorting PHP array without ksort
I am trying to manually sort a PHP array without making use of ksort.
This is how my code looks at the moment:
function my_ksort(&$arg){
foreach($arg as $key1 => $value1){
foreach($arg as $key2 => $value2){
if($key1 > $key2){
$aux = $value2;
$arg[$key2] = $value1;
$arg[$key1] = $aux;
}
}
}
}
It doesn't sort, I can't figure out how to make it sort.
|
You could try this:
function my_ksort(&$arg)
{
$keys=array_keys($arg);
sort($keys);
foreach($keys as $key)
{
$val=$arg[$key];
unset($arg[$key]);
$arg[$key]=$val;
}
}
I'm sorting the keys separately and then deleting the elements one-by-one and appending them to the end, in ascending order.
I'm using another sorting function (`sort()`), but if you want to eliminate all available sorting functions from your emulation, `sort()` is much easier to emulate. In fact, @crypticous's algorithm does just that!
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "php, arrays, sorting, ksort"
}
|
Determinants: divisibility by 6 without remainder and $n\times n$ matrix
1. Compute the determinant of \begin{pmatrix} 1 & 2 & 3 & ...& n\\\ -1 & 0 & 3 & ...& n\\\ -1 & -2 & 0 & ...& n\\\ ...& ...& ...& ...& \\\ -1 & -2 & -3 & ...& n \end{pmatrix} after some elementary raw operation, one can reach: \begin{pmatrix} 1 & 2 & 3 & ...& n\\\ -2 & -2 & 0 & ...& 0\\\ 0& -2& -3& ...&0& \\\ ...& ...& ...& ...& \\\ 0 & 0 & 0 & 1-n & n \end{pmatrix} but I don't sure how to proceed.
2. Why the det. of the following matrix is divisible by 6 without remainder? \begin{pmatrix} 2^0 & 2^1 & 2^2 \\\ 4^0 & 4^1 & 4^2\\\ 5^0 & 5^1 & 5^2 \end{pmatrix} So I know that I have to show that its det. is divisible by $2$ and $3$, or equivalently that the sum of its digits divisible by $3$ and last digit is even. But I don't sure how to start the process.
Thank you.
|
1. Add the first row to the other rows: $$ \pmatrix{ 1 & 2 & 3 & 4 & 5 \\\ -1 & 0 & 3 & 4 & 5 \\\ -1 & -2 & 0 & 4 & 5 \\\ -1 & -2 & -3 & 0 & 5 \\\ -1 & -2 & -3 & -4 & 5 \\\ } \to \pmatrix{ 1 & 2 & 3 & 4 & 5 \\\ 0 & 2 & * & * & * \\\ 0 & 0 & 3 & * & * \\\ 0 & 0 & 0 & 4 & * \\\ 0 & 0 & 0 & 0 & 2\times 5 \\\ } $$ So the determinant is $2(n!)$.
2. The matrix is a Vandermonde matrix and its determinant is $(4-2)(5-2)(5-4)=6$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "linear algebra"
}
|
Como Ler e Converter arquivo de extensão .xsd para uma classe C#
Como Ler e Converter arquivo de extensão .xsd para uma classe C# o intuito disso e converter os schema do site sefaz para pode gerar um xml com esquema correto para poder emitir NFE.
|
Esta linha de comando pode ser usada para gerar as Classes, tendo os Schemas da NF-e:
xsd.exe nfe_v3.10.xsd xmldsig-core-schema_v1.01.xsd /c /edb
Observe que é preciso incluir o nome de todos os XSDs importados no no schema principal, por isto o **nfe_v3.10** e **xmldsig-core-schema_v1.01**
O XSD fica acessível ao utilizar o Prompt de Comando do Visual Studio. .alias("hour")).count().show()
.alias("hour")).count().orderBy(col('count').desc())
Or:
from pyspark.sql.functions import hour, desc
checkin.groupBy(hour("date").alias("hour")).count().orderBy(desc('count')).show()
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "python, pyspark"
}
|
"Button Style" vs. "Button Styles"
I'm working on an app where the user can change how a button looks (size, color, etc.) and I don't know if I should name that tab/section "Button Style" or "Button Styles".
There will also be a "Copy Button Style" or "Copy Button Styles" option.
|
This is more of a semantics question than a grammar question.
I assume that the user will be only able to use one single button style at a time — is that correct? If so, "Button Style" and "Copy Button Style" would be the correct labels to use.
|
stackexchange-ux
|
{
"answer_score": 0,
"question_score": 0,
"tags": "grammar"
}
|
In ASP.NET MVC observing a Folder and generate an Event on File generated or changed
In my ASP.NET MVC Applciation I would like to observe the Application Folder (APP_DATA, or another). If a file with a given name is generated or updated, than I would like to show a modal dialog (bootstrap) for a given timespan.
The only way I know is polling with a script in the cshtml-File and Data-exchange with ViewBag / ViewData: `"setInterval(function () { $('#mydiv').load('/Home/MyMethod'); }, 500);"`
Is it possible to do that in background, and only on File genrated / changed fire an event or something similar?
|
I found a Soulution how to do it: 1\. Observing a folder is realy simple with _FileSystemWatcher_ 2\. _SignalR_ is perfect for firing an event
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "asp.net mvc"
}
|
How does a bool type in a dataframe and?
A bool type dataframe:
m = df_device_commission[['X']].gt(0).any(axis=1)
print(m)
0 True
1 True
2 True
3 False
4 True
dtype: bool
another bool type dataframe:
n = df_device_commission[['Y']].notna().any(axis=1)
print(n)
0 False
1 False
2 False
3 False
4 True
dtype: bool
If I want to m and n, How should I write the code?
|
You can use `numpy.logical_and`:
In [377]: import numpy as np
In [378]: np.logical_and(m,n)
Out[378]:
0 False
1 False
2 False
3 False
4 True
dtype: bool
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "pandas, dataframe"
}
|
How Can I Remove Event?
I am adding a event like that
Button button = new Button();
button.Click += (o,e) =>
{
//Somecode
};
How can Remove this event?
|
This may help;
Button btn = new Button();
this.Controls.Add(btn);
btn.Click += (o, x) =>
{
Button b = o as Button;
FieldInfo eventclick = typeof(Control).GetField("EventClick", BindingFlags.Static | BindingFlags.NonPublic);
object eventValue = eventclick.GetValue(b);
PropertyInfo events = b.GetType().GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance);
EventHandlerList eventHandlerList = (EventHandlerList)events.GetValue(b, null);
eventHandlerList .RemoveHandler(eventValue, eventHandlerList [eventValue]);
MessageBox.Show("Test");
};
|
stackexchange-stackoverflow
|
{
"answer_score": -1,
"question_score": 0,
"tags": "c#, events"
}
|
How to use JQuery UI slide effect to seamlessly slide out one div and slide in another div?
I am using
$( "#viewPort" ).effect( "slide", hideoptions, 1000, callback )
to slide out the "viewPort" div, and in the callback() function I am sliding in the new div into the display by calling
$( "#viewPort2" ).effect( "slide", showoptions, 1000 )
var hideoptions = { "direction" : "left", "mode" : "hide";
var showoptions = {"direction" : "right","mode" : "show"};
The problem is that it is not seamless transition: first the content slides out leaving behind a blank area then the new content slides in.
Is there a way to avoid the blank display?
|
It's because you're calling the effect on #viewPort2 in the callback to the effect of #viewPort. That means it will occur only once the effect on #viewPort has fully finished. Try calling the effect on #viewPort2 right after the one on #viewPort, for example:
$( "#viewPort" ).effect( "slide", hideoptions, 1000); //notice, no callback
$( "#viewPort2" ).effect( "slide", showoptions, 1000);
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 8,
"tags": "javascript, jquery, jquery ui"
}
|
Run video according to URL
I need help. I have a file "video.php" Where it contains an html5 player.
I want instead
**www.mysite.com/myvideo.mp4**
Be it
**Www.mysite.com/video.php?file=myvideo.mp4**
I want the src of the video to change according to what is typed in the url.
**video.php**
<video width="480" height="320" controls>
<source src=" **Name typed in the url** " type="video/mp4">
</video>
|
This will work:
<video width="480" height="320" controls>
<source src="<?php echo $_GET['file']?>" type="video/mp4">
</video>
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "php, html"
}
|
Properties of Harmonic functions and Log
Could anyone advise me on how to prove: If $g$ and $\text{log}|g|$ are harmonic in a simply connected domain $\Omega$, then $g \equiv$ constant on $\Omega.$
Hints will suffice, thank you very much.
|
If $\log |g| $ is harmonic then $$-\frac{1}{g^2} \left(\left(\frac{\partial g}{\partial x}\right)^2 +\left(\frac{\partial g}{\partial y}\right)^2\right)+\frac{1}{g} \left(\frac{\partial^2 g}{\partial x^2} +\frac{\partial^2 g}{\partial y^2}\right) =0,$$ if $g$ is harmonic then $$\frac{\partial^2 g}{\partial x^2} +\frac{\partial^2 g}{\partial y^2}=0$$ hence $$\left(\frac{\partial g}{\partial x}\right)^2 +\left(\frac{\partial g}{\partial y}\right)^2=0$$ but the last equality implies that $g$ is constant.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "complex analysis"
}
|
PHP APCu: Does apc_fetch() pass references?
Or does it create a copy of whatever is stored and add this to the script's local memory?
I have a case in which I'm deciding whether to use APCu to cache a seldom changed variable (once a month), or just to re-declare that variable at run time (optimised with OpCache), and upload a new PHP script whenever I change it.
|
As @zerkmes mentions in his comment, apc_fetch passing references should not be the expected behavior, due to each script having a fixed block of allocated memory.
I've found an experiment (posted by **aktharmiah at gmail dot com** ) in the comments section of: < which confirms this:
class foo{
public $bar;
}
apc_add("foo", new foo());
$fooGot = apc_fetch("foo");
$fooGot->bar = 1234;
print_r(apc_fetch("foo"));
echo '<br>';
print_r($fooGot);
Indeed prints:
foo Object ( [bar] => )
foo Object ( [bar] => 1234 )
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "php, performance, caching"
}
|
SQL Server sp_getapplock AND sp_releaseapplock throws Exception when release lock
I was using SQL Server's lock functions likes below
sp_getapplock
sp_releaseapplock
I have specified `@LockOwner = 'Session'`
But throw belows exception every time:
> _com.microsoft.sqlserver.jdbc.SQLServerException: Cannot release the application lock (Database Principal: 'dbo', Resource: '89999') because it is not currently held_
Any suggestions or ideas are welcome!
REGARDS!
CREATE PROCEDURE [SETLOCK]
@...
AS
DECLARE
@RESULT INT;
BEGIN TRANSACTION
EXEC @RESULT = sp_getapplock @...
@LockOwner = 'Session';
IF @RESULT = -3
BEGIN
ROLLBACK TRANSACTION;
END;
ELSE
BEGIN
COMMIT TRANSACTION;
END;
|
The error is pretty clear: you did not acquired the applock on resource `89999`. You must specify `Session` (as the value for `@LockOwner` parameter) also in the call to `sp_releaselock`.aspx) and **the lock release must occur on the same session as the lock acquisition**. Another possible cause is imbalanced acquire/release calls (you have an extra release).
As a side note there is no need for a transaction when using Session scoped locks.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 4,
"tags": "sql server, locking"
}
|
CHARINDEX is returning 0 even when the substring is present
I'm trying to extract a substring of one of the column.
SELECT PT.col1 AS MyColumn
,(
CASE WHEN CHARINDEX(PT.col1, '$') > 0
THEN SUBSTRING(PT.col1, CHARINDEX(PT.col1, '$') + 1,
LEN(PT.col1) - CHARINDEX(PT.col1, '$') - 1)
ELSE ''
END
)
,T1.col2
,PT.col3
,T1.col4
,T1.col5
//...
All I'm getting is empty string for all the rows. I've tried just to display the index of the `$' character but I'm getting`0`.
The value of `PT.col1` looks like `French (Canada)$fr-CA`, `Portuguese (Brazil)$pt-BR`, ...
Am I missing something?
|
You have to switch the parameters:
SELECT CHARINDEX('a$bc', '$') AS Wrong, CHARINDEX('$', 'a$bc') AS Ok
/*
Wrong Ok
----------- -----------
0 2
*/
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "tsql"
}
|
put forward in explanation or put forward to explain
A hypothesis is a supposition **put forward in explanation** of observed facts.
Is this sentence wrong??and if it is then why?
In a grammar book the right form of this sentence is given by this way - "A hypothesis is a supposition put forward to explain observed facts." or "A hypothesis is a supposition put forward as an explanation of observed facts."
|
There is nothing wrong with this sentence. It is both grammatical and idiomatic in even the most formal writing. Here are some examples:
> Popular culture examples of the usage of the language of deadly sin demonstrate the continued usage of this language but offer little in explanation of why these associations still exist. — Hoverd, W, ‘Deadly Sin’, in _Medicine, Religion, and the Body (International Studies in Religion and Society)_ , ed. Coleman, E and White, K, 2009
>
> In these accounts a _past_ stimulus is cited in explanation of a present action. — Harré, R, _Cognitive Science: a philosophical introduction_ , 2002.
>
> The authors choose to discuss the mechanisms of central pain before describing its clinical features, although surely the latter must be used in explanation of the former. — Burchiel, K.J., ed. _Surgical Management of Pain_ , 2002.
|
stackexchange-ell
|
{
"answer_score": 4,
"question_score": 3,
"tags": "verbs"
}
|
Tosyl Chloride? why not anything else
Why do we encounter only Tosyl groups and not anything at the end of the benzene group (ie not to replace the SO2Cl part..rather the Me part at the other end) and then concat the SHA-256 hash of something unique to the value stored. So the end key might look like
data-one-0000fdb60e164cf0bf07cef647354d26ed17c9492ca4bbf4114878325871fa1d
The problem is that the key is somewhat large and it will have impact of the DB performance. I want to chop off some of the hash to get a 64-bit string (so, 8 chars). So I'd chop the above key to
data-one-0000fdb6
But will it leave enough entropy for the remaining key? The DB _will_ get large, and I don't want collisions, obviously. Will another hash be more suitable for this use, or is trimming SHA-256 fine?
|
Assuming the hash function is good, and SHA-256 is widely believed to be so, the probability of no collisions in $k$ samples into a range of size $n$ (e.g., obtained by selecting a subset of characters) is upper bounded by $exp(-k^2/2n).$
For you, say $k=2^{21}=2,097,152$ (couple million) and $n=2^{64}$ means that your probability of no collision is roughly
$$exp(-2^{42}/2^{65})=exp(-2^{-21})\approx 1-1.2\times 10^{-7}.$$
If you had 8 times more inputs (16 million plus) this would become
$$ exp(-2^{48}/2^{65})=exp(-2^{-17})\approx 1-7.6\times 10^{-6}$$
so probability of collision would be more than one in a million.
|
stackexchange-crypto
|
{
"answer_score": 7,
"question_score": 4,
"tags": "entropy, sha 256"
}
|
If a set $A\subseteq\mathbb{R}^n$ is rectifiable, then $cA$ is rectifiable for all $c\in\mathbb{R}$
**Recall:**
Definition. Let $S$ be a bounded set in $\mathbf{R}^{n} .$ If the constant function is integrable over $S$, we say that $S$ is rectifiable, and we define the $(n$ dimensional) volume of $S$ by the equation $$ v(S)=\int_{S} 1 $$
Theorem. A subset $S$ of $\mathbf{R}^{n}$ is rectifiable if and only if $S$ is bounded and Bd $S$ has measure zero.
> For a set $A\subseteq\mathbb{R^n}$ and a scalar $c\in\mathbb{R}$ let $cA$ denote the set $\\{cx:x\in A\\}$. Prove the following:
>
> **Question** If a set $A\subseteq\mathbb{R}^n$ is rectifiable, then $cA$ is rectifiable for all $c\in\mathbb{R}$
I couldn't prove, may you help? Thanks...
|
**Hint:** Apply a change of variables to get an integral over $S$.
* * *
Using the theorem instead:
* Show that if $S$ is bounded, then $cS$ is bounded.
* Show that if $\operatorname{Bd}(S)$ has measure zero, then $\operatorname{Bd}(cS)$ has measure zero.
We show that the latter condition holds as follows: first, note that $\operatorname{Bd}(cS) = c\operatorname{Bd}(S)$. Then, use the following.
**Claim:** If a set $K$ has measure zero, then so does the set $cK$.
**Proof:** The case where $c = 0$ is trivial. If $c\neq 0$, proceed as follows. Suppose that $\mu(K) = 0$. Let $\epsilon > 0$ be arbitrary. Let $(U_j)_{j=1}^\infty$ be a collection of open sets with $K \subset \bigcup_j U_j$ and $\sum_j \mu(U_j) = \epsilon/c$. We note that $cU_j$ is open for each $j$, $cK \subset \bigcup_j (cU_j)$, and $\sum_j \mu(cU_j) = \sum_j c \cdot \epsilon/c = \epsilon$.
We conclude that $cK$ is indeed of measure $0$.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 0,
"tags": "real analysis"
}
|
Is there a way to incude style in a php session?
I have a menu that scrolls down and will let you select what color you want for the background, but its only for one page, is there a way to include the style of the page near the beginning of the session so that it will go for all pages?
|
Are you using a PHP session at the moment? The call to change the colour of the background should set a session variable. Any pages being displayed should check the session to see if that variable is present.
Have a look at <
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "php, css, background, background process"
}
|
can we make the function, it's integral is cantor function?
I'm curious about making cantor function by integrating function f(x)
cantor function starts with f(0) = 0 and ends with f(1) = 1
when we define E = {x $\in $ X: f(x) > 0} and |E| is measure of E
we can think $\int_{|E|} f(x) = 1 $
but by definition of cantor set, |E| converge to 0
so we can think function f(x) can be uncountably many rectangle, which height deverge
someone tells me this is not function but distribution
then what is accurate definition of function?
|
Let $F$ be the Cantor function. There is no integrable function $f$ such that $F(x)=c+\int_0^{x} f(t)dt$. In fact this represenntation is possible iff $F$ is absolutely continuous whereas the Cantor function is singular.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 0,
"tags": "real analysis, functional analysis"
}
|
How can I add images form a SQL Server database to a DataGrid?
I'm trying to add some images from a database table to my DataGrid. I don't know how to deal with that. How can I add images to a DataGrid? Or should I use something else? Like a StackPanel?
This is what I got so far:
<DataGrid Name="ImageDataGrid" AutoGenerateColumns="False" IsSynchronizedWithCurrentItem="True" ...>
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding screenshot}"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
|
I assume it supposed to be something like this:
<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False" >
<DataGrid.Columns>
<DataGridTemplateColumn Header="Image">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Width="auto" Height="auto" Source="{Binding Image}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "c#, sql server, wpf"
}
|
Dúvida sobre getSource() instanceof
**Instanceof** é um operador binário que testa se um objeto é o subtipo de um determinado tipo. Ex:
Object fonte = e.getSource();
if (fonte instanceof JButton){
...
}
Se **getSource()** retornou informações de um **JButton** o resultado da expressão será **true**.
O que não entendo é o por que do retorno da expressão ser verdadeiro, já que o retorno do **getSource()** é do tipo objeto, então todo objeto é subtipo de **JButton?** Caso eu tenha:
Object fonte = e.getSource();
if (fonte instanceof JLabel){
...
}
Supondo que o **getSource()** agora retorne informações sobre um **JLabel** , como acontece a diferenciação já que **fonte** é sempre do tipo **Object**? **Instanceof** vai testar o contéudo de **fonte**?
|
Isso se chama polimorfismo. E todo objeto implicitamente herda de Object. Entendendo polimorfismo, respondera sua dúvida.
Não entrando em detalhes sobre polimorfismo, como ja sabemos que todo objeto herda de Object, então por polimorfismo um objeto do tipo `Object` pode receber(guardar referencia) de qualquer outro objeto, e é isso que está acontecendo.
E quando você faz a verificação com `instanceof` a jvm em tempo de execução verifica a classe do objeto que está sendo verificada.(ou seja, verifica qual classe foi instanciado esse objeto, se foi instanciada como JButton, JList, etc.)
|
stackexchange-pt_stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java, swing, tipagem, awt"
}
|
Does TestDriven.NET work with VS Express?
Does TestDriven.NET work with VS Express?
EDIT: Yeah, I just installed it and noticed that it wasn't working. It looks like a really cool program.
|
According to the release notes for TestDriven.NET, support for the Express editions of Visual Studio was removed in 2.8 (2.08).
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 9,
"tags": "testdriven.net"
}
|
What is a better option to use django-highcharts package to render charts in template or regular ugly rendering in django?
I am having some confusion to decide what to use for highcharts with django, do I use normal ugly rendering in to `<script></script>` tag or I use the django-highchart (package here)?
|
I would suggest normal rendering from front end only as shown in highcharts documentations.
Try to keep backend and front end separate as much as possible. Of course there is a third-party package that you can use but keeping your code modular and segregated is also important.
In future if there is a front end guy who changes/manages the chart code, He need not be forced to learn django first to do front end related tasks. :)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, python, django, highcharts"
}
|
Using NSPredicate to search an array with an array
I have an array of `Card` objects (NSObjects), each with a field called `tags`, which is an NSArray of NSStrings.
I would then like to split up the user's search term into an array called `keywords` of strings by `componentsSeparatedByString`, then use NSPredicate to filter my array of Cards based on which elements have tags containing at least 1 keyword in `keywords`.
I hope that's not too convoluted! I've tried using the NSPredicate `IN` clause to no avail. How should I do this?
|
Considering `array` contains card Object.
NSArray *keyWordsList = [keywords componentSeparatedByString:@","];
[array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"ANY %K IN %@",@"tags",keyWordsList]]
EDIT:
To search partially you can use LIKE operator.
[array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"ANY %K LIKE[cd] %@",@"tags",[partialkeyWord stringByAppendingString:@"*"]]]
|
stackexchange-stackoverflow
|
{
"answer_score": 61,
"question_score": 20,
"tags": "objective c, ios, nspredicate"
}
|
file name without extension
Is there any method of obtaining the name of the file uploaded to a server without extension, in PHP? I used the `$_FILES['file']['name']` but it returns the extension too.
|
$filename = pathinfo($_FILES['file']['name'], PATHINFO_FILENAME);
pathinfo is a core PHP function since 4.0.3, and the PATHINFO_FILENAME option was added in 5.2.
|
stackexchange-stackoverflow
|
{
"answer_score": 47,
"question_score": 11,
"tags": "php"
}
|
HOL Theorem Prover: Adding to existing theory
I am trying to add a theorem to an existing Theory. The theorem that I am trying to add is:
!l1 l2.LENGTH (APP l1 l2) = LENGTH l1 + l2
My first step is to prove the theorem; however, when I try to set the goal, I am getting several error messages:
set_goal( [],``! (l1:'a list) (l2:'a list).LENGTH (APP l1 l2) = LENGTH l1 + l2``)`
|
I think that should be
∀l1 l2. LENGTH (APP l1 l2) = LENGTH l1 + LENGTH l2
and
set_goal([], ``! (l1:'a list) (l2:'a list).LENGTH (APP l1 l2) = LENGTH l1 + LENGTH l2``)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "hol"
}
|
Water flow at different heights
I'm trying to build an irrigation system for my plants, using only gravity (no pump). It would look like this:
|~~~|
| | <--- water tank
\___/
|
| o <--- pipe opening A
| |
| | o <--- pipe opening B
| | |
\------/------/
Would the amount of water coming out of pipe opening A be larger than for pipe opening B because its position is higher? If so, how can this be calculated (assuming all pipes have the same diameter)?
UPDATE Furthermore, if pipe opening B were to be closed, would this affect the flow through A?
|
THE velocities of water coming out will be different. The smaller height pipe will eject water with more velocity. You can find the velocity by using Bernoulli's equation.
|
stackexchange-physics
|
{
"answer_score": 1,
"question_score": 2,
"tags": "water, fluid statics"
}
|
How do you select all columns, plus the result of a CASE statement in oracle 11g?
I want to select *, and not have to type out all individual columns, but I also want to include a custom column with a case statement. I tried the following:
select *, (case when PRI_VAL = 1 then 'High'
when PRI_VAL = 2 then 'Med'
when PRI_VAL = 3 then 'Low'
end) as PRIORITY
from MYTABLE;
But it is complaining that
ORA-00923: FROM keyword not found where expected
|
Add an alias for mytable like this:
select t.*, (case when PRI_VAL = 1 then 'High'
when PRI_VAL = 2 then 'Med'
when PRI_VAL = 3 then 'Low'
end) as PRIORITY
from MYTABLE t;
This is not dependent on any specific Oracle version, not sure about other databases.
|
stackexchange-stackoverflow
|
{
"answer_score": 54,
"question_score": 32,
"tags": "sql, oracle, ora 00923"
}
|
Is there a way to speed up ajax calls in Drupal forms
I've built a form in Drupal 7 using form API and ajax calls. A typical form item looks like this:
$form['wrapper']['step1']['currency'] = array(
'#type' => 'radios',
'#options' => array(
'USD' => t('USD'),
'GBP' => t('GBP'),
'EUR' => t('EUR'),
),
'#default_value' => (!empty($form_state['values']['currency'])) ? $form_state['values']['currency'] : 'USD',
'#title' => t('Choose Currency'),
'#required' => TRUE,
'#ajax' => array(
'callback' => 'ajax_step1',
'wrapper' => 'step1-wrapper',
'method' => 'replace',
'effect' => 'fade',
'speed' => 'fast',
),
);
Everything is working as should but even when the ajax call just rebuilds a small part of the form it takes couple of seconds (the throbber is working overtime :).
Is this normal?
Is there a way to speed this (keeping things the Drupal way)?
|
When the ajax call is made, it literally rebuilds the entire form and returns only an aspect of it. For instance, in your function **ajax_step1** , you are probably calling to return a certain element from the form, and display it in the **step1-wrapper** div/wrapper element.
If you want to speed up the form return, you need to optimize the form builder itself. Which means, you might need to rewrite the form.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ajax, drupal 7, form api"
}
|
How to know if the scrollview is on top?
my Layout structure is
<LinearLayout>
<TabLayout/>
<Scrollview>
.... other widgets are placed here
</Scrollview>
</LinearLayout>
now the issues is that i have an icon on tablayout. which i want to hide when the scrollview is in normal stage. and when it is scrolled down the icon in tablayout should appear and if scrollview is scrolled top and reaches on top i want to hide the visiblity of the icon on tablayout. How to do it. one way i found that is if somehow i am able to find the top point of scrollview than i can set the visiblity by comparing the the position of scrollview and its topPosition.but i dont know to find the top point of scrollview.
|
Use below code to detect is scroll view is on top:
mScrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
@Override
public void onScrollChanged() {
int scrollY = mScrollView.getScrollY(); //for verticalScrollView
if (scrollY == 0)
//button visible
else
//button invisible
}
});
You can also add some tolerance with changing this line:
if (scrollY == 0)
for something like this (20 px tolerance)
if (scrollY <= 20)
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "android, android layout, scrollview"
}
|
How to find the lists which are using custom columns in MOSS 2007 environment at web app level using powershell?
I have deployed a solution which creates a custom column/field to the entire web app.
But the solution doesn't contain any features.
Now I want to find the lists where that custom column is used. Please help me out.
|
I don't have a MOSS box handy but this should mostly get you there:
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
$spSite = New-Object Microsoft.SharePoint.SPSite("
$webApp = $spSite.WebApplication
foreach ($site in $webApp.Sites) {
foreach ($web in $site.AllWebs) {
foreach ($list in $web.lists) {
if ($list.fields["Custom Field name"]) {
"List has custom field" | Out-File C:\filePath\log.txt -append
}
}
}
}
|
stackexchange-sharepoint
|
{
"answer_score": 0,
"question_score": 0,
"tags": "2007, powershell, sharepoint server, custom field types, spfield"
}
|
“Pas” or “ne pas” ?
Question about the below translation of a software product:
Is _pas spécifié_ correct, or should it be _ne pas spécifié_ ?
And for floor 0, which is more common, _rez-de-chaussé_ or parterre* ?
Dictionary says _rez-de-chaussé_ , but my feeling tells me _parterre_.
!Software translation
|
In this case the dictionnary is right, "rez-de-chaussée" (with an 'e' at the end) is a better translation than parterre which means a part of a garden with an aesthetic purpose.
"Pas spécifié" is not good french, when there is no data we would most likely say : "non spécifié".
|
stackexchange-french
|
{
"answer_score": 10,
"question_score": 7,
"tags": "usage, négation"
}
|
How to use return redirect in laravel controller
public function getleaveType(Request $request){
$leave_types = leaveType::all();
//create leave-type
if($request->isMethod('POST')){
$leave_Type = new leaveType;
$leave_Type->leave_type = $request->input('leaveType');
$leave_Type->staff_type = $request->input('staffType');
$leave_Type->leave_days = $request->input('leaveDays');
$leave_Type->leave_description = $request->input('leaveDescription');
$leave_Type->save();
}
return redirect('leave/leaveType', ['leave_t' => $leave_types]);
}
|
Looks like you are passing data `$leave_types` to `route` and not to `view`.
It should be something like this
return view('view_name', ['leave_t' => $leave_types]);
OR
return view('view_name')->with('leave_t',$leave_types);
Edit:
Try this
public function getleaveType(Request $request){
//create leave-type
if($request->isMethod('POST')){
$leave_Type = new leaveType;
$leave_Type->leave_type = $request->input('leaveType');
$leave_Type->staff_type = $request->input('staffType');
$leave_Type->leave_days = $request->input('leaveDays');
$leave_Type->leave_description = $request->input('leaveDescription');
$leave_Type->save();
}
$leave_types = leaveType::all();
return view('view_name')->with('leave_t',$leave_types);
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -1,
"tags": "php, laravel, redirect, return"
}
|
How do I simplify $O\left({n^2}/{\log{\frac{n(n+1)}{2}}}\right)$
I'm not very certain about how to deal with asymptotics when they are in the denominator. For $$O\left(\frac{n^2}{\log{\frac{n(n+1)}{2}}}\right)$$, my intuition tells me that it should be treated in a similar way as little o. Would that be correct?
Also, is this in any way comparable with $O(n)$ or $O(n^2)$?
|
Your expression is
$$ E = \frac{cn^2}{\log \frac{n(n+1)}{2}}$$
where $c$ is some constant. The simple upper bound for $E$ is
$$ E\le c n^2$$
which implies that $\mathcal{O}(n^2)$. For a better bound
$$E = \frac{cn^2}{\log \frac{n(n+1)}{2}} = \frac{cn^2}{ 2 \log n + \log n - \log 2 } $$
Now it is an easy verification that $E$ is $\mathcal{O}(\frac{n^2}{\log n})$. In other words $E$ is $o(n^2)$(weaker statement as compare to the previous one).
|
stackexchange-cs
|
{
"answer_score": 5,
"question_score": 1,
"tags": "asymptotics, landau notation, big o notation"
}
|
jQuery.noConflict causing issue with jQuery animate
I have just installed an element that slides in from the right. After calling jQuery 1.7.1 I have this in my footer:
$(document).ready(function() {
$('#element').animate({right:'0px'}, 3000).css('overflow', 'visible'); });
See an example here <
The theme I have it installed in is unfortunately quite bloated with tons of other jQuery. But I've narrowed it to exactly one line in all the .js files as to why the above function won't work.
var $j = jQuery.noConflict();
If I eliminate that line, the element slides in as expected, but it also breaks other jQuery elements. I have been running around in circles trying to get it to work.
Is it something obvious I am missing that I need to do?
Thanks for taking a look.
|
Adding this as an answer so the question has an answer: change `$` to `$j` in your footer.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "jquery animate, jquery"
}
|
md5-encrypted string returns different from database than it is inserted
So, I try to check if passwords match.
This is the encryption I use, once when the data is inserted in the database, once to check if the inserted password on the login field matches the one from the database:
byte[] pass = Encoding.UTF8.GetBytes(password);
MD5 md5 = new MD5CryptoServiceProvider();
string newPass = Encoding.UTF8.GetString(md5.ComputeHash(pass));
But every time I try to login (with correct details), it does not work. In the debugger, this is the string that comes from the database:
?]??$PL??f??6?
And the one encrypted from the login field:
]$PLfඇ6
I suppose it's an encoding problem, but can't seem to figure it out myself.
|
This line is inappropriate:
string newPass = Encoding.UTF8.GetString(md5.ComputeHash(pass));
`ComputeHash` returns arbitrary binary data. Either you should keep it as binary data, or if you _do_ need to convert it to text, use Base64 to convert it in a way which will allow you to get back the original data later:
string base64Hash = Convert.ToBase64String(md5.ComputeHash(pass));
You should be fine to store that as a normal string - it'll just be ASCII.
(I wouldn't personally use MD5 to hash passwords, but that's a different conversation.)
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 1,
"tags": "c#, asp.net"
}
|
Unable to connect to SQL on aspnet_regsql.exe
I have a standalone environment, and I am trying to configure FBA on my local machine, I ran `aspnet_regsql.exe,` and it said it's `unable to connect to SQL`.
The account am using is the sp_admin account that I've used to install SharePoint, not the sp_farm account.
I checked the permissions on SQL, and `under security > Logins > sp_admin`, I can see that in the server roles, the account has these permissions: `dbcreator, securityadmin, public, sysadmin.`
Is there a reason why I can't connect to SQL?
|
Is your SQL Server instance definitely accessible over named pipes? By default, SQL Server is locked down quite tightly these days, so you may need to enable named pipes.
<
Also check this one
|
stackexchange-sharepoint
|
{
"answer_score": 0,
"question_score": 0,
"tags": "security, forms authentication, sql, sql server 2012"
}
|
Can't print a string in reverse order in C
I have written this simple program to print a string in reverse order but it is showing segmentation fault.
#include<stdio.h>
#include<string.h>
int main (int argc, char **argv)
{
char *string;
int n;
printf("Enter a string\n");
scanf("%s",string);
printf("\n");
n = strlen(string);
printf("%d",n);
while(n != 0)
{
printf("%c",string[n]);
n--;
}
return(0);
}
Can anybody explain me why I am getting this segmentation fault? Opearating system : Ubuntu , compilor : gcc
|
`char *string` creates a variable which _can_ hold a pointer to a string, but it is not set here. So it points to a random location which, when accessed, segfaults.
To be useful, either allocate some memory and assign that to the pointer:
char *string = malloc(1000); // big enough for string
or, do it all at once:
char string[1000];
Ideally, instead of using a hardcoded constant (like my example `1000`) use a symbolic constant, or better yet, find out how long the string needs to be and then use that.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": -2,
"tags": "c"
}
|
refresh Jtable after inserting new row
I have a jTable that is initialized thorough "right click> table content > bound > Import data to form " , and then the columns are shown from "right click>bind > elements". I have a insert form inside that form too and I want to refresh the jTable after inserting a new row. how should I do it?
|
DefaultTableModel model ;
public MyJframe() {
initComponents();
model=new DefaultTableModel();
jTable1.setModel(model);
model.addColumn("DJID");
model.addColumn("DID");
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
// Code for inserting to database
model.addRow(new Object[]{DaneshjooID,DarsID});
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Exception: " + e.getMessage());
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -2,
"tags": "java, netbeans, jdbc, jtable, derby"
}
|
Do I need to pay for my family, who are 'additional applicants' when applying for Australian work visa?
I am from family of 4 (two adults, two children (5 and 7)). I was looking into Australian work visas and was wondering how many persons to I need to pay for when applying for (190) visa... I would be the only person who works from my family...
In visa fee calculator here (screenshot below) one can select applicants over and under 18, which seem to imply that if I want to bring my family over to Australia I will have to pay ~1,800.00 AUD for adult and ~900.00 AUD for child.
.
Here's an excerpt from the main applicant with spouse and children example.
> 1. Paul applies for an Independent ELICOS Sector (subclass 570) visa in his home country, by lodging a paper application.
> 2. When he applies, he includes his 30-year old wife and 2-year old child as additional visa applicants.
> 3. Paul must pay the base application charge for this visa as the main applicant, the additional applicant charge for his wife (additional applicant 18 years or over) and the additional applicant charge for his child (additional applicant under 18 years old) as additional applicants.
>
|
stackexchange-expatriates
|
{
"answer_score": 4,
"question_score": 5,
"tags": "working visas, australia, family, payment"
}
|
Add an index to MySQL, but only if it doesn't exist
Is there a way that we can run an ADD INDEX only to databases where it doesn't exist?
Sort of doing an ADD INDEX based on the results of SHOW INDEX ON..
Really trying to avoid the overhead of accidentally adding additional indexes where they already exist.
|
I guess you are looking for something like:
CREATE INDEX IF NOT EXISTS index_name ON table(column)
Sadly, this functionality does not exist in mySql. You can use `stored procedure` (as mentioned by Gordon Linoff) for checking if index exists and add index if not.
The information about indexes is available in `INFORMATION_SCHEMA`
You can do the following query to check for existing indexes:
SELECT COUNT(1) indexExists FROM INFORMATION_SCHEMA.STATISTICS
WHERE table_schema=DATABASE() AND table_name='mytable' AND index_name='index_name';
If index already exists it gives 1 else 0. You can use this in a procedure for achieving what you want.
Also check this for more info.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 4,
"tags": "mysql"
}
|
PageRedirection is not working in Salesforce1
I am trying to redirect to specific record type's edit page layout of an object. Redirection works in Full salesforce site but not in Salesforce1. I tried below function to redirect the page in Salesforce1. But it doesn't work, it always displays default record type's edit page layout of the object
sforce.one.navigateToURL("/006/e?RecordType=01280000000UIuJ&nooverride=1",true);
I tried redirecting the page by below way.Redirection happens in Salesforce1 but it displays the page of full salesforce site. Please advise how to achieve this
window.location.href="/006/e?RecordType=01280000000UIuJ&nooverride=1";
|
Try the `createRecord ` method instead:
sforce.one.createRecord('Opportunity', '01280000000UIuJ');
Documentation:
> **createRecord(entityName[, recordTypeId])**
>
> Opens the page to create a new record for the specified entityName, for example, “Account” or “MyObject__c”.
>
> recordTypeId is optional and, if provided, specifies the record type for the created object.
|
stackexchange-salesforce
|
{
"answer_score": 1,
"question_score": 1,
"tags": "visualforce, salesforce1 app"
}
|
Calculus Trigonometric Integral
I have been trying to solve this particular problem and can not figure out where I have gone wrong in my solution. This is a picture of my solution, if anyone could help point out where I have gone wrong it would be appreciated.
|
First of all, your expression in your answer is not necessarily different from the answer. Use the double-angle formula twice to try to recover an expression in terms of powers of $\cos{x}$. But an easy way to see how the given answer is generated is by substitution:
$$\int dx \cos^2{x} \, \sin{2 x} = 2 \int dx \, \sin{x} \, \cos^3{x} = -2 \int d(\cos{x}) \, \cos^3{x} = -\frac12 \cos^4{x} + C$$
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": -1,
"tags": "calculus, integration"
}
|
How to select a link by its label containing non breaking spaces using the symfony dom crawler?
I have a link:
<a
id="return-button"
href="{{ path('user_list') }}"
class="btn btn-secondary">
<i class="icon ion-md-arrow-back"></i> Back to the list
</a>
I try to use it in a Test. For this purpose, I select it by its label:
self::$client->getCrawler()
->selectLink('Back to the list')
->link();
But the test throws an error:
> InvalidArgumentException: The current node list is empty.
It's because of the ` ` in the link label. If I replace it with a simple space, the dow crawler is able to select it.
How can I select this link without removing the non breaking space in it?
|
As mentioned in this issue: < this behavior is a bug due to the XPath engine used by Symfony.
Currently, to avoid the problem, we can specify the non breaking space in the DOM crawler selector by doing:
self::$client->getCrawler()
->selectLink("\xc2\xa0Back to the list")
->link();
Mind the double quotes instead of the simple ones.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "php, html, symfony, domcrawler"
}
|
How to solve equation T(n) = 5T(n/5) + sqrt(n), T(1) = 1, T(0) = 0 using recursion tree?
When I apply master theorem, I get O(n) but when I try to solve it using recursion tree, I get stuck and couldn't make out any solution.
I tried this :
T(n) = 5T(n/5) + sqrt(n)
T(n) = 5(5T(n/25) + sqrt(n/5)) + sqrt(n)
= 25T(n/25) + sqrt(5n) + sqrt(n)
T(n) = 5(5(5T(n/125) + sqrt(n/25)) + sqrt(n/5)) + sqrt(n)
= 125T(n/25) + sqrt(25) + sqrt(5n) + sqrt(n)
.
.
.
T(n) = sqrt(n) + sqrt(5n) + sqrt(25n) + sqrt(125n) + sqrt(625n) + sqrt(3125n) + ...
How do I suppose to solve this GP??
|
The final sum has log_5(n) + O(1) terms, since the recursion bottoms out. The largest is sqrt(5^(log_5(n) + O(1)) n) = sqrt(O(n) n) = O(n). The others decrease geometrically, so they don't matter in the big-O accounting (alternatively, divide through by 1 + sqrt(1/5) + sqrt(1/5^2) + ... = Theta(1)).
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "algorithm, recursion, time complexity, master theorem"
}
|
Swiss franc banknotes design
Why Swiss Franc banknotes do not have year of issue on the paper? I tried to find such number (year) without success - maybe it is with very small font...
|
The first 2 digits of the serialnumber are the printing year. E.g. 00 is 2000, 94 is 1994, 19 is 2019.
Source: SRF
|
stackexchange-money
|
{
"answer_score": 4,
"question_score": 0,
"tags": "currency, cash, chf swiss franc"
}
|
In GLIM, Is the link function of mean linear in explanatory variables?
In the definition of the generalized linear models (GLIM), $g(\mu) = \beta^T X$, i.e. the link function of mean is modelled to be linear in explanatory variables.
But GLIM is said to be generalization of the general linear model. In the general linear model, however, $\mu$ is only required to be linear in parameter $\beta$, not necessarily in $X$.
So this makes me to ask if $g(\mu)$ in GLIM is only required to be linear in $\beta$ and not necessarily linear in $X$? Thanks!
|
In your statement of the _linear_ model for the GLIM
$$ g(\mu) = X^T\beta$$
The model matrix $X$ is not just the variables, but any transformation thereof, such as quadratic terms, etc. This logic carries forward to the general linear model. The difference there being that $g(\eta) = \eta$ (the link function is the identity).
|
stackexchange-stats
|
{
"answer_score": 3,
"question_score": 1,
"tags": "generalized linear model"
}
|
How to get a random element of array of images and display it
I've tried to do something like this but I haven't had any success. I'm not sure if this is the correct syntax
<p id = "Person"></p>
var x = <img src="bob.jpg" width = "500" height = "500">
var y = <img src="joe.jpg" width = "500" height = "500">
var z = <img src="chad.jpg" width = "500" height = "500">
Try to pick out a random image from an array
var myArray = [ x, y, z ];
var randomNumber = myArray[Math.floor(Math.random()*myArray.length)];
Then how do I display it? Is there another document. that i'm supposed to use?
document.getElementById("Person").innerHTML = randomNumber
|
You can try this simple way.
const myArray = ["bob.jpg", "joe.jpg", "chat.jpg"]
const randomImage = () => {
const image = myArray[Math.floor(Math.random() * 3)]; // 0 -> 2
console.log(image);
document.getElementById("Person").innerHTML = `<img src="${image}" width="500" height="500" />`;
}
<button onClick="randomImage()">Random Image</button>
<p id = "Person"></p>
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -3,
"tags": "javascript, arrays, image, display"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.