INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
accessing jquery cloned element
iam doing something like this
var _orgElm = $(this).clone(true);
_orgElm.customResize();
$.fn.custumResize = function() {
return this.each(function() {
// problem is here
// when i apply this function an element, it reads width correctly.
//but when i do this on elements clone it reads zero is there is,
// anyway i can read clone width also
$(this).width();
//some code here ............
});
}
|
I suspect the problem is that the clone has not been added to the document yet. Try inserting it in the DOM and then get the width.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "jquery"
}
|
Timer/stopwatch in Ubuntu 14.04 Unity?
Easy Stopwatch and Zeegaree Lite don't seem to be available in Ubuntu.
What timer/stopwatch can I install in Ubuntu 14.04 (Trusty Tahr)?
|
Have you tried "stopwatch"?
Terminal install command if you dislike the GUI:
sudo apt-get install stopwatch
It is also easily installable from your Ubuntu software center. You find it by typing stopwatch in the search window. Or if you prefer, you can also find it in the synaptic package manager.
The following link tells you more about it, although it is entirely the same information you'd see if you opened the Ubuntu Software Manager.
<
|
stackexchange-askubuntu
|
{
"answer_score": 45,
"question_score": 61,
"tags": "14.04, unity"
}
|
Algorithm to round about n * 10
I am trying to find an algorithm to result:
45 => 100
458 => 1000
8456 => 10000
I would like to "round" this way, i looked into `Math.round()` but it doesn't think to be enough.
|
easiest thing to come up with without thinking:
var n = 455;
var rounded;
for(var i = 1000000000 i>= 1; i/=10)
{
if(i < n)
{
break;
}
else
{
rounded = i;
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "javascript, algorithm, math"
}
|
Adding points to QgsRubberBand polyline instead of giving list of points
canvas = iface.mapCanvas()
polyline = QgsRubberBand(canvas, False) # False = not a polygon
points = [QgsPoint(1,1), QgsPoint(2,2), QgsPoint(3,3), QgsPoint(4,4)]
polyline.setToGeometry(QgsGeometry.fromPolyline(points), None)
polyline.setColor(QColor(255, 0, 0))
polyline.setWidth(3)
This is my sample code. I want to be able to append points to the line rather than updating my list and providing the same list again. Is there any way to do so?
|
You can add a new point to the existing rubber band using `addPoint` method.
For example: `polyline.addPoint(QgsPointXY(10,4))`
 on button click in jetpack compose Android
i want to scroll the view pager horizontally on button click in jetpack compose.Anyone have any idea about this ? Here i am using Accompanist library.
|
You need to use pager state like this:
val state = rememberPagerState()
val scope = rememberCoroutineScope()
Button(onClick = {
scope.launch {
state.scrollToPage(state.currentPage + 1)
// or
state.scrollBy(100f)
}
}) {
}
VerticalPager(
pagesCount,
state = state
) { page ->
}
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 2,
"tags": "android viewpager, android jetpack compose, jetpack compose accompanist"
}
|
How to log flow rate in Akka Stream?
I have an Akka Stream application with a single flow/graph. I want to measure the flow rate at the source and log it every 5 seconds, like 'received 3 messages in the last 5 seconds'. I tried with,
someOtherFlow
.groupedWithin(Integer.MAX_VALUE, 5 seconds)
.runForeach(seq =>
log.debug(s"received ${seq.length} messages in the last 5 seconds")
)
but it only outputs when there are messages, no empty list when there are 0 messages. I want the 0's as well. Is this possible?
|
You could try something like
src
.conflateWithSeed(_ ⇒ 1){ case (acc, _) ⇒ acc + 1 }
.zip(Source.tick(5.seconds, 5.seconds, NotUsed))
.map(_._1)
which should batch your elements until the tick releases them. This is inspired from an example in the docs.
On a different note, if you need this for monitoring purposes, you could leverage a 3rd party tool for this purpose - e.g. Kamon.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 6,
"tags": "scala, akka, akka stream"
}
|
I voted on this answer2 days agoMy vote is now locked inunless the answer is edited
Simple display bug on the toast message: words aren't spaced out enough.
!enter image description here
|
A new build of API has fixed this issue. Yes - I get the [told-you-so] badge.
|
stackexchange-meta
|
{
"answer_score": 9,
"question_score": 14,
"tags": "bug, status completed, android app"
}
|
Restricting search based on a particular country in the Google Maps Places API
I am using the Google Maps' Places API for autocompletion of location as user types. But how can I restrict the suggestions to a particular country?
Here is my javascript:
function initAutocomplete() {
// Create the search box and link it to the UI element.
var input = document.getElementById('autocomplete-input');
var searchBox = new google.maps.places.SearchBox(input);
// [START region_getplaces]
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
});
}
|
Fixed it by changing SearchBox to Autocomplete and passing an options with the requirements..Here is the code if someone needs.
function initAutocomplete() {
// Create the search box and link it to the UI element.
var input = document.getElementById('autocomplete-input');
var options = {
componentRestrictions: {country: 'fr'}
};
var searchBox = new google.maps.places.Autocomplete(input, options);
// [START region_getplaces]
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
});
}
|
stackexchange-stackoverflow
|
{
"answer_score": 15,
"question_score": 9,
"tags": "javascript, google maps, google maps api 3"
}
|
.Net Webmaster API is incorrectly encoding URLs (Google.Apis.Webmasters.v3)
I've been struggling to get the new API to work. I am often getting this error when executing a query:
Error parsing NaN value. Path '', line 0, position 0.
From investigation I think the .Net code is incorrectly encoding URLs in the request by leaving slashes (/) unencoded. This changes the requests URL path and causes a 404.
If you omit the http:// part from the {site} part of a request it works. e.g. **domain.com** not **<
There is no work around if your use an https site. Nor can you make any requests that require you to pass a specific URL outside the home page, as it will need to include a slash (/).
|
This issue is being tracked here:
<
It relates to using .Net 4.0, and can be fixed by upgrading to .Net 4.5
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, .net, google api dotnet client"
}
|
Don't skip empty leading rows when using readxl
`Read_excel()` function automatically skips leading empty rows. Is there a way to avoid this as I need the row.names in R to correspond with row numbers in excel?
It is impossible to satisfy this objective when I am unaware how many leading rows were skipped by read_excel.
|
You can use the `range` argument of the `read_excel` function as the documentation for this argument of the function says:
> A cell range to read from, as described in cell-specification. Includes typical Excel ranges like "B3:D87", possibly including the sheet name like "Budget!B2:G14", and more. **Interpreted strictly, even if the range forces the inclusion of leading or trailing empty rows or columns**. Takes precedence over skip, n_max and sheet.
Additionally, you might want to set `col_names = FALSE`, such that the row-numbering stays the same.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "r, readxl"
}
|
Execute functions in the background (without freeze the UI)
I have 6 functions. I would like to execute 3 of these functions in the background (asynchronous?), in Xcode for Swift 2. Can you help me, how can I execute this 3 functions without a "freeze" in the UI? Thank you so much!
|
Martin R's comment is spot on, you should read Apple's concurrency programming guide. But here's one method you might use:
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)
dispatch_async(queue) {
doSomethingReallySlowAndTedious()
}
Be careful, though. It's especially easy to introduce bugs in your code by just copy-pasting concurrency code. Make sure you know what each function and parameter does.
(Also, consider the worst cases. Can the slow functions get stuck forever? What if the user wants to quit before the slow functions finish?)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "swift, xcode"
}
|
Find all natural solutions $(a,b,c) $ such that $a^2−b, b^2−c, $ and $c^2−a $ are all perfect squares
Find all natural solutions $(a,b,c)$ such that
$a^2-b$,
$b^2-c$,
$c^2-a$
are all perfect squares.
|
Say $a>b$
Since $b<a\leq 2a-1$ we have: $$(a-1)^2<\underbrace{a^2-b}_{=x^2}<a^2\implies a-1 <x<a$$ which is impossible.
So $a\leq b$. With the same procedure we see that $b\leq c$ and $c\leq a$, so $a=b=c$
* * *
So we have $$(a-1)^2\leq a^2-a =x^2<a^2$$ and thus $x=a-1$ so $a^2-2a+1= a^2-a \implies a=1$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "number theory"
}
|
Configure DNS Table on Sonic Wall TZ205
I just installed a TZ-205 on our company network and I can not seem to find where I would add to a DNS table. On our Linksys LRT224 there is a option to add a domain name and an associated IP. Does this function even exist in the Sonic Wall? I want to be able to type in "example.com" and have it point that domain name at my server IP address at home. I know I can edit the hosts file but I use my server at home for development sites I have 5 of them currently on one server so to go to every employees computer and update the hosts file will be time consuming. Thanks
|
The sonicwall can point to one of your own internal DNS servers (running on another device in your network), but it doesn't include a DNS server itself. You can set your server up to do DNS and point the sonicwall at it, then all DHCP clients will use that server for name lookups.
If you have multiple websites and multiple employee workstations, it's worth it to set up your own DNS server. It will save a lot of trouble, especially as you grow.
|
stackexchange-networkengineering
|
{
"answer_score": 2,
"question_score": 1,
"tags": "routing, router, dns, ip forwarding table"
}
|
Best way to get deep property in ES6 shorthand notation
I am running into an issue where in I have a object as below
a = {
b: {
c: 10
}
};
Now this is a dynamic object and can be empty on runtime, like this a = {}, I am trying to read c in ES6 shorthand notation like const {b: {c}} = a;. But getting error every time object is empty. Is there a way I can still use this notation for empty object, like get undefined for c in that case.
I know I can do something like (a.b ? a.b.c : undefined), but i just wanted to know shothand way of doing it.
|
You can do `= {}` for inner objects:
const a = {
b: {
c: 10
}
};
const f = ({b: {c} = {}}) => console.log(c)
f(a)
f({})
In this case `c` becomes undefined if the object is empty
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "javascript, ecmascript 6"
}
|
Encoding.GetEncoding ucs 2 little endian
**I'm trying to find a string or (not so ideally) int representation of`UCS-2 little endian` to input into `Encoding.GetEncoding()`**.
I am looking for this information because I'm using `StreamReader` to read a content of a file and I want to use `Encoding.GetEncoding` to construct it.
The reason for that is I'm reading several different files with variable encodings and I need to be able to specify in configuration which encoding to use for what file.
|
UCS-2 can be considered a subset of UTF-16, and thus any UTF-16 capable decoder should _also_ be able to handle UCS-2; the difference is that UCS-2 doesn't cover the _entire range_ of unicode, and thus there are some _additional_ values that can be expressed in UTF-16 but _not_ in UCS-2. We just shouldn't expect to _see_ those values here, if the file was written by an encoder that only knows UCS-2.
This is pretty much the same as saying that you can use a UTF-8 decoder to read data that was written in pure ASCII (where by "pure" here, I mean 7-bit ASCII, not the extended code-pages that use the 8th bit).
As such, any of:
Encoding direct = Encoding.Unicode;
Encoding byCode = Encoding.GetEncoding(1200);
Encoding byName = Encoding.GetEncoding("Unicode");
should work fine here.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "c#"
}
|
MySQL 5.7 - how to get id for a max value and group by query?
I work on MySQL 5.7, I want to get the ID and TITLE of the last article for each category. For example I have the following table 'Article':
| ID | TITLE | DATE | FK_CATEGORY |
| 1 | title 1 | 2016-10-05 | 1 |
| 2 | title 2 | 2017-10-02 | 1 |
| 3 | title 3 | 2015-10-10 | 2 |
| 4 | title 4 | 2017-04-20 | 2 |
| 5 | title 5 | 2017-04-12 | 3 |
For this example I expect the result to be:
| 2 | title 2 | 2017-10-02 | 1 |
| 4 | title 4 | 2017-04-20 | 2 |
| 5 | title 5 | 2017-04-12 | 3 |
I have tryed this request but it does not work :
SELECT id, title, MAX(date), fk_category
FROM article
GROUP BY fk_category
ORDER BY date DESC
What query do I have to use ?
PS: I do not want to disable ONLY_FULL_GROUP_BY SQL mode
|
Even if you were to disable MySQL's `ONLY_FULL_GROUP_BY` mode, and your current query were to run, it might not yield the correct results. Also, you would not be able to port the query to most other databases. A better approach is to use a subquery which finds the most recent date for each category. Then, join `article` to this subquery to get the result set you want.
SELECT t1.*
FROM article t1
INNER JOIN
(
SELECT FK_CATEGORY, MAX(DATE) AS MAX_DATE
FROM article
GROUP BY FK_CATEGORY
) t2
ON t1.FK_CATEGORY = t2.FK_CATEGORY AND
t1.DATE = t2.MAX_DATE
ORDER BY date DESC
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -1,
"tags": "mysql, date, group by"
}
|
How to validate ToCheckList jQuery plugin (or multiple select fields)?
Anyone ever use the toChecklist jQuery plugin? It basically turns a multi-select box into a list of checkboxes. Makes it easier for users to understand that they can choose more than one item - excellent plugin.
However, I'm trying to **make sure that users on my site pick at least 1 item in the list.** ToChecklist has the capability of limiting the selection to a max value, but not minimum.
I'm already using the jQuery validate plugin to validate the whole form, any ideas to get it to work against a multi-select box (which would then hopefully just work with toChecklist)?
Thanks in advance!
|
The `.toCheckList()` still leaves the original `<select>` options intact, just hidden. This gives you the selected count using the :selected selector:
If you called `$("#myList").toCheckList()`, the code to get selected count would be:
$("#myList :selected").length
Used like:
if($("#myList :selected").length > 0)
alert("Some options are selected!");
else
alert("Oh snap! better pick something");
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "jquery, validation"
}
|
subeclipse not showing same version as svn
Slight oddness going on with svn...
I checked out a repositry with subclipse inside eclipse - the history looks like this: !enter image description here
But when I update on the command line, I get this:
pool188-239$svn up
At revision 1908.
Can anyone tell me why the version numbers are different for the same project?
|
Revision 1906 is the revision where your project was last modified.
Revision 1908 is the current revision of Subversion. When you do an update on your project, the revision number returned is the current revision of Subversion.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "eclipse, svn, subclipse"
}
|
generate gpg public and private keys without any interaction
I would like to know how to generate gpg public and private keys without any human interaction
i need instructions to build a bash to do suck work ,something like:
name=$1
email=$2
pubkeypath=$3
gpg --gen-key --name $name --email $email .........
gpg --export -a $name > $pubkeypath
.
.
.
|
There is a feature for unattendet operation; according to the online documentation, this feature is still experimental, i.e. the interface might break during an update. This interface allows you to pipe a sequence of commands to gpg's stdin, which must be called with the parameters `--gen-key` and `--batch`. A description of the commands possible is found on this webpage.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "centos, gnupg"
}
|
Prevent ScrollViewer from changing its Content size
I want the ScrollViewer to do only one thing - allow me to scroll. I don't want it to allow its Content to grow. Yet it does. How to prevent that?
<ScrollViewer VerticalScrollBarVisibility="Auto" >
<Grid >
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Image Grid.Row="0" Source="a.png"/>
<Grid Grid.Row="1" Height="400"/>
</Grid>
</ScrollViewer>
If I comment out the ScrollViewer - the Image is small. If I leave the ScrollViewer - the Image grows. How to prevent that?
|
You would avoid stretching the Image by setting its `Stretch` property to `None`.
<Image Grid.Row="0" Stretch="None" .../>
The Grid and hence the Image element use the full width of the scrollable area. Since the default Stretch value is `Uniform`, the Image subsequently adjusts its height to keep its aspect ratio.
An equivalent, but simpler layout would be
<ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel>
<Image Stretch="None" Source="a.png"/>
<Grid Height="400"/>
</StackPanel>
</ScrollViewer>
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "c#, .net, wpf"
}
|
Is swiping up/down better than swiping left/right for changing months on a calendar?
I have created a custom View to display a Calendar in Android.
The display is always 1 month. I'm using a swipe to the sides to switch months. Now I have seen some other Apps (including the installed stock Calendar from Google) that change to the next month by swiping down.
Is there a reason why they use this instead of to the sides? which one is more intuitive for the user? I personally like the one to the sides much more but was kinda confused that even the Google calendar uses up/down.
This is the kind of View im talking about: !enter image description here
|
With the google calendar on android, you can scroll down from one month to the next and view a whole month - but here's the key: - it's seamlessly attached top and bottom to the previous and next month without having to think about overlapping parts of the week, or having gaps, or having repeated parts of the week, or greying out days that do not belong to the month which is supposed to be displayed.
In effect, it is a stream of data rather than explicitly chunked into one month or another.
And that for me is a compelling reason to go from month to month vertically rather than horizontally - because my life is not split up month by month - I work Monday to Friday and then there's the weekends. I shouldn't need to be concerned with months breaking midweek.
Example from my phone:
!enter image description here
|
stackexchange-ux
|
{
"answer_score": 0,
"question_score": 0,
"tags": "usability, mobile, android, calendar"
}
|
How do I get NDepend to do a baseline comparison on TeamCity?
I've got NDepend running on TeamCity. I want to use the baseline feature so that it only reports on violations introduced since the baseline.
On my local machine, I can store the results in a baseline folder and everything is fine. But on TeamCity, this baseline folder doesn't exist and will dissapear on each build.
One solution is to check-in my baseline into source control so that it's available when TeamCity does the build. Then, update this baseline locally and re-check-in. That's not ideal though, as it'll mean a lot of 'churn' in our version control system.
What's the best way to get 'Recent violations only' working on TeamCity?
|
NDepend v6 has just been released with built-in support for TeamCity v8 and v9.
The plugin has special support for baseline comparison in TeamCity.
See Getting Started and Walkthrough videos here.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "continuous integration, teamcity, ndepend"
}
|
Exporting Matlab data to excel, 2003 2010
I am attempting to export data from Matlab to excel, I know to do this you use `xlswrite` and I have managed to get this to work but when I increase the number of rows/lines of data I get the following error `Excel returned: Error: Object returned error code: 0x800A03EC.` I know that this error is because I am exceeding the limits of excel 2003 but I am trying to export my data to excel 2010 and my data size is not exceeding the limits of excel 2010. Matlab saves the data as a 97-2003 Worksheet which explains why I am confined to the limits of 2003. Is there a way to save the data as a 2010 worksheet so I can write all of my data to excel? Part of my code:
xlswrite(test_1,Data_1,1)
xlswrite(test_1,Data_2,2)
xlswrite(test_1,Data_3,3)
Data_1 & 2 & 3 are all 3 columns by any number of rows defined by the user
|
Excel 2003 files have the `.xls` extension. For a long time now (like 2009 or 2007) Matlab's `xlswrite` has supported the new 2007 `.xlsx` format so long as your files name specifies this. So if your file name was `"test_1.xls"` then it will save as an `.xls` file i.e. 2003. So to get the new format all you have to do is name it `"test_1.xlsx"`.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "excel, matlab"
}
|
How to make QML component (widget) adjusts according to data
I have a Widget as QML component in Qt Quick application which is to be used in various screens to display contents.
How can I use this particular QML component to adjust according to the items in it.
|
If it's a generic `Item` you can't: you have to manually set the container's size to fit its content.
The only QML components that fits their content are the `Row`, `Column` and `Grid` elements.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "qt, widget, qml"
}
|
Set flag if reference exist in other table
I would like to set the column `active` to 1 if there is a row in table register pointing to the corresponding module table. Unfortunately `m.id` is not visible in the `SELECT EXISTS` query.
SELECT *, active
FROM module m
JOIN
(
SELECT EXISTS(
SELECT 1 FROM register r WHERE m.id = r.module_id LIMIT 1
) AS aktive
);
**test.db**
CREATE TABLE module (
id INTEGER PRIMARY KEY,
tag TEXT
);
INSERT INTO module (tag) VALUES ("Module A");
INSERT INTO module (tag) VALUES ("Module B");
CREATE TABLE register (
id INTEGER PRIMARY KEY,
module_id INTEGER NOT NULL
);
INSERT INTO register (module_id) VALUES (2);
SELECT * from module;
SELECT * from register;
|
SELECT *, (SELECT EXISTS(
SELECT 1 FROM register r WHERE m.id = r.module_id LIMIT 1
) ) AS active
FROM module m;
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "sqlite"
}
|
Is it possible to pass current DataContext as ContructorParameter of ObjectDataProvider?
It would be very useful to pass DataContext as parameter for DataTemplate:
<DataTemplate>
<DataTemplate.Resources>
<ObjectDataProvider x:Key="ServiceDataProvider" ObjectType="{x:Type control:ServiceLayout}">
<ObjectDataProvider.ConstructorParameters>
/*here could be DataContext..but how?*/
</ObjectDataProvider.ConstructorParameters>
</ObjectDataProvider>
</DataTemplate.Resources>
<ContentPresenter
Content="{Binding
Source={StaticResource ServiceDataProvider}}" />
</DataTemplate>
I will use this DataTemplate in ListBox ItemTemplate. So, DataContext will be ListBoxItem bound object (type is known)
May be there are any other ways to pass parameter to constructor from DataTemplate?
|
Thanks to Magnus (MM8)/?ws=usercard-mini) for the answer here: Is it possible to pass current DataContext as ContructorParameter of ObjectDataProvider?
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c#, wpf, datatemplate, datacontext, objectdataprovider"
}
|
'vector iterators incompatible'
std::vector<Enemy*>::iterator it;
for(it;it!=tracked.end();it++){
(*it)->update(timeSinceLastFrame);
}
`tracked` is the vector:
std::vector<Enemy*>
Why am I getting this error? (please say if I haven't included enough details)
|
You never initialized the iterator.
for(std::vector<Enemy*>::iterator it = tracked.begin();it!=tracked.end();it++){
(*it)->update(timeSinceLastFrame);
}
Many implementations (such as VC++, which you appear to be using) perform checks in debug to make sure that when two iterators are compared, they belong to the same object. A default constructed iterator does not belong to any particular instance, and as such the `it != tracked.end()` check will fail with that error.
|
stackexchange-stackoverflow
|
{
"answer_score": 12,
"question_score": 3,
"tags": "c++, vector, iterator, std"
}
|
Modulus Distributing Over Multiplication?
Given positive integers a,b,c and k:
Define a function $M: \mathbb{Z^2} \rightarrow \mathbb{Z}$ as
$$M(x,y) = (x \bmod y)$$
i.e. the remainder of integer division
The following is always true:
$$a+b=c \implies M(M(a,k) + M(b,k), k) = M(c,k)$$
Under which values of k is the following true:
$$ab=c \implies M(M(a,k)M(b,k), k) = M(c,k)$$
That is when does mod distribute over multiplication?
The answer is always:
**Proof** :
Let $a = q_ak + r_a$ and $b = q_bk + r_b$ where $ 0 \le r_a, r_b < k$
$$\begin{align*} c &= ab \\\ &= (q_ak + r_a)(q_bk + r_b) \\\ &= q_aq_bk^2 + q_ar_bk + q_br_ak + r_ar_b \\\ &= (q_aq_bk + q_ar_b + q_br_a)k + r_ar_b \\\ \end{align*}$$
$$\begin{align*} M(c,k) &= M((q_aq_bk + q_ar_b + q_br_a)k + r_ar_b,k) \\\ &= M(r_ar_b,k) \end{align*}$$
$$\begin{align*} M(M(a,k)M(b,k), k) &=(M(q_ak + r_a,k)M(q_bk + r_b,k)) \\\ &= M(r_ar_b, k) \end{align*}$$
QED
|
**Hint** $\rm\ mod\ k\\!:\ A\equiv a,\, B\equiv b\:\Rightarrow\: AB\equiv ab,\ $ so $\rm\ AB\, mod\, k\, =\, ab\, mod\, k$
Yours is the special case $\rm\ A = (a\,mod\,k),\,\ B = (b\,mod\,k)$
|
stackexchange-math
|
{
"answer_score": 5,
"question_score": 4,
"tags": "elementary number theory, discrete mathematics, modular arithmetic"
}
|
How long is this part of the Boeing 737 and cockpit?

|
stackexchange-aviation
|
{
"answer_score": 3,
"question_score": -2,
"tags": "cockpit, tail"
}
|
OCaml: Converting / casting bool to int
How do you cast an ocaml boolean to an integer? (There's no `int_of_bool` function.)
|
Here's one possible implementation:
let int_of_bool b = if b then 1 else 0
The library OCaml Batteries Included has a function `to_int` in its BatBool module.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 2,
"tags": "casting, ocaml"
}
|
How to install R language version 4 in AWS EMR - Amazon linux 2
We have an AWS EMR cluster. By default it comes with
Amazon Linux version 2
R version 3.4.3 (2017-11-30) -- "Kite-Eating Tree"
I like to install latest R version 4. _._
Tried following :
yum -y install
yum -y install R
But it doesn't upgrade R version to v4.0. It only offers to upgrade it to `3.4.3-1.amzn2.0.1`
Amazon Linux 2 - uses EPEL version 7. EPEL v7 doesn't seem to have R v4. But EPEL version 8 has R v4
I am planning to install R from source. But like to know if this is a way to install binary.
Is there any option to install latest R binary on AWS Linux 2 ?
|
Found a way to install the R v4 binary from AWS extras repo
sudo amazon-linux-extras install R4
In future, if some one is hunting for AWS Linux specific software package., this command list the packages that can be installed from AWS extras
amazon-linux-extras list
Reference - Amazon Linux User Guide
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "r, amazon web services, amazon emr, amazon linux"
}
|
Creating Win32 events from c#
I'd like create a kernel(aka named events) from C#.
Do I have to interop services and wrap the native CreateEvent function or is there already a .NET class that does the job?
The function that I need to run should be something like this: hEvent = CreateEvent ( NULL , false , false , "MyCSHARPEvent" );
This should notify all procs that probing forMyCSHARPEvent about the event.
If there is a need to wrap the function, how would I translate the SECURITY_ATTRIBUTES struct from C# to win32?
|
Take a look at the EventWaitHandle class. It's supported from .Net 2.0 onwards and allows creation of named events. It also supports setting event security, depending on which constructor you use.
|
stackexchange-stackoverflow
|
{
"answer_score": 20,
"question_score": 13,
"tags": "c#, events, interop"
}
|
Disable file digests in Sprockets compile task
**I am not using Rails.**
I'm using sprockets' built in compiler task **SprocketsTask**. The source can be found here.
I want to disable the file digests that are appended to each file. So _application-e7aa01ce5sdf9e6sdfdssd8sdfds8bb.css_ will just become _application.css_.
There seems to be no documentation that I can find, and I've looked through the source quite a lot. I'm aware that I could remove the digest after the file has been created, but I thought i'd see if anyone had any better ideas first.
Thanks in advance.
|
# Rakefile
require "sprockets"
assets = Sprockets::Environment.new
assets.append_path "app/assets/javascripts"
task :assets do
assets["application.js"].write_to "output/assets"
end
$ rake assets
**with filters**
# Rakefile
require "sprockets"
assets = Sprockets::Environment.new
assets.append_path "app/assets/javascripts"
LOOSE_APP_ASSETS = lambda do |path, filename|
filename !~ %r~app/assets~ && !%w[.js .css].include?(File.extname(path))
end
precompile = [LOOSE_APP_ASSETS, /(?:\/|\\|\A)application\.(css|js)$/]
task :assets do
assets.each_logical_path(*precompile).each {|path|
assets[path].write_to "output/assets/#{path}"
}
end
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "ruby, rack, sprockets"
}
|
MVC 5, EntityFramework 6 CF, Identity (authorization)
I decided to add authorization by means of Identity added in MVC 5.
In the project there was one context and use EF CodeFirst -
public class PostDBContext : DbContext
I added authorization with Identity EntityFramework use, but there the context -
public class MyDbContext : IdentityDbContext<ApplicationUser>
As it will be more correct: to integrate my old context with a context used for authorization, thereby to change a class from which it is inherited and to transfer everything to one?
Or to leave two contexts?
And what change of my context with DbContext on IdentityDbContext will entail? I use one database. I checked and both options work. Whether will be then difficulties? Thanks!
|
Why not using 1 context, I created a MVC 5 application a few weeks ago, and was wondering the same thing, but it is so easy to just use 1 context. And why not? Everything used to access it should be independent of it...
My tip, use 1 context :)..
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "asp.net mvc 5, identity, entity framework 6"
}
|
Seeking Shuttle Orbiter Ferry Flight log
Can anyone provide a link to a detailed log of shuttle orbiter ferry flights? I'd like to know dates of all overnight stops. I can find beginning and end dates for each ferry, but info on the stops is sketchy.
|
This information can be found in a document produced by the Historic American Engineering Record as part of their effort to document the Space Transportation System. The pdf document is located here (too long to post the log).
|
stackexchange-space
|
{
"answer_score": 3,
"question_score": 5,
"tags": "space shuttle, history, reference request, transport, shuttle carrier aircraft"
}
|
Best way of getting path to "Application Data" directory?
There are several possible ways of getting the path to the application data directory:
* using the `%APPDATA%` environment variable
* calling `SHGetFolderPath` with `CSIDL_APPDATA`
What is the best way to get the path from within an program? Are there any gotchas when I use the environment variable?
Which method is safest across XP, Vista and upcoming versions?
|
I would suggest that calling `SHGetFolderPath()` is the most appropriate, and portable method; the alternatives, such as reading an environment variable, or (worse) trying to extract it from the registry are likely to trip you up in the future.
Raymond Chen has an article explaining why pulling such paths from the registry is a bad idea.
|
stackexchange-stackoverflow
|
{
"answer_score": 12,
"question_score": 12,
"tags": "winapi, path"
}
|
How to i change the time stamp using php mysql
My friend using phpfox social network. He intergrating the phpfox with his own application. In phpfox site they are using the time stamp like this `1297503935` (DB data type : int(10) ).We wre not able to find what way ther are using to get num as a time stamp . Is there is any way to change this integer into normal time stamp.
|
Check documentation for php date
$timestamp=1297503935;
date ( DATE_RFC822 , $timestamp );
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php"
}
|
Cant find Text Element in Headless Mode Selenium C#
I am simply trying to get certain text in headless mode that I can get in windowed mode. In headless mode the string is just "" (Empty).
In windowed mode it works perfectly fine using the code below:
string actualStatusText = p_Util.Driver.FindElement(By.XPath("html/body/div[3]/div/table/tbody/tr[1]/td[4]")).Text;
//body > div.container.body-content > div > table > tbody > tr:nth-child(1) > td:nth-child(4)
//html/body/div[3]/div/table/tbody/tr[1]/td[4]
The comments show the two different ways I can get the text in windowed mode tested in Headless but doesn't work. (Tried both CSS and XPath)
|
Using .getAttribute("innerText") fixed the issue!
Thanks to @RyanWilson in the comments.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "c#, selenium, selenium webdriver, selenium chromedriver, browser automation"
}
|
CMake name of package variables
On CMake (version 3.1.1 on OS X Yosemite), the variables set by different packages using `find_package` seem to follow different conventions.
With `find_package(OpenGL)`, the variables `OPENGL_LIBRARY` and `OPENGL_INCLUDE_DIR` get set (case-sensitive).
But with `find_package(OpenCV)`, variables with those names remain empty, but `OpenCV_LIBS` get set.
What is the right convention, and is there a way to force CMake to use it, on any platform?
|
The right conventions are documented here. For example, a package named `Foo` should make its libraries available in a non-cached `Foo_LIBRARIES` variable and its include directories in a non-cached `Foo_INCLUDE_DIRS` variable.
Because it is entirely up to the maintainer of a CMake find module to follow these conventions, there is no way to enforce them.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "cmake"
}
|
Get internet requesting application android
Hi I want to make an app in which I m monitoring the internet traffic in android.is there a way I can find which application is accessing internet and control it
|
You can monitor Internet traffic using `TrafficStats`. Whether or not there will be per-app (actually, per-UID) statistics will vary by device.
You absolutely cannot "control it".
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "android"
}
|
What is the bigO of an algorithm that doubles with each added n?
Just something I observed with some code I wrote:
n = 24, time = 3s
n = 25, time = 6s
n = 26, time = 12s
n = 27, time = 24s
n = 28, time = 48s
Just looking at this number, what is the bigO of this code? I wanna say 2*n, but we know that the constant does not matter. Is it just O(n)? It doesn't look like it.
Edit: 2^N?
|
So, you mean `time(n) = time(n-1) * 2` ?
Yah, that's **`time(n) = 2^n`**
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 2,
"tags": "algorithm, big o"
}
|
Set lastrow variable as 3 lines offset from the last occupied row
I am trying to set the variable lastrow. I want the value of it to be 3 rows less than the last occupied row of my excel sheet. To be more clear, my current last occupied row is row 50. But I want the lastrow variable to be set as 47. My code so far.
lastrow1 = ws2.Range("A" & Rows.Count).End(xlUp).Row - 3
|
Four things.
1. Ensure you are working with the expected workbook e.g. ThisWorkbook
2. Ensure ws2 is the sheet you intend to work with
3. Ensure column A is the column you want to use to find the last row
4. Check that the lastrow is >= 4 before attempting to remove 3.
Code for check:
lastRow1 = ws2.Range("A" & Rows.Count).End(xlUp).Row
lastRow1 = IIf(lastRow1 < 4, 1, lastRow1 - 3)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "vba, excel"
}
|
Turing Machine divisibility by 6
I need to design a TM to check if a binary number can be dividied by 6. I don't know how to design it.
Thanks
|
As mentioned in a comment to your question, a finite automaton should do:
* There are $6$ states altogether
* State "$0$" is the initial state
* State "$0$" is also the accept state
* All other states are reject states
* The input should be injected MSB first / LSB last
* Please note that in essence `NextState = (2 x CurrState + InputBit) % 6`
* * *

