INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
windows 7 phone Tilt Effect?
How to add TiltEffect for datepicker and stackpanel with out using listbox??
|
I was not happy with the Silverlight toolkit tilt effect, especially the way that it is'magically' applied to elements based on type. So I wrote an alternative. You can also configure how much 'tilt' you want to apply. The sourcecode can be found here:
Metro in Motion Part #4: Tilt Effect
You can then individually apply tile to elements as follows:
<Button local:MetroInMotion.Tilt="6"/>
Where the integer specifies how much tilt to apply. I would recommend using quite low values, the native effect is quite subtle, however people tend to make it far too extreme in their own silerlight applications, Metro effects should be subtle, they should not shout at you!
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "windows phone 7, effects"
}
|
Kotlin async callback unit test
I have a class:
class SomeClass(private val executor: Executor) {
fun doSomething(id: Int, callback: (String, Int) -> Unit) {
executor.execute {
val intValue = id + 1
val stringValue = "Some string result"
callback(stringValue, intValue)
}
}
}
How I can create a unit test for the doSomething method?
|
I have researched this question for about 3 days. I was hoping this could be resolved using Mockito. Fortunately today I found ConcurrentUnit utils for testing async code.
My solution:
val executor = Executors.newSingleThreadExecutor()
lateinit var someClass = SomeClass(executor)
@Test
fun test() {
val waiter = Waiter()
someClass.doSomething(1) { string, int ->
waiter.assertNotNull(string)
waiter.assertEquals(int, 2)
waiter.resume()
}
waiter.await(100, TimeUnit.MILLISECONDS)
}
Thanks all for your help!
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "unit testing, kotlin, mockito"
}
|
jQuery: Wrap outputted text in span?
I have a jQuery script that inserts an `<input>` after the outputted text. My question is how do I wrap the outputted text in a `<span>` before the `<input>` is called?
$(".todo-deadline").each(function() {
$(this).html($(this).text() + "<input readonly='readonly' class='hasDatepicke2' type='text' value='"+$(this).text()+"' />");
});
|
Try
$(".todo-deadline").each(function() {
var $this = $(this), text = $this.text();
$this.empty().append($('<span />', {
text: text
})).append('<input readonly="readonly" class="hasDatepicke2" type="text" value="' + text + '" />')
});
Demo: Fiddle
Or
$(".todo-deadline").html(function(idx, html) {
return '<span>' + html + '</span>' + '<input readonly="readonly" class="hasDatepicke2" type="text" value="' + html + '" />'
});
Demo: Fiddle
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "javascript, jquery"
}
|
Restart tmux sessions in Ubuntu (running Python)
I have five background processes running in tmux on my Ubuntu server. Each pane is a python script that is a never ending while loop.
$ tmux ls
process1: 1 windows (created Fri Dec 14 10:12:40 2018) [143x31]
process2: 1 windows (created Fri Jan 11 10:23:55 2019) [128x30]
process3: 1 windows (created Sun Feb 10 13:30:03 2019) [143x33]
process4: 1 windows (created Tue Dec 18 22:41:50 2018) [145x33]
process5: 1 windows (created Mon Jan 14 15:42:04 2019) [143x33]
Is there a command to stop and start, or restart, all services? Rather than going into each one and manually stopping and restarting it?
Thanks
|
The easiest method will probably involve
bind-key * set-window-option synchronize-pane
This bind (or any other key you choose to set) will allow you to type `<prefix>*` to begin typing to _all_ panes in your window. (Undo this feature with `<prefix>*` again)
For your use case, to stop them all, you'd send `C-C` to all panes by literally typing Ctrl+C. To restart all the processes, just hit the up arrow to go back in each pane's history (or type `!!` if you prefer) and then hit `Enter` to start those up again.
This assumes that starting each process takes the same number of commands in each pane.
I've checked, and I can't find a way to make a tmux pane restart its current process; tmux doesn't seem to know enough about the terminals it's displaying for a more resilient answer.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "python, ubuntu, ssh, tmux"
}
|
MySQL Query: output all players villages by coordinates
I need help with a query. You are given the tables: player (playerID (primary key), playerName) and village (villageID, villageName, x, y, population, playerID (foreign key) and check that x in y is between -400 and 400).
The task is to write a query, where the output is players names, who have ALL of their villages between 100 and 200 on x, and 0 and 100 on y.
Currently i have this query, but it doesnt look for ALL of the villages.
SELECT i.playerName
FROM player i JOIN
village n
USING(playerID)
WHERE (n.x BETWEEN 100 AND 200) AND (n.y BETWEEN 0 AND 100);
|
If you want _all_ the villages, then you need to compare all rows. This suggests aggregation:
SELECT i.playerName
FROM igralec i JOIN
naselje n
USING (playerID)
GROUP BY i.playerName
HAVING SUM( (n.x BETWEEN 100 AND 200) AND (n.y BETWEEN 0 AND 100) ) = COUNT(*);
The `HAVING` clause is guaranteeing that all rows (i.e. cities) meet the condition for a given player.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "mysql, sql"
}
|
Need help with Subquery in parent-child relationship query
I have a query where I have to query contacts and their cases only if case `status != "Completed" or "Pending"`. But in my Parent-child query, cases are getting retrieved irrespective of the filter on status.
select id,Casedeletedcontact__c,(select id,status__c from cases1__r where status__c!='Completed' or status__c!='Pending') from contact

When you use `AND` though, both parts need to be satisfied for the result to be true (and for the child row to be returned). Since the 'Pending' and 'Completed' statuses can only ever satisfy one of those two filters, rows with those statuses will not be included. (`true && false` = `false`)
|
stackexchange-salesforce
|
{
"answer_score": 1,
"question_score": 0,
"tags": "soql, query, filters, parent to child"
}
|
B2C Getting list of identity providers configured for a B2C policy?
Is there a Microsoft Graph API/other API to get the list of identity providers configured for a particular B2C policy?
One extremely hack method could be to retrieve the login page itself and scrape it for the CP and SA_FIELD values. Obviously brittle. URL has the form:
|
AFAIK ,currently there is no such api to get the list of identity providers configured for a particular B2C policy , if you need that feature, you could send a feedback in here .
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "azure, azure active directory, azure ad b2c, azure ad graph api"
}
|
Call a C++ project main() in Python in Visual Studio?
I have **a C++ project and a Python project under one solution in Visual Studio.** I am reluctant to modify the C++ project, because it is complicated and now complete. I don't want to touch on it any more. So to integrate them, I choose to call the C++ project in Python, instead of the other way round.
I wish to **pass the parameters from Python to**
int main(int argc, char** argv)
of **the C++ project.**
How may I do it?
|
The arguments of `main()` are the command-line arguments of the program. So if you do for example this in Python:
subprocess.Popen(['myCppprogram.exe', 'foo', 'bar'], ...)
then the following will hold in `main()`:
int main(int argc, char** argv)
{
assert(argc == 3);
assert(argv[1] == std::string("foo");
assert(argv[2] == std::string("bar");
}
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "c++, python"
}
|
Oracle `partition_by` in select clauses, does it create these partitions permantly?
I only have a superficial understanding on partitions in Oracle, but, I know you can create persistent partitions on Oracle, for example within a `create table` statement, but, when using `partition by` clauses within a `select` statement? Will Oracle create a persistent partition, for caching reasons or whatever, or will the partition be "temporary" in some sense (e.g., it will be removed at the end of the session, the query, or after some time...)?
For example, for a query like
SELECT col1, first_value(col2)
over (partition by col3 order by col2 nulls last) as colx
FROM tbl
If I execute that query, will Oracle create a partition to speed up the execution if I execute it again, tomorrow or three months later? I'm worry about that because I don't know if it could cause memory exhaustion if I abuse that feature.
|
`partition by` is used in the query(windows function) to fetch the aggregated result using the windows function which is grouped by the columns mentioned in the `partition by`. It behaves like `group by` but has ability to provide grouped result for each row without actually grouping the final outcome.
It has nothing to do with table/index partition.
scope of this `partition by` is just this query and have no impact on table structure.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "oracle, database partitioning"
}
|
UICollectionView with 2 separate design
I have `UICollectionView` and the selected cell should like the yellow one in pic. So how to have a separate design for the selected cell and how to draw that curve above it ? Shall I use 2 separate `UICollectionViewCell` for this ? Or there is any alternate way to reuse the same cell on selection.

