INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
When did jerseys get dots on them?
I thought jerseys have last names (or nothing) on the back of them. However, I recently saw dots on a jersey.

4. Re-start the MongoDB instance with access control.
mongod --auth --port 27017 --dbpath /data/db1
5. Authenticate as the user administrator.
mongo --port 27017 -u "myUserAdmin" -p "abc123" \
--authenticationDatabase "admin" | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "mongodb"
} |
Get current displayed text in textview
I have a textView with a max linenumber. When the text extends the max linenumber, I want to show a toggle button to expand the text.
Is there any way to see if the text extends the max linenumbers? | Use `Textwatcher` to corresponding textview.in `onTextchange()` you have to count the length of text.if it cross your limit you may show toggle button.I hope this will help you :) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "android, textview"
} |
Type error: strzal[nr.length] is undefined
My code is:
var strzal = [];
var nr = Object.keys(strzal);
strzal[nr.length][0] = new Image();
strzal[nr.length][0].src = 'data/strzal_01.png';
ctx.drawImage(strzal[nr.length][0], gracz.x, gracz.y);
strzal[nr][1] = gracz.x;
strzal[nr][2] = gracz.y;
strzal[nr][3] = setInterval(functionName, 150);
strzal[nr][4] = gracz.zasieg;
I have error in "strzal[nr.length][0] = new Image();". Something in this line is wrong, but I don't know what. When I added [0] an error has occurred. | `strzal` is empty, and you're trying to acces a variable on an index. You should change it to
strzal[nr.length] = array(new Image());
**_More info:_**
This can be done:
variable[new_index] = other_variable;
This can't be done, because it doesn't exist yet:
variable[new_index][second_new_index] = other_variable;
Javascript doesn't create the indexes all the way, so keep that in mind! | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript"
} |
How are dates typically handled with testing?
I am writing an app at the moment that has some pretty extensive business logic based around dates. I have several hundred thousand records to test and testers who want to see how those records are handled, which has worked well so far, however, some edge cases are difficult to replicate. The reason is that most of the logic is related to today's date, in one way or another. What is the best way to handle this with both unit testing and for traditional testing? The only way I can really think of is allowing for today's date to be faked and fixed. | You can use mocks (dependency injection) to return "today" date to be whatever you want it to be. This will allow you to test problem dates and make sure that new additions will not break the old code.
There are plenty of mocking framework around and I am sure $language that you are using has at least a couple of good ones. | stackexchange-softwareengineering | {
"answer_score": 3,
"question_score": 5,
"tags": "testing, unit testing"
} |
Scrap Data after button click in PuppeteerSharp C#
I am unable to scrap data after clicking the button in PuppeteerSharp C#.
Here is my Puppeteer C# code:
string url = $"
var response = await page.GoToAsync(url, new NavigationOptions
{
Timeout = 0,
WaitUntil = waitUntil
});
if (response.Status == HttpStatusCode.OK)
{
await page.TypeAsync("input[name=q]", "Mukarram Javid Github");
await page.Keyboard.PressAsync("Enter");
await page.WaitForNavigationAsync();
var content = await page.EvaluateExpressionAsync("document.querySelector('#res')");
}
I did not get any data in `content`. Can anybody let me know this solution?
I want to scrap the following content - see the screenshot.
Regards,
"); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#, puppeteer, chromium, puppeteer sharp"
} |
When to use extern "C" in C++?
> **Possible Duplicate:**
> Why do we need extern "C"{ #include <foo.h> } in C++?
I have often seen programs coded like:
extern "C" bool doSomeWork() {
//
return true;
}
Why do we use an `extern "C"` block? Can we replace this with something in C++? Is there any advantage to using `extern "C"`?
I do see a link explaining this but why do we need to compile something in C when we already have C++? | extern "C" makes names not mangled.
It used when:
1. We need to use some C library in C++
extern "C" int foo(int);
2. We need export some C++ code to C
extern "C" int foo(int) { something; }
3. We need an ability to resolve symbol in shared library -- so we need to get rid mangling
extern "C" int foo(int) { something; }
///
typedef int (*foo_type)(int);
foo_type f = (foo_type)dlsym(handle,"foo") | stackexchange-stackoverflow | {
"answer_score": 37,
"question_score": 24,
"tags": "c++, c, extern c"
} |
Theming embeded entities
I'm using the **entity_embed** contrib module (8.x-1.2) in drupal 9.4. I embedding entities inside a node body in ckeditor.
The function `mytheme_theme_suggestions_block_alter()` is not called for block entities.
For embedded nodes it's working fine, I have a `node.html.twig` template inside the entity-embed-container. The problem is only for blocks, where are only field templates, no `block.html.twig`.
 which isn't compatible with the current version. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "servicebus, azure service fabric"
} |
Avoid numeric errors in Naive Bayes method
I am implementing the Naive Bayes method with Gaussian distribution.
The problem that I have is that the variance used on the Gaussian curve (calculated from a training set) is REALLY small. They are on the order of e-07. That means the whole equation,
(1/:math.sqrt(2*:math.pi*:math.sqrt(variance))) *
:math.exp(-0.5*(:math.pow(elem - mean, 2) / variance))
results in really high values (such as `500`, or even more). That becomes a problem later, when I multiply every probability p(x|C) together (it is a vector of 256 features).
I heard that is possible to use logarithms to avoid these kind of numbers. I searched on google but didn't find anything related to the subject. Does anyone know about that? | Working with log-probabilities helps with the problem of intermediate values overflowing (and underflowing). Instead of calculating `L = P(x1|C)P(x2|C)...`, you calculate `log L = log P(x1|C) + log P(x2|C) + ...`. You can do two things with `log L`:
1. If you're trying to maximize likelihood, you can directly maximize log-likelihood instead since `log` is monotonic and increasing.
2. If you want a normalized probability `L/Z` in `[0,1]`, you can calculate this as `exp(log L - log Z)`, which is possible even if `L` and `Z` are too large to fit in your floating point type.
In my experience this trick is often necessary when implementing probabilistic graphical models. | stackexchange-softwareengineering | {
"answer_score": 6,
"question_score": 1,
"tags": "algorithms, numeric precision"
} |
How to tell if two ethernet interfaces are on the same lan?
I have to secure interfaces on Linux servers by setting bonding interfaces. The cabling information is not accurate.
Is there a simple way to know if two interfaces are connected to the same LAN?
Some interfaces have no IP, if possible I would prefer to not set dummies IPs.
* * *
I finally did it using `arping`, it was already installed on the servers:
ifconfig eth2 up
ifconfig ethO up
tcpdump -i eth2 -c 3 arp net 10.10.10.10
and in another terminal :
arping -D -I eth0 10.10.10.10
`tcpdump` should displays lines like that:
16:15:43.032103 arp who-has 10.10.10.10 (Broadcast) tell 0.0.0.0
16:15:44.032277 arp who-has 10.10.10.10 (Broadcast) tell 0.0.0.0
16:15:45.032441 arp who-has 10.10.10.10 (Broadcast) tell 0.0.0.0
*`-D` is optional but it gives a nice 0.0.0.0 source address. | Some ideas, assuming interfaces are eth0 and eth1:
* Sniff on both interfaces at the same time for non unicast traffic. You should see all packets twice
( tcpdump -nni eth0 -c 10 broadcast or multicast & tcpdump -nni eth1 -c 10 broadcast or multicast & ) | sort
* Probe with an IP-less protocol.
For example with this tool to generate DHCP requests: <
( sleep 1; ./dhd eth1 > /dev/null ) & tcpdump -nni eth0 udp and port 68
You should see something like this:
14:46:16.449738 IP 0.0.0.0.68 > 255.255.255.255.67: BOOTP/DHCP, Request from 00:50:56:99:76:cb, length 300
14:46:16.650330 IP 0.0.0.0.68 > 255.255.255.255.67: BOOTP/DHCP, Request from 00:50:56:99:76:cb, length 300 | stackexchange-unix | {
"answer_score": 6,
"question_score": 4,
"tags": "linux, networking, ethernet"
} |
Which way should I follow for the load test in .Net?
I saw a few ways for load test. However really I'm confused about it! Because my story is :
I collect datas from a web service, and I serialize them to give somewhere. Someone wants to calculate avarage time of my code( **from collect data to serialize them** ) for 100 or 150 users. These users can access my code same time asynchronously. So I want to make specific load test just in my code. Which way should I follow? Multithread? ThreadPool? PerformanceCounter? in C# | Anywhich way, really.
On non-tech: I'm detecting a bit of 'them against me/us' there; perhaps you can get 'them' to help you specify/build it?
More often than not, in these type of scenarios, it is better to keep the test drivers external, because
* you are testing real code, not test-specific interfaces
* you can distribute load across machines (even different types of clients)
* it is often easier to monitor the activity (using PerfMon, WMI, Process Explorer, bandwidth monitoring etc.)
* it can take a bit of complexity out of your system (by not requiring testing infra structure)
Most of this comes down to preferring _integration test_ over _unit test_ when doing stress tests. The other part comes from the UNIX filosofy: let each program do a single task well. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "c#, multithreading, load testing, performancecounter, stress testing"
} |
Are cicadas kosher?
I'm not Jewish so please be patient with me :)
I've been seeing a lot of news about an upcoming cicada emergence, including talk of how delicious they are, and it got me wondering if they are kosher or not.
I've seen a few articles talking about locusts being kosher in the context of a cicada emergence, but nothing explicitly stating that cicadas are kosher themselves.
Is there any official teaching on this, or a generally accepted position? | Good question, but no. Leviticus 11:22 allows only four species of locust. No other insects are kosher. Rabbi Aryeh Kaplan (who was also a scientist) translated them as follows:
> "the red locust, yellow locust, spotted gray locust, and white locust."
He noted: **Some sources (King James; JPS) translate chargol as cricket, but this is incorrect, because the cricket is wingless, and the Talmud clearly states that all permitted locusts have wings that cover the body (Chullin 59a).**
The murky territory is how certain we can be that we've got those translations right, and thus many don't eat any locusts at all. Rabbi Dr. Natan Slifkin feels quite confident about _Scistocerca gregaria_ , and maybe _Locusta migratoria_ , as being included in those four species. Many Jews of European ancestry don't eat any at all, to play it safe.
But no one would claim cicadas are one of those four kosher species. | stackexchange-judaism | {
"answer_score": 3,
"question_score": 4,
"tags": "bugs, non kosher species"
} |
Javascript search if LocalStorage variable exists
I am programming a chat system. I always make a Localstorage variable when a new chat is opened. Created like this:
localStorage.setItem("chat_"+varemail, data);
Now i want to check how many of them I have so something like: "chat_"+... count. How can I do this? | You'd grab the array of keys of the `localStorage` object, and use Array.filter to grab only the items starting with "chat_":
var length = Object.keys(localStorage).filter(function(key) {
return /^chat_.+/.test(key);
}).length;
Here's a **JSFiddle** | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript"
} |
fbpanel: disable mouse scroll action entirely
I am using `fbpanel 7.0-4` on Debian 10.
I have applied patches from @Arkadiusz Drabczyk, to put `fbpanel` on one monitor, and to disable virtual desktop switching on mouse scroll:
fbpanel: only use one monitor
<
These patches work great, I just need one more small modification:
With the patches applied, mouse scroll no longer switches virtual desktops when cursor is on the panel. But it still acts as "minimize window" when mouse is scrolled directly on the application "dock" (or what is the right word) in the panel. Normally, I can minimize active window by left clicking on the application. That is useful. But also, when cursor is on the application, mouse scroll has same effect, also minimizing and maximizing the current window. This second action I would like to disable.
How can I disable this feature, or disable all mouse scroll actions entirely for `fbpanel` ?
I wand to disable mouse scroll only, not actions for mouse click. | The taskbar documentation section is missing the option you need, but it is present in the source code as `usemousewheel`, so you don't need a patch.
plugin {
type = taskbar
config {
usemousewheel = false
}
} | stackexchange-unix | {
"answer_score": 1,
"question_score": 1,
"tags": "x11, desktop environment, openbox, application, fbpanel"
} |
Is $f(x)x$ convex for increasing function $f$?
Suppose that $f:(0,\infty)\to[0,1]$ is strictly increasing and infinitely differentiable. I have an intuition that $$ g(x)=f(x)x $$ should be convex in $x$ (i.e. increasing at accelerating rate) because $g(x)$ can be interpreted as a proportion of a number both of which go up when the number goes up, but I can't prove it nor come up with a counterexample.
I tried differentiating: $$ g'(x)=xf'(x)+f(x)\implies g''(x)=xf''(x)+2\underbrace{f'(x)}_{>0}\overset{?}{>}0. $$ Thank you for your help. | Let $f(x) = 1- e^{-x}$.
Then for $x > 2$
$$g''(x) = e^{-x}(2-x) < 0$$
and $g(x) = xf(x)$ is not convex. | stackexchange-math | {
"answer_score": 4,
"question_score": 5,
"tags": "calculus, real analysis, algebra precalculus, convex analysis"
} |
Can a Windows audio driver sit atop the default windows driver and post process its output?
Is it possible to write a driver to sit on top of another driver, take the lower driver's output and post process it.
I wanted to write a driver to make sure the volume level was always constant. In my head, this driver would site on top of the audio card driver and post process the output before handing back to the OS to send to the speakers.
I read about MS miniport and this seems to provide some basic guaranteed exposures.
The constant volume level implementation is not what I'm really concerned about in this question. I'm wondering if it is even possible to write a 'filter' driver for lack of a better word so I could do some sound post-processing.
**Edit:** OK, I'm guilty of not googling this first, turns out it's actually called a filter driver which makes me look like a moron. I would be a total noob at this though, so any good direction, or text would be appreciated. | For Windows Vista and beyond, it is quite challenging to write such an audio driver. That's because Windows Vista audio devices primarily use an I/O mechanism where the audio driver exposes the DMA buffers directly to the audio subsystem or application. So the audio engine writes directly into the DMA buffers of the audio adapter and there is no opportunity for a filter driver to inspect the samples being sent to the audio solution.
For Vista and beyond, you can achieve the same result with an sAPO which is a processing element that accompanies a driver package that allows the sAPO to inspect and modify audio samples. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "windows 7, filter, driver, miniport"
} |
Hide empty cells in UITableView
I have a searchable tableview, but would like to only display the number of cells that are returned once a user starts a search. For instance, if a user types in a charecter and there is only one cell that matches the search, the remaining cells the remaining cells of the table are empty. I was wondering if there is a way to hide those empty cells. I was also wondering if there is a way to hide the table view if a person's search does not match any data (by default, it displays a table of empty cells saying "No Results").
Thanks. | Change your implementation of `tableView:numberOfRowsInSection:` in your data source to return the number of search results instead of the total number of items. Then populate those cells with the search results instead of with the rest of the data. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 12,
"tags": "iphone, objective c, uitableview, uisearchbar"
} |
`tee` and `bash` process substitution order
I'd have supposed this code would have printed " _oof_ " first:
echo foo | tee >(rev) | ( sleep 1 ; cat ; )
Output:
foo
oof
Increasing the `sleep` time doesn't change the order. Why doesn't that work?
* * *
Note that other tools _do_ work as supposed, _e.g._ : `echo foo | pee rev 'sleep 1 ; cat'`. | In
echo foo | tee >(rev) | (sleep 1; cat)
In `bash` like in `ksh`, but unlike `zsh`, the stdout of `rev` also is the pipe to `(sleep 1; cat)`.
`echo`, `tee`, `rev` and the `(...)` subshell are started at the same time, but `tee` writes `foo\n` to stdout _before_ the pipe to `rev`, so in any case, `rev` will write `oof` to the pipe after `tee` writes `foo`, so `oof` can only come last. Delaying `cat` has no incidence.
If you wanted the output of `rev` _not_ to go through the pipe to `(sleep 1; cat)`, you'd use `zsh` or do:
{ echo foo 3>&- | tee >(rev >&3 3>&-) 3>&- | (sleep 1; cat) 3>&-; } 3>&1
Note that `zsh` also has a builtin `tee` in its `multios` feature, so you can do:
echo foo > >(rev) > >(sleep 1; cat)
However in:
echo foo > >(rev) | (sleep 1; cat)
The output of `rev` would go through `cat` (confusingly considering it doesn't in the `echo foo >(echo bar) | (sleep 1; cat)` case). | stackexchange-unix | {
"answer_score": 8,
"question_score": 3,
"tags": "bash, pipe, process substitution, tee"
} |
How to get a list of Ints via a LINQ statement?
I have the following class
public class PaymentItemViewModel
{
public List<int> Placements { get; set; }
public int StandardPayment { get; set; }
}
Then a function returns the following
IEnumerable<PaymentItemViewModel> paymentItems
How can I get a list of all the Placements Ids, using LINQ?
Can i do something like the following?
List<int> placementIds = paymentItems.Any(x=>x.Placements) ?? | Probably you are looking for `Enumerable.SelectMany` method
List<int> placementIds = paymentItems.SelectMany(vm => vm.Placements).ToList() | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "c#, .net, asp.net mvc 4"
} |
reactjs: how to define componentDidMount inside ES6 const?
I have this react component that is not an ES6 `class`. It's a `const` like :
import React from 'react';
import Dashboard from './components/Dashboard';
const Home = (props) => {
const componentDidMount = () => {
console.log('component mounted'); // not working
}
return <Dashboard />;
}
Inside this const how do i define the `componentDidMount` function like i would do in a normal ES6 `class`? this is how i did it before.
import React from 'react';
import Dashboard from './components/Dashboard';
class Dashboard extends React.Component {
componentDidMount() {
console.log('component mounted');
}
render() {
return <Dashboard />;
}
} | Stateless functional components don't support the lifecycle methods.
You can either convert it to a stateful component or wrap it in a stateful container.
Good example of wrapping to get the lifecycle methods:
< | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 13,
"tags": "reactjs"
} |
File upload in Ajax: what are my best options?
I have a web form that includes a file input (for a photo) and a text field (for a description).
When the user submits the form, I would like to POST the file to an API on another domain. The API call accepts binary file information. I was hoping to send the POST request via Ajax, but it seems it's not possible to send files via Ajax.
So, can I point the form directly at the API URL? The problem with this is what to do with the response: how can I handle a 200 response and forward the user to a 'success' page on my app, without Ajax?
Or do I need to do the POST in a server-side script instead? | > I was hoping to send the POST request via Ajax, but it seems it's not possible to send files via Ajax.
Not only that you cannot upload files with AJAX but you cannot send AJAX request to different domains.
So here's what you could do:
Have the form POST to a server side script on your server. This script will fetch the uploaded file and description and it will send them as a new POST request to the distant domain. Based on the response your server side script will redirect to wherever you want. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, html, ajax, http"
} |
Should I download all the models/classifiers manually for Stanford NLP "hello world"?
I'm learning how to use the Stanford NLP library (i.e. learning how to write a "hello world" application) and I'm using for this purposes following code snippet But, as usua,l I get a lot of `FileNotFoundException` exceptions, which means, that I haven't downloaded some libraries.
Whether I **should** download manually all these models and include them in my project as foreign resources OR it would be better to extract somehow all these models from the jar? | As long as you have all the jars provided in the folder:
stanford-corenlp-full-2015-04-20/
in your classpath you should have all the resources you need to start with the toolkit.
Could you provide more details about the error you're getting? | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, nlp, stanford nlp"
} |
StructureMap rules for different namespaces
My scenario is:
Two different parts (ASP.NET MVC Areas) of my project need the same constructor injection as Singleton but different instances setup slightly differently.
E.g.
Site Area = its own singleton
Admin Area = its own singleton
Could this be achieved via StructureMap? The parts of the project are in different namespaces. | You can do this if you crate one singleton as the default and one as a named instance. And on those places you need the named instance you map up your dependencies to used the named instance instead of the default.
Container container = new Container(x => {
x.For<ISomeDependency>().Singleton().Use<SomeDependency>(); // User
x.For<ISomeDependency>().Singleton().Add<SomeDependency>().Named("admin");
});
In the example above "Use<>" marks the default, while "Add<>" is adding an named instance.
This will get you your default:
container.GetInstance<ISomeDependency>();
While this one will get you your named instance:
container.GetInstance<ISomeDependency>("admin"); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c#, structuremap"
} |
Profile doesn't match the entitlements file's value for the application-identifier entitlement
I am trying to upload an app to the app store and I am getting this error on the page that has the certs. As far as I can tell I have changed the field so they have matched, but I am missing something.
!this is what pops up
Any help would be greatly appreciated.
!info.plist | I'm not sure why this fixed it, but I went into my Target's Capabilities tab, turned iCloud ON, tried to do an archive build, it failed, I turned iCloud OFF again, tried to do an Archive build and it succeeded, and after that it was able to automatically resolve certificates again. | stackexchange-stackoverflow | {
"answer_score": 220,
"question_score": 111,
"tags": "ios, xcode, code signing, entitlements, xcarchive"
} |
How to make session to allow different project?
I am planning to make a project management with PHP/MySQL/Codeigniter.
It will have 10 - 20 users and 20 - 30 projects going on at the same time.
Let's say John is a member of project A, B and C. Cindy is in A, D, F G etc.
I want to make it only members of project can access the project.
Now I am not sure how to approach this.
What do you suggest in terms of DB-design and session.
Any resources will be appreciated. | You can use Zend_Acl with Codeigniter or you could try EzAuth | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 4,
"tags": "php, mysql, database design, session, codeigniter"
} |
Is there a way to change avatar in telegram bot using python?
I was trying to find some documentation, but i`ve failed. I would be grateful if you send me doc or example how to do it. | In order to change your profile photo you should use MTPROTOAPI. One of the good libraries written in Python is called telethon. You can check here on how to update profile information.
install telethon:
python3 -m pip install --upgrade telethon
update profile photo:
import asyncio
from telethon import TelegramClient
from telethon.tl.functions.photos import UploadProfilePhotoRequest
# Use your own values from my.telegram.org
api_id = 12345
api_hash = '0123456789abcdef0123456789abcdef'
client = await TelegramClient('anon', api_id, api_hash)
await client(UploadProfilePhotoRequest(
await client.upload_file('/path/to/some/file')
)) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "python, telegram bot, python telegram bot"
} |
How to enable kernel pstore?
I'm trying to enable the kernel persistent storage (pstore) in order to help debug a module which malfunctions and freezes my laptop on suspend, but I'm having difficulties doing so. My kernel (4.1.20) config with related parameters is
# gunzip -c /proc/config.gz | grep PSTORE
CONFIG_CHROMEOS_PSTORE=m
CONFIG_PSTORE=y
CONFIG_PSTORE_CONSOLE=y
# CONFIG_PSTORE_PMSG is not set
# CONFIG_PSTORE_FTRACE is not set
CONFIG_PSTORE_RAM=m
I have also tried loading the `ramoops` module, but when I do
# cat /sys/module/pstore/parameters/backend
(null)
it doesn't seem to have enabled anything. /sys/fs/pstore is empty as well, altough mount says that it is mounted. I have tried to panic my kernel using this but nothing showed up.
What am I doing wrong? Is it even supposed to work on a normal laptop, or am I completely in the dark? I could not find very much while looking for this feature. | You need to determine a piece of memory that survives a reboot. Then it's probably the easiest approach to pass that via kernel parameters, see the ramoops Documentation in the kernel tree. | stackexchange-unix | {
"answer_score": 2,
"question_score": 5,
"tags": "kernel modules, debugging"
} |
Is there a didmount method for function?
I've looked a lot for that, but never actually found answer for it. I have a function (not a class) that returns some React.Component and I like using it due to how easy it is to use states. Normally I use classes, but there are some places it just feels better to use a function.
Is there any way to check if the function gets didmounted? I don't want to create any memory leaks.
Example function:
export default function foo() {
const [bar, setBar] = React.useState(false)
function looping() {
<some code with useState>
}
return (
<div>Something</div>
)
} | You can use useEffect hook:
export default function foo() {
const [bar, setBar] = React.useState(false)
useEffect(() => {
console.log('mounted')
return () => {
console.log('unmounted')
}
}, [])
function looping() {
<some code with useState >
}
return (
<div>Something </div>
)
}
There's also useLayoutEffect, which works synchronously. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "reactjs"
} |
Showing a set is computable
Let $V = \\{\ulcorner\phi\urcorner \mid A \vdash \phi\\}$, where $A$ is $\\{(\forall{x})(\forall{y})x=y\\}$. I'm having trouble understanding why my book* states (in the solution to problem $1$, Section $7.7.1$) that $V$ is computable, even though $U = \\{\ulcorner\phi\urcorner \mid \emptyset \vdash \phi\\} = \\{\ulcorner\phi\urcorner \mid \emptyset \vDash \phi\\}$ is not computable (by the undecidability of the Entsheidungsproblem).
A note about notation: $\ulcorner\phi\urcorner$ is the Gödel number of the formula $\phi$.
*"A Friendly Introduction to Mathematical Logic" (Leary; Kristiansen; $2$nd edition) | The reason is that it is much "easier" to check whether a sentence follows from $A$ than whether it is true or not, since $A$ essentially tells you all objects that you are quantifying over are the same. That is, checking if $\exists x . \phi$ is true (where $x$ is the only variable in $\phi$) amounts to checking whether $\phi$ is true for some arbitrary choice of $x$. The same obviously holds for $\forall x. \phi$. Since we can write any formula $\phi$ in the form $\forall x_1 \exists x_2 \forall x_3 \ldots \exists x_n . \phi'$ (where the only variables in $\phi$ are $x_1, \ldots, x_n$), to check whether $\phi$ is true, it suffices to check whether $\phi'$ is true for some arbitrarily chosen value of $x_1 = x_2 = \ldots = x_n$. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "logic, computability"
} |
URL routing for master detail pattern
Are there any best practices for URL routing in a master detail application?
Let's say the master is a list of fruits. And the master can be filtered based on user security (not all users have access to banana, client side filters (only show green fruits), etc.
The URL route for an apple cannot be as simple as /apple, because there is no guarantee that apple is currently in the master list.
Or would it make sense to handle detail items that are not in the master? You could update the master list to ensure that apple is there, or leave the master list as is, without apple.
Or would you handle routing differently than /apple? | I would keep your routing as simple as possible - /apple seems perfectly valid.
If the user is not allowed to view /apple then show them an error message, if they are allowed to but apple is currently hidden by filters, I'd remove those filters and show them the apple.
Basically - routes should refer to distinct resources and not be clouded by other concerns. | stackexchange-softwareengineering | {
"answer_score": 3,
"question_score": 0,
"tags": "routing"
} |
Can I hide the new messages notification in the Mail icon for only one of my email accounts?
Basically I would like to have two email accounts setup on my iPhone 4, one my personal account and one for work.
However for the work account, I'd like to not have it's unread message count included in the number of unread messages displayed as a part of the Mail app's icon (the number in the red circle).
Is this possible to do? | You can effectively turn off push notifications for a particular email account... sort of. Go to the Settings app, and hit "Mail, Contacts, Calendars". Go to "Fetch New Data", then scroll down and go to "Advanced". For the email account whose little red badges you don't want, change the setting to "Manual" instead of "Push".
This will prevent new messages from pushing a notification icon to the home screen. However, when you open the Mail app to check your other email, the app will sync the "Manual" account with the server and you'll get a badge if there are unread messages there. So, like bmike mentioned, the real way to get rid of those badges is to get closer to inbox zero. | stackexchange-apple | {
"answer_score": 1,
"question_score": 6,
"tags": "iphone, email, notifications"
} |
Как из терминала заменить слово в файлах в Ubuntu?
Во всех файлах в папке и во вложенных папках. | Например, так:
grep -lr -e 'было' . | xargs sed -i 's/было/стало/g' | stackexchange-ru_stackoverflow | {
"answer_score": 12,
"question_score": 3,
"tags": "linux"
} |
What is the name of the university in this seal?
I was able to read the second half (), but not the actual name of the university.
||email) from HP
But I get:
> ORA-00942: With error table or view does not exist | Could it be that user and table are in different schemas? What is the output of 2 next statements:
select user from dual;
select owner from all_tables where table_name = 'HP'; | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "sql, oracle, oracle10g"
} |
Distance between points on a polar coordinate system
Imagine a polar coordinate system with radius = 1. The line that connects these two coordinates is a spiral: (0,0) (10π,1).
How can the length of this spiral be calculated? (Points above are just samples for a "multi rotation" situation... But it can be any two points..) | I'll give a hint on how to setup the problem:
You can use the formula for the arc-length in polar coordinates.
$$ds=\sqrt{r^{2}+(\frac{dr}{dθ})^{2}}dθ$$
with $L=\int ds$.
With a standard spiral you have r to be a linear function of theta $r(\theta) = r_{0}+b(\theta - \theta_{0})$. | stackexchange-math | {
"answer_score": 0,
"question_score": 0,
"tags": "polar coordinates, arc length"
} |
SQL query for DATA AND TIME field minus FIVE hours
I'm creating reports from database where I have to select Created date with time from database but in my databse **TIME AND DATE** is different then actually created time. It's **5 HOURS more** then actual created time.
How Can I select field with minus 5 hours .?
Thanks | You can do it like this:
SELECT `field` - INTERVAL 5 HOUR FROM `your_table` | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "mysql, datetime"
} |
Python pandas dataframe to list by column instead of row
I would like to know if there is an easy way to convert pandas dataframe to list by column instead of row ? for the example below, can we have [['Apple','Orange','Kiwi','Mango'],[220,200,1000,800],['a','o','k','m']] ?
Appreciate if anyone can advise on this. Thanks
import pandas as pd
data = {'Brand': ['Apple','Orange','Kiwi','Mango'],
'Price': [220,200,1000,800],
'Type' : ['a','o','k','m']
}
df = pd.DataFrame(data, columns = ['Brand', 'Price', 'Type'])
df.head()
df.values.tolist()
#[['Apple', 220, 'a'], ['Orange', 200, 'o'], ['Kiwi', 1000, 'k'], ['Mango', 800, 'm']]
#Anyway to have ?????
#[['Apple','Orange','Kiwi','Mango'],[220,200,1000,800],['a','o','k','m']] | Just use Transpose(T) attribute:
lst=df.T.values.tolist()
**OR**
use `transpose()` method:
lst=df.transpose().values.tolist()
If you print `lst` you will get:
[['Apple', 'Orange', 'Kiwi', 'Mango'], [220, 200, 1000, 800], ['a', 'o', 'k', 'm']] | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "python, pandas, list, dataframe"
} |
How to define properties on a type defined by a javascript function?
I need to work with a legacy library that's plain old javascript, but which I have renamed with a .ts extension so I can gradually refactor it. This is mostly working, but the code does one thing that Typescript doesn't like:
function TestUtil() {}
TestUtil._startTime;
and the Typescript compiler is complaining that `Error TS2339 (TS) Property '_startTime' does not exist on type 'typeof TestUtil'.`
I cannot find any syntax that will let me indicate that `TestUtil` should be treated like `any`, so that I don't get this kind of compilation error. How can I get around this | If you want `TestUtil` to be defined as `any` (which is probably not recommended), you can do this as such:
const TestUtil:any = function() {} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "typescript"
} |
Random Walk Limit Behavior
Suppose $\\{ X_t \\}$ is a sequence of i.i.d. random variables, with support $\\{-1,1\\}$ and distribution $P(1)=P(-1)=1/2$. Thus, $S_t = \sum_{s=1}^{t} X_s$ is a zero mean random walk. Also, $S_t$ is a martingale, but the conditions for Doob's martingale convergence theorem do not apply. What is it possible to say about the limiting behavior of $S_t$? | For any random walk on $\mathbb{R}$ there are only four possibilities. Exactly one of the following happens with probability one.
1. $S_n = 0$ for all $n$
2. $S_n \to \infty$
3. $S_n \to -\infty$
4. $-\infty = \liminf S_n < \limsup S_n = \infty$
This is because $\limsup S_n$ is an exchangeable random variable, meaning reordering finitely many of the $X_i$ doesn't change it's value.
In your case we end up in option 4. since clearly we are not in 1., and by symmetry if we were in 2. then we should also be in 3., so it must be that we are in 4. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "random walk"
} |
How to temporarily load an env file for a single shell command, as a bash util/function/alias?
Similar to Running shell script using .env file, but I'd like to have an `xargs`-like "append usage":
xenv path/to/existing/envfile <WHATEVER COMMAND TO RUN>
For example, with an `envfile` on disk like:
FOOBAR="Hello Word"
I'd like to get:
% FOOBAR="old value"
% echo $FOOBAR
old value
% xenv path/to/envfile echo $FOOBAR
Hello World
% echo $FOOBAR
old value
I've tried variations like:
xenv() {
(set -a && source "$1" && "$@")
}
xenv() {
(set -a && source $(realpath "$1") && "$@")
} | Based on your `xenv()`:
$ xenv() { (set -a && source "$1" && shift && "$@"); }
$ cat envfile
FOO='hello world'
$ FOO='old value'
$ echo $FOO
old value
$ xenv ./envfile bash -c 'echo $FOO'
hello world
$ echo $FOO
old value
$
Note that usage like `xenv ./envfile echo "$FOO"` does not work because `$FOO` would expand in current shell's env. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "bash"
} |
Encrypt multiple partitions (different OS)
I have a disk with multiple partitions:
* Windows 7 (one partition )
* Debian 8.2 (3 partitions : root `/` \+ `/home` \+ `swap`)
I'm using Grub 2 for dual booting. I want to know the best way to encrypt all of the data on my disk. Is it possible to encrypt everything with one procedure, or should I encrypt each OS separately.
If I need to encrypt each OS, the procedure should be different on each OS, right? In this case what are the best encryption programs?
I can reinstall and re-partition everything if it'll help the process. | You will need to encrypt separately for each system
On **Windows** : Bitlocker is built-in and easiest to use. An alternative is Veracrypt.
On **Linux** : The traditional approach is to use dm-crypt.
It is technically possible to have a separate, encrypted partition used by both systems (when dual booting) if it is encrypted by portable technologies. The now-defunct Truecrypt could do that, Veracrypt should be able too (as it is a fork) but I have not tested that. | stackexchange-superuser | {
"answer_score": 1,
"question_score": 1,
"tags": "encryption, windows, debian"
} |
What "former requirement" certainly has no place in estoppel?
Screenshot on the left: _O'Sullivan & Hilliard's The Law of Contract_ (2018 8 ed). p. 328.
Right: Paul Davies. _JC Smith's The Law of Contract_ (2018 2 ed). p. 466.
> ; (I know this is built in functionality but all the example follows in two step manner, using where function and using update function).
$this->db->where('id','3');
$this->db->update('data', $record);
Should I create a separate where function and return $where value in-order to keep MVC pattern clear
function where($field,$value)
and
function update($able,$record,$where)
how to achieve this? | You can use two methods like you mentioned to get more object oriented. Then you will be able to use that function to update any table record.
and also the above answer is correct as well.
$this->db->update('mytable', $data, array("id" => $id)); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "php, codeigniter, query builder"
} |
Android client consumes API returns bad request
I am currently learning django and android. I created a REST API for my backend. The endpoints are working since I can GET/POST with Postman, Insomnia, and httpie. However, if I try it with my android app it gives the response 'Bad Request'. I've been working on it for many hours now. Could someone explain to me why is this happening?
![1]: ![2]: | Solved. I was using a lightweight server by django to run my api. Found out about gunicorn. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "android, django, rest, retrofit"
} |
Is there a CSS only solution to :hover on touchscreens?
I know there are many solutions with JS, but non of them work perfectly for me. Is there a solution with pure css? | With the new Level 4 Media Queries, this issue seems like it’s solved for good.
@media(hover: hover) and (pointer: fine) {}
* Media Queries 4 Hover
* Media Queries 4 Pointer | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "html, css"
} |
Irrationals: A Group?
I understand that the set of irrational numbers with multiplication does not form a group (clearly, $\sqrt{2}\sqrt{2}=2$, so the set is not closed). But is there a proof or a counter-example that the irrationals with addition form (or do not form) a group?
Thank you!
Edit: In particular, I am wondering if the set is closed with respect to addition. | $0$ is not irrational. The set of irrationals is not even closed under addition:
$$(1-\sqrt{2})+\sqrt{2}=1$$ | stackexchange-math | {
"answer_score": 13,
"question_score": 2,
"tags": "abstract algebra, group theory"
} |
add css to hover menu parent but not child
Im trying to do something similar to this: CSS Menu - Keep parent hovered while focus on submenu im using !important to override bootstrap colors it works for the parent but i dont want the child li>a to be effected
.hover-li:hover a{
color: blue !important;
}
.hover-li ul li {
color: white !important;
}
the structure is like this:
<li class = "hover-li">
<a></a>
<ul>
<li><a></a></li>
<li><a></a></li>
<li><a></a></li>
</ul>
</li> | Try this
.hover-li:hover > a {
color: blue !important;
}
it only affects direct children | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "css, twitter bootstrap"
} |
Graph engine for retrive movie relations
I have many small graphs (title relations: prequel, sequel, adaptation, ...) and I want to retrieve all graphs that contain the title from the given collection. For query: `Harry Potter 2`, `Star Wars 3`, `Harry Potter 1` I want to get 2 vertex-edge collections.
I was checking Neo4j, GUN, OrientDB, Arango, but I don't find this.
Can you recommend a solution based on a free/FOSS graph db? | OrientDB is free open source software, you can download it here <
Suppose you have a class called `Movie` with an attribute called `title`, you can write a query as follows:
TRAVERSE bothE(), bothV() FROM (
SELECT FROM Movie WHERE title IN ["Harry Potter 2", "Star Wars 3"]
)
You can also specify one or more edge classes if you want to limit the traversal:
TRAVERSE bothE("prequel", "sequel"), bothV() FROM (
SELECT FROM Movie WHERE title IN ["Harry Potter 2", "Star Wars 3"]
)
This will return all the vertices and edges connected to movies with those titles.
You can also add a Lucene index to the `title` property and perform full text queries with stemming and all the rest
I hope it helps | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "mysql, graph, neo4j, orientdb, arangodb"
} |
How do I remove the "Request New Password" link?
When I visit www.example.com/user, there is a page that shows the login/password and as well as a "Request New Password" tab.
How do I remove this "Request New Password" tab from the user page? | The No Request New Password module is probably the easiest way to go, though you'll need to dig for the 6.x releases. This disables any request to `user/password`, so this path with neither be accessible directly nor display in menus/tabs/links.
Alternatively, you can put its main function into your own custom module:
/**
* Implementation of hook_menu_alter().
*/
function MYMODULE_menu_alter(&$callback) {
$callback['user/password'] = array('access arguments' => array(FALSE));
} | stackexchange-drupal | {
"answer_score": 1,
"question_score": 1,
"tags": "users, 6"
} |
iPhone communication with Windows C# App
I am create an iPhone app that needs to talk to a Windows C# app. The app will run as either a Service or Form Application.
What would be the best way to accomplish this? Ideally exposing a service-type architecture would be best as I don't need a stateful connection (stateless is fine in this case).
Can a WCF service hosted by my app using a form of TCP binding be consumed by my iPhone? Or can an app host using httpBinding without the aid of IIS or some other web server? | Here's what I ended up doing:
In my .NET windows service, I created WCF service bound using a WebHttpBinding endpoint. Doing so exposed my WCF services as JSON.
From the iPhone, using Objective-C, I used the ASIHTTPRequest and json-framework libraries to talk to and parse the JSON web service exposed by my .net app. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "c#, asp.net, wcf, xcode, ios4"
} |
PyCharm doesn't identify 'import random' (Python 3.8)
I was working on my discord bot when PyCharm suddenly didn't identify `random`. If is relevant, I uninstalled official python to free up some space on my computer.
Code (?):
import random | You must have an official python version installed to use python according to this page. To help you understand this is basically trying to put on whipped cream to a cake but the whipped cream doesn't exist.
If you install a new version of python than previously:
;
But i send multiple attachment in email not working.
My code is :
$Email->attachments('path/to/example.txt','path/to/example1.txt','path/to/example3.txt','abs/path/to/example4.txt','path/to/example5.txt'); | Try this code for multiple attachment :
$Email->attachments(array(
'example.txt' => array(
'file' => 'path/to/example.txt',
'mimetype' => 'text/plain'
),
example1.txt' => array(
'file' => 'path/to/example1.txt',
'mimetype' => 'text/plain'
),
example3.txt' => array(
'file' => 'path/to/example3.txt',
'mimetype' => 'text/plain'
),
example4.txt' => array(
'file' => 'path/to/example4.txt',
'mimetype' => 'text/plain'
),
example5.txt' => array(
'file' => 'path/to/example5.txt',
'mimetype' => 'text/plain'
)
)); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "cakephp, email attachments, cakephp 2.3"
} |
Systemd starts unknown openvpn instances - how could I disable this?
this is my output by `tail -f /var/log/syslog/`.
May 26 08:02:29 ovpn-server systemd[1]: [email protected]: Main process exited, code=exited, status=1/FAILURE
May 26 08:02:29 ovpn-server systemd[1]: [email protected]: Failed with result 'exit-code'.
May 26 08:02:29 ovpn-server systemd[1]: Failed to start OpenVPN service for ovpn/42.
But there are not a config file like `ovpn-42.conf` at `/etc/openvpn/server/`. How could I debug this or better disable this? | You can copy and paste the unit name right out of the log entry, and then disable it.
systemctl disable [email protected] | stackexchange-serverfault | {
"answer_score": 2,
"question_score": 1,
"tags": "ubuntu, openvpn, systemd, tail"
} |
Reverse a string in php without using any string function
In yesterday Interview I was asked that how to reverse a string with out using any string function like strrev() or strlen(). I found this example on website but it gives error.is it possible to do this without strlen().
> Uninitialized string offset: -1 in D:\xampp\htdocs\PhpProject1\index.php on line xx
$string = "ZEESHAN";
$i =0;
while(($string[$i])!=null){
$i++;
}
$i--;
while(($string[$i])!=null){
echo $string[$i];
$i--;
} | $string = 'zeeshan';
$reverse = '';
$i = 0;
while(!empty($string[$i])){
$reverse = $string[$i].$reverse;
$i++;
}
echo $reverse; | stackexchange-stackoverflow | {
"answer_score": 16,
"question_score": 5,
"tags": "php"
} |
Opencart - mySQL cart entry is updated every time a page loads. Where is the method?
Quick question for you today. I am running an Opencart website, and in the `customer` table there is a column titled `cart` which is a serialized array that stores the users' cart contents i.e.: `a:2:{i:92;i:2;i:12;i:3}`. Every time a new page on the site is loaded (it could be the home page, the account page; any page), that `cart` database entry is updated from the session data (basically, the session variable holds the cart contents, and then the contents transfer to the database every page load).
_**Could you point me to the direction where this method exists AND where it is called?_** | `/system/library/customer.php` has the code in it that you are looking for. It contains all of the possibilities for this (loads when logging in, saves with each page load, and saves to db on logout) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "php, mysql, session, opencart, cart"
} |
Formula isn't Correctly Calculating
I am trying to figure out why the following is not correctly calculating
x = Math.pow(w,e);
When I calculate it in Java, I get 1075, but I am supposed to get 779.
int e = 17;
int w = 803;
int n = 2773;
double x = 0;
x = Math.pow(w,e) % n;
System.out.println(x); | `double` floating point numbers have 53 bits of precision, which is not enough to store the exact value of a huge number like 80317. To do modular exponentiation in Java, you can use the `modPow`) method on `BigInteger`s. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "java, equation, modulo"
} |
Filtering nested attributes in rails 3
My application is composed of `Category` that `has_many products`. Category as well as products have a publication date.
The show page of category display the product from that category.
The show and index actions of Category_controller are very simple (published is a scope):
def index
@categories = Category.published
end
def show
@categories = Category.find(params[:id])
unless @categories.datepublication <= Time.now
redirect_to categories_path
end
end
As you can see it display published category and redirect you to category index when you are being too curious for your own sake.
Now it would be great to display only published products in the show view of a category. I do not know how to do that except with a if in the view, but it seems to me that filtering elements is not the job of the view. What is the correct MVC way of filtering a nested element ? | You can chain scopes, even through associations. From your example I gather that your categories have a publication date but your products also have their own publication date, is that right?
In that case you could set up a scope on your products similar to the one you have on your categories and just use it the same way, i.e.:
@products = @category.products.published
Then whether you want to preload the @products instance variable in the controller or just use @category.products.published in the view is up to you. If the application is simple enough I usually just use the scoped query in the view myself. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ruby on rails, ruby on rails 3, view, nested attributes"
} |
How can I identify only base tables when iterating through all tables in SQL smo?
This is my code:
Server server = new Server(new ServerConnection(con));
server.ConnectionContext.Connect();
foreach (Table table in server.Databases[sqlDatabase].Tables)
{
if (table <is a base table>)
Basically this pulls back views as well I think. The SQL I use to identify the wanted tables is:
`SELECT TABLE_NAME FROM MyDatabase.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'`
However there doesn't seem to be a `TABLE_TYPE` property on the results which are `Microsoft.SqlServer.Management.Smo.TableCollection`. According to SQL, the TABLE_TYPE is either `BASE TABLE` or `VIEW` so only two possibilities.
How can I identify only tables (and not views)? | Looping over the TablesCollection will not enumerate the Views, so your code should works as it is without worrying about Views.
Indeed you have a Views collection as `server.Databases[sqlDatabase].Views`
And, in this collection as well as in the Tables collection, you could differentiate your own views/tables from the system views/tables using the property `IsSystemObject`
var myTables = server.Databases[sqlDatabase].Views
.Cast<Table> => !v.IsSystemObject));
var myViews = server.Databases[sqlDatabase].Views
.Cast<View>().Where(v => !v.IsSystemObject)); | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "c#, sql server, sql smo"
} |
SQLite DateTime comparison
I can't seem to get reliable results from the query against a sqlite database using a datetime string as a comparison as so:
select *
from table_1
where mydate >= '1/1/2009' and mydate <= '5/5/2009'
how should I handle datetime comparisons to sqlite?
update: field mydate is a DateTime datatype | SQLite doesn't have dedicated datetime types, but does have a few datetime functions. Follow the string representation formats (actually only formats 1-10) understood by those functions (storing the value as a string) and then you can use them, plus lexicographical comparison on the strings will match datetime comparison (as long as you don't try to compare dates to times or datetimes to times, which doesn't make a whole lot of sense anyway).
Depending on which language you use, you can even get automatic conversion. (Which doesn't apply to comparisons in SQL statements like the example, but will make your life easier.) | stackexchange-stackoverflow | {
"answer_score": 67,
"question_score": 140,
"tags": "sql, sqlite"
} |
How to reuse same method from other component
How can I refactor two components which needs to use exactly the same methods? defining a parent component and the same method there?
Vue.component("one", {
method: {
functionA:
}
});
Vue.component("two", {
method: {
functionA
}
}); | You can always create a mixin:
var mixin = {
methods: {
consoleMessage() {
console.log('hello from mixin!')
}
},
created() {
this.consoleMessage()
}
}
Vue.component('one', {
mixins: [mixin],
template: `<div>one</div>`
})
Vue.component('two', {
mixins: [mixin],
template: `<div>two</div>`
})
new Vue({
el: '#app'
})
<script src="
<div id="app">
<one></one>
<two></two>
</div> | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 2,
"tags": "javascript, vue.js, vue component"
} |
Matching null objects in regex
I'm trying to match all objects in an array that have a property with value of `null`
[
{
id: 1,
name: "None",
grade: 'A'
},
{ <== match here
id: 2,
name: null,
grade: 'C'
}, <== to here
{
id: 3,
name: "None",
grade: 'B'
},
]
I currently have the following regex statement that tries to match surrounding text between the , though it will not match when I insert 'null' in between the multiline match
`\{((.*\n.*)+null(.*\n.*)+)\}`
Is there an easier way to implement this? | \{[^{]*null[^}]*\}
**Explanation**
* `\{` : We want the first opening bracket
* `[^{]*` : Assuming it is a flat object, we need every character to be not another opening bracket
* `null` : This is the magical text we're after
* `[^}]*` : We need the rest of the object, so look for all characters that aren't the closing bracket
* `\}` : match the closing bracket
* * *
I know this is not robust, but if your data is strictly formatted, this should do it.
After seeing your attempt, you might want to look into the character class | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "regex"
} |
Git keeps failing to pull from upstream on server
Whenever I ssh into my VPS I always have to run through a slew of commands in order to get my git repo to fetch changes from upstream. Sometimes I get lucky enough and it works. For the most part it gives me the not found error:
ERROR: Repository not found.
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
I've added the following to the end of the `.bashrc` file on the machine:
eval "$(ssh-agent)"
eval "ssh-add /home/deploy/.ssh/id_rsa3"
When I ssh in I see the following output in the shell:
Agent pid 7974
Identity added: /home/deploy/.ssh/id_rsa3 (/home/deploy/.ssh/id_rsa3)
The fingerprint for the public key for `id_rsa3` matches the deploy key saved in the repo settings on Github. It never works unless I manually run the above commands. Why is that? | Se up the configuration in `~/.ssh/config` for you `ssh` to work with the key in non-standard location:
Host git-host-you-are-using-to-pull-from
IdentityFile /home/deploy/.ssh/id_rsa3 | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "git, ssh"
} |
Terminate $interval on view leave
I have a simply counter running `doRefresh()` in an ionic/angular application, as you can see it is calling itself with the $interval, but when a user leaves this view. The counter is still running. I cant get it to stop running. I have tried many things including the code below. Please help. Thnk you
$interval(function () {
$scope.doRefresh();
console.log("refresh done");
}, 3000);
$scope.$on('$ionicView.enter', function(){
$scope.$on("$destroy",function(){
if (angular.isDefined($scope.doRefresh())) {
$interval.cancel($scope.doRefresh())
console.log("Destroyed");
}
});
}); | `$interval` returns the promise you need to cancel the interval. See the following code:
var refresher = $interval(function () {
$scope.doRefresh();
console.log("refresh done");
}, 3000);
$scope.$on('$ionicView.enter', function(){
$scope.$on("$destroy",function(){
//This really wouldn't be needed, as refresher should always be defined.
if (angular.isDefined(refresher)) {
$interval.cancel(refresher);
refresher = undefined;
console.log("Destroyed");
}
});
}); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, angularjs, node.js, ionic framework"
} |
Media file type support on browser
I have a file server hosted on tomcat. I am using nginx in front of tomcat. I am using video tag to play videos saved on the server. Some of my media files(eg. .mkv) are not playing in the browser. Some videos are playing but the audio is missing.
Is there any way to support any kind(or atleast the most common video types) to support on browser player? | The commonly supported formats are mp4 and ogg..
For reference U can visit these link
**Reference 1**
**Reference 2** | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "html, tomcat, video, nginx"
} |
iOS format specifies type int but the argument has type int *
I have a method like this:
-(void)processSomeNumeber:(int *)number
{
NSLog(@"show me the number %d", number);
}
But I'm getting this error:
> "format specifies type int but the argument has type int *"
Does anyone know why or how I can fix this? | Use:
-(void)processSomeNumeber:(int )number
{
NSLog(@"show me the number %d", number);
}
Or
-(void)processSomeNumeber:(int *)number
{
NSLog(@"show me the number %d", *number);
} | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 0,
"tags": "ios, objective c"
} |
Integrating 3rd party forum software with my own code
I'm about to start a new PHP project and I'm going to need to make use of 3rd party forum software.
What's the best way to tackle integration of the forum into my code? Things like user authentication, having the user only have to login once, etc.
I'll be using the CodeIgniter framework if that is of any help. I found the article on integrating Vanilla with CL Auth & CodeIgniter but it wasn't to my liking at all.
Does anyone have any specific recommendations on PHP forum software? I'm open to any suggestions or pointers/help. | In my experience Simple Machines Forums is relatively easy to integrate into existing code.
What comes to authentication, it may be easiest for you to use the forum's authentication in your application, rather than attempting to use your application's authentication in the forum. It doesn't matter which forum you choose to use - this is usually the esiest way, since forums tend to have complex code related to auth and access, which can be tricky to modify to use some other system. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "php, codeigniter, integration, forum"
} |
How is the Cantor's paradox resolved in the ZFC system?
How is the Cantor's paradox resolved in the ZFC system?
Thanks. | Assuming that ZF is consistent, the axioms of ZF, with or without the axiom of choice, simply do not permit a ‘set of all cardinalities’ to be formed; that collection is a proper class, and in ZF there are no proper classes as formal objects. They are rather to be identified with predicates. For example, what is (informally in ZF, formally in, e.g., NBG) the proper class of all sets can be identified with the predicate $x=x$. The discussion of Cantor’s paradox in Wikipedia is a reasonable starting point. | stackexchange-math | {
"answer_score": 7,
"question_score": 3,
"tags": "elementary set theory, axioms, paradoxes"
} |
Extending Django Admin templates
I try to modify django admin templates
I created custom template with the name corresponding to template, that I want to override.
I try the following
{% extends "admin/change_form.html" %}
<h1>HELLO</h1>
If I reload the page I dont see h1 tag.
If I try
{% extends "admin/change_form.html" %}
{% block field_sets %}
<h1>HELLO</h1>
{% endblock %}
I seen only h1 tag and dont see model's editing fields.
What have I do to see form and h1 tag in same time ? | This should work:
{% extends "admin/change_form.html" %}
{% block field_sets %}
{{ block.super }}
<h1>HELLO</h1>
{% endblock %}
You must call the block from the source `change_form.html` template. Do that with `{{ block.super }}` as shown above. You can, of course, reverse the order between `super` and `h1` according to your needs. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "django"
} |
Can I get a 6-month UK tourist visa if I'm unemployed?
I am from India. My husband is going to the UK to work for 5 months. So I want to go with him as a tourist, but I'm unemployed and don't maintain a proper bank balance to travel. But I can manage all of the travel expenses before leaving, which would be given by my father-in-law from India. I can show his bank balance details. Is this approved in the UK visa application? | You will need to demonstrate strong ties to India that are a compelling reason to return but without a job and assets of your own this will likely be very difficult to do. Obtaining funds from your father-in-law to improve the appearance of your financial situation is unlikely to help. There is an excellent answer here UK visa refusal on V 4.2 a + c (and sometimes 'e') that may help you. | stackexchange-travel | {
"answer_score": 2,
"question_score": 1,
"tags": "uk, india, standard visitor visas"
} |
How to verify/change git user info?
In git you have to set a global `user.name` and `user.email`. These will be used as author info in the shared git repository which is served via Apache with Ldap authentication.
The problem is that I want to use this authentication process not just for deciding if a user can or not to push but also to ensure that I have the correct author in the git repository.
How would something like this be accomplished? | How does pushing work? Through a CGI script? If so, there will be an environment variable containing the username called `REMOTE_USER` (see here). Put **an`update` hook** in your repository that checks whether all the new commits are allowed for the user specified in that variable.
Note that a drawback of this approach is that if multiple people have pushed something to branch A, no normal developer can push all of those changes over to `master` or so, too, because some of the commits don't belong to him. You might want to check whether the new commits already exist on some other branch and, in that case, let them through without a check. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "git"
} |
XSD milliseconds format
while dealing with our vendor (SAS), we are passing the datetime field as '2018-04-25T19:09:33.84Z', vendor is complaining the format should be '2018-04-25T19:09:33. **0** 84Z' instead,would it by any chance to twik BizTalk to do that? | It seems you've at least agreed to use **ISO 8601** to express datetime data. This is correct by Xml standards.
So, here's the problem, **both are correct**. Which is right depends entirely on the actual correct **value you are sending**.
.084 is 84 milliseconds while .84 is 840 milliseconds. Relatively, a huge difference.
If you are meaning to communicate 84 milliseconds, you are correct, they are wrong. If you are meaning to communicate 840 milliseconds, then your data is wrong or you are constructing the source DateTime incorrectly. It's not BizTalk or .Net. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "biztalk"
} |
How to redirect a site to a new site
I have a site which has pages like this:
blabla.com/page/whatever
blabla.com/category/whatever
blabla.com/about
...
How can I redirect each of these to a new domain, like:
blabla.net/page/whatever
blabla.net/category/whatever
blabla.net/about
...
?
Using .htaccess | Use the Redirect directive:
Redirect /
This directive automatically preserves anything specified after the `/`. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": ".htaccess, redirect"
} |
Check whether an element occurs in a list using recursion
def check(x,num,i):
for n in range(len(x)):
if x[i] == num:
return True
else:
return(check(x,num,i+1))
return False
def User(x,num):
return(check(x,num,0))
User([2,6,1,9,7,3],5,0) this should out put false since 5 is not in the list
checks whether an element occurs in a list recursively
so for example:
Input: a list L read from the keyboard, for example L = [2,6,1,9,7,3] an element e, for example e = 9
but for some reason, i get an error when the number is not in the list | The beauty (and purpose) of recursion is that you do **not** need the loop:
def check(x, num, i):
if not x[i:]: # index past length
return False
if x[i] == num:
return True
return(check(x, num, i+1))
You can also do without the index parameter:
def check(x, num):
if not x:
return False
return x[0] == num or check(x[1:], num) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -2,
"tags": "python, list, recursion"
} |
How to find out sum of a column with respect to another columns maximum and minimum
I have worked with DB2, and I just moved to the SQL Server. I'm a bit confused by a query.
Lets suppose I have table data like
StoreID | Sales
A | 23
B | 50
B | 50
In this data with the stored procedure parameter, I wanted to roll up the sum of Sales. I will get a parameter of StoreID, but in this parameter I can get 'ALL' too.
In DB2 I can get all data using a stored procedure (which has StoreID in a parameter named ParameterStore) with a query like
if(ParameterStore= 'ALL') Then
Set Loc_min = X'00';
Set Loc_max = X'FF';
ELSE
Set Loc_min = ParameterStore;
Set Loc_max = ParameterStore;
END if;
Select Sum(Sales) From Store_data where StoreID between Loc_min and Loc_max;
How can I do this in SQL Server to get the same result? | T-SQL syntax for `IF` is slightly different. You can use it like this:
/*
DECLARE @ParameterStore VARCHAR(10);
DECLARE @Loc_min INT;
DECLARE @Loc_max INT;
*/
IF @ParameterStore = 'ALL'
BEGIN
Set @Loc_min = 0x00;
Set @Loc_max = 0xFF;
END
ELSE
BEGIN
Set @Loc_min = @ParameterStore;
Set @Loc_max = @ParameterStore;
END;
Having said that, what you are trying to achieve could be done as follows:
-- DECLARE @ParameterStore VARCHAR(10);
SELECT SUM(Sales)
FROM Store_data
WHERE CASE
WHEN @ParameterStore = 'ALL' THEN -1
WHEN @ParameterStore = StoreID THEN -1
END = -1 | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "sql, sql server"
} |
Europe/Paris -> CET; Asia/Hong_Kong- > HKT; Europe/Moscow -> MSK
how can i convert 'timmezones' to 'human readable' format in python3?
I.e.:
Europe/Paris -> CET;
Asia/Hong_Kong- > HKT;
Europe/Moscow -> MSK
Thank you a lot for any feedback. | >>> pytz.timezone('Europe/Paris').tzname(datetime.datetime(2018,1,1))
'CET'
>>> pytz.timezone('Europe/Paris').tzname(datetime.datetime(2018,7,1))
'CEST' | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "python 3.x"
} |
Show only next 10 divs
I have a list with generated divs like this:
<div class="news-loaded">...</div>
<div class="news-loaded">...</div>
<div class="news-loaded">...</div>
<div class="news-loaded">...</div>
etc.
On scroll I want to fade in 10 divs and show a fake loader.
For now I have this code:
$(window).scroll( function(){
$('.ajax-loader').each( function(i){
var bottom_of_object = $(this).offset().top + $(this).outerHeight();
var bottom_of_window = $(window).scrollTop() + $(window).height();
if( bottom_of_window > bottom_of_object ){
$('.news-loaded').fadeIn(300);
}
});
});
So if the ajax loader div is visible it now loads ALL divs but I just want to load the next few divs. | I'm sure there's lots of ways, but I tend to use slice().
In your case, the following might do the trick:
Replace: `$('.news-loaded').fadeIn(300);`
With:
$('.news-loaded').slice(0, 9).fadeIn(300);
**EDIT:** Credit to freedomn-m for this enhanced version of the above:
$('.news-loaded').not(':visible').slice(0, 9).fadeIn(300); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "jquery, html"
} |
Deriving FileName from data in Apache Pig
I am working on a situation where I want to store my data in pig script into a file. This is pretty straight forward to do that, but I want file name to be derived from the data itself. So, I have a field in data as timestamp. I want to use say MAX(timestamp) as filename to store all the data for that day.
I know the usage of STORE data INTO '$outputDir' USING org.apache.pig.piggybank.storage.MultiStorage('$outputDir', '2', 'none', ',');
But this variable "outputDir should be passed as the parameter. I want to set this value with a derived value of the field.
Any pointers will be really helpful.
Thanks & Regards,
Atul Aggarwal | In MultiStorage you specify a root directory because typically a HDFS installation is shared by many users, so you do not want data written anywhere. Hence you cannot change the root directory but you can specify which field is used to generate directory names within that directory (in your case 2). The Javadoc is helpful but I am guessing you have seen that already? | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "hadoop, apache pig"
} |
How to transform any string in struct field name like
I would like to know if there is a native way to transform strings like:
* `a.string`
* `a-string`
* `a_string`
* `a string`
In a string that follows the convention for public field members of structs, in Go.
The idea is to write a function that accepts a string and try to get the value of the field, even if the passed string is not using the PascalCase convention, example:
type MyStruct struct {
Debug bool
AString bool
SomethingMoreComplex
}
var myStruct MyStruct
func GetField(s string) reflect.Value {
v := reflect.ValueOf(myStruct)
return v.FieldByName(s)
}
function main() {
GetField("debug")
GetField("a.string")
GetField("a-string")
GetField("a_string")
GetField("-a.string")
GetField("something-more-complex")
}
I was using the strcase package, but it only works for ASCII. | By the magic of regular expressions
<
package main
import (
"fmt"
"regexp"
"strings"
)
func ConvertFieldName(s string) string {
r := regexp.MustCompile("(\\b|-|_|\\.)[a-z]")
return r.ReplaceAllStringFunc(s, func(t string) string {
if len(t) == 1 {
return strings.ToUpper(t)
} else {
return strings.ToUpper(string(t[1]))
}
})
}
func main() {
fmt.Println(ConvertFieldName("debug"))
fmt.Println(ConvertFieldName("a.string"))
fmt.Println(ConvertFieldName("a-string"))
fmt.Println(ConvertFieldName("a_string"))
fmt.Println(ConvertFieldName("-a.string"))
fmt.Println(ConvertFieldName("something-more-complex"))
}
Outputs
Debug
AString
AString
AString
AString
SomethingMoreComplex | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "go, struct, reflect"
} |
Pigeonhole Principle Question...Fifteen different integers from 100 to 199 are given.
Question was too long to fit on title.
Fifteen different integers from 100 to 199 are given. Show that it is always possible to select from these 15 integers at least two different sets $\\{a_1, b_1\\}$ and $\\{a_2, b_2\\}$ such that the last two digits of $a_1 + b_1$ are the same as the last two digits of $a_2 + b_2$.
I know (blasted) pigeons are involved somehow, and I know in some way, if you choose 14 integers, then the 15th will overfill the "pigeonholes" and hence at least two different sets. But I don't have any idea how 14 could come out - any clues will be nice! Thanks. | Hint: Note that there are ${15 \choose 2}=105$ pairs. You are correct about pigeonholes. | stackexchange-math | {
"answer_score": 3,
"question_score": 0,
"tags": "pigeonhole principle"
} |
Solve: $ z^5 = \bar{z} * (- \frac{1}{2} + \frac{\sqrt3}{2} i)$. P.S. if $z = x+y*i$, $\bar{z} = x - y*i$.
Solve: $ z^5 = \bar{z} \left(- \frac{1}{2} + \frac{\sqrt3}{2}i\right)$. P.S. if $z = x+y i$, $\bar{z} = x - y i$.
Seems trivial but I can not solve it. I tried to write $z, \bar{z}$ using $x$ and $y$ and I got nothing. Then I tried by multiplying everything by $z$ and still I got nowhere. Any hint helps. | If$$z^5=\overline z\left(-\frac12+\frac{\sqrt3}2i\right),$$then\begin{align}\lvert z\rvert^5&=\lvert z^5\rvert\\\&=\left\lvert\overline z\left(-\frac12+\frac{\sqrt3}2i\right)\right\rvert\\\&=\lvert z\rvert.\end{align}Can you take it from here? | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "complex numbers"
} |
Change CKEditor default newpage_html
Here's my scenario: I have CKEditor with docprops enabled and fullpage set true. With fullpage true the contentsCss does nothing, that's a "won't fix" in Trac.
I'm trying to modify the NewPage code that gets replaced. Currently (with fullpage true), this is what clicking NewPage enters:
<!DOCTYPE html />
<html>
<head>
<title></title>
</head>
<body></body>
</html>
That's great, but there is no way to edit it. Using newpage_html only enters code into the body tags, not replacing the whole thing.
I want to replace the entire code so I can declare my CSS defaults which I can't do since fullpage is enabled.
I've looked high and low and I can't find out how to modify this. I can't even find where the default code is coming from in the source code! Any help would be glorious! | Use config.newpage_html (it was missing from the docs)
CKEDITOR.replace( 'editor1',
{
fullPage : true,
extraPlugins : 'docprops',
newpage_html : '<!doctype html><html><head><title>My test</title>' +
'<link href="sample.css" rel="stylesheet" type="text/css" />' +
'</head><body>New page, type here</body></html>'
}); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "ckeditor"
} |
Preload data in Ember: Fixture vs REST adapter
I have a fairly complicated Ember.js object that I'd like to send with the initial HTML/javascript when the page loads (to avoid a separate trip to the server), but then allow the user to modify it.
So I know how to set up FIXTURE data which is there directly, and I know how to set up the RESTAdapter so I can load/save to the server... can I do both?
It _seems_ like the store gets set up once, for one or the other. Can I have multiple stores, for one data source?
Thanks! | Regardless of which adapter you use, you can always load data directly into the store. For example,
App.Store = DS.Store.extend({
init: function() {
this._super();
this.load(App.Post, {
id: 1,
text: 'Initial post.'
});
}
});
App.Post = DS.Model.extend({
text: DS.attr('string')
});
For a complete example, see this jsfiddle. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 4,
"tags": "ember.js, ember data, preload"
} |
How to fetch address from CocoaAsyncUDPSocket
Does anyone know how the delegate method for receiving UDP data in CocoaAsyncSockets work when it comes to fetching the source address? Specifically the method
-(void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext
The address comes back as `NSData*` but interpreting it using `NSUTF8StringEncoding` returns `null` and `NSASCIIStringEncoding` returns a bunch of garbled characters. How is it supposed to be interpreted? | Figured out how to do it, the data is in the form of a `struct sockaddr_in*`. After importing `<arpa/inet.h>`you can do the following:
struct sockaddr_in *addr = (struct sockaddr_in *)[address bytes];
NSString *IP = [NSString stringWithCString:inet_ntoa(addr->sin_addr) encoding:NSASCIIStringEncoding]; | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "ios, objective c, udp, cocoaasyncsocket"
} |
Can't use function return value in write context in
Ошибка Can't use function return value in write context in
При таком коде:
if (!empty($_GET('price'))){
$by = price;
}else{
$by = NAME;
}
if (!empty($_GET('price'))){
$order = $_GET['price'];
}else{
$order = ASC;
}
Как правильно сделать тоже самое? :) | > $_GET('price')
надо поменять на
$_GET['price'] | stackexchange-ru_stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "php"
} |
How to return 0 instead of Nan in Swift?
let need = (Singleton.shared.getTotalExpense(category: .need) / Singleton.shared.getTotalIncome()) * 100
needsLabel.text = "" + String(format: "%.f%%", need)
If total expenses and total income are both zero I don't want NaN to be returned. How can I make it so if need = Nan, it returns 0 | You'd need to conditionally check if you both numerator and denominator are zero, which is one reason it would result in `NaN`, and conditionally assign zero to the result.
let expenses = Singleton.shared.getTotalExpense(category: .need)
let income = Singleton.shared.getTotalIncome()
let need = expenses == 0 && income == 0 ? 0.0 : expenses / income * 100
You could also check if the result of division is `NaN` (which could be if any of the operands was `NaN`):
let ratio = expenses / income * 100
let need = ratio.isNaN ? 0.0 : ratio
Be aware that you might also need to handle a scenario where you divide non-zero by zero - this would result in `Inf` \- it all depends on your use case:
if ratio.isInfinite {
// do something else, like throw an exception
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ios, swift, iphone, xcode, nan"
} |
Setting SelectedValue of ASP.NET menu programatically
I have a MultiView and a Menu in my ASP.NET page - each menu item has a Value property which corresponds to the ViewIndex of the tab to show.
I will sometimes need to set the active view programatically, which works fine for the MultiView, but setting the Selected property of the Menu control is a bit more difficult. I could loop through each item til the value matches the view index I want to show, but this seems a bit hacky.
Any ideas? | I recommend using the MultiView's OnActiveViewChanged event to select the menu item.
protected void myMultiView_ActiveViewChanged(object sender, EventArgs e)
{
int index = ((MultiView)sender).ActiveViewIndex;
myMenu.FindItem(index.ToString()).Selected = true;
}
This way, whenever the view is changed (via SetActiveView(), or otherwise), the menu selection will remain synced. Note that you may also need to set the active view on the `OnMenuItemClick` event of the menu. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c#, asp.net, menu, multiview"
} |
TableView технический вопрос работы с коллекцией JavaFx
Всем привет! У меня есть коллекция:
ObservableList<Product> productList = FXCollections.observableArrayList();
и таблица `TableView table=new TableView<>();` с двумя столбцами:
TableColumn nameOfProdCol=new TableColumn("Наименование товара");
TableColumn priseOfProdCol=new TableColumn("Цена товара");
Как поместить в столбцы соответствующие данные? | Всё проще, чем я думал.
1. Установить generic для таблицы. В нем указать тип, с которым мы будем работать, в моем случае это:
`TableView<` **Product**`> table=new TableView<>();`
2. В колонках нужно установить generic с двумя параметрами: первый из которых- тип generic, что и в таблице, а второй- совпадающей с типом поля "Наименование товара". В моем случае нужно поменять
До:
`TableColumn nameOfProdCol=new TableColumn("Наименование товара");`
После:
TableColumn nameOfProdCol=new TableColumn("Наименование товара");
3. Привязать ИМЯ поля, с которым будем работать в колонке:
`//public class Product {//используемый тип в коллекции и самой таблице
//private String` **name**`=null; //продукция //... //}`
`nameOfProdCol.setCellValueFactory(new PropertyValueFactory("` **name**`"));`
//4. Добавляем коллекцию в таблицу и..
`table.setItems(productList);`
Готово! | stackexchange-ru_stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "java, javafx, arraylist, tableview"
} |
is there better or correct way to use objects with vector in c++?
i have a class like this:
class Foo{
public:
Foo();
Foo(int, int, int)
~Foo();
private:
int a;
int b;
int c;
}
and int main function and like to save my elements(objects) in a vector:
int main()
{
vector <Foo*> foo; // <------this line
for(int i=0; i<=500; i++){
foo.push_back(new Foo(i+1,i+2; i+3)); //<------ this line
}
is there a better solution to do that and replace 2 line above?
tnx all; | You need to unlearn that Java thing where you write "new" all the time just to create an object.
int main()
{
vector<Foo> foo;
for(int i=0; i<=500; i++)
foo.push_back(Foo(i+1, i+2, i+3));
}
or, in C++11,
int main()
{
vector<Foo> foo;
for(int i=0; i<=500; i++)
foo.emplace_back(i+1, i+2, i+3);
} | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "c++, class, pointers, object, vector"
} |
parent url of an opensocial container
Is there a way to get the "parent url" of an Opensocial container?
Google Sites embeds gadgets through an Opensocial container and I'd like to grab the parent's URL to generate a message.
Is this possible? | Of course there is.
`gadgets.util.getUrlParameters()["parent"]` or `gadgets.util.getUrlParameters().parent`
shoud give you the parent url. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "javascript, opensocial"
} |
ATI graphics card to feed three monitors
Assuming the monitors can take any kind of port and signal (digital/analog, DVI/HTMI, VGA, DisplayPort) so as to keep this only video card related:
I'm looking to get a three-monitor setup using a single ATI Radeon HD 5XXX card. If I understand correctly the ATI hardware, the DVI and HDMI ports share the same video feed (since they're exactly the same digital video signal). However, what about VGA and DisplayPort?
For instance take this video card from Gigabyte:
!Gigabyte video card with DVI, DP and VGA ports
It has DVI, VGA and DisplayPort connectors. Can it feed three monitors?
If not, what card should I get that can feed three monitors? I think it would need to have two DVI and one DP. The monitors are 1920x1080 and two 1280x1024.
Here is another image. This one has a DVI, VGA and HDMI:
!Asus video card with DVI, HDMI and VGA ports | Reading AMD's ATI Eyefinity Validated Dongles page I can confirm this:
* A maximum of two VGA, DVI, HDMI or passive DisplayPort connections can be used.
* Active DisplayPort is required for three or more connections.
That means I can connector three monitors, two using the DVI/HDMI/VGA ports and the other using DisplayPort, either directly or via an active converter. | stackexchange-superuser | {
"answer_score": 3,
"question_score": 2,
"tags": "graphics card, hdmi, dvi, vga, displayport"
} |
Newbie stuck on a jQuery question...conditional statement
So I'm a complete newbie and stuck on a conditional statement. Here's my code:
<script type="text/javascript">
$(document).ready(function(){
if($('span.fc_cart_item_price_total') == 0) {
$(span.fc_info).addClass('foo');
};
});
</script>
So I'm attempting to see if span with a class of "fc_cart_item_price_total" has a value of "0", to then add a class of "foo" to the span with a class of ".fc_info". This code above is not working. Here's the HTML:
<span class="fc_info">Info 1</span><br />
<span class="fc_cart_item_price_total">$0.00</span><br />
<span class="fc_info">Info 2</span>
Here's the other challenge I have. I'm trying to select the span with the value of "fc_info" before the span with the class of "fc_cart_item_price_total" but have no idea of how to just select this one span. | For each cart item whose price is $0.00, this will add the "foo" class to the preceding (and only the preceding) fc_info.
$(function() {
$(".fc_cart_item_price_total:contains($0.00)").each(function(i, n) {
(n=$(n)).prevAll(".fc_info:first").addClass("foo");
});
}); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "jquery, conditional statements"
} |
Find the slope of a curved line
$f(x) = 8 b^x$
!enter image description here
My answer will be in terms of $b$.
I know you find the slope typically with $\dfrac{y_1-y_2}{x_1-x_2}$, but that doesn't seem to work in this situation. | Write $\,Q=(5,8\cdot b^5)\,\,,\,P=(1,8\cdot b)\,$ , then the slope between these two points is:
$$m_{PQ}=\frac{8b^5-8b}{5-1}=2b(b^4-1)$$ | stackexchange-math | {
"answer_score": 3,
"question_score": 2,
"tags": "calculus, graphing functions"
} |
Is it geologically feasible for a mountain cave system to allow passage from one side of a mountain range to another?
I have a mountain range that separates two places that certain people will want to go between fairly regularly. Right now they have to travel around or over a mountain range to do that.
I've been thinking about ideas of how to make traversal easier and quicker and one possibility that occurred to me was a cave(rn) system that could be entered on one side and eventually exited through the opposite side, similar to what Tolkien did with the Mines of Moria.
The difference here, however, is that Moria was excavated while I'm supposing this to be a natural formation. I don't know enough about geology to say whether or not this is absurd. | This is definitely possible, but often such systems are not so easy to walk in and out. Please take a look at this cave in Abkhazia: < It has four known entrances on different heights, distance between them is several kilometers: < . Take a look at its entrance: < – not an easy path, right?
There is also a smaller cave that has entrance and exit, that is available to the general public to visit: < but it is not as long, probably less than a kilometer. | stackexchange-worldbuilding | {
"answer_score": 12,
"question_score": 7,
"tags": "travel, mountains, caves"
} |
Using the <img> element in XHTML
I'm a noob and learning HTML to begin with.
I used the following code and tried to validate it at validator.w3.org.
<p><img src="C:\Users\46506090\Pictures\FS Capture\2015-08-28_103100.png" alt="stay calm" width="100" height="80" /></p>
I'm getting the following error during validation.
!enter image description here
_I don't understand what needs to be done to fix this_. The `Clean up Markup with HTML-Tidy` option in this validator page adds the following code to make it clean.
<meta name="generator" content="HTML Tidy for Linux (vers 25 March 2009), see www.w3.org" /> | The syntax error is caused by (looks like) not having a space between the closing ~~parenthesis~~ quotation mark and the next parameter name, but it looks like it's fixed in your initial example, just not in the screenshots. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "html, xhtml"
} |
Starting with the Android source code
I'd like to start looking into the Android source code. I'd like to start with the easiest place. Which is the easiest place to start with - any application / framework? Please suggest. | A simple google search would provide you appropriate results
Information on Android Open source website
<
Android Source code
< | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "android, android source"
} |
Is "coil loading" a type of impedance match?
If I have a too short dipole, or vertical, I can add a coil to lenghten in electrically. But it's my understanding that I could also do this with any other kind of match: given the complex impedance at the frequency of interest, I could calculate, for example, a LC network that will match my radiator to present 50 ohms.
So what's the difference between doing it one or the other way? Is a "loading coil" a type of match or does it behave differently? | The short answer to your question is, "Yes."
Every change made to an antenna is likely to change the feedpoint impedance: lengths, diameters and configurations of driven and parasitic conductors; positions, values and parasitic characteristics of "loading" circuits; distance from ground and "nearby" conductive structures, including near-resonant feedlines; etc., etc., etc.
The approach used to maximize power transfer from the transmitter to the antenna may or may not include impedance matching circuitry at the feedpoint or as part of the antenna structure, depending on the losses incurred in the feedline as a result of any mismatch. In typical ham antenna applications, resources of time and treasure are relatively limited, so the need for and implementation of impedance matching means are driven by higher-order design constraints. | stackexchange-ham | {
"answer_score": 4,
"question_score": 5,
"tags": "antenna, impedance matching"
} |
dynamic array in C resizing
I've got a problem with dynamic array. I have to write a program which adds a character to dynamic array starting with 0 elements going to 10. I mustn't use realloc and I have to free the array each time.
#include <stdio.h>
#include <stdlib.h>
void add(int **ptab, int n, int new_elem)
{
int *tab2, y;
tab2 = malloc(n * sizeof(int));
for(y = 0; y < n; y++)
{
tab2[y] = (*ptab)[y];
}
*ptab = tab2;
(*ptab)[n] = new_elem;
free(ptab);
}
main()
{
int *ptab, i, x;
*ptab = NULL;
for(i = 0; i < 10; i++)
{
scanf("%d", &x);
add(&ptab, i, x);
}
for(i = 0; i < 10; i++)
{
printf("%d", ptab[i]);
}
} | *ptab=tab2;
(*ptab)[n]=new_elem;
free(ptab);
should be
free(*ptab);
*ptab=tab2;
(*ptab)[n]=new_elem;
Currently, you're overwriting the old array pointer before freeing it, so you no longer know what you're supposed to free. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "c, arrays"
} |
Sql Parameters supplied for object 'Firm' which is not a function
**Structure tables and result query on sqlfiddle**
I want use query:
INSERT INTO Firm('name', 'name_original', 'id_city', 'id_service', 'id_firm')
VALUES
('РЭД-АВТО ООО', 'РЭД-АВТО ООО', '73041', '2', '1429'),
('УМ-3 ЗАО ', 'УМ-3 ЗАО ', '73041', '2', '49806'),
('ООО West Hole', 'РЭД-АВТО ООО', '73041', '2', '10004');
But i get errors:
Parameters supplied for object 'Firm' which is not a function. If the parameters are intended as a table hint, a WITH keyword is required.:
INSERT INTO Firm('name', 'name_original', 'id_city', 'id_service', 'id_firm')
VALUES
('РЭД-АВТО ООО', 'РЭД-АВТО ООО', '73041', '2', '1429'),
('УМ-3 ЗАО ', 'УМ-3 ЗАО ', '73041', '2', '49806'),
('ООО West Hole', 'РЭД-АВТО ООО', '73041', '2', '10004')
Tell me please why i get errors and how correct insert data ? | Remove the quotes around your column names.
INSERT INTO Firm(name, name_original, id_city, id_service, id_firm)
VALUES
('РЭД-АВТО ООО', 'РЭД-АВТО ООО', '73041', '2', '1429'),
('УМ-3 ЗАО ', 'УМ-3 ЗАО ', '73041', '2', '49806'),
('ООО West Hole', 'РЭД-АВТО ООО', '73041', '2', '10004'); | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 3,
"tags": "sql, sql server, sql server 2008"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.