{
if [ -e "$file_name" ]
then
IFS=''
while read line
do
curr_rec=$line
echo ${curr_rec:3:4}
done < "$file_name"
else
echo "error"
fi
}
file_name="$1"
get_file_totals
|
It would be more efficient to rewrite this, thereby avoiding the issue in the first place:
#!/bin/ksh
get_file_totals()
{
if [ -e "$file_name" ]
then
cut -c4-7 "$file_name"
else
echo "error" # consider stderr by appending >&2
fi
}
file_name="$1"
get_file_totals
|
stackexchange-unix
|
{
"answer_score": 1,
"question_score": 1,
"tags": "shell script, scripting, ksh, variable substitution"
}
|
VirtualizingStackPanel not aligning menu items vertical on applying theme
Before applying WPF theme - BureauBlue.xaml theme, I can see menu items aligning vertically with the below code:
<Menu.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientation="Vertical"/>
</ItemsPanelTemplate>
</Menu.ItemsPanel>
But the same logic is aligning the menu items horizontally once I apply the theme.
Could you please assist me in resolving this?
|
I am able to solve the problem.
I am supposed to use VirtualizingStackPanel to display the menu items vertically.
In the theme style for Menu, StackPanel orientation is coded as Horizontal.
I just copied the code from the theme xaml and created a new style where the only change is Orientation from Horizontal to Vertical.
For the Menu, I have applied the new style as a DynamicResource.
It worked.
Thanks...
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "wpf, xaml, themes, menuitem, virtualizingstackpanel"
}
|
onClick starting another activity
private OnClickListener startListener = new OnClickListener() {
public void onClick(View v) {
startService(new Intent(SimpleServiceController.this,
SimpleUpdateService.class));
startActivity(new Intent (this, AlarmManagerListening.class));
}
};
Problem occur at startActivity execution. It doesnt allow me to start an activity. May I know what's wrong with the code?
|
The error you are facing is because of the use of **this** in `startActivity(new Intent (this, AlarmManagerListening.class));`. Since you are instantiating a new instance of OnClickListener **this** refers to the instance of the listener and not to your service which is required as a Context. By utilizing `SimpleServiceController.this` you specify that **this** refers to your controller which is a subclass of Context like required by the `new Intent()` method.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -1,
"tags": "android"
}
|
Adjusting column width according to Screen Size in DataGridView (WinForms)
I have achieved the following till now (Columns are NOT resizing automatically as per the size of the application):
!Static Column Widths
I want to achieve the following so that columns resize dynamically whenever user changes the size of the application:
!Dynamic Column Widths
I am using DataGridView in .Net 2008
|
Specify a value for `DataGridViewAutoSizeColumnsMode`:
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
You can set it in the grid properties at design-time too:
!enter image description here
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "c#, .net, winforms, datagridview"
}
|
Kotlin - How to know if editText lost focus
In my app I need to be able to catch if an `editText` lost focus, I've found how to do it in java but I'm not quite able to find how to do it in kotlin.
The Java answer I found was this one:
EditText txtEdit = (EditText) findViewById(R.id.edittxt);
txtEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
// code to execute when EditText loses focus
}
}
});
Can anyone help me convert this to kotlin?
|
This way
// Class level
lateinit var editText: EditText
// Method onCreate/onCreateView
editText = findViewById(R.id.whatever)
editText.setOnFocusChangeListener { view, hasFocus ->
if(!hasFocus) {
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "android, kotlin"
}
|
with cte union all select
I have two tables **Arrears** and **Invoices** . I am trying to do the following:
;with Acc.. as ( select ....from ....)
select ..... from Arrears
UNION ALL
select ... from Invoices
the problem is that results are like :
A header | B header
---|---
row | row
row | row
the output should be like this:
Table | B header | c header
---|---|---
Arrays | row | row
Invoices | row | row
|
You could add a string literal to each query to indicate what table it came from:
SELECT 'Arrays' AS table_name, *
FROM arrays
UNION ALL
SELECT 'Invoices' AS table_name, *
FROM invoices
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "sql, common table expression, union all"
}
|
Reporting Services across multiple sub-sites
I have several sub-sites on our new Sharepoint site.
We are moving our reporting services reports from a set up using an old single `SSRS` web portal, into Sharepoint.
What is the recommended structure to use?
1. A document library within each sub-site for SSRS reports.
2. A single library at the sub-sites root.
If we go for option two how do we then reference relevant reports within each sub-site?
|
Since you added the information that you would like the changes and updates to filter through to all instances of the report in other sites, I would recommend a centralized approach.
You can choose to expose the document library that holds the reports (.rdl) file and then users can open the report, or you can add a report viewer web part on a page and have it automatically render the report (the path to the report file is in the web part properties).
I would put the reports in document library at the site collection root and then have pages in my sub-sites with the report viewer web part loaded on them. When you swap out or update the report in the central library, all report viewer web parts that are viewing the report would be automatically updated.
|
stackexchange-sharepoint
|
{
"answer_score": 1,
"question_score": 1,
"tags": "sharepoint enterprise, 2013"
}
|
argv: Sanitizing wildcards
I was working on an example in the K&R C book where it asks you to essentially build an RPN calculator that takes input through command line arguments. My solution essentially iterates through the given arguments and spits out the answer, but I noticed something:
If I were to give the multiplication character (an asterisk) `'*'` without single quotes, gcc assumes that to be a wildcard input, so my input of
$./rpn 5 10 *
gives me an output of
read 5
read 10
read rpn
read rpn.c
= 0
Wrapping the asterisk with single quotes remedies the issue
$./rpn 5 10 '*'
read 5
read 10
read *
= 50
My question is would there be a way to sanitize input so that my program does not require the asterisk to be wrapped in single quotes, or is this behavior caused by something more fundamental (e.g. Linux/POSIX/UNIX binary execution and argument handling)?
|
The shell is expanding the glob before executing the program. You quote the glob not because of GCC, but because of the shell. If you don't want this behavior then use a shell that does not honor globs.
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 9,
"tags": "c, linux, shell, gcc, glob"
}
|
what happens when two exceptions occur?
what will the program behave when they have two exceptions. And none of them have been caught yet. what type of handler will be called . lets say both the exceptions were of different type. i apologize if i am not clear but i feel i have made myself clear enough. thank you!!!
what if the try block throws an exception and try block is exited which destroyes all the automatic variables.Lets say one was an automatic object and its destructor again threw an exception.Now we have two uncaught exception.My question is based on this fact. thank you!!
|
It depends entirely on the language. However, in all the languages I know there can't _ever_ be multiple exceptions at the same time (in the same thread). If an exception has been thrown, it travels up the call stack until it's caught, with no code executing during this time. If the exception is not caught, the program crashes before another can be thrown. If it is caught, the exception is no longer "active" and if the handler throws a new exception, the old one is forgotten.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 5,
"tags": "exception"
}
|
How to reduce CPU usage in Windows?
If I use
import os
os.nice(10)
The error is
AttributeError: 'module' object has no attribute 'nice'
`nice` is probably only for Linux systems, so how do I reduce the CPU resources available to my program?
It checks whether a particular process is running, and if it is not, then it executes it.
My code looks like this:
import subprocess, psutil
proc = subprocess.Popen(['flux'])
pid = proc.pid
while 1:
if not psutil.pid_exists(pid):
proc = subprocess.Popen(['flux'])
pid = proc.pid
I would like it to use the minimum possible resources.
|
You're _busywaiting_ ; that loop will execute as fast as it can. Nice'ing the process (even if that API existed on Windows) would not help. It would just let other processes go first if they wanted to use the CPU, but your program would still get to eat up all the remaining cycles.
A simple way to fix this is to sleep a bit between checks:
import time
...
while 1:
time.sleep(1)
if not psutil.pid_exists(pid):
proc = subprocess.Popen(['flux'])
pid = proc.pid
But a better way is to just block until the program finishes. You can do that like so:
import subprocess
while True:
subprocess.call(['flux'])
Since `subprocess.call` blocks until the process exits, your code won't spend any cycles during this time.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "python, resources, nice"
}
|
How do I ignore the header row with datatables targets?
I have a table where I want to enable clicks on the second column (column 1) as follows:
"columnDefs": [
{
"className": resetclass, "targets": [1]
},
]
This adds a class to the TDs in that column which I track and then process clicks. But I don't want this applied to the header row because I still want the DataTables sort click to work. What is happening is the added class action click it taking precedence over the sort click. Is there a way to target column 1 EXCEPT for the header (th) row?
Thanks, in advance.
Solution for others: Add addClass command to createdCell
{
'createdCell': function (td, cellData, rowData, row, col) {
$(td).attr('data-id', rowData.id);
$(td).addClass(resetclass);
},
'targets': 1,
},
|
Maybe columns.createdCell will work for what you want.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "jquery, datatables"
}
|
Can you have multiple evaluations in your WHEN clause?
Can you have multiple evaluations in your WHEN clause?
For example is there a way to do something like this:
when (x == "Open" and y == "Ready") $ do...
I can get a single condition to work, but what if I need both to be true?
|
How about something like
when (x == "Open" && y == "Ready") $ do
...
`&&` is just a normal infix operator defined as
True && a = a
False && _ = False
Notice that with laziness this has exactly the same short circuiting properties we get in other languages!
* * *
On a totally separate note, instead of using strings to represent different states the Haskell-ish way would be to define your own type
data StateOfFoo = Ready
| Open
| Closed
| ...
deriving(Eq)
and then use `x == Open && y == Ready` for example. This way you make it clear in the types what you expect `x` and `y` to be.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": -1,
"tags": "haskell"
}
|
Does a voice coil vibrate at the same frequency as the source sound file?
As a disclaimer I know very little about this so I'm probably describing this in a very imprecise way. Say you generated a sine wave on your computer at 800Hz and played it through a speaker. Would the speaker also vibrate at 800Hz?
|
I would expect so, assuming the speaker is capable of vibrating with the same speed.
As far as I know each speaker has a range in which it can vibrate (usefully). Mostly bigger speakers are better suited for vibrating at lower speeds (and having more 'pressure', more air that is moved), small speakers can resonate faster (thus higher frequencies).
That is why for lower frequencies you need bigger speakers, and for higher frequencies smaller speakers will do.
|
stackexchange-electronics
|
{
"answer_score": 9,
"question_score": 6,
"tags": "resonance, frequency response"
}
|
parse RGB values from a string with php
Is there a way to parse multiple RGB values from a string? In what way should the colours be coded?
Eg.
`$string = "foobar [rgb:123abc] some other text and another color: [rgb:ffeecc]"`
I want `[rgb:xxxxxx]` to be replaced with something like `<div style="background: #xxxxxx;"> </div>`
|
You could use this regex to pick up the pattern...
/\[rgb:([0-9a-f]{6})\]/i
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "php, parsing, rgb"
}
|
How to combine tabular form and text area in one page?
I have a page, containing tabular data(region type SQL Query (updateable report)). It only updates existing rows using Submit. The wizard created ApplyMRU process. It works fine. But now I would like to place a text area in the same page, which will be bound to different table and will get updated once the same Submit button is pressed. How can I accomplish it?
I've created item for text area, but not sure what type of source I should set. Database column doesn't let me specify table. Also I guess I need a second after submit process, but not sure which one.
|
Keep your existing ApplyMRU infrastructure for the tabular form, and just define a second PL/SQL process that executes during page submit that will do whatever it is you want with your text area, eg:
insert into notes (id, text) values (:P1_ID, :P1_TEXT_AREA);
Take note of the order of the processes, as you may want to execute one before the other.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "oracle apex"
}
|
Are contraception effectiveness percentages per-user or per-use?
The efficacy of contraception methods is typically given as two percentages: _typical use_ , and _perfect use_.
For both of these, is the denominator of the percentage the number of **couples** who used the contraception method, or the number of **instances of sexual intercourse** during which it was used?
In other words, if a contraceptive is 98% effective, does that mean:
* 2% of couples who used this method ( **any number of times** ) got pregnant, or
* Of all the **individual instances** of sexual intercourse during which this method was used, 2% of them resulted in pregnancy?
|
Neither.
The percentages given are the percentage of couples using that method who will conceive **over a year**. So if 100 people use that 98% method, 2 will get pregnant each year.
Here is a page from the National Health Service in the UK that explains this as well as providing some numbers for some methods.
|
stackexchange-health
|
{
"answer_score": 6,
"question_score": 3,
"tags": "sex, effectiveness, contraception"
}
|
False disk usage report on a btrfs root partition
I checked my disk usage using `btrfs filesystem df /` and it shows high disk usage like so 
|
Eventually I figured it, because of BTRFSs concept of "free space", programs like filelight fail to report the correct usage, and in fact, I do use space as `btrfs fi df /` reports. For example, here's dolphin report ;
}
<li><a href="index.html"><img id="btnicon"src="
|
Since the image is in inside `a` you can do this:
li a:hover #btnicon {
transition: .7s ease-out;
-webkit-filter: brightness(200%);
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "html, css, hover"
}
|
Canvas elements cut off at the
When I place a square on the canvas at 0,0 coords the top left is cut off:
var canvas = document.getElementById('c');
var context = canvas.getContext('2d');
context.strokeStyle = 'blue';
context.rect(0, 0, 200, 100);
context.fillStyle = 'yellow';
context.fill();
context.lineWidth = 7;
context.strokeStyle = 'black';
context.stroke();
<canvas id="c" width="500" height="500"></canvas>
Why is this?
|
It's because half the stroke is inside the rect.fill and **the other half of the stroke is outside the rect.fill**.
Kind of like css borders, you must account for them when sizing/positioning.
In canvas's case, the stroke is always half-in / half-out the object.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "javascript, html, html5 canvas"
}
|
Pronunciation of -phemism
I know how to pronounce euphemism, which I ask NOT about. Yet I only encountered its antonym dysphemism today. Though I still don`t understand phonetic symbols (see here), am I right that the root _-phemism_ must be pronounced identically in both words? I see that the prefixes differ.
If so, is ODO's audible pronunciation clip wrong? I hear an additional NUH sound between `fe` and `mism`, which I would try to transcribe as: diss-`phe`-NUH-`mism`.
Footnote: I'm using Firefox and tried to link to that pronunciation clip for your convenience, but I can't extract a link. Please advise or edit this if you can.
|
You are correct. There seems to be some mistake in ODO's audio clip. However, the phonetic symbols have been listed down correct.
> Euphemism : /ˈjuː **fəmɪz(ə)m** /
> Dysphemism : /ˈdɪs **fɪmɪz(ə)m** /
For the correct pronunciation, you can refer to this link
|
stackexchange-ell
|
{
"answer_score": 3,
"question_score": 4,
"tags": "pronunciation"
}
|
Why should I connect the red/positive terminal first when jump starting?
So, it's fairly popular consensus online that it's red/positive clips to the positive/red posts, then the black/negative clip to the frame
One site mentions sparks, but you'll still get a spark when connecting black to frame. If positive is the potential shouldn't it be keep disconnected as long as possible?
Why do I connect the positive first?
|
Conventional lead acid batteries produce hydrogen gas as a byproduct of the charging process. This gas tends to collect in and around the battery. As you are aware making the final connection can generate a substantial spark. By making the frame connection the point where the spark occurs it is far enough from the hydrogen gas to avoid an explosion.
|
stackexchange-mechanics
|
{
"answer_score": 11,
"question_score": 14,
"tags": "battery, jump start"
}
|
How to persist the workflow from a CodeActivity or NativeActivity?
I have an activity, and would like to save the state (persist) the workflow so its state will save to the database. Can you please show me or redirect me how this may happen?
|
There's a Persist activity in the toolbox under Runtime.
I don't think you can Persist from inside an activity as the workflow must be in a persist-able state before it can persist.
I prefer to set `_workflowApplication.PersistableIdle = WorkflowApplicationPersistableIdle;`
Then put in a Delay activity where you want to trigger the Persist. The advantage is that you can do stuff in `WorkflowApplicationPersistableIdle()`. e.g
private PersistableIdleAction WorkflowApplicationPersistableIdle(WorkflowApplicationIdleEventArgs e)
{
if (_canWeUnloadThisWorkflow)
{
_workflowController.RemoveWFManagerFromList(this);
return PersistableIdleAction.Unload;
}
return PersistableIdleAction.None;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "workflow foundation 4"
}
|
Storing time using default in mongoose schema , saves the same time again and again
I have a mongoose schema which includes:
dateTime: {
type: Date,
default: moment().tz("Asia/Karachi").format(),
},
But when I am saving records in MongoDB its storing the same time again and again.
Record One saved: enter image description here
Record Two saved:
enter image description here
|
By specifing a `default` value this exact value will be used for all the records. You probably want to define a `default` function instead:
dateTime: {
type: Date,
default: () => moment().tz("Asia/Karachi").format()
},
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "node.js, mongodb, mongoose, mongoose schema"
}
|
Regex "NOT" exists Pattern
I have a regular expression which matches words which do NOT start with "DEF".
Now I would like to modify it to following three cases:
1. Does NOT END with "DEF"
2. Does NOT Contains "DEF"
3. Does NOT Equal TO "DEF"
what should I modify the string patterns ?
Regex pattern Match word which does NOT start with word "DEF": ^(?!DEF).*$
match word : ADEFCCC
Does Not Match : DEFXXX
|
Does not end with DEF: ^.*(?<!DEF)$
Does not contain DEF: ^((?!DEF).)*$
Does not equal DEF: ^(?!DEF$).*$
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 3,
"tags": "c#, regex"
}
|
"Compile error: Type mismatch"
I have simple VBA program which requires checking a range and telling user whether there are any empty cells -if so, which cells.
The problem line is this:
Dim outputsrange("inputnum+1:inputnum+outputnum") As range
The function:
Sub check()
' Goal: check if there are any entry truth table cells for outputs
Dim outputsrange("inputnum+1:inputnum+outputnum") As range
If IsEmpty(outputsrange) Then
MsgBox ("The following cells are empty:" & vbNewLine & emptycell) ' what's the property for these empty cells
End If
End Sub
This gives error:
> Compile error:
>
> Type mismatch
How do I fix this type mismatch?
|
You could try something closer to this.
Dim outputsrange As range
Set outputsrange = Range(inputnum + 1 & ":" & inputnum + outputnum)
With inputnum as 1 and outputnum as 5 that should set outputsrange as rows 2 through 6.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "vba, excel"
}
|
Failed to connect to oracle SQL Plus
I tryed to connect to SQL Plus as the admin "System", I'm sure that the password I wrote was correct but the connection failed. I also tried to connect with Scott/tiger but it failed as well.
What can be the problem, and how to resolve it please ?
this is what I get after trying to connect using both System and Scott:
!enter image description here
|
I succeeded to connect after these instructions in cmd:
SQL> connect sys/manager as sysdba
Connected.
SQL> shutdown immediate;
ORA-01109: database not open
Database dismounted.
ORACLE instance shut down.
SQL> startup
ORACLE instance started.
.....
ORA-01172:...
ORA-01151:....
SQL> recover database;
Media recovery complete.
SQL> alter database open;
Database altered.
SQL> exit
|
stackexchange-dba
|
{
"answer_score": 0,
"question_score": 0,
"tags": "oracle, sqlplus"
}
|
How to swap non-copyable elements in a vector?
I would like to swap `String` elements of a vector
let mut v_sa: Vec<String> = vec![];
...
let temp_a = v_sa_ib[j];
v_sa_ib[j] = v_sa_ib[j+1];
v_sa_ib[j+1] = temp_a;
It works with integers but not with `String`s. I also tried to create a second vector `temp_b` (same type of `temp_a`) and to populate it instead of swapping but i got always the same error: `the type of this value must be known in this context`.
How can I fix it?
|
You can use the `swap()` method of `Vec` to swap two elements directly:
v_sa_ib(j, j+1);
There is also a generic swap function called `std::mem::swap` but it is difficult to use here because obtaining two mutable references two different elements of the same `Vec` is quite involved.
The reason why it worked with integers is that integers implement the `Copy` trait, so Rust can automatically create new copies.
|
stackexchange-stackoverflow
|
{
"answer_score": -1,
"question_score": 0,
"tags": "string, vector, rust, swap"
}
|
Is it grammatically correct to say “Utilities Operations”?
My department is titled _Utilities Operations._ We run the utilities (heating, cooling, power) for a public university.
It seems to me that the correct title should be either _Utility Operations_ or _Utilities Operation._
|
As already hinted in the comments and by the capitalization of the two words, **Utilities Operations** is a proper noun. At least the person who named it thought so. As a proper noun grammaticality does not really apply.
As Max Williams already provided, Utility Operations is the most used of all combinations of pluralization as evident in this ngram.
Since you however ask specifically for the grammaticality of the term that does not help you. Besides the arbitary spelling possibilites of a proper noun the combination is more or less a compound noun (I cannot name an English compound noun with both parts in plural right now). Most of them are pluralized at the last word (Cambridge).
So, if you want to use the two words in a sentence without referring to your department the best possibility might be **utility operations**.
|
stackexchange-english
|
{
"answer_score": 0,
"question_score": 0,
"tags": "grammatical number"
}
|
Spring pageable cache key for each page
I am trying to do something like following
@Cacheable(value = ACTIVE_DATA_CONFIGURATION_CACHE, key = "#tenant.id.concat('-').concat(#pageable.page)")
public Page<DataConfiguration> findAllByTenant(final Pageable pageable, final Tenant tenant) {
}
exception
org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'page' cannot be found on object of type 'org.springframework.data.domain.PageRequest' - maybe not public?
at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:224)
|
For your use case try using `KeyGenerator`
@Cacheable(value = "doOneThing", keyGenerator = "CustomGenerator")
Something like this:
public class CustomGenerator implements KeyGenerator {
public Object generate(Object target, Method method, Object... params) {
String code = "UNIQUE_CODE"; // implements logic from params
return code;
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "spring, spring data, spring cache"
}
|
MPI Java under windows
Ive been working with MPI and OMP parallel solutions in C as an assignment to school. I liked programming that way but im more into java. I did a little research and found lots of wrappers and API's but all of them were quiet old. So my question is whats the best "tool" for working with MPI OMP in java nowadays. Im a win user.Just saying that becase i found some solutions which had poor windows support
thx in advance
|
The most relevant and pain-less MPI Java implementations for you are: FastMPJ and MPJ Express. FastMPJ is a commercial product with free TCP/IP version whereas MPJ Express is an open source library.
Both have full support in Windows, as they are pure (non-wrapper) Java implementations. Both have extensive documentation on running on Windows, and using IDEs such as Eclipse, Netbeans and JCreator, check out their user's guide and documentation.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "java, windows, api, mpi"
}
|
Xcode Auto Layout with custom view
I am working on my first project using Auto Layout and custom views. My question is this:
I created my custom view in Interface Builder then added constraints to stretch the view if needed which is working the way I want it to, however, consider the following code snippet from my custom view class -
// MyCustomView
-(id)initWithCoder:(NSCoder*)decoder
{
self = [super initWithCoder:decoder];
if(self != nil)
{
CGFloat layerWidth = self.bounds.size.width;
CGFloat layerHeight = self.bounds.size.height;
}
return self;
}
This code return the size set in IB. My drawing code relies on the new width and height (if the view has been stretched) but I don't know how to retrieve them.
|
First, that code is utterly silly because you are creating variables `layerWidth` and `layerHeight` and throwing them away, which is pointless.
Second, `self.bounds.size` is always the view's width and height. However, it is pointless to ask about this in `initWithCoder:`, which (as you have rightly seen) happens long before the view is put into the interface and even longer before the auto layout takes place that resizes it. If your drawing code relies on the bounds size, then retrieve the bounds size _when you draw_. If you need to draw again because the view has changed size, and if this is not happening all by itself, then implement `layoutSubviews` to tell the view that it needs to be drawn again.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ios, xcode"
}
|
How to set a HashSet<string> as a Value in Dictionary?
I have an array of strings called "subjects". I'm trying to fill my dictionary and using some class as key and HashSet "string" as Value, but can't make it properly and receive an error "cannot convert string[] to System.Collections.Generic.HashSet"string"". So what i need to put in my dictionary to make it work?
Dictionary<Student, HashSet<string>> studentSubjectDict = new Dictionary<Student, HashSet<string>>();
studentSubjectDict.Add(Student11, subjects);
|
As @Jeron Mostert said, `new HashSet<string>(subjects)` or `subjects.ToHashSet()` solve this problem
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c#, dictionary, hashset"
}
|
VBA - Listbox and Data
I have a listbox called listbox1 that shows me the data in sheet1 but the problem is that it doesn't show me all of the data sometimes i have 3000 line of data and it shows me anlo first 50 line this is the code i am using if someone can help please :
ListBox1.List = Sheets("Sheet1").Range("A1:F3000").Value
|
if you need datas from one column only then you'd go:
ListBox1.List = Application.Transpose(Sheets("Sheet1").Range("A1:A3000")) '<== change "A"s in Range("A1:A3000") to wanted column index
otherwise if you want to list data from more columns you have to go like this:
Private Sub UserForm_Initialize()
Dim Data As Variant
...
Data = Sheets("Sheet1").Range("A1:F3000")
With UserForm1.ListBox1 '<== change it with actual UserForm and ListBox names
.ColumnCount = 2
.List = Data
End With
but you'd be able to select one or more (up to `ListBox` `MultiSelect` property setting) _entire_ row, and not single "cells".
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "vba, excel, userform"
}
|
Property of permutation matrices
I need the formal proof of this fact. I define the permutation matrix in this way
given $\pi$ a permutation of $n$ elements its permutation matrix is: $${P}_\pi=\begin{bmatrix} {e}_{\pi_{1}} \\\ \vdots \\\\{e}_{\pi_{n}} \end{bmatrix},$$ where ${e}_i$ is the row vector with $1$ in the $i$-th position and $0$ in every other position. How can I prove that $${P}_{\sigma}^T{P}_{\pi}^T={{P}_{\sigma\circ\pi}}^T\quad?$$
thanks!
|
Observe that, for every $j=1,\ldots,n$, $$ P_\pi e_j=e_{\pi^{-1}(j)}. $$ Hence $$ P_\pi P_{\sigma}e_j=P_\pi e_{\sigma^{-1}(j)}=e_{\pi^{-1}(\sigma^{-1}(j))}=e_{(\sigma\circ\pi)^{-1}(j)}=P_{\sigma\circ \pi}e_j. $$ Thus $$ P_\pi P_{\sigma}=P_{\sigma\circ \pi}\quad\text{or}\quad P_\sigma^TP_{\pi}^T=P_{\sigma\circ \pi}^T. $$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "linear algebra, matrices, matrix equations, matrix calculus"
}
|
LINQ: Stop lazy loading or force properties to be loaded
Consider a report in Windows forms which uses Linq to Objects as a datasource.
I have an entity named `Loan` with an association named `Customer`. The problem is that when I try to access the `.Customer` property in a report, it returns null or empty string.
I suppose this is because of lazy loading but I'm not sure to be honest. Is there a way to fix this issue?
|
In your case, closing the data context leads to null values for data that was not retrieved through a join. Use the DataLoadOptions to explicitely tell the context to perform a join:
using(var yourDataContext = .....)
{
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<Loan>(loanRecord => loanRecord.Customers);
yourDataContext.LoadOptions = dlo;
//write code to retrieve data
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "winforms, linq to sql"
}
|
Validation image for URL/Domain using Regex? rails 3
I want validate a url that is a image e.g.:
or any url or domain that end with a picture format:
I have this regex:
^[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$
You can see <
**But this regex don't filter extensions .jpg .jpeg .gif .png**
**I want only allow a url or domain that end with a picture.**
|
Well, you could just check the ending of the string. You don't even have to use regex here, but here we go.
\.(png|jpg|gif)$
<
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "ruby, regex, ruby on rails 3"
}
|
writing proc avg in tcl script in NS2
I want to calculate avg of { energy_level ,number of nodes & traffic's data on nodes } by one mobile sink in the network with 5 static nodes. I have to calculate this avg with proc in tcl script code not with awk code.
Please help me
|
If you have collected a list of values that you want to compute the average of, use this procedure to do the computation:
proc ArithmeticMean {listOfValues} {
set length [llength $listOfValues]
if {$length == 0} {
return 0.0
}
set sum [::tcl::mathop::+ {*}$listOfValues]
return [expr {double($sum) / $length}]
}
The summing of the values uses the `+` “operator command” with expansion syntax, and is the cheapest way of adding them all together.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "tcl, proc, ns2"
}
|
Footer gap appears when little content
So I'm really confused.. my websites footer sits perfectly on the homepage, however as soon as you load content into it for the other pages (via jquery) the footer instantly gains a huge gap at above it.. It isn't until I fill it with loads of text that it finally starts to fill the gap and not keep pushing the gap further and further down the page.
< (please note only "Home, What We Do & Sites" work on the navigation)
I know the coding is really messy, but surely it makes no sense.. why is there a threshold to get past before that gap stops appearing?
|
Try removing the setting below:
#holen_wrapper {
width: 922px;
/* height: 100%; */
margin-right: auto;
margin-left: auto;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "jquery, html, css, web"
}
|
\cal gives "Undefined control sequence" error
I've used `\cal` throughout my document and now when I go to switch the document class the `\cal` is giving me a "Undefined control sequence." error. Any thoughts on why the document class would make a difference?
|
You could define `\cal` by yourself, such as for example the `article` class does. In the `minimal` class it's undefined, and this way you can fix it:
\documentclass{minimal}
\makeatletter
\DeclareRobustCommand*\cal{\@fontswitch\relax\mathcal}
\makeatother
\begin{document}
$\cal ABC$
\end{document}
!enter image description here
|
stackexchange-tex
|
{
"answer_score": 9,
"question_score": 6,
"tags": "math mode, errors"
}
|
Java stream group by and sum multiple fields
I have a List fooList
class Foo {
private String category;
private int amount;
private int price;
... constructor, getters & setters
}
I would like to group by category and then sum amount aswell as price.
The result will be stored in a map:
Map<Foo, List<Foo>> map = new HashMap<>();
The key is the Foo holding the summarized amount and price, with a list as value for all the objects with the same category.
So far I've tried the following:
Map<String, List<Foo>> map = fooList.stream().collect(groupingBy(Foo::getCategory()));
Now I only need to replace the String key with a Foo object holding the summarized amount and price. Here is where I'm stuck. I can't seem to find any way of doing this.
|
A bit ugly, but it should work:
list.stream().collect(Collectors.groupingBy(Foo::getCategory))
.entrySet().stream()
.collect(Collectors.toMap(x -> {
int sumAmount = x.getValue().stream().mapToInt(Foo::getAmount).sum();
int sumPrice= x.getValue().stream().mapToInt(Foo::getPrice).sum();
return new Foo(x.getKey(), sumAmount, sumPrice);
}, Map.Entry::getValue));
|
stackexchange-stackoverflow
|
{
"answer_score": 24,
"question_score": 21,
"tags": "java, java 8, java stream, grouping"
}
|
JavaScript REST retrieve elements
I have a result from Fiddler (please see the attached image), how can I get the results where the arrow is pointing to? This is what I have done so far and thank you:
 {
$.ajax({
url: "myUrl",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function(data){
$.each(data.d.query, function(list){
});
},
error: function(error){
alert("Error message\n" + JSON.stringify(error));
}
}
);
}
|
Simply go to the results objects and iterates over it
function GetRefiners() {
$.ajax({
url: "myUrl",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function(data){
$.each(data.d.query.PrimaryQueryResult.RefinementResults.Refiners.results.Entries.results, function(list){
callWhatYouNeed();
}
};
},
error: function(error){
alert("Error message\n" + JSON.stringify(error));
}
}
);
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "javascript, rest"
}
|
Magento backend gives me a blank page when trying to edit order of more than $4,000
Typically, the orders I have received have been less than $1,000, comprising of less than 10 products. I had no problem editing those order (removing out of stock items, etc).
In the past month, I got one order for over $5,000 (35 products) and another for $4,000 (39 products). When I go to the backend to sales>orders and click the order number, it shows the order, when I click "edit", it asks me "Are you sure?" and when I click "ok" it gives me a blank page.
Help...
I am running Magento 1.4.1.1 on shared hosting
|
You are running out of server resources:
* check your php configuration
* enable php error display from index.php
* see if your server meets Magento system requirements
* this error is also logged to your server php error log
|
stackexchange-webmasters
|
{
"answer_score": 2,
"question_score": 1,
"tags": "magento"
}
|
How do I use the awesome window manager?
I've installed awesome on my Ubuntu laptop, and I like it. But I feel kind of lost. I don't know any keyboard shortcuts and the man pages aren't really any help (for instance, what does Mod4 mean?).
Is there any kind of brief introduction to awesome I can read?
|
Here is one person's introduction
Here is a guide to installing it with Ubuntu
And here is a history and additional links via Wikipedia)
Hope that helps!
|
stackexchange-superuser
|
{
"answer_score": 16,
"question_score": 19,
"tags": "linux, ubuntu, documentation, awesome wm"
}
|
How do I define a scaffold template?
Each time I generate a scaffold I need to customize the stylesheet. So it takes much more time to update style for index, form and show page. If I paste the predefined template code then I will have to change rails code instance variables and path.
Is there any way to define a specific style for each and every scaffold so that I used this to save time and overhead.
In short, I want to layout my page generate from scaffold like my form, index and show page with a predefined style.
I want to use custom mark-up and stylesheet in the generated scaffold. I want to do a one time definition of this scaffold template and use it every time I generate a new scaffold.
|
I partially solved my problem though .
rails g bootstrap:layout [LAYOUT_NAME]
and
rails g bootstrap:themed [RESOURCE_NAME]
generate a scaffold by this command rails g scaffold product name:string description:text
then implement bootstrap theme on your scaffold through this command
rails g bootstrap:themed products -f
pass the -f option to force it to overwrite the generated view files
you can generate a layout through command.
rails g bootstrap:layout appstructure this file will be save in view/layout and reflect on each and every page.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "ruby on rails"
}
|
Pass a role to authenticate basic http from postman
I am using `Spring boot security` and defined user in memory authentication to authenticate `http basic` but I am not seeing option in `Postman` to pass user role so my question is how can i pass role in `postman` for all requests??
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password(passwordEncoder().encode("passowrd"))
.authorities("ADMIN");
}
|
You don't need to pass `Role` from Postman request as `inMemoryAuthentication` you have set `user` with role `"ADMIN"` so path you have defined can be accessed by `ADMIN` role and if you try to call end points by this user, you will have access as "user" as role is `"ADMIN"` in your memory where user will be authenticated in basic auth.
So from Postman just select `Basic Auth` and pass `user as user` and `password as password`, you will be able to call those end points for which have defined to access by `"hasRole = ADMIN.`.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "spring, spring boot, spring security, postman"
}
|
why markers are not plotted in map using react?
I am using this map to plot my points
<
I am not able to show plot points here is my code <
<Marker
key={park.trackingId}
position={{
lat: park.endPoint.coordinates[1],
lng: park.endPoint.coordinates[0]
}}
onClick={() => {
setSelectedPark(park);
}}
|
It actually has markers, but it is zoomed-out, I think you interchanged the position also, try to change it to:
<Marker
key={park.trackingId}
position={{
lat: park.endPoint.coordinates[0],
lng: park.endPoint.coordinates[1]
}}
onClick={() => {
setSelectedPark(park);
}}
/>
Hope this helps!
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "reactjs, google maps, react google maps"
}
|
php or mysql gets stuck when importing in to db
we have a php script that runs this console command
cat import.sql | mysql -u user -ppassword
so it simply imports a file in to the DB
the file is quite big ~ 120 mb
but it contains only insert/replace queries like this one:
/*!40000 ALTER TABLE `actionList` DISABLE KEYS */;
REPLACE INTO `actionList` VALUES (1,'buttonClick','Click on a button'),(2,'buttonClose','Click on the close button');
/*!40000 ALTER TABLE `actionList` ENABLE KEYS */;
I removed the lock table from the code.
Now when this script is running my other pages cant load until this script is finished.
Any ideas why this is happening?
|
This wasn't a DB lock it was the session lock.
As we ran the script it took a lot of time, and the session was open, so other pages try to use the session but couldn't.
So I added:
session_write_close();
and it solved the problem.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 3,
"tags": "php, mysql"
}
|
How to bind enabled/disabled status to a control instead of view model?
Usually, I'd bind a status of being enabled/disabled (or visible/hidden/collapsed) to a property in the view model. However, I wonder if there's a smoother way in the particular case with radio buttons.
I have a set of three radio buttons and when I select one of them, I'd like to make a certain text box to become enabled (or visible). When I check another radio button, I wish the text box to become disabled (or hidden).
How do I bind property of a control to a state of another control?
|
{Binding ElementName=myControl, Path=myProperty}
You may also need converter
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, wpf, xaml, data binding"
}
|
When a VirtualBox VM's Adapter is set to Internal Network can the Firewall of the Host Machine Control Access to the guest VM's Ports?
In a VMs network settings:
1. Right click settings,
2. then in the resulting Settings dialog select `Network` from the side bar
3. And click any `Adapter N` tab,
4. If I set the `Attached to:` drop down to `Internal Network`
If I change the settings on the firewall of the host machine, will it affect the VM with a Internal Network adapter? Or would I need another adapter?
|
> Will a host outside the network be able to access the internal network?
No. That's the whole point of an internal network.
> Or will I need another adapter type for that?
Yes, that would be the simplest way but another adapter might not be required. Another VM might be configured to do port forwarding, NAT or network routing and then allow remote access.
|
stackexchange-superuser
|
{
"answer_score": 1,
"question_score": 0,
"tags": "networking, virtualbox, virtual machine"
}
|
How to use other libraries in swift?
I'm learning swift, primarily from command line. I don't want to create ios / mac apps. Just want to learn the language and probably create some scripts.
Within this context, how do I import 3rd party libraries? Say SwiftJSON. Instructions are given for importing in Xcode. But I don't want to use Xcode. I there any alternate method to use code developed by others?
(I do develop on Mac)
|
The Swift Package Manager is the best approach. However, it is new enough that SwiftJSON does not appear to have defined a `Package.swift` file. [It would be easy enough to add it].
In your code you define a `Package.swift` file that expresses a dependency on SwiftJSON as such:
import PackageDescription
let package = Package (
name: "MyPackage",
dependencies: [
.Package (url: " majorVersion: 0),
]
)
and then in your code, simply `import SwiftJSON`, put your 'script code' in `main.swift` and then build with:
swift build
You'll then have an executable in .build/debug/MyPackage
See < for an example.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "swift, swift2"
}
|
ActiveAdmin belongs_to relationship input based using string box on attribute other than id
I am using activeadmin in a standard rails app.
I have items belongs_to user relationship
On the admin#items form (edit and new) instead of having a select with all user emails, etc I want to instead have a string text field where an admin can input a user email instead of an id or selecting one from a dropdown.
On save I want to validate that email belongs to a user and assign the item to that user if it does.
I have
f.inputs "Item Details" do
f.input :user, as: :string
end
However that shows the user object in the view and I want to take in an email.
Or
f.inputs "Item Details" do
f.input :user_id, as: :string
end
takes in the ID when I want the email.
|
First I added a parameter that was not an object attribute, in this case the object's user's email.
f.input :user_email, as: :string, :input_html => { :value => f.object.user.try(:email) }
Then in the controller for the update and edit methods I handled the processing of that parameter. Additionally i deleted the param before super was called in order to avoid issues with the model. This assigns the user to the item via the user's email.
def update
user = User.where(email: params[:item][:user_email]).first
if user
params[:item][:user_id] = user.id.to_s
params[:item].delete(:user_email)
super
else
flash[:notice] = "That email does not belong to a valid user"
redirect_to admin_group_path(params[:id])
end
end
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ruby on rails, activeadmin"
}
|
How to get the build number at runtime?
I'm writing a project and I need to get a phone build number.
 function and it'll load the jQuery from a remote source, just like it was on your local machine.