msdn documentation - SPField.EnforceUniqueValues Property
|
According to the Docs, the best answer to me is that the AllowDuplicateValues attribute is used when defining the field in XML code while the other is used when writing .Net code.
|
stackexchange-sharepoint
|
{
"answer_score": 3,
"question_score": 2,
"tags": "field definition"
}
|
Pushwoosh - Google Cloud Messaging - Transmission
I have to write at school about the transmission of Pushwoosh and Google Cloud Messaging. For example, which protocol is used when a notification got send from the Server via the Remote API. So I would like to know how Pushwoosh works generally, with which protocols.
I don`t really understand much of data-transmission (http, etc.) so it is hard for me, to find that out. It would be great to get an answer, if someone knows how Pushwoosh works.
Thank you!
|
To send message to GCM Pushwoosh uses GCM protocol. That's pretty much POST JSON message over HTTP protocol: <
When sending message to Pushwoosh via Remote API you again POST JSON message over HTTP protocol: <
HTTP protocol: <
JSON: <
I hope it helps!
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "network protocols, google cloud messaging, transmission, pushwoosh"
}
|
remove escape characters from char in c#
I am facing a problem while retrieving nchar(2) from database and assigning to a char variable in c#. Below are the sample values:
**DB value:** S **C# variable value** "S " **DB value:** null **C# variable value** "\0 "
I am retrieving with dynamic variable and after assigning it to a char variable, it is throwing an error. Do I need to trim first and remove the escape characters before assigning it to char variable or is there any standard functions to perform the task?
|
Try this:
string dbValue = ...; // FROM DB!
string cValue = dbValue == null ? String.Empty : dbValue.Trim('\0').Trim();
You will get an empty string as result, for db's null values and also for empty strings...
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c#"
}
|
MySQL Function use provided variables throws error
I want to create a function for calculating the distance between points.
The calculation is going as expected, but i receive an error here:
DROP FUNCTION IF EXISTS CalculateDistance;
CREATE FUNCTION CalculateDistance(breite double, laenge double) RETURNS INT READS SQL DATA
BEGIN
DECLARE breite DOUBLE;
SET @ibk_laenge = breite;
> CREATE FUNCTION CalculateDistance(breite double, laenge double) RETURNS INT READS SQL DATA
>
> BEGIN
>
> DECLARE breite DOUBLE
>
> MySQL meldet: Dokumentation 1064 - You have an error in your SQL syntax; check the manual that >corresponds to your MySQL server version for the right syntax to use near '' at line 5
What's wrong with that?
|
You need to change the delimiter first:
delimiter //
CREATE FUNCTION CalculateDistance ...
END //
delimiter ;
Otherwise the function definition stops at the first `;` which would make it incomplete.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "mysql, create function"
}
|
Android Studio "Edit Configuration" dialog doesn't fit into screen
This might sound weird, that the edit configuration dialog is so big that it doesn't fit my screen and I can't access buttons and options at the bottom:
!Huge dialog
I tried to resize it, but it doesn't let itself be resized or moved higher. Any ideas how to fix that?
|
I feel kinda stupid for not checking this before... But here is the solution:
## !Edit configurations in the dropdown menu
Clicking that will get the same dialog in a scrollable and resizable format: !Same dialog, scrollable and resizable
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "android, android studio"
}
|
ASP Chart - remove unwanted values which are appended to X axis
I have created a simple ASP chart which is displaying a date range (a week) in days on the X axis, and an integer value on Y axis.
I have created a datasource to pull the data, which currently returns this data (forgive the formatting, there are two columns, Date and Value)...
* Date value
* 24/04/2013 9
* 25/04/2013 10
* 26/04/2013 7
* 27/04/2013 12
* 28/04/2013 13
* 29/04/2013 10
* 30/04/2013 1
However when the chart renders, it is appending a day to both the beginning and end of the X axis - Resulting in the dates 22/04/2013 and 1/05/2013 appearing and my x-axis data series. My datasource does not mention anything apart from the data quoted above.
How can I remove the two appended days from the beginning and end of the chart?
Thanks in advance
|
Found the answer!
Under the property "ChartArea" > "Axis" > Change "IsMarginVisable" to false...
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "asp.net, charts"
}
|
Enterprise distribution of an iOS app from a third party developer
I've been asked if we can distribute an iOS app internally (via AirWatch) which has been developed by a third party. We can't use the App Store is because the developer is re-branding their app for our company.
So they would have to sign their app with our Distribution Certificate but what is the safest way (for us) to allow them to do this?
|
You should sign the app yourself. so the 3-rd party developer have no access to your certificates.
1. Enroll to Apple Developer Enterprise program .
2. Create enterprise certificate.
3. Create provisioning profile and any other certificates that the app needs (the developer should know which extras are needed).
4. Get the ipa file (the app) from the developer.
5. Resign the ipa with your own certificate you created earlier - to do so use the iReSign tool.
6. Diatribute the app via your MDM (AirWatch).
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "ios, in house distribution"
}
|
Extracting the same string structures with regex
I'm running the next code:
Pattern p = Pattern.compile("(<http:.*>)");
Matcher m = p.matcher("<http:[email protected]>,<http:[email protected]>");
if (m.find()) {
int groupCount = m.groupCount();
for(int i = 0; i < groupCount; i++){
String groupValue = m.group(i);
System.out.println(groupValue);
}
} else {
System.out.println("nothing was fined");
}
And as output I have only one group value: "http:[email protected],http:[email protected]" But I expect that there should be two groups : Group_1: http:[email protected] Group_2: http:[email protected]
How should I change my regex to achieve this?
Thanks!
|
It's not group. It will be group if your pattern look like "(http:.*)(http:.*)". Group is expression between parentheses. Try this:
Pattern p = Pattern.compile("(<http:([^>]+)>)");
Matcher m = p.matcher("<http:[email protected]>,<http:[email protected]>");
while (m.find()) {
String groupValue = m.group(1); // m.group(2) for email only without http: and <>
System.out.println(groupValue);
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "java, regex"
}
|
How to import .XML code style into IntelliJ Idea 15
I want to use a specific code style in my editor defined in an XML file, which looks something like this:
<code_scheme name="CustomStyleName">
<option name="JAVA_INDENT_OPTIONS">
<value>
...
How is it possible to import this style into IntelliJ Idea. When I go to Preferences->Editor->Code Style->Manage it is only possible to import an Eclipse XML Profile.

|
stackexchange-stackoverflow
|
{
"answer_score": 21,
"question_score": 17,
"tags": "intellij idea, configuration, intellij 15"
}
|
Sequent Calculus
What is sequent calculus? See wiki: <
So basicaly I'd like to produce something like this:
!a sequent calculus
Maybe using Tikz?
|
Have a look at
<
There are some packages described for teXing such sequences. I would guess that the sequence you posted is done using proof.sty
|
stackexchange-tex
|
{
"answer_score": 4,
"question_score": 4,
"tags": "tikz pgf, tables, calculations"
}
|
concatenate strings in a character vector based on element names
I have a named character vector, `a`, that I would like to concatenate some of its elements based on their name
a <- c('item 1' = 'first_i1', 'item 1' = 'second_i2', 'item 2' = 'only_i2')
a
item 1 item 1 item 2
"first_i1" "second_i2" "only_i2"
expected result using blank space as the separator
a_out <- c('item 1' = 'first_i1 second_i2', 'item 2' = 'only_i2')
a_out
item 1 item 2
"first_i1 second_i2" "only_i2"
|
We can concatenate with `paste` by using grouping variables as the `names` of the `vector` 'a'
tapply(a, names(a), FUN = paste, collapse = ' ')
# item 1 item 2
#"first_i1 second_i2" "only_i2"
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "r, string concatenation"
}
|
How to avoid checking for empty value in Haskell?
I'm trying to grasp how Haskell programs can avoid testing for "empty value". I am struggling to get rid of case expression in this program:
main = do url:outputPath:[] <- getArgs
let maybeUri = parseURI url
case maybeUri of
Just uri -> download uri outputPath
Nothing -> return ()
My very rough understanding is that I should use monad transformer so that I can use single `mappend` on Maybe value within IO monad and 'do' syntax should be able to support it. How can I achieve this?
|
Use `forM_` from `Data.Foldable`, which has the following type:
forM_ :: (Monad m, Foldable t) => t a -> (a -> m b) -> m ()
`Maybe` implements the `Foldable` class, behaving like a list with zero or one elements, so when you specialize the `t` in the above type signature to `Maybe` you get:
forM_ :: (Monad m) => Maybe a -> (a -> m b) -> m ()
You use it like this:
forM_ maybeUri $ \uri -> download uri outputPath
It will only run the action if the `Maybe` value turns out to be a `Just`.
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 4,
"tags": "haskell, monads, option type"
}
|
Disable highlight of ListView row on mouse hover?
When I hover the mouse over a ListView item, the row is highlighted. The ListView in C# does not highlight the ListView row on mouse hover however. Is there's a way I can disable the highlight effect in WinAPI?
|
The easiest way is to turn off themes for the control.
SetWindowTheme(hwndCtl, L" ", L" ");
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c++, listview, winapi"
}
|
Mysql php - web app scale? (What means large?)
I'm working on a web app, and i already have a hosting. I made some websites and apps for my clients (quite small traffic), but now i would like to create a web app which is free to use, so i expect 5000+ users.
I read a lot of questions and answers here what means large traffic and large table. Like hundreds of GB-s and 10 million rows is not large. I guess it isn't, but i would like to start this app and i have a "simple" hosting (php, mysql, "unlimited" db size).
**Can you define size intervals, scales? ex.: "100M < rows means large"?**
I guess for example if 5000 users has got 1000 rows/user is enough to serve with this hosting. But i don't want to interrupt users with performance problems so if this user count become 500.000, i don't want to get lost in the dark and loose users.
**Where is the approximate limit, whate could make performance issues?** (with this hosting)
|
I guess that for the start this should be fairly enough. As time will pass You will see whether Your project has success and brings hundreds of new users every day. If so then You will have to consider moving to a bigger hosting or to a dedicated server and after that You may consider creating a cluster of PHP and MySQL servers...
So, shortly: for the start this is enough.
To performance issues - this does not depend only on the amount of users, rows, etc. It also depends on how the webapp will be written - sure there could be done som PHP and SQL performance tuning but until You will have a webhosting You can do only a little (if any) server performance tuning.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "php, mysql, web applications, hosting, large data"
}
|
When Managed Bean creates and property of the beans creates?
In our application we use jsf,we have to redirect the user to home page after their session will be expired.For that i need a path of the home page which i kept in my logout managed bean as a managed bean property.But after session expired if i try to access that it will arise null pointer exception(managed bean becomes null).Then i have decide to try alternative (i.e)create logout class manually and try to access the property, at that time the property which i wants to access is become null.How can i access that property? Please help me. Thanks in advance.
|
In addition to the previous answer:
You could use (in web.xml)
<error-page>
<exception-type>javax.faces.application.ViewExpiredException</exception-type>
<location>viewexpired.jsp</location>
</error-page>
Or Context Parameters instead of Session Attributes. See:
* <
* <
Or use (in faces-context.xml)
<managed-bean-scope>application</managed-bean-scope>
for your bean, so it will stay independent from the session.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java, jsf, ajax4jsf"
}
|
Не работает transition по linear-gradient
Всем привет!
Когда я использую смена цвета через `hover` таким образом:
.button {
background: linear-gradient(180deg, #EEF2EE, #D4D4D4);
-webkit-transition: .5s ease-in-out;
-moz-transition: .5s ease-in-out;
-o-transition: .5s ease-in-out;
transition: .5s ease-in-out;
}
.button:hover{
background: #FFDC29;
}
Мой элемент `buttom` становится прозрачным между обычным состоянием и `hover`.
Помогите правильно реализовать смену цвета, спасибо!
|
Обычно пользуются следующим трюком:
.button {
position: relative;
display: inline-block;
background: linear-gradient(180deg, #EEF2EE, #D4D4D4);
z-index: 1000;
}
.button::before {
content: "";
display: block;
opacity: 0;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #FFDC29;
transition: opacity 0.5s ease-in-out;
z-index: -1000;
}
.button:hover::before {
opacity: 1;
}
<div class="button">Button</div>
_Т.к transition по gradient'ам все еще не поддерживается._
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "css, css3, transition, linear gradient"
}
|
Adding editable content to prestashop footer template
Please help. I need to add editable content (for example company contacts) to prestashop footer template (footer.tpl).
Hardcoding the footer.tpl is no problem but i need to add editable content (via backend). What is the simplest way to include CMS block content in to the footer.tpl?
Prestashop 1.5
|
The simplest way is to get one of the free modules and to attach it to "footer" hook.
* <
* <
* <
Note that some of them do not have multi-lingual support - in case you need it.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -3,
"tags": "prestashop, prestashop 1.5"
}
|
Arc Length with Vector-Valued Functions
"Consider the path of a particle in a conservative force field represented by the vector-valued function $r(t) = \langle 4(\sin t - t \cos t), 4(\sin t + t \sin t), (\frac{3}{2})t^2 \rangle$."
"A) Find the arc length function $s$."
"D) Show that $|r'(t)| = 1$."
To do this, I took the first derviative of the function. Then, I set up the square root of the sum of each dervived component squared. However, I could not get this to simplify down to $1$, as I assume I should be able to by the instructions in part D. My prof suggests reparameterizing the original function to make the problem simpler. Any thoughts on the new parameter?
|
We have: $$s(t)=\int_0^t |\mathbf r'(\tau)|d\tau$$ Therefore: $$s'(t)=|\mathbf r'(t)|$$
The chain rule and the inverse derivative rule tell us that: $$\mathbf r'(s)=\frac{d\mathbf r}{ds} = \frac{d\mathbf r}{dt} \frac{dt}{ds} = \frac{\mathbf r'(t)}{s'(t)} $$
So that: $$\mathbf r'(s)=\frac{\mathbf r'(t)}{|\mathbf r'(t)|} \Rightarrow |\mathbf r'(s)|=\frac{|\mathbf r'(t)|}{|\mathbf r'(t)|}=1$$
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 0,
"tags": "calculus, derivatives, vectors"
}
|
Must parameter binding be safer (PDO)
I'm making PHP-code, and use database, MySql. I wonder about parameter binding, and here is an example with a field (pw) excluded;
If the user sends a username via form, and it comes as POST
$username = $_POST["username"];
and then is used to log in;
$query = "SELECT * FROM users WHERE username = :username";
then
$stmt = $conn->prepare($query);
$stmt->bindParam(":username", $username);
Has there been any protection? I mean compared to using the POST variable directly.
Greetings
|
It makes no difference whether you use:
$stmt->bindParam(":username", $username);
or
$stmt->bindParam(":username", $_POST['username']);
They both contain the same value, and binding them to the parameter is exactly the same.
The protection comes from binding the parameter with a prepared statement, not the choice of variable to bind it to.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "php, mysql, pdo"
}
|
wordpress wpcf7 - get form value in message body
I have integrated wordpress contact form 7. I have to get form value in message body so that recipient see what exactly user submits the value in form.
|
When you're editing the form, go to the "Mail" tab and below you should see the available field values that can be copied and pasted into your message body a few fields below. There should be a row like below:
[your-name] [your-surname] [your-email]
If you highlight any of those and paste them into the "Message Body", the value that a customer inputs on the frontend should come through to the recipient.
:
return A[1:] + A[:-1]
For speed-up and to avoid allocating a new output array for each function call, I would like to have the output array as an argument, and alter it in place:
def inplace_func(A, out):
out[:] = A[1:] + A[:-1]
However, when calling these two functions in the following manner,
A = numpy.random.rand(1000,1000)
out = numpy.empty((999,1000))
C = original_func(A)
inplace_func(A, out)
the original function seems to be _twice as fast_ as the in-place function. How can this be explained? Shouldn't the in-place function be quicker since it doesn't have to allocate memory?
|
I _think_ that the answer is the following:
In both cases, you compute `A[1:] + A[:-1]`, and in both cases, you actually create an intermediate matrix.
What happens in the second case, though, is that you _explicitly_ copy the whole big newly allocated array into a reserved memory. Copying such an array takes about the same time as the original operation, so you in fact double the time.
To sum-up, in the first case, you do:
compute A[1:] + A[:-1] (~10ms)
In the second case, you do
compute A[1:] + A[:-1] (~10ms)
copy the result into out (~10ms)
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 6,
"tags": "python, arrays, function, numpy, in place"
}
|
Should I dispatch an action when typing?
I'm working with a small project using ReactJS and Redux. I stored data in Redux store and looking for good practice on how to update data in there. I can pass data from store to state and update state every time I type, then update state to store, but I wonder is that a good way to do, or I should update store immediately when typing? Is there a performance issue? Thanks in advance.
|
1) If the input value is not required by other components (be it sibling, parent, or even unrelated components), there is not need to persist it on your store. You should just encapsulate it within your component's state
[inputvalue, setInputValue] = useState('');
<input value={inputvalue} onChange={(e) => setInputValue(e.target.value)}
2) If it is required by other components, you choose to keep the input in store. Do take note that if you follow this approach, you will have to update the store at every instance the input value has changed.
Assuming that it is a connected component,
const { inputValue, updateInputValue} = props;
<input value={inputValue} onChange={(e) => updateInputValue(e.target.value) }
3) If there are any side effects (such as fetching of data from external API) that arise from input change, you might want to debounce the firing of the side effect.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "reactjs, redux"
}
|
NYTimes iPad app style grid view
Does anyone know how the look of the New York Times iPad app (specifically this view: < was achieved?!Article selection view
Essentially, I'm wondering if someone could point me in the right direction for creating something like the above grid with cells that are different sizes.
|
Basically, you start with a UIScrollView and then start to re-create all of the work UITableView does for you automatically.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "ios, ipad, gridview"
}
|
How to store integers sepated by commas in a variable in Python
I am trying to store randomly generated integers in a single variable. They need to be separated by commas such that I can put the variable into a function and it will accept the syntax.
from SimpleGraphics import *
import random
pieColourR = random.randint(0, 255)
pieColourG = random.randint(0, 255)
pieColourB = random.randint(0, 255)
colourA = (pieColourR, pieColourG, pieColourB)
setFill(colourA)
rect(200, 100, 400, 400)
The three RGB values need to be accepted by the "setFill" function. I am doing this to randomly generate 3 different colours that will be consistent for the entire run time of the program.
Right now I get this error:
_tkinter.TclError: unknown color name "166 134 15"
|
ukemi has answered your question correctly. You do not want to pass three arguments into the `setFill()` function, you want to pass a single argument with a known name or, alternatively, a pseudo-name created using the method ukemi described.
However, there _are_ cases in which you want to convert a tuple or list into separate arguments to pass into a function. This can be done with Python's unpacking syntax:
someFunction(*colorA)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "python, python 3.x"
}
|
SQL query where it sorts by Release Date first, then Episode, Then part
I'm trying to figure out how to do this query where all the newest entries (episodes) are at the top (first). BUT, if two episodes are uploaded on the same day it sorts by episode number (keeping the date order from before but sorting only within each day by episode) then if there are multiple parts to an episode, sorting within each episode by part as well.
. "ORDER BY `part`,`episode`,`release_date` DESC";
i've tried this order by search as well as
. "ORDER BY `release_date`,`part`,`episode` DESC";
but both of these result in episode 1 being at the top, but I want the most recent episode to be at that top (so the higher number episode)
|
After `release_date`, it should be first sorted by `episode` and then `part`
"ORDER BY `release_date`,`episode`,`part` DESC";
There is also an option of ASC/DESC per column, if required.
"ORDER BY `release_date` DESC,`episode` DESC,`part` ASC";
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "php, sql"
}
|
How to use setcontent to pull in taxonomy content
Having trouble getting setcontent to work as expected with Taxonomies.
I'm in a record template and want to pull in other items that share any of the same taxonomy values. So I don't want to hardcode the values in, but instead compare to my current record.
For example, here's a hardcoded query, checking for items that have 'Apps' in their topics taxonomy.
{% setcontent relinterviews = 'interviews' where { topics: 'Apps' } %}
Instead I need something like this pseudo code, but that works:
{% setcontent relinterviews = 'interviews' where { topics in record.taxonomy.topics } %}
Ideally, I want to be pulling in items that match two different taxonomies - Topics and Roles - but I'd settle for one.
|
Try these:
1. To search for two of the same taxonomy.
`{% setcontent relinterviews = 'interviews' where { topics: 'Apps || Other' } %}`
2. To search across two separate taxonomies.
`{% setcontent relinterviews = 'interviews' where { topics: 'Apps', roles: 'MyRole' } %}`
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "bolt cms"
}
|
subprocess.Popen : how to pass a list as argument
I just need a hint on how to do things properly.
Say I have a script called script.py which uses a list of names as argument ["name1", "name2", etc. ].
I want to call this script from another script using the subprocess module. So what I would like to do is the following :
myList = ["name1", "name2", "name3"]
subprocess.Popen(["python", "script.py", myList])
Of course that doesn't work because the subprocess.Popen method requires a list of strings as arguments. So I considered doing the following :
subprocess.Popen(["python", "script.py", str(myList)])
Now the process starts but it doesn't work because it has a string as argument and not a list. How should I fix that properly?
|
Concatenate them using `+` operator.
myList = ["name1", "name2", "name3"]
subprocess.Popen(["python", "script.py"] + myList)
BTW, if you want use same python program, replace `"python"` with `sys.executable`.
|
stackexchange-stackoverflow
|
{
"answer_score": 38,
"question_score": 18,
"tags": "python, subprocess, popen"
}
|
Why is this trigonometric identity true?
Suppose $$\frac{{{{\sin }^4}(\alpha )}}{a} + \frac{{{{\cos }^4}(\alpha )}}{b} = \frac{1}{{a + b}}$$ for some $a,b\ne 0$.
Why does $$\frac{{{{\sin }^8}(\alpha )}}{{{a^3}}} + \frac{{{{\cos }^8}(\alpha )}}{{{b^3}}} = \frac{1}{{{{(a + b)}^3}}}$$
|
There is a very direct way to solve this. First, use the given equation to find, for example, $\sin^2 \alpha$:
$$x=\sin^2 \alpha$$
$$\frac{1}{a} x^2+\frac{1}{b}(1-x)^2=\frac{1}{a+b}$$
Solving this easy quadratic, we get a single root:
$$x=\frac{a}{a+b}=\sin^2 \alpha$$
It follows:
$$1-x=\frac{b}{a+b}=\cos^2 \alpha$$
Now substitute these values into the second equation and see that it holds.
|
stackexchange-math
|
{
"answer_score": 34,
"question_score": 20,
"tags": "trigonometry"
}
|
What is the location of the docker image files on OS/X?
There are several questions regarding how to _view_ docker images on local machine including I can't find my Docker image after building it
The `docker images` command does report that an image was successfully created:
$docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
caffeonspark cpu bd347271dc01 28 minutes ago 5.28 GB
This question is about the physical locations of the docker files - to do operations like copying/backups etc. How would the paths be found on OS/X?
|
On Mac, Docker images are stored within the VM. See this Question.
On Linux, Docker images are stored in `/var/lib/docker`, so backing up that directory should be sufficient.
I don't think you should be copying images from that directory. The normal way to share a built image between machines is with Docker Hub or with a private Docker registry. If you want to share images that are not published to a registry, you can simply share the Dockerfile.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "docker"
}
|
iOS validate RSS
I have an app that reads RSS feeds, is working fine, but I would like to validate the rss link that the user types like the w3 validator
thanks in advance! ;)
|
Since RSS is just XML, I'm guessing you're using `NSXMLParser` to parse the feed.
If you implement the `-[NSXMLParserDelegate parser:parseErrorOccurred:]` method, you will be notified if the feed can't be parsed for whatever reason.
The `parser` object in the method contains the line and column number where the error occurred.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ios, rss, validation"
}
|
I need an example of how to use a Javascript timer to find out when a user has created a new facebook event.
I'm new to facebook development and coding in general. I know there are currently no real time updates for the event object and that I somehow have to figure out how to poll facebooks servers using javascript. Is there an example of this anywhere? My app is dependent on knowing when a new event has been created so the app can grab its info.
|
You might use the global setTimeout() function.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "javascript, facebook fql"
}
|
Можно ли создать индекс на представление
На сколько я понимаю создать индекс можно только на материализованное представление. Прав ли я, или есть какие-то способы создания индекса на обычное представление.
|
В нынешней архитектуре `PostgreSQL` невозможно даже если не касаться любых вопросов о поддержании актуальности данных такого индекса при обновлениях нижележащих таблиц.
Все реализуемые в `PostgreSQL` индексы должны следовать `Index Access Method API`, который в свою очередь требует, чтобы поиск по индексу возвращал `TID` \- `tuple id`, физический адрес строки в датафайлах таблицы.
У `view` нет физического представления данных на диске. Следовательно не может быть `TID` строки, следовательно невозможно сделать `Index Access Method`. Поэтому нет, поверх `view` индекс построить не выйдет.
У `Materialized Views` физическое представление есть и индексы по ним реализованы. По правде говоря, индексы и вовсе не знают, построены они на таблице или материализованном представлении, для них это одно и то же.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "sql, postgresql"
}
|
Define pointer to memory with the size of union
I'm struggling with the demo code like below:
typedef volatile union
{
unsigned U;
int I;
struct
{
unsigned some_array:32;
} B;
} bar;
#define foo (*( bar*) 0xABCDU)
I know that `0xABCDU` is some address in memory. How can I read the `foo` in English?
|
`( bar*) 0xABCDU` is `0xABCDU` reinterpreted as a pointer to `bar`. `*( bar*) 0xABCDU` is dereferenced pointer (a reference if it was C++).
(Outer braces are to prevent it from possible misinterpretation due to operators precedence)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c, pointers, unions"
}
|
kubernetes petset on google cloud
I am running a kubernetes cluster on google cloud(version 1.3.5) . I found a redis.yaml that uses petset to create a redis cluster but when i run kubectl create -f redis.yaml i get the following error : error validating "redis.yaml": error validating data: the server could not find the requested resource (get .apps); if you choose to ignore these errors, turn validation off with --validate=false
i cant find why i get this error or how to solve this.
|
PetSet is currently an alpha feature (which you can tell because the `apiVersion` in the linked yaml file is `apps/v1alpha1`). It may not be obvious, but alpha features are not supported in Google Container Engine.
As described in api_changes.md, alpha level API objects are disabled by default, have no guarantees that they will exist in future versions, can break compatibility with older versions at any time, and may destabilize the cluster.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 4,
"tags": "kubernetes, google kubernetes engine"
}
|
How to quickly solve a series of exponential equations.
> When $2^x - 2^{-x} = 4$, then $2^{2x} + 2^{-2x} =\hbox{ ?}$ and $2^{3x} - 2^{-3x} =\hbox{ ?}$
I have a doubt with this one. I assume I should use some kind of formula to solve it because if I solve the first equation I get that $x = \log_2(1 + \sqrt5)$ and then I just solve the other two equations and get that the result of the second one is $18$ and the last one is $76$.
The thing is that this exercise is supposed to be done quickly but this method takes a lot of time to calculate. Is there another way to solve it that I'm missing?
|
**hint**
Let $$X=2^x$$
then
$$2^x-2^{-x}=X-\frac 1X=4$$
$$(X-\frac 1X)^2=X^2+\frac{1}{X^2}-2$$ $$=4^2=16$$ thus $$2^{2x}+2^{-2x}=X^2+\frac{1}{X^2}=16+2=18$$
Now do the same with $(X-\frac {1}{X})^3$.
|
stackexchange-math
|
{
"answer_score": 5,
"question_score": 3,
"tags": "algebra precalculus"
}
|
http upload of huge files over slow network (interruptible)
I want to implement a client+server which allows uploading of big files over very slow and faulty networks.
This means the upload needs to be interruptible.
Example: If 80% of the upload data was already transferred, then (after the tcp connection was lost and created again) the second request should only transfer the missing 20%.
In my case the client-server communication needs to use https.
An upload can last up 12 hours.
Client and server will be implemented with Python.
Of course I could invent my own protocol on top of http. I guess this would be simple.
But, I would like to implement a standard/spec (if there is any).
Are there open source tools which already implement this?
|
There is <
Quoting:
> People are sharing more and more photos and videos every day. Mobile networks remain fragile however. Platform APIs are also often a mess and every project builds its own file uploader. There are a thousand one-week projects that barely work, when all we need is one real project. One project done right.
>
> We are the ones who are going to do this right. Our aim is to solve the problem of unreliable file uploads once and for all. tus is a new open protocol for resumable uploads built on HTTP. It offers simple, cheap and reusable stacks for clients and servers. It supports any language, any platform and any network.
>
> It may seem to be an impossible dream. Perhaps that is because no-one has managed to solve it yet. Still, we are confident and we are going to give it our best shot. Join us on GitHub and help us make the world a better place. Say "No!" to lost cat videos! Say "Yes!" to tus!
|
stackexchange-softwarerecs
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python, http"
}
|
What does expectation of an indicator random variable signify?
This was a question in my probability theory class recently:
> There are $5$ balls, numbered $1-5$, in a bag. We take $3$ of those balls at random. What is the expected value of the sum of the $3$ balls taken out of the bag?
Here's one approach that my instructor suggeseted:
Let $I_i$ be the Indicator random variable for ball with the number $i$, which is 1 if the ball is selected and $0$ otherwise.
We then calculate the the required expected value of the sum as :
$$ \sum_{i=1}^{5} iE[I_i]=\frac{3}{5}(1 + 2 + 3 + 4 + 5)\boxed{=9} $$
I don't understand why this approach works. Why would the summation of the multiplication of the expectation of the indicator random variable with the number that it is associated with giving me the correct answer?
|
The indicator $I_i$ is a Bernoulli random variable that takes the value $1$ if ball $i$ was one of the 3 balls you chose and $0$ otherwise. Recall the expected value of a Bernoulli random variable is the probability of success, which in this case is $3/5$.
Notice the sum of the values of the 3 balls you chose can be expressed as $$S=\sum_{i=1}^5 iI_i.$$
Use linearity of expectation to compute $E[S]$ and you are done.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "probability, expected value"
}
|
Запрет доступа в локальную сеть через WiFi
Имею Linksys EA4500, подключил его к внутренней сети `10.0.0.0`. Он раздает сеть `10.0.5.0`, и гостевую сеть `192.168.3.0`. Так вот вопрос, как из гостевой сети запретить доступ к сети `10.0.0.0`? Не хочу чтобы при прописывании `\\10.0.0.0` попадали в сетевые папки. Спасибо.
Вижу на уровне роутера это запретить невозможно, думаю логично тогда будет запретить доступ на уровне шлюза, подскажите как это сделать в Ubuntu, если запрещать сетевой доступ какие это порты? или разрешить лучше только порт proxy) Думаю... дальше)
|
Извините, это тоже я, который Anton Reshin. Просто, с другого логина зашёл. Там, для таких, ещё отдельную подсеть надо на роутере сделать.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "ubuntu, сеть, wifi, nat, linksys"
}
|
Finite dimensional division algebra over pseudo-algebraic closed field
Is it true that any finite dimensional division algebra over a pseudo-algebraically closed field is trivial? We know that this is true for algebraically closed field.
|
The fact that every finite dimensional division algebra is trivial is not only true over an algebraically closed field but it is in fact equivalent to the field being algebraically closed. Remember that (extension-)fields are just a special case of division algebras. Thus, if it would be true over pseudo-algebraically closed fields, we would have that a field is algebraically closed if and only if it is pseudo-algebraically closed.
However, this is not the case, as for example finite fields are pseudo-algebraically closed.
|
stackexchange-mathoverflow_net_7z
|
{
"answer_score": 6,
"question_score": 3,
"tags": "ag.algebraic geometry, fields"
}
|
cassandra hints are high due to gc pause events - this is creating a cycle
Our clusters were running great from days and all sudden today morning hints are high. And they will not go down naturally.
What we are seeing is, gc is taking longer time than 200ms which is causing nodes to be DOWN and thereby leading to increase in hints. This is a vicious circle, and I am not sure how to fix it.
Machine config: 128GB RAM, 2TB hard disk, 24 core machine. JVM heap size 16Gb, GCpausemillisecods 200ms, parallelgcthreads 8.
Please let me know, how can I tune GC config to break this gc pause to hint loop?
|
We increased the size of JVM heap to 32GB, and took memtable off heap for write heavy customers.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "cassandra"
}
|
Get group radio button selected value via jquery
How can I get the selected radio button value via jQuery? I tried:
var selectedPlan = $("input[name=Plan[packageId]]:checked'").val();
alert(selectedPlan);
bBt didn't work.
<td style="vertical-align: top;">
<input type="radio" value="1" name="Plan[packageId]">
<lable>3 Games</lable><br>
<input type="radio" value="2" name="Plan[packageId]">
<lable>5 Games</lable><br>
<input type="radio" value="3" name="Plan[packageId]">
<lable>10 Games</lable><br>
</td>
here is the fiddle <
|
You need to escape the CSS meta characters or wrap them in quote for preventing the selector from breaking:
var selectedPlan = $("input[name='Plan[packageId]']:checked").val();
**Working Demo**
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -1,
"tags": "javascript, jquery, html, jquery selectors, radio button"
}
|
Not getting the value of session variable on paypal transaction processing in php
i cant get the value of session variable on paypal transaction processing.when transation complete my table is updated, for updation i use a session variable,at that time i can't get the value of the session variable.
is sessions not get in paypal? please help me to find a solution......
|
I'll assume that you're using simple payment integration that requires your user to click the "return to merchant website" button to post the data back to your website.
You can access the session variables if (i) user completes the payment and comes back to your website before session expires (ii) the user returns to the website on which session was started. This means if your user starts checkout on "website.com" and the session is started here, the user should return to "website.com", not "www.website.com" for the session variables to be accessible.
Using sessions is not reliable; e.g. is user spends a long time on PayPal website, the session on your website will timeout. As a workaround, if you are interested in specific session variables, you can pass them to PayPal in custom hidden form fields; PayPal echos these fields back to your return script as-is.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php"
}
|
Riot.js: Toggle class on label if input has value
I need to toggle class `.has-data` on `label` if `input` has some data
<label>
<input type="text">
</label>
Can it be done just using some markup without writing javascript?
|
No, you'll have to write some JavaScript, but the JavaScript is pretty minimal. Change the HTML to this:
<label class="{ has-data: entry }">
<input type="text" onkeyup="{updateEntry}">
</label>
And add this section to the component's script:
<script>
this.entry = '';
updateEntry(e) {
this.entry = e.target.value;
}
</script>
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, riot.js"
}
|
Не рабочая часть кода,что посоветуете сделать
if(start.Day == 30 &&(new int[]{3,5,7,9,11}).contains(start.Month) ||
start.Day == 28 && start.Month == 1) {
start.Day = 1;
start.addMonths(1);
} else {
start.addDays(1);
}
|
Ошибка в том, что компилятор не понимает, что Вы подразумеваете под
[3, 5, 7, 9, 11]
исправьте на
(new int[] { 3, 5, 7, 9, 11}).contains(start.Month)
И должно заработать.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c#, visual studio"
}
|
SimpleXML, XPath: how to get content of element by unique id?
kept trying for hours, brain messed up, need help:
XML-file:
<?xml version="1.0" encoding="UTF-8"?>
<testresult>
<body>
<itemset name="sc">
<item name="1">1</item>
<item name="2">3</item>
<item name="3">0</item>
</itemset>
</body>
</testresult>
Now I want to retrieve the content (`0`) of the item with the unique name "3" into `$value` ...
$value = $resultxml->xpath("//item[@name='$name']");
unfortunately not... what do I need to do to have `$value` to contain `0`?
|
$results = $xml->xpath("//item[@name='$name']");
$value = (int)$results[0];
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "php, xml, xpath, simplexml"
}
|
Saving/Retrieving igraph Graph attributes
I am trying to save and then retrieve an igraph Graph with the graph attributes. Specifically, I have a two-terminal graph, and I am storing the source and sink as graph attributes so I can retrieve them in constant time. Note, the vertices are not in any specific order (e.g., the first vertex is the source and the last is the sink).
I have searched the documentation but I can't see that any of the formats support storing/retrieving graph attributes. Am I missing anything?
My fallback is to use boolean source/sink vertex attributes, but that takes more space and requires linear time to retrieve the right vertices.
|
GraphML supports numeric and string attributes that can be attached to the entire graph, to individual vertices or to individual edges (actually, it supports even more complex ones but igraph's GraphML implementation is limited to numeric and string attributes). So, you could use `Graph.write_graphml()` and `Graph.Read_GraphML()`. Also, you can simply save an igraph graph using Python's `pickle` module (i.e. use `pickle.dump()` and `pickle.load()`) and you will get all the graph/vertex/edge attributes back (even complex Python objects) -- the only catch is that the `pickle` format is not interoperable with other tools outside the Python world.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "python, attributes, igraph, file format, read write"
}
|
Dropping PendingIntents
Is it ok to drop PendingIntents in android if they are never used. Such as in an AppWidgetProvider where a PendingIntent that was never used be overwritten by a new PendingIntent.
Or should we call cancel on all unused PendingIntents to clean up memory appropriately?
|
There is no need to call cancel.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "android, android pendingintent"
}
|
MovieClipSWFLoader.play() and stop() cannot work
I have a problem in playing and stoping the loaded swf file with "MovieClipSWFLoader”. MovieClipSWFLoader.load() seems to work correctly, but play() and stop() does not work.
I use ...
* Action Script 3.0
* Flex SDK 4.6.0
* Adobe AIR 13.0.0.83
My source codes are as follow:
<
Can anyone help me? Thanks in advance :-)
|
Try getting the `movieClip` property of the `MovieClipSWFLoader`. This way you will know if the actual content is a MovieClip which can be played.
And if so, try manipulating the MovieClip directly, just to be sure you what you're doing.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "actionscript 3, apache flex, actionscript, air, flex4"
}
|
CentOS 6.5 server time zone won't persist?
I'm setting my timezone like so:
ln -sf /usr/share/zoneinfo/Europe/London /etc/localtime
It works fine, I check with `date` and all is good.
But then a few days later I'll realise it's reset itself to CEST, so 9am becomes 10am, etc.
The server is located in Paris, in the CEST time zone. But I should be able to use any zone I want, surely? I (and most of my users) am based in the UK, so I want to operate on that timezone.
I just did a yum update and noticed it wanted to update tzdata. That had the effect of changing from BST to CEST, but I don't think it's the only thing that triggers the change, as I'm sure it's gone wrong on days where I've done no such update. I could be wrong though.
What's the trick to set a timezone **permanently**?
Thanks
|
Very simple upon further googling. Editing `/etc/sysconfig/clock` to say London instead of Paris did the trick. `yum reinstall tzdata` with clock set to Paris triggered the problem, but `yum reinstall tzdata` with clock set to London has the desired effect.
|
stackexchange-serverfault
|
{
"answer_score": 1,
"question_score": 1,
"tags": "centos, timezone"
}
|
Universal Property of Tensor Product, Uniqueness
There is a universal property for free modules, where for any map $f:B\rightarrow S$ there is a map $g:F(B)\rightarrow S$ such $g\cdot b=f$ where $b$ is the canonical map from the basis set into the free module $F(B)$.
This property is used in the proof (linked below) that the tensor product is the only module that satisfies the "universal property for tensor products."
<
The universal property for tensor products replaces $f$ above with a bilinear map. Now suddenly the free module isn't good enough; we the only module which satisfies the universal property is the tensor product. The free module can't also satisfy it, as the tensor product is unique up to isomorphism.
So in short, I don't understand why the free module $F(V\times W)$ doesn't satisfy the universal property for tensor products!
Thanks for any help!
|
The canonical map $V \times W \to F(V \times W)$ is not bilinear. One way to construct the tensor product $V\otimes W$ is that it is the largest quotient of $F(V \times W)$ for which the composite of this canonical map with the map to the quotient _is_ bilinear.
|
stackexchange-math
|
{
"answer_score": 4,
"question_score": 2,
"tags": "abstract algebra, tensor products"
}
|
pythonでのデコレーターに関して
python
|
functools.lru_cache
(1)
def get_first_image(url):
"""URLHTML"""
#
return image_data
2,3URLURL2
from functools import lru_cache
@lru_cache()
def get_first_image(url):
"""URLHTML"""
#
return image_data
decoratorget_first_image
|
stackexchange-ja_stackoverflow
|
{
"answer_score": 8,
"question_score": 2,
"tags": "python"
}
|
Algebraic expressions and permutation groups
Suppose that I pick a subgroup $G$ of $S_n$ for some $n$.
Is it always possible to find an algebraic expression in $n$ variables (in other words, a rational function in those $n$ variables) that is preserved for exactly those permutations in $G$? (Permutations work on the variables of the expression).
If yes, I'd very interested in the proof.
|
Let $f$ be the sum over the orbit of $X_1X_2^2\cdots X_n^n$ under the action of $G$, i.e. $$f(X_1,\ldots,X_n) =\sum_{\pi\in G} X_{\pi1}^1X_{\pi2}^2\cdots X_{\pi n}^n.$$ Then $f$ is $G$-invariant by construction and for any $\pi \notin G$, we note that the monomial $\pi(X_{1}^1X_{2}^2\cdots X_{n}^n)=X_{\pi1}^1X_{\pi2}^2\cdots X_{\pi n}^n$ is missing from $f$, so $\pi f\ne f$ as required.
* * *
My polynomial has degree $1+2+\ldots + n =\frac{n(n+1)}{2}$ and can easily be improved to $\frac{n(n-1)}2$. Can one do better than $O(n^2)$?
|
stackexchange-math
|
{
"answer_score": 5,
"question_score": 4,
"tags": "abstract algebra, group theory, finite groups, symmetric groups"
}
|
Counting the number of invariant subspaces
Suppose that we are given a linear transformation $L: \mathbb{R}^4 \rightarrow \mathbb{R}^4$ with characteristic polynomial $t^4+1$. Find the number of invaiant subspaces.
The roots of this polynomial are all complex. In particular, this factors as the product of two irreducible quadratics, call them $p(x), q(x)$ so by the fundamental theorem for modules over PIDs, $\mathbb{R}^4=\mathbb{R}[x]/(p(x)) \oplus \mathbb{R}[x]/(q(x))=A \oplus B$.
Thus, so far I have 4 invariant subspaces, $\\{0\\}, \mathbb{R}^4, A, B$. There can't be any invariant subspaces of dimension 1 since the eigenvalues are complex. But, how can I show there are no other invariant subspaces of dimension 2 or 3?
|
If we suppose that it exist a subspace $R$ of dimension 2 such that $R$ is invariant by $L$ so $A\cap R$ will be invariant by $L$ too and the dimension of $A\cap R$ is :
**Case 1: $\dim(A\cap R)=0 $** that mean $A\cap R=\\{0\\}$ so $\mathbb{R}^4=A\oplus R=A\oplus B$ and then $R=B$.
**Case 2: $\dim(A\cap R)=1 $** that impossible because $L$ haven't a invariant subspace of dimension one.
**Case 3: $\dim(A\cap R)=2 $** and it's mean that $A\cap R=A$ so $R=A$.
Finally the only invariant subspaces of dimension 2 are $A$ and $B$
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 2,
"tags": "linear algebra"
}
|
Binding DataSet to a Repeater
I have a `<asp:Repeater>` control and I am binding a `DataSet` to it with a number of different `DataTables`.
I'm confused as to how to access and bind one table at time to my repeater.
I would like to do something like this
<ItemTemplate>
<tr>
<td>
<asp:Label ID="Label2" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "heading_id") %>' />
</td>
</tr>
</ItemTemplate>
...but first for the table one then a new `<tr>` and then data from the table two and so on.
|
Sounds like you want nested repeaters, with the outside one representing the DataSet's DataTables, and the inside one representing the rows within a DataTable.
Personally, I've found nested repeaters to be horrible to work with because of the custom data binding, and unless you're doing a lot of event binding, I'd probably go with a more inline approach, something like the following:
<% foreach (var dt in MyDataSet.Tables) { %>
<table>
<% foreach (var row in dt.Rows) { %>
<tr>
<td><label><%= row["heading_id"] %></label></td>
</tr>
<% } %>
</table>
<% } %>
In your code-behind, you'd just need to assign your DataSet object to a protected field or property.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "c#, asp.net, webforms, dataset, repeater"
}
|
Classification with large volume of missing data
When building a model to classify a student is going to be admitted to a special program or not, the main features include,
gender | Ethnicity | State | Zip code | Test score | Education | Job title | Current gpa | Admission
As the data is collected online, many features are missing a lot of data. Feature 'Test score' should be important to the Admission decision, but it misses about 80%. Seems imputation is not practical.
Should keep it as a feature and use EM or Bayesian network, SVM those algorithms which are not sensitive to missing data, Or directly remove this feature when build model? Any suggestions?
|
You should **drop the feature**. The test scores can not be averaged out with just 20% of the scores present. Random values with a distribution can't be added either because they are test scores.
You could try building a model with the rows which consists of those values and see if it's effective or not.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "classification, svm, missing data"
}
|
ive been making a app in xcode 5.1.1 but i updated to xcode 6
i have been creating a app in xcode 5.1.1 for a while now ios 7.1, now that i have updated xcode to 6, do i continue as normal or should i need to do something in order to keep developing correctly? Or should i need to downgrade back to 5.1.1?
I ran the app in xcode 6 and it runs perfectly fine so far. I also went into the build settings to see the deployment target which is 7.1
so does this mean i can only release to 7.1?
thanks, for the help, appreciate it a lot.
|
look at @Acey 's answers, he put them perfect.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ios, xcode"
}
|
randomness in nature
What is the explanation of the apparent randomness of high-level phenomena in nature? For example the distribution of females vs. males in a population (I am referring to randomness in terms of the unpredictability and not in the sense of it necessarily having to be evenly distributed). 1\. Is it accepted that these phenomena are not really random, meaning that given enough information one could predict it? If so isn't that the case for all random phenomena? 2\. If there is true randomness and the outcome cannot be predicted - what is the origin of that randomness? (is it a result of the randomness in the micro world - quantum phenomena etc...)
where can i find resources about the subject?
|
This is, of course, a very important problem. One (extreme) point of view is that any form of classical (=commutative) randomness reflects "only" human uncertainty and does not have an "objective" physical meaning.
(Further answers to this question and more discussion are welcome on the posting entitled "Randomness in nature" on my blog "Combinatorics and More". Here is a link to a subsequent post with further discussion.) Some related material can be found in the site of the conference "The Probable and the Improbable: The Meaning and Role of Probability in Physics".
|
stackexchange-mathoverflow_net_7z
|
{
"answer_score": 7,
"question_score": 8,
"tags": "lo.logic, mp.mathematical physics, st.statistics, pr.probability, mathematical philosophy"
}
|
WARNING: Module mcrypt ini file doesn't exist under /etc/php/7.2/mods-available
I've been trying to install phpmyadmin in Ubuntu 16.04.3 LTS having a lamp installed, php 7.2, mysql Ver 15.1 Distrib 10.2.12-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2 and apache2.
and I am following this article from digitalOcean, but when I came to the part that I need to run `sudo phpenmod mcrypt` I got a message saying..
WARNING: Module mcrypt ini file doesn't exist under /etc/php/7.2/mods-available
WARNING: Module mcrypt ini file doesn't exist under /etc/php/7.2/mods-available
I am doing this on ubuntu installed in godaddy
Can you give best solution for this?
|
Just try and run this code and your error should be gone.
sudo ln -s /etc/php/7.1/mods-available/mcrypt.ini /etc/php/7.2/mods-available/
You should have the `mcrypt.ini` file inside `mods-available` and if you don't have this file there you will get this error.
**NOTE** : If you do it this way you will not get this error anymore, but you will get other error:
PHP Warning: PHP Startup: Unable to load dynamic library 'mcrypt.so' (tried: /usr/lib/php/20170718/mcrypt.so (/usr/lib/php/20170718/mcrypt.so: cannot open shared object file: No such file or directory), /usr/lib/php/20170718/mcrypt.so.so (/usr/lib/php/20170718/mcrypt.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
**So, based on my research`mcrypt` is not supported in php7.2, so you don't have to execute `sudo phpenmod mcrypt` at all. Maybe I am wrong, but if someone have more information, let me know.**
|
stackexchange-askubuntu
|
{
"answer_score": 4,
"question_score": 4,
"tags": "server, apache2, mysql, php, lamp"
}
|
How to run `tr` (translate command) and mute its output?
I'm using `tr` and `sed` command to replace text in my file like this `tr '\n' ' ' < afile.txt | sed '$s/ $/\n/'` and as discussed here. Though running that on a big file will get my console spammed with output replaced text.
So my need is to run the commands, but silence its output. My google search here and calling `tr --help` not helpful to me so I ask here.
|
It's unlikely that you'd like to discard the output from the pipeline. It is more likely that you'd like to store it somewhere rather than having it flood your terminal.
I think this is what you're looking for:
$ tr '\n' ' ' < afile.txt | sed '$s/ $/\n/' >anotherfile.txt
This will put the result of the pipeline into the file `anotherfile.txt` rather than onto the terminal. You are then free to inspect it and to replace the original file with it (`mv anotherfile.txt afile.txt`) if this makes sense with what it is you're trying to achieve.
The `>` at the end of the pipeline is an _output redirection_ that will redirect the standard output stream of `sed` into the specified file. It works in the "opposite way" of the _input redirection_ `<` that is used earlier in the pipeline to send the contents of `afile.txt` into the standard input stream of `tr`.
|
stackexchange-unix
|
{
"answer_score": 3,
"question_score": -1,
"tags": "bash, text processing, tr"
}
|
What are the most secure options for backing up your mnemonic seed?
You can gpg encrypt a text file or write it down on a piece of paper, but what are other good options to secure your mnemonic seed? I want to hear your ideas :)
|
You could also scrypt your paper wallet. Then use base64 to get the encrypted data in a printable format. This way somebody stealing it will still need a password to get the keys or mnemonic seed and scrypt will make sure that brute force attacks are infeasible even for weak passwords.
Encode:
scrypt enc -t120 data.txt | base64 > data.enc.txt
Decode:
base64 -d data.enc.txt > data.enc
scrypt dec data.enc
One major drawback though is that you'll probably have to scan+OCR to get the encrypted data back from paper into a digital format ;-)
|
stackexchange-monero
|
{
"answer_score": 11,
"question_score": 7,
"tags": "security, mnemonic seed"
}
|
How to implement counting sort for integers in Clojure?
Say I have an array of integers `xs` taking values from `0` to `max`, and I need to sort it in O(n) time, so I can't just do `(sort xs)`.
Is there a way to do it with the `frequencies` function?
In another language I would then do a `for` to iterate over integers from `0` to `max`, and for each value `x` in that range, look up `(frequencies x)` and then do `repeat (frequencies x) x` or something.
Crucially I need to do this IN ORDER from smallest to highest, which is what makes the whole thing a sort. So I DON'T want to just `map` each number in `xs`.
Any ideas for a clojure-ish idiomatic solution?
Thanks.
|
Updating a vector isn't quite O(1) but you can use that to create the counts for each element:
(defn counting-sort [s]
(if (empty? s)
s
(let [counts (reduce (fn [v e]
(update v e inc))
(vec (repeat (inc (apply max s)) 0))
s)]
(apply concat (map-indexed #(repeat %2 %1) counts)))))
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sorting, clojure, counting sort"
}
|
Does Saved Document Library Template become available to all subsites?
I have a test Site Collection. I've added a document library to the root site and added content types to it. When I save this Document Library as a template under Library Settings, this "App" becomes available to a subsite I created.
Will this work in a real environment? If Permissions on the root site and a subsite are different, would this App still be available?
Thanks!
|
To answer your final question - the app (Document Library template) would still be available on the subsite. Whether or not users can use the template you have created would be determined by their user permissions.
I believe the individual permission is 'manage lists', see this link for more info. For further reading this link is also of use. PLease note that there are multiple OOTB groups that have the 'manage lists' permission. (A group is assigned a collection of permissions, which behave cumulatively).
. I was planning on just using a HTML text box tag with a drop down menu that the user can use to toggle their text style.
I am not sure, however, how to change the style of the text that the user puts in the text box and then save the user's post (with styling preferences) in a MySQL database.
|
You can use tools below that designed specially for your need.
* Editor.js
* WYSIWYG
* ContentTools
* Aloha Editor
* summernote
* CKEditor
* Trumbowyg
* Redactor
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, php, html, css, mysql"
}
|
Как передвинуть камеру вперёд?
Надо передвинуть камеру вперёд по нажатию на кнопку, но у камеры есть rotation, и из-за этого я никак не могу это сделать.
|
Для того, чтоы понять, куда смотрит объект (то есть получить тот самый перед, куда нужно сдвинуть камеру) вы можете использовать gameObject.transform.forward Для самого сдвига можно использовать разные пути: сдвиг в Update (как предложил @RiotBr3aker в первом ответе), с помощью Vector3.MoveTowards, Vector3.Lerp и т.д.
Если вы хотите двигать камеру быстрее (или медленнее), чем она двигается с помощью transform.forward, то можно умножать это на speed. После чего можно поиграться с этой переменной speed, найдя оптимальную скорость.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "unity3d"
}
|
Accessing hidden field and room
When i add room to my project my logcat has many warnings like:
> Accessing hidden field Landroid/database/sqlite/SQLiteDatabase;->mCloseGuardLocked:Ldalvik/system/CloseGuard; (greylist-max-o, linking, denied)
Why i get this warnings and how to fix it?
 per day, so the result should look like this:
date, playerid
2015-05-05, 1
2015-05-05, 2
2015-05-06, 1
2015-05-08, 1
2015-05-08, 1
The important thing is, that I would like to have double date-entrys for each player-id per day.
How can I solve this?
|
Though your sample output doesn't contain a "count", I'm assuming you would like it to have a count-per-player-per-day. If that's true, you'll be interested in `GROUP BY` and `COUNT()`:
SELECT
`date`, playerid, COUNT(*) AS `count`
FROM
your_table
GROUP BY
`date`, playerid
ORDER BY
`date`, playerid
If you're interested in _only_ the players that have multiple entries for a single day, check out `HAVING`:
SELECT
`date`, playerid
FROM
your_table
GROUP BY
`date`, playerid
HAVING
COUNT(*) > 1
ORDER BY
`date`, playerid
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "mysql, count, group by"
}
|
Changing the architecture of fabric
I have been trying to make some changes in fabric architecture, for example, like the processing of parallel transactions from orderer's end, etc.. Now, how would I make the fabric to use my new configurations? Where do I need to make changes? Also, these configurations do not require any changes in the interface, so I think it would not be a problem.
|
After making the changes build the fabric project. You should see new docker images for the latest tag.
You can update docker-compose.yaml to use the appropriate image.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "hyperledger fabric, hyperledger"
}
|
Why does electric arc in a switch prefer a curved path over a straight path?
Recently I found this video of a 500 kilovolts line being opened under load.
When the switch contacts are pulled apart an electric arc predictably starts. While the contacts are close to each other the arc runs along a straight path between the contacts. Then as contacts are pulled further apart the arc starts to bend and turn into a steep curve and its length becomes several times greater than the distance between the contacts. Then finally the arc just fades out.
That doesn't make sense to me. As I see it the arc should take the least resistance path and that's clearly a straight path, not a steep curve. Even more, if the arc takes a curved path why would it fade out suddenly instead of just taking a less curved path of less resistance and continue running?
Why does the arc behave this way - first prefers a curved path and then suddenly fades out?
|
This was a comment but the links were too long.
As well as what others have said - look up " **magnetic blowout** " and be suitably amazed. More for DC but certainly not only. A magnet is used to deflect the arc so it lengthens and fails
Equipped in even very small and common switching devices. Many of these and these
!enter image description here
* * *
Even Tesla did it :-)
!enter image description here
Interest only - from here
EXPERIMENTS WITH ALTERNATE CURRENTS OF HIGH POTENTIAL AND HIGH FREQUENCY.
BY NIKOLA TESLA.
A LECTURE DELIVERED BEFORE THE INSTITUTION OF ELECTRICAL ENGINEERS, LONDON.
With a Portrait and Biographical Sketch of the Author.
NEW YORK: 1892
|
stackexchange-electronics
|
{
"answer_score": 11,
"question_score": 16,
"tags": "switches, high voltage, power engineering"
}
|
Does the Count for Questions posted decrease at times
I am not sure if I was looking at it properly, but as of writing this, post count is: **1,464,644**. I think I may have seen a larger figure few days back, something like, **15....**.
I know that posts get closed, but there is always a reference to those and we can view them. Is there some kind of mechanisms that completely removes incorrect posts and hence a decrease in post count.
|
Certain posts which are poorly framed, and/or offtopic tend to be deleted by Moderators and/or High-rep users. In addition, there are couple of background processes which delete old posts meeting certain criteria:
> * less than (question age in days * 1.5) views
> * 0 score or lower
> * no answers
> * 1 comment or less
> * asked more than 365 days ago
>
In addition unanswered, negatively voted questions with zero answers are also deleted after 30 days.
|
stackexchange-meta
|
{
"answer_score": 4,
"question_score": 0,
"tags": "discussion, questions"
}
|
Android, GoogleMaps: how to pass address to Res
I have a text variable in my java code, whose value is a location address. I'd like to write this address into a text box, placed in the Res folder:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="
<fragment xmlns:android="
xmlns:tools="
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.currentplacedetailsonmap.MapsActivityCurrentPlace" />
<EditText
android:id="@+id/text_box"
android:inputType="text"/>
So, does it exist a java coded method, by which I can achieve this target?
Thank you very much.
|
You can Enable Edittext use this
android:enabled="false"
and in your java code simley `edittext.setText("Your Data");`
**Use TextView instead of Edittext** (if you want to display only)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "java, android, xml, google maps"
}
|
How to make ChildWindow blocking
The ChildWindow is a modal window, but it does not block. Is there any way to make it blocking? I basically want a ShowDialog() method that will call ChildWindow.Show() but then not return until the user has closed the ChildWindow. I tried using Monitor.Enter() to block after ChildWindow.Show(), but the ChildWindow never rendered and the browser just hung. Anyone have any ideas?
|
I don't believe it supports that behavior. You can vote for it on CodePlex. Depending on what you want, you might either look at some of Tim Heuer's workarounds here, or use a different custom control, like the Silverlight Modal Control (on CodePlex).
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 14,
"tags": "silverlight, silverlight 3.0"
}
|
Android: Change SeekBar Behavior
I want my SeekBar to only change progress when the thumb is dragged. Right now it also changes position when anywhere on the progress bar is clicked. Is there a way to remove that extra functionality?
|
I suppose you could use SeekBar.getThumbOffset along with SeekBar.getProgress in the onStartTrackingTouch method to filter touch events that don't lie in that area using a touch listener:
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int)event.getX();
int y = (int)event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
}
return false;
}
Is there an easy way? I don't think so.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "android, touch, progress, seekbar"
}
|
PhpStorm - copy & paste removes indentation
If I copy paste indented text e.g.:
foo
bar
123
to PhpStorm, then the formatting and indentation gets lost.
 {
if(self::$_instance = 'Connected') {
self::$_instance = new self();
}
return self::$_instance;
}
private function __construct() {
$this->_connection = new mysqli($this->_host, $this->_username,
$this->_password, $this->_database);
}
public function getConnection() {
return $this->_connection;
}
}
|
This should maybe be a singleton, but currently is has bugs and won't work as expected.
The aim of a singleton is, to only have one instance of a class and no possibility to create another one. To achieve this, one creates a static method (`getInstance`), which stores the instance of the class and lazy instantiates it.
Currently there is a bug
if (self::$instance = 'Contected') ...
First, this isn't a comparison and because of this, the value is always true and each time you call `getInstance`, you actually create a new one, instead of returning the singleton.
This should be changed to
if (!self::$instance) ...
To get the actual singleton, you simply have to call the `getInstance`-method.
$foo = Foo::getInstance();
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -4,
"tags": "php"
}
|
How to read one line from `tail -f` through a pipeline, and then terminate?
I would like to follow changes to a file via `tail -f` and then print out the first line that matches a `grep` command before terminating. What's the simplest way to do this? So far I've been experimenting with things like:
tail -f foo.log | grep 'bar' | head -1
However, the pipeline just hangs, presumably due to buffering. I also tried
tail -f foo.log | grep --line-buffered 'bar' | head -1
This prints out the line, but the process does not terminate unless I hit ^C, presumably because a second line of input is needed to terminate `head -1`. What's the best way to solve this problem?
|
tail -f foo.log | grep -m 1 bar
if the file foo.log is writen rarily to, you can do:
grep -m 1 bar <( tail -f foo.log )
It should be noted that the tail -f will stay in background until it will get another line to output. If this takes long time it might be problematic. solution in such case is:
grep -m 1 bar <( exec tail -f foo.log ); kill $! 2> /dev/null
kill will kill leftover tail -f process, and we hide errors, because it's possible that the tail will be gone by the time kill will be invoked.
|
stackexchange-superuser
|
{
"answer_score": 13,
"question_score": 10,
"tags": "bash, unix"
}
|
Is Radeon HD 6950 working with 11.10?
I have tried to install the AMD Proprietary Driver by following this guide < but I guess I didn't succeed. In the standard Unity mode, the movement of the windows were really slow/laggy, but the 2D mode was working just fine.
Can anyone who succeed to use 11.10 with HD6950 help me? Which driver should I use and how should I install it?
|
I use HD 5850, so it's not exactly the same, but my impression is that it's the same for all the newer cards. The proprietary driver is _much_ slower than the open Radeon driver. I also had some problems with it, but none with the open driver. It's installed by default, so you don't need to install it. Your link doesn't appear to be functional, so I don't know what you did.
|
stackexchange-askubuntu
|
{
"answer_score": 1,
"question_score": 3,
"tags": "drivers, 11.10, radeon"
}
|
How to paste a screenshot into Pinta
tI want to paste a screenshot into Pinta, so I press `PrtScr` (Print Screen) button on my laptop. But when I `Ctrl` \+ `V` it into Pinta, Pinta says
Image cannot be pasted
The screenshot does not contain an image
What do I have to do? Thanks a lot
|
Open the screenshot in Pinta using the Open button in the Pinta toolbar.
1. Save a screenshot in a commonly used image format, like .png or .jpg.
2. Open Pinta and click the ****Open icon in the top left corner.
3. A new **Open Image File** window will open. Browse to the screenshot and click the Open button in the lower right corner to open it in Pinta.
|
stackexchange-askubuntu
|
{
"answer_score": 1,
"question_score": 0,
"tags": "screenshot, pinta"
}
|
SQLite3 wrong values when multithreading
this is a general question: I'm using an sqlite3 DB and running a python program that changes, reads and writes to that DB.
I'm running the following command:
SELECT COUNT(*) FROM table WHERE prm1='a' AND prm2='b' prm3=12345;
When I run it regularly, it results the correct answer.
But when I run it multithreaded-ly, it results with different answers (sometimes it's correct, but sometimes wrong). Just for clarification: No write is being done in the meantime.
Are there any problems with running SQL commands simultaniously that I'm unaware of?
|
When using multithreading and querying the SQL table, you CANNOT use the same connection and need to open a new connection per each thread.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, multithreading, sqlite"
}
|
How to remove an object from an array of objects in jquery?
I have this code:
var pinpoints= [ { "top": 50,
"left": 161,
"width": 52,
"height": 37,
"text": "Spot 1",
"id": "e69213d0-2eef-40fa-a04b-0ed998f9f1f5",
"editable": true },
{ "top": 0,
"left": 179,
"width": 68,
"height": 74,
"text": "Spot 2",
"id": "e7f44ac5-bcf2-412d-b440-6dbb8b19ffbe",
"editable": true } ]
How would I be able to remove some an object from the array under `pinpoints`.
|
You can use `pop()` to remove the last element of the array, or you can use the `splice()` method to remove a specific element.
For example,
pinpoints.splice(1, 1); // removes element with index 1
pinpoints.splice(3, 10); // removes ten elements, starting at index 3.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "javascript, jquery, jquery plugins"
}
|
How to export my eclipse java project to the remote server as a runnable jar?
Is there a way to export my eclipse java project as a runnable jar to my remote server directly from eclipse. Can this be done using Ant?
|
Yes this can be done by ant. Use the jar task to create a jar and the scp task to transfer your jar to a server.
Some examples:
<target name="jar" depends="compile">
<mkdir dir="${dist}" />
<jar jarfile="${dist}/myjar.jar" basedir="${target}">
<fileset dir="${source}">
<include name="**/*.gif" />
<include name="**/*.properties" />
</fileset>
</jar>
</target>
<target name="dist" depends="jar" >
<scp file="${dist}/myjar.jar" trust="true" keyfile="/tmp/keyfile.openssh" todir="user@server:/directory" passphrase="phrase" />
</target>
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "eclipse, ant, jar"
}
|
How do I check for nulls and empty string for a needle in a haystack?
Situation: I am coming across a lot of checks in my code. And I would like to know of a way in which I can reduce them.
if(needle!=null && haystack!=null)
{
if(needle.length()==0)
return true;
else
{
if(haystack.length()==0)
return false;
else
{
// Do 2 for loops to check character by character comparison in a substring
}
}
}
else
return false;
|
Perhaps a different code style would increase the readability of your code and reduce the amount of nested `if` statements for all of your checks.:
if (needle == null || haystack == null || haystack.isEmpty())
return false;
if (needle.isEmpty())
return true;
// compare strings here and return result.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 2,
"tags": "java"
}
|
how can I use "\newproof{pot}{Proof of Theorem \ref{thm2}}" in elsarticle
For refering a proof to a theory I know there are other ways to use but I want to know how to use by this " \newproof{pot}{Proof of Theorem \ref{thm2}}". If I put this in preamble and make proof environment by \begin{pot} ... \end{pot}, it will refer all proof to thm2.
|
You can define a generic environment using `\newproof` that has a text depending on a macro that can be redefined.
\documentclass{elsarticle}
\newtheorem{theorem}{Theorem}
\newcommand{\proofofref}{}
\newproof{zproofof}{Proof of \proofofref}
\newenvironment{proofof}[1]
{\renewcommand{\proofofref}{#1}\zproofof}
{\endzproofof}
\begin{document}
\begin{theorem}\label{1+1}
$1+1=2$
\end{theorem}
\begin{theorem}\label{twins}
There exist infinitely many twin primes.
\end{theorem}
\begin{proofof}{Theorem \ref{twins}}
It's really easy, isn't it?
\end{proofof}
\begin{proofof}{Theorem \ref{1+1}}
Too difficult.
\end{proofof}
\end{document}
;
jsonObj.put("email", email);
jsonObj.put("password", password);
// Create the POST object and add the parameters
HttpPost httpPost = new HttpPost("
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);`
Currently I am working in an android project where i need to pass an array user[email], user[password] to a web page using json...please if any one can help me width this asap..Thank you!
|
I'm not sure what you mean. But I guess you need something like this:
JSONArray jsonArray = new JSONArray(listOfUsers);
String jsonRepresentationForListOfUsers = jsonArray.toString();
You can look here for further documentation.
<
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "android, arrays, json"
}
|
How do I write this style of rightarrow?
How can I write this style of right arrow?
x}$
Let $0\leq x\le 1$, and $n$ a positive integer. Define the function
$$f(n,x)=\frac{1}{n}+\frac{1}{n-x}+\frac{1}{n-2x}+\dots+\frac{1}{n-(n-1)x}.$$
For which $x$ is the sum bounded by a constant for arbitrarily large $n$?
If $x=0$, this is $\frac{1}{n}+\frac{1}{n}+\dots+\frac{1}{n}=1$, a constant. If $x=1$, it is $\frac{1}{n}+\frac{1}{n-1}+\dots+\frac{1}{1}$, a divergent sum. The question is what happens in between.
As mfl wrote, the sum is bounded above by $\frac{1}{1-x}$. Is it also true that the sum converges to $\frac{1}{1-x}$?
|
**Hint**
$$\frac{1}{n}+\frac{1}{n-x}+\frac{1}{n-2x}+\dots+\frac{1}{n-(n-1)x}\le \frac{n}{n-(n-1)x}\underbrace{\nearrow}_{n\to \infty} \frac{1}{1-x}$$ for $0<x<1.$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 2,
"tags": "sequences and series"
}
|
Regular expression \p{L} and \p{N}
I am new to regular expressions and have been given the following regular expression:
(\p{L}|\p{N}|_|-|\.)*
I know what * means and | means "or" and that \ escapes.
But what I don't know what `\p{L}` and `\p{N}` means. I have searched Google for it, without result...
Can someone help me?
|
> `\p{L}` matches a single code point in the category "letter".
> `\p{N}` matches any kind of numeric character in any script.
Source: **regular-expressions.info**
If you're going to work with regular expressions a lot, I'd suggest bookmarking that site, it's very useful.
|
stackexchange-stackoverflow
|
{
"answer_score": 252,
"question_score": 171,
"tags": "xml, regex, character class"
}
|
What is "deuchère" ?
In this panel from _Astérix et Cléopâtre_ , I saw a word that was not in the dictionary: _deuchère_. I am also not entirely sure about _vé_ and _té_ , although I assume the joke is that the letters V and T are the approximate shapes the man and then the bird seem to be making with their arms/wings.
 et non "deuchère" qui est écrit ici.
