INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
angular/material - how to get mat-toolbar shadow over the page content?
I currently have a standard layout for my app, toolbar with a fixed sidenav and content section. I have since discovered that I can get the drop shadow on the toolbar with the class inclusion `mat-elevation-z4`, however I cannot seem to get the shadow to overlay the content section when I have scrolled down in the section itself.
I have also attempted to use the z-index to correct this...
`mat-toolbar` I gave `z-index: 2` and `<div class="container">` I gave `z-index: -1`
If somebody could give me some advice, I would be grateful. | The issue is because of the z-index. The toolbar is overshadowed by the content section which affects the box-shadow of toolbar. In order to keep the box-shadow visible, you need to give a higher z-index to toolbar (which you already did). But Z-index works on positioned elements, hence provide position to the .mat-toolbar.
Example:
.mat-toolbar {
position: relative;
} | stackexchange-stackoverflow | {
"answer_score": 27,
"question_score": 8,
"tags": "html, css, angular"
} |
Are there other verbs like “be” and “go”?
The verbs _be_ and _go_ have the nice peculiarity that their various forms ( _be_ / _was_ and _go_ / _went_ ) come from originally distinct verbs. Are there other such verbs? | I guess not. As stated here:
> **Go** is an irregular verb. Along with **be** , **go** is one of only two verbs with a suppletive past tense in the English language."
(The link for "suppletive" will point you to the "suppletion" wiki page, where there are examples, also for other languages. _Suppletion_ also applies to adjectives, nouns, etc.)
This is another page for the English suppletive verbs, which are only two. | stackexchange-english | {
"answer_score": 9,
"question_score": 7,
"tags": "etymology, verbs, irregular, suppletion"
} |
Having a special character such as a period in a python key
I'm trying to generate sql insert statements using sqlalchemy like this.
def get_sql(self):
"""Returns SQL as String"""
baz_ins = baz.insert().values(
Id=self._id,
Foo.Bar=self.foo_dot_bar,
)
return str(baz_ins.compile(dialect=mysql.dialect(),
compile_kwargs={"literal_binds": True}))
This returns `keyword cannot be expression`. Escaping the period like `\.` also doesn't work.
One solution I came up with is using `FooDOTBar instead of Foo.Bar` and then replacing all "DOT" with "." in the generated sql files, this corrupts some other data though and is not optimal. Any better suggestions to deal with this from the ground up? | In your query, `values` can be assigned with dictionary. So you can do something like:
baz_ins = baz.insert().values({"Id": self._id, "Foo.Bar": self.foo_dot_bar})
Check out the insert documentation for more options | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python, sqlalchemy"
} |
Is it possible to use multer inside router?
Is it possible to use multer inside router like example below?
app.get('/', (req, res)=>{
multer({});
} | Yes this is possible with multer.
They have used this in one of their example in Error Handling section. Multer Error Handling
var multer = require('multer')
var upload = multer().single('avatar')
app.post('/profile', function (req, res) {
upload(req, res, function (err) {
if (err instanceof multer.MulterError) {
// A Multer error occurred when uploading.
} else if (err) {
// An unknown error occurred when uploading.
}
// Everything went fine.
})
}) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, node.js, multer"
} |
Is the dual of an equivariant metric equivariant?
Let $g$ a finite dimensional $K$-vector space, and let $g:V \otimes V \to K$ be an inner-product. If As usual, we can use the musical isomorphisms of $g$ to define an inner product on $V^*$, which we will denote by $g^*$. Now if we also assume that $V$ is a module for some group $G$, such that $g$ is $G$-equivariant, then with respect to the dual action of $G$ on $V^*$, does it automatically follow that $g^*$ is also $G$-equivariant? | Yes. Simplest way: $g$ is $G$-invariant iff $g:V\to V^*$ is $G$-equivariant iff $g^{-1}:V^*\to V$ is $G$-equivariant iff $g^*$ (better write $g^{-1}$) is $G$-invariant. | stackexchange-math | {
"answer_score": 3,
"question_score": 1,
"tags": "linear algebra, modules"
} |
Count Similar Array Keys
I have a POST request coming to one of my pages, here is a small segment:
[shipCountry] => United States
[status] => Accepted
[sku1] => test
[product1] => Test Product
[quantity1] => 1
[price1] => 0.00
This request can be any size, and each products name and quantity's key would come across as "productN" and "quantityN", where N is an integer, starting from 1.
I would like to be able to count how many unique keys match the format above, which would give me a count of how many products were ordered (a number which is not explicitly given in the request).
What's the best way to do this in PHP? | Well, if you know that every product will have a corresponding array key matching "productN", you could do this:
$productKeyCount = count(preg_grep("/^product(\d)+$/",array_keys($_POST)));
preg_grep() works well on arrays for that kind of thing. | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 4,
"tags": "php, arrays, post"
} |
how to calculate distance between two different shapes numpy array in order to do KNN implementation
1.Now I had two Numpy array which shape size are training set (21000,784) and test set(2000,784) respectively. Is this possible to do calculation?
test_lable = label_test
((data_train_set - data_partial_test)**2).sum(axis=1)
print(data_partial_test.shape)
print(data_train_set.shape) | The problem is that the subtraction is performed along the first axis by default. And since the arrays differ in number of rows, it returns an error:
train = np.array([[1,2,3],[4,5,6]])
test = np.array([[1,2,3],[4,5,6],[7,8,9]])
((train - test)**2).sum(axis=1)
> ValueError: operands could not be broadcast together with shapes (2,3) (3,3)
To subtract along the first axis, you can add another axis to `test`:
((train - test[:,None])**2).sum(axis=1)
array([[ 9, 9, 9],
[ 9, 9, 9],
[45, 45, 45]]) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python, numpy"
} |
MDX query from PHP
Is it possible to create an MDX query for JasperServer using PHP as a host language, given that my underlying relational database is MySQL?
What I would like to do is send the query to JasperServer in order to create an OLAP View and receive the view as a result (preferably in some text-based format, as oposed to an image or PDF).
I'm using JasperServer CE 4.2.1.
As a side note, is it even correct to think about making MDX queries from you application, just like you would make SQL queries? If yes, is there any way to make MDX queries to any OLAP server using PHP?
**Edit:** Added missing information: I'm using MySQL as a relational database server. | It's very likely your OLAP server supports XMLA. And XMLA is not more than SOAP with a specific format. I don't know a php library supporting XMLA, so you'll have to go the hard way :
The big job is marshalling/unmarshalling the XML -> The standard is defined by Microsoft and followed by almost all other vendors -> <
Maybe you can oversimplify for your needs. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "php, mdx, olap, jasperserver"
} |
Retrieving id from a row that I've just written to the database
How can I retrieve an `id` from a row that I've just written to the database?
Basically, I have a function in my ASP.NET a booking form that needs to write to two tables, but I need the id from what's been written in table 1, to also be store in table 2.
So:
1. write to `table 1`
2. retrieve `id` from `table 1`
3. write to `table 2`
How can I achieve this?
Regards Tea | In Asp.Net with a Sql 2008 server, you can use the **ExecuteScalar** function like this:
string query = "INSERT INTO Table1 (id_field)
OUTPUT SCOPE_IDENTITY()
VALUES (...)";
OR
string query = "INSERT INTO Table1 (...) VALUES (...); SELECT SCOPE_IDENTITY() ";
In the last example, notice I'm performing an INSERT and then a SELECT in the same request...
And to get the identity use:
int lastId = (int)command.ExecuteScalar(); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "asp.net, sql server, sql server 2008"
} |
Joining two tables by two columns where the data types don't match
I am trying to join two tables of a MySQL database one two columns:
SELECT ol.utdate, ol.session, dl.utdate, dl.dsession FROM observation_log ol
LEFT OUTER JOIN diary_log dl ON (ol.utdate = dl.utdate AND ol.session = dl.dsession);
The trouble is ol.session is a CHAR and dl.dsession is a TINYINT(4). The correspondence between the two is integers for letters in the alphabet:
=======================
ol.session||dl.dsession
=======================
A ||1
B ||2
C ||3
...
=======================
How can I convert (map or cast, not sure the correct verb to use here) either ol.session or dl.dsession to either both be a letter or an integer?
Thanks, Aina. | You can use the MySQL `ASCII()` function to convert upper case letters from the `ol.session` column to numbers which should match the `dl.session` column:
SELECT
ol.utdate,
ol.session,
dl.utdate,
dl.dsession
FROM observation_log ol
LEFT OUTER JOIN diary_log dl
ON ol.utdate = ol.utdate AND
ASCII(ol.session) - 64 = dl.dsession
Note that `ASCII('A')` returns 65, with `ASCII('B')` returning 66, and so on. So if we subtract `64` from `ASCII(ol.session)` we can bring things into alignment. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "mysql, casting"
} |
How to get yesterday date in node.js backend?
I am using **date-format** package in node back end and I can get today date using
var today = dateFormat(new Date());
In the same or some other way I want yesterday date. Still I did't get any proper method. For the time being I am calculating yesterday date manually with lot of code. Is there any other method other then writing manually ? | Try this:
var d = new Date(); // Today!
d.setDate(d.getDate() - 1); // Yesterday! | stackexchange-stackoverflow | {
"answer_score": 27,
"question_score": 9,
"tags": "javascript, node.js, date, date format"
} |
Entity Framework is not working in class library project
I have created a class library project in VS2010 ultimate with .net 4.0 and Entity fwk-4.1.
After adding a ref to the Entity framework dll, I am not able to use the Data Annotation attributes like 'Required' on class properties.
Could you please let me know what is the solution? | `Required` attribute is defined inside `System.ComponentModel.DataAnnotations` namespace and is available in `System.ComponentModel.DataAnnotations` assembly(dll)
1) Make sure to add a reference to `System.ComponentModel.DataAnnotations` assembly(dll)
2) Add a using statement to import the `System.ComponentModel.DataAnnotations` namespace in your class file.
using System.ComponentModel.DataAnnotations;
public class YourModel
{
[Required]
public string Name {set;get;}
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -2,
"tags": "asp.net mvc, entity framework 4.1"
} |
Efficient pointer to integer mapping and lookup in C++
I want to map pointer to integer for purpose of serialization. The pointers may be of different types and may point to polymorphic objects possibly using multiple inheritance. I need to query the map to know if the pointer is stored in it and if it is, then what is the associated integral value.
What is the correct way to do it?
The simple way of `map<void*, int>` that I thought of would not work because `operator <` is not defined for arbitrary pointers. Or is that not a problem on common systems?
Another solution would be to have a `vector<void*>`. But this would require to loop over all pointers stored in and I am not sure if the casting to `void *` would not break the `operator ==` for objects using inheritance. | You are in luck with your initial idea of using `map<void*, int>`.
Although you are right that `operator<` is not defined for pointers, the predicate used by `std::map<>` is `std::less<>` and the C++ standard requires that `std::less<T*>` also works for arbitrary pointers.
Quote from the C++ standard to support this ([lib.comparisons]/8):
> For templates `greater`, `less`, `greater_equal`, and `less_equal`, the specializations for any pointer type yield a total order, even if the built-in operators `<`, `>`, `<=`, `>=` do not. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 2,
"tags": "c++, pointers, dictionary"
} |
how to get connected clients in MongoDB
I'm writing an app using mongo as its db. I want to print the clients connected to the db, for example, print their ip. How can I get that info?
I tried using
db.serverStatus().connections
But it gives me the number of computers with access to my db. | You can use `db.currentOp(true)` and iterate over the `inprog` array of the result set, using the `client` field. | stackexchange-stackoverflow | {
"answer_score": 14,
"question_score": 16,
"tags": "mongodb, database"
} |
Parallel Iterators
I am designing a C++ data structure (for graphs) which is to be used by parallel code (using OpenMP).
Suppose I want to have a method which enables iteration over all elements (nodes). Of course, this iteration is going to be parallelized.
Is it possible to use an iterator for this purpose? How should an iterator look like that enables parallel access? Would you advise for or against using iterators in this case? | OpenMP parallel loops don't play nicely with iterators. You'll want to implement an indexing mechanism (`operator[]` taking an integral argument) on your graph class.
If you do want to use OpenMP 3.0 iterator support, make sure you have a random access iterator. Implementing it as an pointer to a node or edge is the simplest choice. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 6,
"tags": "c++, iterator, iteration, openmp"
} |
Implementing link into HTML/CSS button
I need to add a link into these buttons:
<div class="buttons">
<button class="action bluebtn"><span class="label">CREATE NEW ACCOUNT</span></button>
<button class="action redbtn"><span class="label">EDIT ACCOUNT</span></button>
<button class="action greenbtn"><span class="label">IMPORT EDI TEXT FILES</span></button>
<button class="action"><span class="label">LOG OUT</span></button>
</div>
Can somebody help me? | You have several options here, depending on whether you can change the HTML:
If you can change the HTML make the buttons into a regular `<a href=" or you can add an onclick event:
<button class="action bluebtn" onclick="javascript:document.location='some-url'">
<span class="label">CREATE NEW ACCOUNT</span>
</button>
If you can't change the HTML, grab the buttons using something like jQuery and add the onclick event there:
$("button.bluebtn").click(function(){
document.location = 'some-url';
return false;
});
But I do recommend changing the buttons into regular links if you can. Having `<button>` elements acting as links makes no sense... | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "html, css, button, hyperlink"
} |
Write a method called replace3sWith4s() that takes an integer array, and changes any element that has the value 3 to instead have the value 4
Write a method called replace3sWith4s() that takes an integer array, and changes any element that has the value 3 to instead have the value 4.
need to include a for loop aswell
void replace3sWith4s (int [] x) {
for (int i = 0; i < x.length; i++) {
if (x[i] == 3) {
}
}
}
heres my code at the moment what else do i need to do??
using java | So close....
if (x[i] == 3) {
x[i] = 4;
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -5,
"tags": "java, arrays"
} |
How to replace "_" and "-" in my URL string using Sharepoint Designer 2010
I have a name that will always be in this format with varying numbers of _ and - symbols.
e.g. CWTE_4_3-My_Friendly_Name e.g. Inette_5-Friendly_Again
I need to convert these in my sharepoint designer workflow to replace the "_" and the "-" markes with "%2D" and "%5F" respectively.
I tried to do this in my Infopath form but Translate only works across one character limit. so I could replace "-" with "{" but not with "%2D".
Can I do this in Sharepoint Designer? I don't know if I can because the number of the _ and - varies. | OK so the solution was here: spdwfextensions.codeplex.com using the Replace() function from the Invoke C# action in SPD. THANKS!!! – April D. | stackexchange-sharepoint | {
"answer_score": 2,
"question_score": 1,
"tags": "sharepoint designer, designer workflow"
} |
Loading multple HTML Pages with different Backgrounds
I am trying to program a TAB based paging.
My problem is each Tab contains a different background, so when I click on the hyperlink, the new background DOES NOT load, BUT the content loads.
Any ideas?
Code here
< | Tested your jsfiddle, adding !important to your css rules does the trick: <
Edit:
Depending on what effect you are looking for you could also remove the .ui-content part of each rule (so that it's just #services) that would apply the background to the whole page and not just the content part: < | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "css, jquery mobile"
} |
Android Studio doesn't show the Android Tab in the Tools dropdown menu
I am trying to run a project created by a colleague, so he zipped up the file and I downloaded it on my computer. I already viewed this link about the issue, however the reported solutions workn't for me. Here is a screenshot regarding my settings for SDK Tools, SDK Platforms and the dropdown menu in question. I have tried turning it on and off again. .value = '=HYPERLINK("C:\\file.xlsx")'
This creates a link but when I click the link I get the error "cannot open the specified file". The cell value is `=HYPERLINK("C:\file.xlsx")`. If I create a link to the same file using the "Insert Link" button in Excel it works and both cells show the same file path. Also I will need to create a link to a non-excel file that needs to be opened with a different program. How can I do this? | You should use the `add_hyperlink` method.
Example:
ws.range(15, 8).add_hyperlink("C:\\file.xlsx") | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "python, excel, xlwings"
} |
Five reputation is missing in my SO
Five reputation points are missing in my SO. It is showing only 2109. But it is showing in other SE and Android Enthusiasts as 2114.
Why is it missing? Whats wrong?
!enter image description here
Link from my meta: | Someone upvoted this question of yours (can't tell when) and yesterday at 21:59 his account got deleted so those 5 points vaporized.
Here is how I know this:
!unupvote screenshot
There is no "-5" as one would expect and this might be considered a bug but I'm pretty sure that's the reason for the missing 5 points.
The reputation in the "Accounts" tab is heavily cached so you still see the old reputation - after you will post new question or answer on Stack Overflow the cache should be refreshed. | stackexchange-meta | {
"answer_score": 9,
"question_score": 4,
"tags": "discussion, stack overflow, reputation"
} |
define global variables and functions in build.gradle
Is there a way to define global variables in `build.gradle` and make them accessible from everywhere.
I mean something like this
def variable = new Variable()
def method(Project proj) {
def value = variable.value
}
Because that way it tells me that it `cannot find property`. Also I'd like to do the same for the methods. I mean something like this
def methodA() {}
def methodB() { methodA() } | Use extra properties.
ext.propA = 'propAValue'
ext.propB = propA
println "$propA, $propB"
def PrintAllProps(){
def propC = propA
println "$propA, $propB, $propC"
}
task(runmethod) << { PrintAllProps() }
Running `runmethod` prints:
gradle runmethod
propAValue, propAValue
:runmethod
propAValue, propAValue, propAValue
Read more about Gradle Extra Properties here.
You should be able to call functions from functions without doing anything special:
def PrintMoreProps(){
print 'More Props: '
PrintAllProps()
}
results in:
More Props: propAValue, propAValue, propAValue | stackexchange-stackoverflow | {
"answer_score": 29,
"question_score": 24,
"tags": "groovy, gradle"
} |
Jekyll - Liquid Exception: Unknown operator forloop
I've updated jekyll and now get this error:
Liquid Exception: Unknown operator forloop in collection.html
Here's the code in question:
{% for tag in site.content_data.tags %}{{ tag }}{% if not forloop.last %}, {% endif %}{% endfor %}
How would I resolve this error? | I suspect your `{% if not forloop.last %}` is not the valid syntax, as I don't see it in the operators section.
Have you tried `{% if forloop.last == false %}`? | stackexchange-stackoverflow | {
"answer_score": 18,
"question_score": 8,
"tags": "for loop, jekyll, liquid"
} |
Google Reader API: How can I remove a feed from a single folder?
So let's say I have the following setup in Google Reader
**Folder One**
* Engadget
* Gizmodo
**Folder Two**
* Engadget
* webOSroundup
Using the Google Reader API, I would like to remove engadget from only Folder One...leaving Folder Two untouched.
I know how to pull engadget out of Folder One and leave him ungrouped, but if I unsubscribe it takes it out of both folders.
Any ideas? | To remove a subscription from a folder you'll need to send a `POST` request to `/reader/api/0/subscription/edit` with the parameters:
* `s=feed/ the feed stream ID
* `ac=edit`: the action type (other possible values are `subscribe` and `unsubscribe`)
* `r=user/-/label/Folder One`: the folder you wish to remove it from (you can use the `a` parameter to add it to a folder; you can repeat either one more than once to add/remove it from multiple folders)
* `T=token`: the usual action token used for all state-changing requests | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "google reader"
} |
How to record the browsing history in Chrome indefinitely?
I first thought it was a bug that my browsing history in Chrome was getting lost but there seems to be a hard limit of 90 days for it: “Your History page shows the websites you've visited on Chrome in the last 90 days. It doesn’t store pages from secure websites, pages you've visited in Incognito mode, or pages you've already deleted from your browsing history.” The part about the Incognito mode and deleted entries is intuitive, but I’m dismayed to find that all the rest of my older browsing history is lost.
Is there a trick, app, or extension that works around that and records all browsing history, HTTP and HTTPS, indefinitely? Thank you! | You can't do this directly in chrome history, but there are multiple third-party solutions that allow you to back up existing history regularly. One that is automated and seems to be all round the best is this extension. You an also use this one to manually export into a spreadsheet. | stackexchange-superuser | {
"answer_score": 1,
"question_score": 1,
"tags": "google chrome, browser, history"
} |
How to regain my voice
I've been a great singer since school but took a year long break now every time I sing with full fledged voice it feels hoarse after and I can't sing well after that for a day ,my voice durability was far superior before the break Also I suffered reflux esophagitis and pharyngitis during the break :( Any idea what I can do to regain my voice | The best is and always will be conversation with a professional tutor. I can offer one bit of advice though: sirens. Starting on a note you can sing comfortably and taking up slowly until it becomes difficult is a safe way to see where you're at. But don't... force anything. If your voice has been through the wars you should stay to your comfort zone until said zone begins to expand naturally. | stackexchange-music | {
"answer_score": 1,
"question_score": 0,
"tags": "voice, tenor"
} |
Reading multiple text lines from a file as stream
I need to read and process very large text file in powershell which I am able to do using the following pattern. However reading line by line seems inefficient to me.
$reader = [System.IO.File]::OpenText($file)
while(!$reader.EndOfStream){
$line = $reader.ReadLine()
###Do something
}
so instead of reading line by line, is it possible to read multiple lines in one go from some kind of stream object? | Why not use the built-in command for this:
Get-Content $file -ReadCount 1024 | Foreach {$_} | Where {$_ -match 'pattern'}
This reads 1024 lines at a time. Run those through a Foreach command to flatten the array of 1024 lines into single lines for processing - in this case, filtering based on a regex pattern. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": ".net, powershell, scripting"
} |
<body> background-color property doesn't work correctly with HTML5 DOCTYPE
So I've got a basic 2-column HTML layout that I've applied some basic CSS to:
html {
background-color: gray;
}
body {
width: 900px;
background-color: white;
margin: 0 auto;
overflow: hidden;
}
.logo, .nav, .contact {
float: left;
width: 248px;
border: 1px black solid;
}
.about, .banner, .content {
float: right;
width: 648px;
border: 1px black solid;
}
The problem is, the when I add the `<!DOCTYPE html>` declaration to the beginning of my page, the `background-color` attribute doesn't work for the `body` tag. I assume this has something to do with it defaulting to quirks mode without the DOCTYPE, but what am I doing wrong that might be invalid CSS? (I've validated with jigsaw and it doesn't show any errors/warnings.) | Because you were missing the DOCTYPE — which really should have been there to begin with — your page was being rendered in quirks mode. In quirks mode, browsers are known to stretch the height of `body` to 100% of the height of the viewport. In standards mode, which is triggered by having an appropriate DOCTYPE, `body` behaves like a regular block-level element, being only as tall as its contents by default. In your case, this results in `body`'s background color not being visible.
There's nothing inherently wrong with your CSS, which is why it validates, but if you want `body` to stretch to the height of the viewport in standards mode, you should add the following height properties to `html` and `body` respectively:
html {
height: 100%;
}
body {
min-height: 100%;
} | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 3,
"tags": "css, html, doctype"
} |
Reduced performance in bumblebee after 3.0 to 3.2 update
I had installed bumblebee 3.0 for my nVidia geforce 635M card in ubuntu 12.10 and got instant results - temp ad fan speeds reduced, batt backup extended to almost 6 hrs. (from 1.5-2 hrs earlier) and upon comparing glxspheres with and without optirun, got the fps to jump from ~60 to ~130.
But when bumblebee updated to version 3.2, I suppose it updated fine and was active, but the batt life reduced to about 4 hrs. Also optirun glxspheres gave an fps of ~60, although it did recognize the nvidia card and mentioned it in the output.
is this a bug or some limitation on 3.2? should i revert to using 3.0?, and if so, how to fix it.
PLease help as I loved the long batt backup and higher fps earlier.
Also, I saw in some post on the internet that someone got an fps in the range of 1300 - 1600 fps after starting nvidia hardware acceleration whereas I had got only 130 fps...whats the catch there? | Thanks Qasim for the news, bumblebee 3.2.1 released with bugfixes specially for Ubuntu Raring Ringtail 13.04 solved all the perf issues.
< | stackexchange-askubuntu | {
"answer_score": 0,
"question_score": 0,
"tags": "performance, bumblebee"
} |
Invalid Host header when running Create React App on localhost subdomain
After updating to the react-scripts 1.0.0 I get this error when I try to open my app in the browser on a localhost subdomain: 'Invalid Host header'
My app was set up to serve different data for different subdomains: group1.localhost:3000 group2.localhost:3000 ...
I found that adding the code below to my webpack config should fix the problem.
devServer: {
disableHostCheck: true
}
But how can i fix it in CRA without ejecting? | Please update to `[email protected]`.
It fixes this issue for users who don't use the `proxy` feature in React.
If you **do** use the `proxy` feature, please follow these instructions. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 9,
"tags": "webpack, create react app"
} |
How to get the position from classname onclick?
I want to get the position of an label on a click event. For exameple:
<label class="labelClass" onclick="getPosition()"> label1 </label>//return position 1
<label class="labelClass" onclick="getPosition()"> label2 </label>//return position 2
<label class="labelClass" onclick="getPosition()"> label3 </label>//return position 3 ...etc
<label class="labelClass" onclick="getPosition()"> label4 </label>
<label class="labelClass" onclick="getPosition()"> label5 </label>
function getPosition() {
//pseudocode to get position
var label = document.getElementsByClassName("labelClass");
alert(label.position) //something like this;
} | You have to convert the `HTMLCollection` to an `Array` so that you can find the index of the element from the list. Hope this works for you..
<label class="labelClass" onclick="getPosition(this)" > label1 </label>//return position 0
<label class="labelClass" onclick="getPosition(this)" > label2 </label>//return position 1
<label class="labelClass" onclick="getPosition(this)" > label3 </label>//return position 2 ...etc
<label class="labelClass" onclick="getPosition(this)"> label4 </label>
<label class="labelClass" onclick="getPosition(this)"> label5 </label>
function getPosition(label)
{
var list=document.getElementsByClassName("labelClass");
list = [].slice.call(list);
alert(list.indexOf(label));
}
Here is the jsfiddle | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "javascript, onclick, label, getelementsbyclassname"
} |
Capitalize specific words on the page
I have your typical MVC3 app with lots of CRUD pages. And in these pages there are lots of lists with Id columns... The client told me today that they always want to see "ID" instead of "Id" but the fields are usually more fully qualified (IE: "Job Id" or something)
Is there a way, with css, to text transform ONLY the "Id" part of the text (to all caps) without adding any extra html?
I think part of the solution involves this pseudo class: div:contains(" Id ") but I'm not sure if it's even do-able...
Also I don't mind doing this w/ jquery, but I'm trying to minimize refactoring. | Based on the other answers here is the short version with valid replacement:
$("h3").text(function() {
return $(this).text().replace(/\b(id)\b/gi, "ID");
});
**DEMO:** < | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "javascript, jquery, html, css"
} |
VSC++2010: -Zm135
I would like to read detailed description of -Zm135 Visual Studio 2010 command line option. Briefly, this is an option to set when virtual memory for PCH is exceeded. Additionally, what is a meaning of -Zm letters? | It specifies percentage of memory available for precompiled headers: < | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "c++, visual studio 2010, pch"
} |
pydoop cp method - how to specify keyword argument "errors"
I am using pydoop to copy files between hdfs locations. The pydoop.hdfs.cp(src_hdfs_path, dest_hdfs_path, **kwargs) method documentation is on this page. <
According to the documentation, the keyword arguments are the same as open() function. So I tried the following code
import pydoop.hdfs as hdfs
hdfs.cp(srcpath, destpath, errors='ignore')
The code works if the file does not exists in the destination path. Otherwise it gives a file already exists error. In other words, the errors='ignore' argument does not work.
Does this look like a pydoop bug or did I supplied the wrong argument?
Thanks. | As the open documentation says
> errors is an optional string that specifies how encoding and decoding errors are to be handled...
`error='ignore'` ignores _**only**_ encoding/decoding errors while reading or writing to files.
The error that "file already exists" is thrown by `hdfs.cp` function. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, hadoop, hdfs"
} |
iOS SDK :: vibration & plays a beep sound.
I need to vibrate iOS device, devices that don’t support vibration, Will plays a beep sound.
For this I am using
Import AudioToolbox.framework
#import <AudioToolbox/AudioToolbox.h>
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
It vibrate on iPhone device, but No sound on **iPad and iPod**. While refrences say that it will play sound. What I am doing wrong ?
Making the iPhone vibrate
< | Try setting the AudioSession:
#import <AudioToolbox/AudioToolbox.h>
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *err = nil;
[audioSession setCategory: AVAudioSessionCategoryPlayback error:&err];
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
//or: AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 15,
"tags": "ios, iphone, objective c, ipad, ipod"
} |
How to know CPU frequency?
I'm running Ubuntu 16.04. How can I find out what frequency my computer's CPU has? I just need to know the CPU frequency according to the manufacturer and the real CPU frequency I have.
Are there some terminal commands allowing that?
**EDIT**
There is output from `lscpu`
CPU MHz: 1400.042
CPU max MHz: 2700.0000
CPU min MHz: 800.0000
but from details i get another
.ready(function(){
$("#cookies").addClass("display");
});
$("#close-cookies").click(function(){
event.preventDefault();
$("#cookies").addClass("close-cookies");
});
And this is the HTML:
<div id="cookies">
<p>blablablabla</p>
<p><a href="#" id="close-cookies">CLOSE</a></p>
</div> | you didn't initialize the `event` variable
$("#close-cookies").click(function(event){
and this needs to be inside
$(document).ready(function(){
so the fixed code should be:
$(document).ready(function(){
$("#cookies").addClass("display");
$("#close-cookies").click(function(event){
event.preventDefault();
$("#cookies").addClass("close-cookies");
});
}); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, jquery, html, firefox, popup"
} |
Windows command line: how to make it so I can type "php" instead of "C:\php\php.exe"
How to make it so I can type "php" instead of "C:\php\php.exe" in Windows command line (and this persisting after I restart)?
I tried to set it as an environment variable but that didn't work. I have no idea what I'm doing. | 1. In the windows search bar, enter `env`. Then open the app.
2. Click on the edit environment variables button (at the bottom)
3. Select the variable names `Path` and click on `edit`
4. Enter the path (`C:\php`) to the new line and save | stackexchange-superuser | {
"answer_score": 3,
"question_score": 0,
"tags": "windows, windows 11"
} |
Import csv file in a child folder with ChDir to get relative path Power Query
I have an `xlsm` file in a parent folder, and I want to import whatever CSV file is in a child folder regardless of its label
I want to use the relative path of the xlsm file to do this
I am trying:
FP = ChDir (CurrentProject.Path) & "\SourceData\"&"*.csv",
Source = Csv.Document(File.Contents(FP),[Delimiter=",", Columns=18, Encoding=1252, QuoteStyle=QuoteStyle.None])
But I am getting the error:
`Expression.Error: The name 'ChDir' wasn't recognized. Make sure it's spelled correctly.`
What is the best way to do this?
Thanks | this combines all the CSV files in the parent and subdirectories
You can modify as needed
let Source = Folder.Files("C:\directory"),
#"Filtered Rows" = Table.SelectRows(Source, each [Extension] = ".csv"),
#"Added CSVdata" = Table.AddColumn(#"Filtered Rows", "CSVdata", each Table.PromoteHeaders(Csv.Document([Content])), type table),
#"Added Custom" = Table.AddColumn(#"Added CSVdata", "Custom", each let name = [Name] in Table.AddColumn([CSVdata],"SourceFile", each name)),
#"Combined CSVdata" = Table.Combine(#"Added Custom"[Custom])
in #"Combined CSVdata" | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "excel, import, powerquery"
} |
What is the meaning of malloc, realloc, calloc? I want to know full name of these functions
I have tried to find it in google, but I couldn't. I am studying C. And now my stage is pointer and function about management memory. But malloc, realloc, calloc...etc are hard to memorize. So I want to know the full context. It will help to remember their meaning. I do not speak English well. So my writing may be weird. Please understand. Thanks for reading. | **M** emory **Alloc** ation (and reallocation etc...)
There is an awful lot to say about these functions but check out this article for a start.
And if you can still buy it read "The C Programming Language" by Brian Kernighan and Dennis Richie. A **MUST** Read | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -7,
"tags": "c"
} |
Can I use Firebase Dynamic Links for a web app?
I don't see any option for Web under "receiving dynamic links" in Firebase Dynamic links page.
> Without the SDK, there's no way to connect a post-install user with a pre-install click.
I have a desktop app that runs on node.js like a web app, using nw.js. What I'm trying to do is create referral links for users. After someone clicks a referral link, I need to be able to track his referrer. But the problem is that link is only going to take him to the download page, after he downloads and opens up the app for the first time, how can I reach his referrer info? The desktop app has no connection with the website that users download from.
I understand that this can be done with Dynamic Links SDK but can I use that SDK in a web app?(desktop app actually but runs with HTML/node.js) | The post-install deeplinking in Dynamic Links is just for Android and iOS - so there isn't an equivalent for a desktop app. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 7,
"tags": "firebase, firebase realtime database, firebase dynamic links, referrals"
} |
How do I change the header included in a JSP page based on the value of a session Attribute?
Here is my code:
<%
if(session.getAttribute("loggedIn").equals(null))
{
%>
<%@ include file="header.jsp"%>
<%
}
else if(session.getAttribute("loggedIn").equals("user"))
{
%>
<%@ include file="pheader.jsp"%>
<%
}
%>
This is how I am setting the session attribute:
if(utype.equals("admin"))
{
session.setAttribute("loggedIn", "admin");
}
else
{
session.setAttribute("loggedIn", "user");
}
This is throwing a null pointer exception. I understand since nobody is logged in, the attribute value is null.
How do I fix this? | First, do not use scriptlets in JSP. Use JSTL and EL:
<c:choose>
<c:when test="empty loggedIn">
<%@ include file="header.jsp"%>
</c:when>
<c:when test="loggedIn == 'user'">
<%@ include file="pheader.jsp"%>
</c:when>
<c:otherwise>
<%-- handle the default case --%>
</c:otherwise>
</c:choose>
Second, if you insist on using scriplets, do
if (session.getAttribute("loggedIn") == null)
instead of
if (session.getAttribute("loggedIn").equals(null))
as you cannot invoke the `equals` method, if there is no object. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "jsp"
} |
CVSS score for no-input validation
During a security assesment I found that an application wrote JavaScript from input fields directly in the database. The application it self had good output sanitization so no XSS was possible in that application. A different application that used the same data didn't have good output sanitization and had a XSS vulnerability, which has been fixed since then.
So wat I have now is a finding that input data is not properly validated, which might pose problems for applications that do not sanitize output well but not in the current application. What CVSS score would I put on that? I cannot well make it a high vulnerability because it is impossible to exploit now. But in the future it could pose problems and I do want it fixed in the context of "defense in depth"
**Question: What would the CVSS score be for a non-exploitable input validation vulnerability?** | The score would be 0.0. Since there is no immediate impact, the confidentiality, integrity and availability would be set to _none_ , which would make the score 0.0.
Also, it is not necessarily a security issue that user input is saved as-is in the database. The important thing is that it is correctly encoded on output. | stackexchange-security | {
"answer_score": 2,
"question_score": 1,
"tags": "penetration test, validation, cvss"
} |
How to close wicd gui without leaving dangling process
If I open the wicd gui with `wicd-gtk &`, closing it (even using the "Quit" button) may close the gui, but always leaves a process `wicd-client` running in the background apparently doing nothing. I noticed this because I checked my running processes after 20 days of uptime only to find about 15 `wicd-client`s listed. FYI I'm running debian jessie.
How come these processes don't die with the gui and how can I fix this?
I have noticed that if I start the client without backgrounding it (i.e. simply with the command `wicd-gtk`) when I close the gui, the terminal still hangs until I CTRL-C. Upon hitting CTRL-C, the `wicd-client` process closes. | `wicd-gtk` hangs when its window is closed unless it is invoked as `wicd-gtk --no-tray` or `wicd-client --no-tray` (without`wicd-curses` installed, `wicd-client` invokes `wicd-gtk`).
The quick solution is to put something like this in your PATH or shell profile that replaces `wicd-gtk` with `wicd-gtk --no-tray`.
For users who do not want to run the client in the background, or use the feared `wicd-curses` client, this is annoyingly not configurable without the command-line option; `wicd-client.py` would need to be patched. The patch could be a check for an existing process, then bringing up a GTK window attached to that process instead of starting. | stackexchange-superuser | {
"answer_score": 2,
"question_score": 2,
"tags": "linux, debian, gui, wicd"
} |
How to make spring managed classes in method signature optional?
How can I define a spring managed method signature where the injected service is optional?
The following does of course not work as the `@Autowired` annotation is not allowed inside the method signature. But that's what my intention is.
@Bean
public MyService myService(@Autowired(required = false) OptionalService optional) {
MyService service = new MyService();
//configure service if optional service is supplied
return service;
} | You shouldn't use @Bean with method but instead declare your class `MyService` with `@Service` and have it scanned with your Spring configuration. Then you can have a field of type `OptionalService` with `@Autowired(required = false)`. Your service should look like this :
@Service
public class Myservice {
@Autowired(required=false)
private OptionalService optional;
}
Then if you need to do something after your optionalService has been injected by Spring (or not as it's not required), you can have your service implements `InitializingBean` and its `afterPropertiesSet` method and do it here. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 1,
"tags": "java, spring"
} |
how to check if two doubles are equal in java
I am writing a program to help students practice division, how can I compare the user Input and the correct answer if they are doubles | You can convert it to BigDecimal, and compare with the required precision of decimal places
BigDecimal aa = new BigDecimal(a);
BigDecimal bb = new BigDecimal(b);
aa = aa.setScale(4, BigDecimal.ROUND_DOWN);
bb = bb.setScale(4, BigDecimal.ROUND_DOWN);
return aa.equals(bb); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -2,
"tags": "java"
} |
How to create multiple empty elements inline with React
What is the best way to create multiple empty elements inline using React within render in a declarative fashion?
For example, say I wanted 8 empty divs, the following was my first attempt although it doesn't work, is there a better way?
render() {
return (
<section>
{
new Array(8).map(()=> <div />)
}
</section>
);
} | I'd use a small helper for it:
const times = (length, fn) => Array.from({ length }, (_, i) => fn(i));
To be used as:
times(8, i => <div key={i} />) | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "javascript, reactjs"
} |
Audit log for seeing who updated content when
Hopefully a simple question - is there any kind of ready-made audit log built into Sitecore so I can see who edited content when? I know without versioning the content, the last updated date/user would likely keep overwriting itself, but even knowing who was the last to do something with an item would be useful data. The History table might give some useful info perhaps but I’m not sure. Thanks. | Audit information is available in the logs, and I thought there was a way to isolate them in a separate log file by changing log4net settings. But you could also use the Audit Trail module from the marketplace: <
> Helps you to answer following questions:
>
> * Who did change?
> * When it happened?
> * What all actions happened on aparticular day?
> * ...
> | stackexchange-sitecore | {
"answer_score": 7,
"question_score": 5,
"tags": "content management"
} |
Do I need the meta-key for vim?
I'm looking in to learning emacs or vim. I started out with emacs but found the need for a meta key to be a hassle, especially since I have a non-english keyboard layout on my macbook.
So far I haven't seen any references to meta in vim, so my question is: **Can I live without meta in vim?**
If so that'll settle the vim vs. emacs question for me, otherwise I'll just have to learn to live with some workaround. | There are no internal key bindings that use the meta key in Vim, but--with some caveats--it can be mapped. | stackexchange-superuser | {
"answer_score": 1,
"question_score": 1,
"tags": "vim, emacs, keyboard layout, language"
} |
Computing $\int_{|z|=1}\frac{\tan(z)}{z e^{\frac{1}{z+2}}}$
> Compute the integral for $z\in\mathbb{C}$: $$\int_{|z|=1}\frac{\tan(z)}{z e^{\frac{1}{z+2}}}$$
Inside the domain of $|z|=1$ the singular point I was able to detect was zero, however I do not know how to claissify it:
$\lim_{z\to 0}\frac{\tan(z)}{z e^{\frac{1}{z+2}}}$
If $x\in\mathbb{R}$ then using L'Hopital:$\lim_{x\to 0}\frac{\tan(x)}{x e^{\frac{1}{x+2}}}=\frac{1}{e^{\frac{1}{2}}}$. However I do not know how to proceed in the complex case.
I know by the book solution that the integral equals $0$.
**Question** :
How should I compute the integral?
Thanks in advance! | * $\tan z$ has simples poles at $\frac{\pi m}{2}i$ for odd integers $m$. All of them are outside the unit disc.
* $\frac1z$ has a simple pole at $z = 0$ but get cancelled by a zero of $\tan z$. This makes $z = 0$ a removable singularity of the integrand.
* $e^{\frac{1}{z+2}}$ has an essential singularity at $z = -2$. Once again, it is outside the unit disc.
Combine them, we find there are no singularities that matter on or inside the disc. The integrand is holomorphic over the unit disc (in fact, over a larger disc $|z| < \frac{\pi}{2}$). By Cauchy integral theorem, the integral over unit circle vanishes. | stackexchange-math | {
"answer_score": 4,
"question_score": 0,
"tags": "complex analysis"
} |
check if a private channel invite link is invalid/expired in telethon
When you try to access a private channel using expired link in telegram client you will get this message expired link
is there a way to check if a channel invite link is invalid or expired without joining the channel ? | You can use `checkChatInvite`:
from telethon.sync import TelegramClient
from telethon import functions, types
with TelegramClient(name, api_id, api_hash) as client:
result = client(functions.messages.CheckChatInviteRequest(
hash='A4LmkR23G0IGxBE71zZfo1'
))
print(result.stringify()) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "telethon"
} |
tableview constraisnts in iphone 6 and 6 plus
I am using a tbaleview and want to make sure they looks good in both the smaller and larger iPhones ( 6 and 6 plus), but even after setting all the constraints on the left right and top to 0, I still see this. Any thoughts ? Thanks.` to use HTML in your XML Strings. Simply referencing a String with HTML in your layout XML will not work.
This is what you should do in Java
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
textView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>", Html.FROM_HTML_MODE_COMPACT));
} else {
textView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>"));
}
And in Kotlin:
textView.text = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(html, Html.FROM_HTML_MODE_COMPACT)
} else {
Html.fromHtml(html)
} | stackexchange-stackoverflow | {
"answer_score": 1560,
"question_score": 878,
"tags": "android, html, xml parsing, textview"
} |
Найти пропущенные даты
Имеется результат выборки:
link date_change
15 2018-09-30 00:00:03.740
15 2018-09-30 00:00:03.740
15 2018-09-11 14:54:15.403
15 2018-09-11 14:51:49.713
15 2018-09-07 11:52:08.710
15 2018-09-07 11:45:39.983
15 2018-09-07 10:33:38.367
15 2018-09-07 09:45:16.723
15 2018-09-06 14:27:54.007
15 2018-09-06 14:11:09.190
16 2018-09-06 09:28:39.890
16 2018-09-04 18:45:37.693
16 2018-09-03 15:15:44.907
Необходимо найти пропуски дат для каждого "link", в результате получив что-то вроде:
link cnt date_1 date_2
15 19 2018-09-11 2018-09-30
15 4 2018-09-07 2018-09-11
16 2 2018-09-04 2018-09-06 | SELECT DISTINCT t1.link,
DATEDIFF(day,
CAST(t1.date_change AS DATE),
CAST(t2.date_change AS DATE)) cnt,
CAST(t1.date_change AS DATE) date_1,
CAST(t2.date_change AS DATE) date_2
FROM test t1, test t2
WHERE DATEDIFF(day, t1.date_change, t2.date_change) > 1
AND t1.link = t2.link
AND NOT EXISTS (SELECT 1
FROM test t3
WHERE t1.link = t3.link
AND t1.date_change < t3.date_change
AND t3.date_change < t2.date_change)
fiddle
А по-хорошему - сразу преобразовать дату-время в дату (и DISTINCT) в секции WITH.
PS. На реальных данных, вероятно, придётся везде в показанном запросе все вхождения date_change изменить на CAST к дате, а не только в выходном наборе. | stackexchange-ru_stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "sql, sql server"
} |
Is there an Eclipse equivalent of Visual Studio snippets?
Is there an Eclipse equivalent of Visual Studio snippets, if so what is it? | Yes, there are.
You can access the existing ones selecting the Window>Preferences dialog. Then you navigate to Java > Editor > Templates subtree.
There you can see the existing ones. The first column is both the name and the activation code. For example, the "main" template inserts a default main block at cursor position.
You can use it inside the editor by typing "main" and pressing "CTRL + space". Then a pop-up is displayed so you can choose what template you want.
In the aforementioned dialog you can both define new templates or edit the existing ones at your will.
One thing to consider is that the content assist (the CTRL+space key combination) will only bring the appropriate results if the cursor is inside the context indicated in the second column.
That is, the "while" template, for example, will only work if the cursor is inside a Java Statement, and so on. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "eclipse, visual studio"
} |
stored procedures location influence their performance?
I have a procedure SP_MYPRO that updates data in MYDB1.
1) the performance of SP_MYPRO would be different if I place it in MYDB2 instead of MYDB1?
2) what if the procedure SP_MYPRO only read data, does not update anything? | This is something you can easily test for yourself, but in my testing, no, there is no significant overhead in calling a stored procedure across a database boundary (I am sure you could make something noticeable though if you tried hard enough).
However, I would say that a stored procedure should live closer to the data that it manipulates than the object(s) that call it. This way, if you move the database, all that breaks is the _remote_ calls to that procedure, rather than all of them. | stackexchange-dba | {
"answer_score": 3,
"question_score": 1,
"tags": "sql server, performance, stored procedures, query performance"
} |
How do I search part of a column?
I have a mysql table containing 40 million records that is being populated by a process over which I have no control. Data is added only once every month. This table needs to be search-able by the Name column. But the name column contains the full name in the format 'Last First Middle'.
In the sphinx.conf, I have
sql_query = SELECT Id, OwnersName,
substring_index(substring_index(OwnersName,' ',2),' ',-1) as firstname,
substring_index(OwnersName,' ',2) as lastname
FROM table1
How do I use sphinx search to search by firstname and/or lastname? I would like to be able to search for 'Smith' in only the first name? | Judging by the other answers, I may have missed something... but to restrict a search in Sphinx to a specific field, make sure you're using the extended (or extended2) match mode, and then use the following query string: `@firstname Smith`. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "mysql, sphinx"
} |
MVC3: Use javascript to clone HTML elements that use models
Is it possible to use the Javascript method clone() to clone an mvc html element like dropdown list that is defined using a model?
I have a drop down list with options from a model; and I want to add a similar drop down list when the user clicks on a button. My drop down list is defined as
<div id="parent">
<div id="id">
@Html.DropDownListFor(m =>m.mymodel)
</div>
</div>
I have added a code like this for my JS
var new = document.getElementById('id').cloneNode( true );
document.getElementById( 'parent' ).appendChild( new );
But this does not work. If I cannot use cloning, how else can i achieve this? | You can't use `new` as a variable name -- that's a reserved word in Javascript. Your approach should work, but just be aware that the `id` attribute has to be unique in an HTML document. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, asp.net mvc 3, clone, html.dropdownlistfor"
} |
basic probability birthday question
I figure this is a trivial question since it's right in the beginning of the book but I get a different answer from that of the answer in the back of the book. I get .0847 while in the correct answer is .0828.
Anyways here is the question:
If birthdays are equally likely to fall on any day, what is the probability that a person chosen at random has a birthday in January?
January has 31 days and there are 365 days in a year so $31 \over 365$ would be $p$ for a non leap year. On a leap year it's $31\over 366$. Since a leap year occurs once every four years I thought I'd get my answer by doing:
$${31\over 365}*{3\over 4} + {31\over 366} * {1\over 4}$$
Any suggestions? | Since January has $31$ days, the most days a month can have, and $\frac1{12}= 0.0833\ldots $, there is no obvious way to get a figure as low as $0.0828$.
Either it is a trick question or you have spotted an error. | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "probability"
} |
Integrate firebase notifications topics and firebase authentication
I am currently using the firebase notifications console to send notifications to specific android devices using topics. Is it possible to link the topics that the device is subscribed to with the user account that is logged in through firebase authentication.
Ideally I want it so that the when the user logs in, a request can be sent to determine all the topics the user was previously subscribed to on a different device and subscribe to the same topics on this device. Similarly when the user logs out, the device should unsubscribe from all the topics.
I would prefer if this could be done without having to write any server side code. | There is no automatic mapping of authenticated user and subscribed topics. However you can do this mapping yourself via the Firebase Realtime Database. When a user subscribes to a topic you can add an entry to the FRD and when that user signs in on another device you can check the FRD and automatically subscribe the user to the required topics. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "android, firebase, firebase authentication, firebase cloud messaging, firebase notifications"
} |
Shutdown ExecutorService when no task has been submitted for a given time
I'm using an `ExecutorService` to call a service which basically connects to an application (local or remote via SSH), and allows to send commands to it and get its output.
So, the `Thread` created by the `ExecutorService` is waiting for user input, and this input is then processed as a task through an implementation of the call method, which returns the output and looks like this:
@Override
public String call() throws Exception {
write(command);
return readResult();
}
I would like to stop the `Thread` (shutdown the `ExecutorService`) when no task has been called for a given time, but I can't find how to do it... `Future.get` or `ExecutorService.invoke[All|Any]` can handle a timeout, but only regarding tasks it calls.
Any idea on how I could manage to do this? | You could just use `Executors.newCachedThreadPool()`, whose doc says:
> Threads that have not been used for sixty seconds are terminated and removed from the cache. Thus, a pool that remains idle for long enough will not consume any resources. Note that pools with similar properties but different details (for example, timeout parameters) may be created using ThreadPoolExecutor constructors.
This shuts down the threads, not the entire executor, but that should be fine if the executor isn't actually taking any resources. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "java, executorservice, callable"
} |
Как сделать, чтобы синий цвет подстраивался под размер картинки и всегда покрывал её?
Как сделать, чтобы синий цвет подстраивался под размер картинки и всегда покрывал её?
.intro {
max-width: 1920px;
margin: 0 auto;
}
.intro__bg {
max-width: 1920px;
position: absolute;
width: 100%;
height: 100%;
background-color: rgba(34, 40, 75, 0.86);
}
.intro__bgimg {
z-index: -1;
width: 100%;
position: relative;
}
<div class="intro">
<div class="intro__bg"></div>
<img src=" alt="Intro" class="intro__bgimg">
</div> | Сделать ее фоновым изображением, и сверху наложить маску-цвет полупрозрачную
body {
margin: 0;
padding: 0;
}
.intro {
max-width: 1920px;
margin: 0 auto;
}
.intro__bg {
max-width: 1920px;
width: 100%;
display: block;
position: relative;
}
.intro__bg:after {
content: '';
position: absolute;
width: 100%;
height: 100%;
background-color: rgba(34, 40, 75, 0.86);
z-index: 2;
top: 0;
left: 0
}
.intro__bgImg {
max-width: 100%
}
<div class="intro">
<div class="intro__bg">
<img src=" alt="" class="intro__bgImg">
</div>
</div> | stackexchange-ru_stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "html, css, css3, html5"
} |
When request the resources of HTML page will open new TCP connections?
We know when request a web page, there will open a TCP connection, request the html page.
there is an example: 
we know, in the main HTML page, there are many js files, css files and images embed in it. when request those resources, will open new TCP connections? or just use the existing connection? | It depends on the actual application protocol used and its configuration. With HTTP/2 and HTTP/3 (which is not even TCP, i.e. it uses UDP) the same underlying connection will be used as long as the requested resource is on the same server.
With HTTP/1 a new TCP connection will be created or an existing one reused, depending if an existing connection can be used at all (HTTP keep-alive), is idle and how many TCP connections are already used to the target. Details are browser specific too. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "http, tcp, httprequest"
} |
convert java.util.Map[String, Object] to scala.collection.immutable.Map[String, Any]
How do I convert java.util.Map[String, Object] to scala.collection.immutable.Map[String, Any], so that all values in the original map (integers, booleans etc.) are converted to the right value to work well in Scala. | As VonC says, `scala.collections.JavaConversion` supports mutable collections only, but you don't have to use a separate library. Mutable collections are derived from `TraversableOnce` which defines a `toMap` method that returns an immutable Map:
import scala.collection.JavaConversions._
val m = new java.util.HashMap[String, Object]()
m.put("Foo", java.lang.Boolean.TRUE)
m.put("Bar", java.lang.Integer.valueOf(1))
val m2: Map[String, Any] = m.toMap
println(m2)
This will output
Map(Foo -> true, Bar -> 1) | stackexchange-stackoverflow | {
"answer_score": 36,
"question_score": 28,
"tags": "java, scala, scala collections"
} |
A simpler approach to solve "how many k-permutations of aaabbccdef are there?"
Given a problem as follows.
> How many 4-permutations of "aaabbccdef" are there?
# Attempt
Divide the problem into disjoint cases:
* 4-permutation of $\\{a,b,c,d,e,f\\}$
* permutation of $\\{2*x, y, z\\}$
* permutation of $\\{2*x, 2*y\\}$
* permutation of $\\{3*a, x\\}$
The number of permutations for
* case 1: $P^6_4=360$
* case 2: $C^3_1\times C^5_2\times\frac{4!}{2!}=360$
* case 3: $C^3_2\times \frac{4!}{2!\times 2!}=18$
* case 4: $C^5_1\times \frac{4!}{3!}=20$
Total number of permutation is $758$.
# Question
Is there any simpler approach which is very useful for longer words to be made? | One way is to do this is to use exponential generating functions: take $4!$ times the coefficient of $x^4$ in $$\left(1 + x + x^2/2!+x^3/3!\right) \left(1+x + x^2/2!\right)^2\left(1+x\right)^3$$ which comes out to $379/12 \cdot 24 = 758$. We get this product by taking a factor of $$1 +x + \cdots + x^k/k!$$ for each distinct letter, where $k$ is the number of times the letter is used; hence $1+x + x^2/2! + x^3/3!$ for `aaa`, one $1 + x + x^2/2!$ for each of `bb` and `cc`, and a $1+x$ for each of $d,e,f$. See my answer to this question for the details, but I can explain more if it is unclear. Essentially this is just another way of writing that we sum the multinomial formula for each choice of multiset of size $4$. | stackexchange-math | {
"answer_score": 2,
"question_score": 4,
"tags": "combinatorics"
} |
Is a refresh token an entity or value object?
I have a `User` entity, which _may_ have a `RefreshToken` (for authentication).
Notes:
* A refresh token doesn't have "identity", but is related to a single user - it is only valid for that user. In the db that means a foreign key to users table. In Entity Framework I can however model it as an "owned" type so that it's part of the users table.
* A refresh token can be revoked, i.e. deleted from the database
* A refresh token can be renewed - at the domain level that means replacing the old with a new one, but at the db level that means simply updating the existing record (unless it's an "owned" type in which case I'll update the user record)
So, is the `RefreshToken` an entity or a value object? | The refresh token is solely defined by its values. And there is no continuity of the object when the values change, because it would be replaced by a new token. This is why it is a value object.
This does not prevent that one of the value refers to a given user-id, which gives the impression of continuity between successive values. But it is not sufficient to make it an entity.
Worthwhile to note: tokens are designed for a value semantic, because once they are issued, they are copied and sent across the net to systems that may not have access to the original source, and using protocols that do not allow update. | stackexchange-softwareengineering | {
"answer_score": 4,
"question_score": 0,
"tags": "domain driven design, entity framework, authentication"
} |
Android - How to Set a semi-transparent layout?
I'm new to android application. !enter image description here
In this picture,there is a bottom layout with some options like play,delete etc.., and has its transparency to show its background.
How to I get like that ? | use `android:background ="#88676767"` change the first _88_ to your selection of opacity
In reply to your comment:
ImageView iv = (ImageView) findViewById(your_imageId);
iv.setColorFilter(Color.argb(150, 155, 155, 155), Mode.SRC_ATOP);
**Third option:**
LinearLayout layout = (LinearLayout) findViewById(R.id.your_id);
Drawable d = getResources().getDrawable(R.relevant_drawable);
d.setAlpha(50);
layout.setBackgroundDrawable(d); | stackexchange-stackoverflow | {
"answer_score": 57,
"question_score": 19,
"tags": "java, android"
} |
Need to display a notification in my iOS application when there is new update (latest version) available in app store
I need to display a notification in my iOS Application when there is a new update available in app store, when I click the notification I need to redirect user to the my app page in itunes.apple.com. | Take a look at Urban Airship. Its a 3rd party server that helps you send push notifications to the devices. The tutorial is available here | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "ios, apple push notifications"
} |
how to connect obiee to postgres db?
Need to connect Postgres database to OBIEE 12c. Is there any official documentation? Is it possible not to use third-party drivers, such as from Cdata? Which driver do I need JDBC or ODBC? OBIEE deployed on Linux | OBI can analyze anything you want via ODBC. You need an ODBC driver. JDBC will only be available when you switch to future Oracle Analytics Server versions. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "database, oracle, postgresql, oracle12c, obiee"
} |
Trying to merge two Google Sheets FILTER function
I have a set of data, I would like to get only an extract of those data. I'm able to do it with the use of this functions:
=filter(row($B$2:$B$10);search("3";$B$2:$B10))
.getWorkbench().getActiveWorkbenchWindow().getActivePage();
IFileStore fileStore = EFS.getLocalFileSystem().getStore(new Path(path));
try {
IDE.openEditorOnFileStore(page, fileStore);
} catch (PartInitException e1) {
e1.printStackTrace();
}
Text files are opened properly but perl script files are executed. I think it uses the default file association to open the file. How can I change it so that my perl script be opened in text editor ? | Try something like this. It bypasses the lookup for default editor in _getEditorId()_ (called by _openEditorOnFileStore()_ ) and directly opens an editor by your choice.
String editorId = "some.editor.ID";
IFileStore fileStore = EFS.getLocalFileSystem().getStore(new Path(path));
page.openEditor(new FileStoreEditorInput(fileStore), editorId);
(wild guess code, but hopefully should work) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "eclipse, editor, eclipse rcp, rcp"
} |
Putting MINUTES in the Max Attribute on a Progress Element
So I have a songDuration variable:
for example:
this.songDuration = 4:20
I am using angular 4, so I am using interpolation to input the value
<progress value="{{songTime}}" max="{{songDuration}}"></progress>
when I do this, I get the error message "The provided double value is non-finite" in the console.
How could I convert this variable to a value that would be compatible with the max attribute? | Try this
convert(input) {
var parts = input.split(':'),
minutes = +parts[0],
seconds = +parts[1];
return (minutes * 60 + seconds).toFixed(3);
}
Then
this.songDuration = this.convert('4:20');
this.songTime = this.convert('<something else>');
(comment if there was any problem) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "angular, audio, progress"
} |
How to apply a function on a selection of columns in a pipe sequence in R?
I have a dataframe (or a tibble no matter) with many columns and I want to apply a function (let's say rowSums) on only 7 of them, but I don't want to get reed of the others. The trick is that I want to do so in a pipe sequence \- create (or read the data) \- apply the function \- optional operation after that
Here is a reproductible exemple on a dataframe where I would like to rowSums on the first 3 columns
data <- data.frame("v1" = runif(10, 0, 10), "v2" = runif(10, 0 ,10), "v3" = runif(10, 0 ,10), "v4" = rep("some_charchter", 10))
the way I would usually do it is
data$sum <- rowSums(data[,1:3])
but I want something like this
data <- data.frame("v1" = runif(10, 0, 10), "v2" = runif(10, 0 ,10), "v3" = runif(10, 0 ,10), "v4" = rep("some_charchter", 10)) %>%
mutate(sum = rowSums())
Thanks for your help ! | You can access your data object inside a pipe using `.`. Therefore `mutate(sum = rowSums(.[, 1:3]))` does the trick:
data <- data.frame("v1" = runif(10, 0, 10), "v2" = runif(10, 0 ,10), "v3" = runif(10, 0 ,10), "v4" = rep("some_charchter", 10)) %>%
mutate(sum = rowSums(.[, 1:3]))
data
v1 v2 v3 v4 sum
1 2.280871 0.1981815 7.5349128 some_charchter 10.013965
2 1.250208 7.6687056 0.6193483 some_charchter 9.538262
3 6.782954 3.6973201 2.7694021 some_charchter 13.249677
4 3.809574 6.8641731 3.1271489 some_charchter 13.800896
5 9.339726 4.4571677 5.4489081 some_charchter 19.245802
6 6.623371 3.9594287 0.6025072 some_charchter 11.185307
7 6.843193 1.3548732 3.1826649 some_charchter 11.380731
8 2.377099 7.5661778 9.6320561 some_charchter 19.575333
9 3.582874 2.1485691 8.2970807 some_charchter 14.028524
10 4.565336 3.7073800 0.3355328 some_charchter 8.608248 | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 4,
"tags": "r, dplyr, tidyverse, magrittr"
} |
JQplot hide serie by clicking on its legend name : tooltip always displayed
I am using JQPlot with legend plugin to toggle series displaying by clicking on its legends names.
legend: {
show: true,
placement: 'outsideGrid',
renderer: $.jqplot.EnhancedLegendRenderer
}
It is working, but the serie tooltip is always displayed when the serie is hidden. It is an issue if you have plenty of series and you want hide all but one : all tooltip of the hidden series are displayed on mouse over.
Here is a fiddle to explain the problem : < | I experienced this bug a while back. See my post on the jqPlot Google group: <
Essentially, the code is checking to see if each line is visible before raising an event. The problem is that the visibility is not being dealt with correctly on the Javascript side (the CSS is fine), hence the issue you are seeing where a hidden series is still deemed visible.
My solution was to set `s.show = s.canvas._elem.is(':hidden');` in the `Series.prototype.toggleDisplay` method.
This appears to have been resolved since version 1.0.4r1120 - try updating to a more recent version to see if that helps. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "jquery, graph, jqplot"
} |
Jquery selecting for button
I have a a list that is generated via PHP and SQL and within each styled row I have a favorite button. I want it so when I click the favorite button it toggles a class that changes the color of it.
It works for the first one but any other button in my list doesn't work.
<button id="favorite" type="button" class="btn btn-xs btn-success" title="Follow">
<span class="glyphicon glyphicon-star"></span>
</button>
<script>
$("#favorite").click(function() {
$(this).toggleClass('clicked');
});
</script>
I looked on similar questions before posting but I didnt see anything related to what I'm trying to accomplish and even google didn't really help me. I'm sure this is a simple task. I'm fairly new to JQuery | If you change your `id` to a `class`, your code should work fine:
<button class="favorite btn btn-xs btn-success" type="button" title="Follow">
<span class="glyphicon glyphicon-star"></span>
</button>
<script>
$(".favorite").click(function() {
$(this).toggleClass('clicked');
});
</script> | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "javascript, jquery, selector"
} |
GWT PRESENTER MOCKING
Is it a good practice for using `GWT.create` for instantiating a Asynchronous Interface in the GWT Presenter?
The reason why i am asking is i need to write Junit test cases for the presenter (i dont want to use the GWTTESTCASE) and using mockito to mock and stub things that i require.
But i cannot mock on these Asynchronous interfaces because i am using GWT.create to create them
Please let me know in case more details are required
Thanks | An instance of the asynchronous interface should be passed to the presenter via a constructor or set method, so all the GWT.create calls are outside the Presenter. This allows you to pass in a mock instance within the Junit tests. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 1,
"tags": "gwt, mocking, mockito"
} |
How to input ⍻(not check mark) in latex?
I want to know how to input not check mark in LaTeX. Information of this symbol: < | Hope it helps You (I'v tried)
 -- (1,.7) -- (.25,.15) -- cycle (0.75,0.2) -- (0.77,0.2) -- (0.6,0.7) -- cycle;}
\newcommand{\notcheckmark}{{$\surd$}\textsuperscript{\textcolor{black}{\kern-0.35em{\bf--}}}}
\begin{document}
0) \notcheckmark\\
1)% bbding
\bcancel{\Checkmark} or \bcancel{\CheckmarkBold}\\
2) \halfcheckmark\\
% cancel
3) \( \bcancel{\surd} \)\\
\end{document} | stackexchange-tex | {
"answer_score": 4,
"question_score": 2,
"tags": "symbols, unicode, unicode math"
} |
How to import numbered files in R
I have multiple files named `xdata.ascii` and `x` is a number. How can I import all the files with names from `1data.ascii` to, for example, `100data.ascii`. I have other `.ascii` files that have a different name and do not want to import them. | We can use `list.files` to get all the files that have the pattern
files <- list.files(pattern = "\\d+data\\.ascii", full.names = TRUE)
Then read the files by looping over with `lapply` into a `list`
lst <- lapply(files, read.csv) | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 4,
"tags": "r, import"
} |
Functionality of sprintf for NSString
How can I get the functionality of `sprintf` in Objective-C? The function is of course part of `stdio` in C, so I could certainly invoke it, but since I'm using Foundation, I need it to work with `NSString`s as well.
## EDIT
I apologize for my inarticulateness, but I'm actually hoping for something more like the PHP `sprintf` **function** that returns a string. (This was perhaps slightly evident before Josh Caswell's very efficient edit of my question.) It would be like `NSLog` but instead of writing to console would give a string (or pointer) as a return value. | One option:
NSString *OCSprintf(NSString *format, ...) NS_FORMAT_FUNCTION(1,2);
NSString *OCSprintf(NSString *format, ...)
{
va_list args;
va_start(args, format);
NSString *result = [[[NSString alloc] initWithFormat:format arguments:args] autorelease];
va_end(args);
return result;
}
This just wraps `stringWithFormat:` (more precisely, one of its cousins) as a function as you requested. The `NS_FORMAT_FUNCTION(1,2)` ensures you still get format string checking. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "objective c, cocoa, nsstring, printf"
} |
Laptop keyboard issue – some of the keys don't work
I have a problem with built-in keyboard. I use Acer V3 GT 572G with installed Ubuntu 14.04 + KDE. Problem exists from the first day of usage (I got it only few days).
**Problem:** it happens that some of the keys don't work. Always the same keys are affected (left ctrl, backspace,i,o) and few additional which sometimes work and sometimes don't (some of the numbers from the top of the keyboard). Problem exists only with built-in keyboard, USB keyboard works fine. Problem occurs in most cases after log ut, but sometimes it cannot be predicted; I get an impression that it's related with the position of the laptop, but I am not able to confirm it with absolute certainty.
In the beginning reboot helped, currently I need to restart the laptop more than 1 time to 'fix' it.
**Question:** Can you help me? Should I do some more test, what should I check? | Since everything works with a USB keyboard, it is definitely a hardware issue. The first thing you should try is to remove the keyboard. Consult your manual or Acer's website for support on how to do so. Once it is removed, used canned air and blow air in between the keys. This may dislodge some debris that might be preventing the keyboard from working properly. Reattach the keybaord's ribbon cable to the motherboard and test if it works normally. If it does not, then you need to replace the keyboard, as some part of it is broken. You should be able to get a replacement from Acer. If it does work normally, then put it back in the case and close it up. If it stops working in the case, then it could be the case is flexing the keyboard enough to cause an issue. If thats the problem, then you would have an issue thats harder to fix. Acer would be able to replace the case, probably at cost if its not under warranty. | stackexchange-superuser | {
"answer_score": 2,
"question_score": 6,
"tags": "ubuntu, keyboard"
} |
Java - Swing setting colour to text in JTextArea
I have a JTextArea which has its text set to a string of information. In this string of information I have a variable which I would like coloured red, to do this I edit the string as follows:
"Result: <html><font color=red>" + negativeValue + "</font></html>"
I would expect this to give Result: ## where the number is red. However it just puts the following into the text area:
Result: <html><font color=red>##</font></html>
I'm not really sure how to get this working, so could someone offer advice as to how to do so? | `JTextArea` is not a component designed for styled text. If the text can be all one color, call `setForeground(Color)`.
Otherwise use a styled text component such as a `JEditorPane` or `JTextPane`. For more info. on using them, see How to Use Editor Panes and Text Panes.
Also as pointed out by others, the entire `String` must start with `<html>` . | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 5,
"tags": "java, string, swing, colors"
} |
Как найти все class(css) в строке?
Каким образом можно извлечь из строки все class=" **class_name** " ?
Не силен в регулярных выражениях, но думаю извлекать все что после =" и до первой "
Буду очень благодарен за помощь с рег. выражением. | Ваш **вариант** можно существенно **ускорить**:
preg_match_all('~class="\K[^"]+~is', $str, $arr);
* * *
И кроме этого, не будет захвата ненужных подстрок. | stackexchange-ru_stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "php"
} |
Where to place an unmanaged DLL for use importing into a C# program?
This must be a really stupid question, but I'm still very green when it comes to C#.
Anyway, I've got a DLL and I'm importing it with a line like this:
[DllImport(@"MyCoolDll")]
I've lifted this straight from the demo app provided by the vendor, but it keep complaining that it can't find the DLL. The actual error (from Visual Studio 2010) is like this:
Unable to load DLL 'MyCoolDll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
I've tried placing the compiled DLL in the bin/debug and bin/release folders. I've even tried copying it to system32, but nothing seems to work.
Any ideas? | Your DLL may have dependencies that also need to be loaded. Did you check for that? | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "c#, dll, visual studio 2010, dllimport"
} |
python: retrieving ceiling key and floor key in a dictionary or a set
I have a dictionary with a bunch of integer keys. for keys I don't have, I'd like to be able to retrieve the smallest and largest keys right before and after they key I want to retrieve but that does not exist.
The Treemap class in java has two methods doing exactly this: `ceilingkey()` and `floorkey()`.
> How can I do this with python?
As an example I have a dictionary like this:
{ 1: "1", 4: "4", 6: "6" ..., 100: "100" }
If I ask for key `1`, I'll retrieve `"1"`, but if I look for key `3`, I should get `KeyError` and hence be able to get `floor(3) = 1` and `ceil(3) = 4`. | def floor_key(d, key):
if key in d:
return key
return max(k for k in d if k < key)
def ceil_key(d, key):
if key in d:
return key
return min(k for k in d if k > key)
I'm not sure how you want to handle border conditions. Note that this will raise an exception (`ValueError`) if you are asking for the floor/ceiling of a key that's lower/higher than anything in the dict. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 10,
"tags": "python, dictionary, tree"
} |
Solving the marginal probability given the probability distributions
Given the probability distributions as follows
$P(b_1|a_0,c_0)=p$
$P(b_1|a_1,c_0)=o$
$P(b_1|a_0,c_1)=n$
$P(b_1|a_1,c_1)=m$
$P(a_1|c_1)=x$
$P(a_1|c_0)=y$
$P(c_1)=r$
I need to find $\dfrac{P(b_1|a_0)}{P(a_0)}$
My attempt:
$\dfrac{P(b_1|a_0)}{P(a_0)}=\dfrac{P(b_1|a_0)}{P(a_0,b_0)+P(a_0,b_1)}=\dfrac{P(a_0,b_1,c_1)+P(a_0,b_1,c_0)}{P(a_0,b_0,c_0)+P(a_0,b_0,c_1)+P(a_0,b_1,c_0)+P(a_0,b_1,c_1)}$
I was able to solve the numerator using the given probabilities and the formula $P(a,b,c)=P(b|a,c)\cdot P(a|c)\cdot P(c)$ but I cannot figure out how to solve the denominator part | Although you haven't explicitly stated, it seems that there are three RVs $a,b,c$ with binary values, e.g. $a_1$ meaning $a=1$.
Given the last three probabilities, i.e. $P(a_1|c_1), P(a_1|c_0), P(c_1)$ you can find the complete joint distribution of $P(a,c)$. And, when you multiply the first four probabilities with corresponding joint distributions of $a$ and $c$, you can find the complete joint distribution of $P(a,b,c)$, from which you can find any probability you like.
For example: $$P(a_0,b_0,c_0)=P(b_0|a_0,c_0)P(a_0,c_0)=(1-p)P(a_0|c_0)P(c_0)=(1-p)(1-y)(1-r)$$
Besides, your numerator is incorrect, it should have been the following: $$P(b_1|a_0)=P(c_1,b_1|a_0)+P(c_0,b_1|a_0)$$ | stackexchange-stats | {
"answer_score": 1,
"question_score": 1,
"tags": "probability, distributions, conditional probability, marginal distribution"
} |
Matlab multiply matrix with matrix along third dimension
I have a matrix `A` of size `m x n x 3` and I have have a `3x3` matrix `K`. Now what I want to do is something like this:
for row = 1:m
for col = 1:n
A(row,col,:) = K*[A(row,col,1);A(row,col,2);A(row,col,3)];
end
end
I'd like to have an efficient solution without a loop, as loops are very slow, because `m x n` is usually the size of an image.
Anyone got an idea? | M = 1000;
N = 1000;
L = 3;
A = rand(M,N,L);
K = rand(L,L);
Q = reshape((K * reshape( A, [M*N, L] ).' ).', [M, N, L]);
Error check:
Z = zeros(M,N,L);
for mm = 1 : M
for nn = 1 : N
Z(mm,nn,:) = K * squeeze( A(mm,nn,:) );
end
end
max( abs( Z(:) - Q(:) ) )
ans =
0 | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 3,
"tags": "matlab, matrix, matrix multiplication"
} |
Font affects MS Word's spell check ability?
When I use the Wingdings font, the spell checker doesn't work (Wingdings isn't the only font I have this problem, there are others).
How can I fix this, how can I force the spell checker to ignore the font, and focus on the characters themselves?
This is what I mean: !My document
BTW I did **not** click ignore, or anything of that nature. | I'd assume this is because different fonts could signify different languages. English fonts are checked using the appropriate English spelling dictionary, but for non-English fonts it would not make sense to check it using an English dictionary. Wingdings being a symbol font, not a language font, is probably not checked by any dictionary ever.
Another way to look at it is this: If you were typing in a font such as MSP Mincho (Japanese), you would not want the system to spell check the output based on an English dictionary. | stackexchange-superuser | {
"answer_score": 4,
"question_score": 4,
"tags": "windows, microsoft office, microsoft word 2007, spell check"
} |
Ajax and SEO. Will my loading part of the html be indexed by SE?
So, I have an index.html file.
I load some div from another.html file like so: a href="another.html"
Then, in jQ, I'm using .preventDefault(); on this anchor tag before .load
Will my another.html file be indexed by Google, Yahoo and so on? | Yes. In fact, they way you did this is called Progressive Enhancement and is how dynamic website _should_ be built as it allows for non-JavaScript enabled users to still get to the content. Good job. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ajax, seo"
} |
XGBoost custom formatting for training console outputs
The Python API of XGBoost, by default, displays metrics in the following format to the console during training:
[0] validation_0-mlogloss:6.93514 validation_1-mlogloss:6.98867
[1] validation_0-mlogloss:6.46165 validation_1-mlogloss:6.53638
[2] validation_0-mlogloss:6.12659 validation_1-mlogloss:6.22222
...
I've never found a trace of this in the documentation, but is it possible to use a callback for custom formatting and have the output look more like:
6.93514,6.98867
6.46165,6.53638
6.12659,6.22222 | Maybe the callback: xgboost.callback.EvaluationMonitor(rank=0, period=1, show_stdv=False)
Otherwise, mock/patch() the source code (<
I think for the function _fmt_metric | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, xgboost"
} |
Google Trends: What difference of the buttons "Top" and "Rising"
<
I can't understand, what is: What difference of the buttons "Top" and "Rising". What queries in this pages? What do the numbers(100, 40) mean? | top: what has been at top overall. Rising: what is becoming popular. **Example:**
desktop usage has been on top.
however, cell phone use is rising and is popular (rising more than everything else even computers)
top is average of some long time...where recent acceleration is what recently popular or rising means. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "google trends"
} |
How to change the page layout with memoir?
On the question How to do the memoir headings fix but not have my text going over the page bottom margins? was said by @daleif:
> Also use the memoir interface to change the layout instead of manipulating individual lengths
So, how would I use the _memoir interface_ to set the `\setlength{\headheight}{14.0pt}`?
Also, for changing the page layout I am using this:
\setlrmarginsandblock{2.5cm}{1.5cm}{*}
\setulmarginsandblock{2cm}{1.5cm}{*}
\checkandfixthelayout%
Would this be correct with the _memoir interface_ mentioned for changing the layout?
* * *
Related:
1. Specific margin size in memoir
2. Trying to understand Memoir page layout
3. Memoir Page Layout doesn't work as expected: Text shifted right | As stated in section 2.5 of the `memoir` manual _Headers , Footers and Marginal Notes_ you can do that by setting
\setheadfoot{14pt}{<hfootskip>}
Be advised of the recommendation
> It is usual to set the `\headheight` to at least the value of the `\baselineskip` of the normal body font. | stackexchange-tex | {
"answer_score": 1,
"question_score": 1,
"tags": "margins, memoir"
} |
Client Side Cart: Adding two items with same description in array
Hello i am building a cart using local storage i have soo far been able to add and remove items in the cart now what i want to do now is this:
When a user adds an item that already exists in the cart array the quantity property alone is updated instead of adding another separate item to the cart array, is there an array function that does this already? | Assuming that each cart item is an object, just update the property of the object if the user has already added it to the cart:
for (var i=0; i<cartItems.length; i++) {
if (cartItems[i].name == addedItem.name) {
cartItems[i].quantity += 1
}
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, angularjs"
} |
Android Multiple Scrolling Views
I need to have a dynamically set grid of images surrounded by a scalable image. Both of these views need to scroll concurrently.
Attempt 1:
<RelativeLayout>
<GridView />
<ScrollView>
<ImageView />
</ScrollView>
</RelativeLayout>
This however only has the ImageView scrollable.
Attempt 2:
<RelativeLayout>
<GridView android:background="@drawable/img"/>
</RelativeLayout>
If I switch to putting the image as the gridview's background the gridview scrolls, but the image does not scale with the scroll, rather it just fills the whole screen.
I have looked through other posts and have seen the ExpandableGridView proposal, but I would like to stay away from a hack that would take up a lot of memory on each scroll since I am displaying a lot of thumbnail images.
Any advice would be greatly appreciated. | Correct me if I'm wrong, but it sounds like you have a `GridView` that displays a bunch of thumbnails and you have a background that you're wanting to scroll with the GridView, right?
If so, you can't (at least I don't think you can) accomplish that with two scrollable views. The system has no way of differentiating which view the user is trying to scroll. If you really want to have the background scroll, your best bet would be to use the same method that is used in scrolling videos games.
The way that most scrolling games work is by scrolling a long image or cycling between two images and creating a scrolling simulation when the user "scrolls." If you'd like to see how this works, check out this video game tutorial. It should give you a basic idea of how to go about creating a scrolling simulation. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "android, gridview, scroll"
} |
Starting Python script without explicitly having X11 open
I had Python v2.3 on my system. When I wanted to run a Tkinter script I could just use
python myscript.py
I recently upgraded to Python 2.5 and now I need to have X11 running and the "DISPLAY" environment variable set before I can run any of my scripts. This is bad for me, because I can't distribute any scripts without explicitly stating "if you're running Python > v2.3, you will need to have X11 open before running this script". Is there a way around this? I'm on OS X Tiger. | If I had to guess (and I do...), it sounds like you installed an X11 based version of python and tkinter rather than one that uses the native windowing system on OSX. I think you can safely write your scripts without telling people they have to have X11 running. You merely have to say they have to have a proper environment set up -- either a native version of python+Tkinter or have X11 running and have an X11-based version of python+Tkinter
In other words, this isn't a regression in python that you have to code around, it's just a side effect of your particular installation of python. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "python, macos, x11, tkinter"
} |
Can magnons or phonons exist at zero temperature?
Can in principle, magnons or phonons exist at zero temperature? If not, why? If yes, how? | Phonon modes are the eigenmodes of the dynamical matrix. The solutions exists independent of temperature. But at zero temperature none of these modes are occupied. Only the zero point energy remains. In that sense: no, there are no phonons at 0K. | stackexchange-physics | {
"answer_score": 4,
"question_score": 1,
"tags": "condensed matter, solid state physics, symmetry breaking, quasiparticles"
} |
How can I make a SWT table's cell editable in Eclipse RCP?
My question is that I have a SWT Table in Eclipse RCP project. I want its cells to be editable when I desire. How can I achieve such a functionality in Eclipse RCP, suggest me. Or, can we achieve exactly this functionality with JFace, Nebula Table controls ? | There are a couple of ways to do this. Please have a look at the following snippets:
* SWT Snippet: edit the text of a table item (in place)
* JFace Snippet: Snippet88 \- Demonstrates different CellEditor-Types in one COLUMN with 3.3-API of JFace-Viewers
Hope these examples are useful to you.. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "swt, cell, rcp"
} |
Character Case Problems
So I have my login form in my website.
And for example my username is JuvarAbrera (saved in mysql).
When I try to login using this username ---> juvarabrera
It is still logged-in in my website. Now, I want it NOT to logged-in because of the the J and A are uppercased.
So, how can I do that? I think I explained it very well.
Thanks. :) | You can collate the value in the query:
SELECT `id` FROM `users` WHERE `username` = 'php_value' COLLATE utf8_general_cs | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "php, mysql, character"
} |
CSS 3 fade animation on hover - issue in Opera
So I have these rules:
a{
background-color: transparent;
-webkit-transition: background-color .3s ease-in-out;
-moz-transition: background-color .3s ease-in-out;
-o-transition: background-color .3s ease-in-out;
-ms-transition: background-color .3s ease-in-out;
transition: background-color .3s ease-in-out;
}
a:hover{
background-color: #fff;
}
which are supposed to make the browser fade in/out a white background on mouse over.
It works in Chrome and Firefox, but in Opera it fades from a grey color to white, instead of transparent to white...
How can I fix that?
Thank you | I don't know the answer to your explicit question, but maybe if you transition from rbga rather than from transparency?
a{
background-color: rgba(255,255,255,1);
}
a:hover{
background-color: rgba(255,255,255,0);
} | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "css, css transitions"
} |
Android check if string contains number before a word
I am currently using an arraylist to store some text and then later checking that list to see if it contains certain words and parsing them for the numbers. For example my arraylist could contain:
[cancel, port, 4.5, 3 min, 3/4 terminal]
And I want to parse the `3 min` to get the number `3`. I currently use:
for (int i = 0; i < textArray.size(); i++) {
if (textList.contains("min")
number = Double.parseDouble(textList.get(i).replaceAll("[^0-9]", ""));
}
But the issue I am having is that it will see the `3 min` and it will also see the `3/4 terminal` because it contains `min`. Is there a way to use contains to make sure the word is exactly `min`? | Instead of `contains()` use `endsWith()`:
if (textList.endsWith(" min") {
number = Double.parseDouble(textList.get(i).replaceAll("[^0-9]", ""));
} | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "java, android"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.