If you want to do it properly, take a look at < which will allow you to add it through the wp_head() hook, which will check to make sure the script hasn't already been loaded.
|
stackexchange-wordpress
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript"
}
|
Create SOAP message from WSDL using axiom
I'm a starting a project which consist in sending a request to a web-service (which is already available) and parsing the response. I have the WSDL and URL endpoints. Does anyone have a startup tutorial on how to build something from there?
I would like to use Axis2 + Axiom to send the service request and receive and process the response. I'm using eclipse as dev env. I've been search for a tut on how to do this but with no success.
Any suggestion would be greatly appreciated!
|
this might help you
creating a webservice client using eclipse
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "web services, wsdl, axis2, axiom"
}
|
Free WPF Graph control for input / output adjustment
Im looking for a nice wpf control to do the following:
1) Present a graph to the user, with points that you can drag to change the curve..
2) During runtime (Backgrond thread not related to WPF) access this curve and give it an input and get an output that corresponds to the curve
A simple example
!enter image description here
An input of 20 would in the example above give an output of about 30
edit: Oh, almost forgot, its a plus if its bindable because I use Caliburn Micro (MVVM)
edit: Solved it with a Curve fit algorithm !enter image description here
|
I used a cubic spline interpolation as curve fittting, I ported this one
<
Then for solving Y values for known X values, use this <
Result: !enter image description here
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 4,
"tags": "wpf, graph"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.