Tout comme "vé" (regarde), "té" (tiens), et "fada" (fou), cela vient de l'occitan, en particulier du provençal et du languedocien.
La blague est que les ouvriers venant du sud de l’Égypte sont traduits avec des mots typiques du français parlé au sud de la France. D'ailleurs, un lecteur français lira probablement ça avec l'accent du Sud. ^^
|
stackexchange-french
|
{
"answer_score": 12,
"question_score": 1,
"tags": "vocabulaire, traduction"
}
|
Trouble understanding the relation between MongoDB and RocksDB
As I am learning to use Parse, I came across a announcement from parse saying they were using RocksDB and MongoDB.
Even after research, the relationship between Rocks and MongoDB is not clear cut to me, and what are the benefit to use RocksDB instead of a simple MongoDB.
As I understand it, RocksDB is a key-value store, while MongoDB is a noSQL database.
So, what is the point of adding RocksDB on MongoDB (or is it Mongo on Rocks?), and in that case, where are stored the data?
|
So using RocksDB for caching frequently asked query results from Mongo is a key to good application caching.
If we are asking about weather in Limerick, Warsaw and Moscow - it is faster to store query with it's result in key-value DB and retrieve on demand (having a TTL flag set) instead of hammering mongo with same queries.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "mongodb, rocksdb"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.