INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Use if else statement in R dataframe
d = data.frame(A=c(1,1),B=c(0,20),C=c(0,10))
d$B[d$B>0] = TRUE
d$C[d$C>0] = TRUE
d$B[d$B==0] = FALSE
d$C[d$C==0] = FALSE
Is there a way to do the 4 last operations in one line to simplify things like an if else statement for dataframe.
|
We can compare the entire dataframe (except the first column) and check if the value is greater than 0 or not and convert that value into numeric
d[-1] <- as.numeric(d[-1] > 0)
d
# A B C
#1 1 0 0
#2 1 1 1
Or if we want to keep the values as logical we can remove the `as.numeric` call
d[-1] <- d[-1] > 0
# A B C
#1 1 FALSE FALSE
#2 1 TRUE TRUE
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "r, dataframe"
}
|
Arcpy - LayerList - Count/Length
I use arcpy to load all layers in the current map document, and I need all layers but not the last one (this is my layer for the symbology template).
How can I access the length or count of the layer list or another way to exclude the last layer?
I already tried to use length and count, but it did not work.
My code so far:
arcpy.env.overwriteOutput = 1
mxd = arcpy.mapping.MapDocument("CURRENT")
lyrList = arcpy.mapping.ListLayers(mxd)
for lyr in lyrList:
#for each layer, but not the last one
#do something
|
You may simply use the `len`-funtion:
lyrList = arcpy.mapping.ListLayers(mxd)
num = len(lyrList)
If you want to loop all the layers except the last one use:
lyrList = arcpy.mapping.ListLayers(mxd)[:-1]
|
stackexchange-gis
|
{
"answer_score": 4,
"question_score": 0,
"tags": "arcpy, layers, length, list, count"
}
|
Can i download android platforms from any other site except http://dl-ssl.google.com or android.com?
This may sound very awkward but in my country many of the google services & sites are blocked, one of them is < So i cannot download android platforms and some other resources. Can i download them from any other site or source?
|
You can try:
* <
* <
It will be more work to figure out what repositories you want but they are alternate sites.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "android"
}
|
SQL big query optimalization
I have the following query:
SELECT `Product_has_ProductFeature`.`productId`, `Product_has_ProductFeature`.`productFeatureId`, `Product_has_ProductFeature`.`productFeatureValueId`
FROM `Product_has_ProductFeature`
WHERE `productId` IN (...'18815', '18816', '18817', '18818', '18819', '18820', '18821', '18822', '18823', '18824', '18825', '18826', '18827', '18828', '18829', '18830', '18831', '18832', '18833', '18834'..)
I have around 50000 productId's. The execution is 20 seconds long. How can I make it faster?
|
This is more of a comment.
Returning 50,000 rows can take time, depending on your application, the row size, the network, and how busy the server is.
When doing comparisons, you should be sure the values are of the same type. So, if `productId` is numeric, then drop the single quotes.
If the values are all consecutive, then eschew the list and just do:
where productid >= 18815 and productid <= 18834
Finally, an index on `productid` is usually recommended. However, in some cases, an index can make performance worse. This depends on the size of your data and the size of memory available for the page and data cache.
MySQL implements `in` efficiently (using a binary tree). It is possible that much of the overhead is in compiling the query rather than executing it. If you have the values in a table, a `join` is probably going to be more efficient.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "mysql, sql"
}
|
Boundary of a simplex
I've been wondering why the boundary of a simplex $\sigma : C_q (X) \rightarrow C_{q-1}(X)$ is defined to be $\partial \sigma = \sum (-1)^i \sigma \circ f_{i,q}$ with alternating sign.
Why can it not be the sum over all faces without alternating sign? Thanks for your help!
|
Because we want to have $\partial\circ\partial=0$ to built homology.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 2,
"tags": "algebraic topology"
}
|
UIpickerdate validation in iOS
its an registration apps where user selected date from uipickerpicker should be greater than equal to current date and if user enter past date then show alert text "Cant enter past date" in ios.. IF we set Property to UIDatePicker then user is unknown to actual date select it will store current date that main issue with using property...
|
Instead of that, you can use the minimumDate property of `UIDatePicker`. Set the minimumDate to current date, so your date picker don't allow the user to pick a past date.
[yourDatePicker setMinimumDate:[NSDate date]];
If you want to compare the date you can do it like:
NSDate *currentDate = [NSDate date];
if ([pickedDate currentDate] == NSOrderedDescending)
{
// Picked date is lesser than current date
// Show validation result
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ios, iphone, iphone developer program"
}
|
Force flash on native mobile camera
I am taking a photo with the user's native camera application via HTML, like so:
<input
type="file"
accept="image/*"
capture="camera" />
This opens the user's native camera application and gives a reject/confirm dialogue, which fits our use case perfectly.
Firstly and most importantly - can we force the flash using this or any other method?
Also, it would be nice to force the rear camera, but this is not necessary.
Thanks!
|
I think the first comment is correct, but by using a client-side image EXIF data library it seems that we can accept/reject photos based on flash fired.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, html, camera"
}
|
Random password generator in PHP not returning password
I am trying to set up a random password generator function in php but this is not working for me. I get the error:
> Notice: Array to string conversion in C:\xampp\htdocs\php-testing\index.php on line 12
>
> Array
What am I doing wrong?
<?php
function pwGenerator($len = 10) {
$charRange = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789!@#$%^&*()";
$pw = array();
$length = strlen($charRange);
for ($x = 0; $x < $len; $x++) {
$n = rand(0, $length);
$pw[] = $charRange[$n];
}
return $pw;
}
echo pwGenerator();
|
You cannot convert array into string directly. So instead of storing it in array you can attach characters with a string. and now it is working.
<?php
function pwGenerator($len = 10) {
$charRange = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789!@#$%^&*()";
$pw = null;
$length = strlen($charRange);
for ($x = 0; $x < $len; $x++) {
$n = rand(0, $length);
$pw .= $charRange[$n];
}
return $pw;
}
echo pwGenerator();
?>
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "php, arrays"
}
|
Why Muslim Clerics forbade trip to Mars?
I recently heard on NPR that Clerics issued an fatwa that forbids going to Mars.
If it is taboo why?
|
That is an Ijma and is for safety, because _At the moment, there is no technology available that would allow for a return trip from Mars_ (source)
In this link you can find:
> The committee of in the UAE that issued the fatwa against such a journey doesn't have anything against space exploration, Elon Musk's Mars visions, or anything like that. Rather, the religious leaders argue that **making the trip would be tantamount to committing suicide** , which all religions tend to frown upon.
Perhaps, when there is enough advancement to make a round trip or if Mars is declared suitable for habitation, the consensus will be lifted.
|
stackexchange-islam
|
{
"answer_score": 11,
"question_score": 7,
"tags": "sharia, science"
}
|
How to store complex objects into hadoop Hbase?
I have complex objects with collection fields which needed to be stored to Hadoop. I don't want to go through whole object tree and explicitly store each field. So I just think about serialization of complex fields and store it as one big piece. And than desirialize it when reading object. So what is the best way to do it? I though about using some kind serilization for that but I hope that Hadoop has means to handle this situation.
Sample object's class to store:
class ComplexClass {
<simple fields>
List<AnotherComplexClassWithCollectionFields> collection;
}
|
HBase only deals with byte arrays, so you can serialize your object in any way you see fit.
The standard Hadoop way of serializing objects is to implement the `org.apache.hadoop.io.Writable` interface. Then you can serialize your object into a byte array using `org.apache.hadoop.io.WritableUtils.toByteArray(Writable ... writable)`.
Also, there are other serialization frameworks that people in the Hadoop community use, like Avro, Protocol Buffers, and Thrift. All have their specific use cases, so do your research. If you're doing something simple, implementing Hadoop's Writable should be good enough.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 3,
"tags": "serialization, hadoop, hbase"
}
|
Why is there a horizontal scrollbar when my total width is 100vw?
Here is the code. I don't know why there is a horizontal scrollbar.
<html>
<head>
</head>
<body style="width: 100vw">
<div style="float: left; width: 220px">a</div>
<div style="float: left; width: calc(100vw - 220px)">b</div>
</body>
</html>
|
This is due to the default `margin` in the browser stylesheet.
body {
margin: 0;
}
<html>
<head>
</head>
<body style="width: 100vw">
<div style="float: left; width: 220px">a</div>
<div style="float: left; width: calc(100vw - 220px)">b</div>
</body>
</html>
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "html, css"
}
|
AWS certificate timestamp format
I want to check the expiration date of an SSL certificate placed in the Certificate Manager on my AWS account. When retrieving a certificate from AWS using the CLI - like this:
aws acm describe-certificate --certificate-arn *arn*
I get values looking like '1478433600.0' returned in the "NotAfter" property. I cannot recognize the format and I can't find anything in the docs - can anybody shed some light on this one for me?
<
Best regards
|
That format is
> unix epoch time
<
The timestamp you pasted represents this date and time:
Sunday, November 6, 2016 12:00:00 PM
See for yourself: <
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "amazon web services, aws certificate manager"
}
|
Is there an ideal of $(C^0(\mathbb{R}),+,\cdot)$ that isn't prime?
Let $C^o(\mathbb{R})$ be the ring of continuous functions over $\mathbb{R}$ with multiplication and addition of functions.
What sort of ideals can exist in that ring apart from those that are caracterized by a root (for example all the funtions $f$ s.t. $f(3)=0$)
Is there an ideal that isn't prime?
I found the $I=\\{f\in C^o(\mathbb{R})\ :\ f(x_1)=0$ and $f(x_2)=0\\}$ if we take $f(x)=x-x_1$ and $g(x)=x-x_2$ we have that $fg\in I$ but $f\notin I$ and $g\notin I$
There is also $\langle p(x) \rangle$ where $p$ is a recucible polynomial in a ring of polynomials
Are there different examples?
|
The zero ideal isn't prime, for example.
It's a well-known exercise (for example, Kaplansky's _Commutative rings_ page 7 exercise #1, the first in the book) that for a commutative ring, having all proper ideals prime is equivalent to being a field.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 2,
"tags": "abstract algebra, ring theory, ideals, examples counterexamples, maximal and prime ideals"
}
|
How to celebrate one's probation period being over?
Apparently it's a thing to do, when your probation period is over, so would one go about that? A big dinner? Sweets? Drinks?
And also imporant: Who's to be invited for that? The whole company? Your direct colleagues? Your hiring manager and above?
|
As someone quickly approaching the end of their 6 month prob period, I would say cakes/sweets/treats for the office. If it is a huge office, then for your team and maybe people you've worked with closely/directly during your time there.
Anything bigger than that makes it more of a deal than it is. You expected to survive your prob period (presumably!), they expected you to survive it, so it was expected
|
stackexchange-workplace
|
{
"answer_score": 2,
"question_score": -3,
"tags": "team, probation"
}
|
How to set the maximum date to the cupertino datepicker in flutter?
I want to set the maximum date of the datepicker of Cupertino Picker to current date So that users can not select a future date.
|
pass a `maximumDate`
CupertinoDatePicker(..., maximumDate: DateTime.now())
<
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 2,
"tags": "flutter"
}
|
Two independent current sources with one opamp?
!schematic
simulate this circuit - Schematic created using CircuitLab
The above circuit delivers a predetermined current to the load: $$i_L=-\frac{u_s}{2R}$$
Is it possible to extend it, so that it does the same thing, but for two diffrent loads, while using only one opamp (and resistors)?
Basically, I am looking for a way to create two independent current sources.
|
As Andy states you will need an op-amp per current source. One can simply not direct a specific current in more than one direction.
|
stackexchange-electronics
|
{
"answer_score": 0,
"question_score": 1,
"tags": "operational amplifier, current source"
}
|
How to select by elements in a UniData multivalued field
I'm trying to do an ad hoc search of records that contain duplicate values in the first and second elements of a multivalued UniData field. I was hoping something like this would work but I'm not having any luck.
LIST PERSON WITH EVAL "STATUS[1] = STATUS[2]"
After some testing it looks like I stumbled across a way of reading the field right to left that many characters. Interesting but not useful for what I need.
LIST PERSON NAME EVAL "NAME[3]" COL.HDG 'Last3'
PERSON Name Last3
0001 Smith ith
Any ideas on how to correctly select on specific field elements?
Apparently the EXTRACT function will let me specify an element but I still can't get a selection on it to work properly.
LIST PERSON STATUS EVAL "EXTRACT(STATUS,1,2,0)" COL.HDG 'Status2'
PERSON STATUS Status2
0001 Added Processed
Processed
|
I would use eval with @RECORD placeholder with the dynamic array notation as such (assuming that STATUS is in Attribute 11.
Edit: Previous answer was how I would do this in UniVerse
SELECT PERSON WITH EVAL "@RECORD<11,1>" EQ EVAL "@RECORD<11,2>"
Script Wolf's more better way that works in UniVerse and UniData.
SELECT PERSON WITH EVAL "EXTRACT(@RECORD,11,1,0)" EQ EVAL "EXTRACT(@RECORD,11,2,0)"
Good Luck.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "unidata, uniquery"
}
|
Change Mozilla readonly attribute
Is it possible to change Mozilla's readonly attributes: Specifically changing:
navigator.webdriver = false;
//changing it from true to false;
I know changing the _dom.webdriver.enabled_ value in the about config removes the navigator.webdriver variable, however I would like for the following outcome to be true
navigator.webdriver === false;
//should return true
It's worth mentioning that by default the value is always **false** , but when running Firefox with Selenium the value changes to **true** I am open for any methods, since I have full control of both the browser:Mozilla and the browser profile. _Hopefully I won't need to recompile Firefox_.
|
run `Object.defineProperty(navigator, "webdriver", {value: false})` in the page's context.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "selenium, firefox, firefox addon, geckodriver"
}
|
sed with two conditions
I have a file that contains a bunch of lines.
I would like to remove entries from file which starts with `nnn` and are longer than 25 characters.
For now I am able only to make two separates `sed`:
sed '/^nnn/d' input.txt > output.txt
sed '/^.\{25\}./d' input.txt > output.txt
but this is not my goal.
Example input:
nnnASDDGfdgdsfndsjfndsjfdfgGHGHGhfhfd
nnnASDDGfdgdsfn
sadbSADSDDFSDFrrrRRRRRRRttTGGGG
Desired output:
nnnASDDGfdgdsfn
sadbSADSDDFSDFrrrRRRRRRRttTGGGG
|
**`sed`** solution:
sed -E '/^nnn.{23}/d' file
* `/^nnn.{23,}/` \- match only line that starts with `nnn` and has more than 25 characters (`.{23,}` \- match character sequence of at least 23 characters long)
* `d` \- delete the matched line
* * *
The output:
nnnASDDGfdgdsfn
sadbSADSDDFSDFrrrRRRRRRRttTGGGG
* * *
The same with **`awk`** command:
awk '!/^nnn.{23}/' file
|
stackexchange-unix
|
{
"answer_score": 6,
"question_score": 8,
"tags": "text processing, sed"
}
|
Does the Horde size modifier stack with creature size modifier, or replace it?
When attacking a Horde in Deathwatch, do you apply both the Horde size modifier and the size modifier applicable to the individual creatures? Or does the Horde size modifier replace the creature size modifier?
|
The size bonus is replaced by the bonus dependent on the Horde's magnitude. The normal size bonus for individual creatures are not cumulatively added together (Deathwatch Core Rulebook; Pg. 359; “Attacking A Horde”):
> Characters must still roll to hit a Horde, but **the appropriate size bonus should apply** to these tests **based on the Horde’s Magnitude.**
Now this doesn't mean you have to stick to this rule, especially if the horde comprises mostly of obviously larger opponents. Do not feel as if you're forbidden from increasing the modifier up a notch or two to account for how much easier it is to actually hit such a horde.
|
stackexchange-rpg
|
{
"answer_score": 1,
"question_score": 2,
"tags": "creature size, deathwatch"
}
|
Writing an XSD schema to validate any XML file as valid
I'm often getting the warning in Eclipse:
> No grammar constraints (DTD or XML schema) detected for the document: logback.xml
Because of Logback's configuration file "flexibility" no validation schema is possible.
Thus, as a way of getting around the issue altogether, is there an XSD available on the internet that validates any structurally valid XML file as being valid, so I can trick Eclipse into being silent about the issue?
|
You can always disable the warning in eclipse. Go to Preferences-->XML-->XML FILES --> Validation and Select "ignore".
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "eclipse, xsd, logback"
}
|
Convergent sequence and $\lim_\limits{n \to \infty}n(a_{n+1}-a_n)=0$
> Let $(a_n)_n$ be a real, convergent, monotonic sequence. Prove that if the limit $$\lim_{n \to \infty}n(a_{n+1}-a_n)$$ exists, then it equals $0$.
I tried to apply the Stolz-Cesaro theorem reciprocal: $$\lim_{n\to \infty}n(a_{n+1}-a_n)=\lim_{n \to \infty} \frac{a_n}{1+\frac{1}{2}+\dots+\frac{1}{n-1}}=0$$ but I can't apply it since for $b_n=1+\frac{1}{2}+\dots+\frac{1}{n-1}$ we have $\lim_\limits{n \to \infty} \frac{b_{n+1}}{b_n}=1$. I also attempted the $\epsilon$ proof but my calculations didn't lead to anything useful.
|
Hint. You are on the right track. Note that $a_n$ is convergent to a finite limit and the harmonic series at the denominator is divergent. Therefore $$0=\lim_{n \to \infty} \frac{a_n}{1+\frac{1}{2}+\dots+\frac{1}{n-1}}\stackrel{\text{SC}}{=}\lim_{n\to \infty}\frac{a_{n+1}-a_n}{\frac{1}{n}}=\lim_{n\to \infty}n(a_{n+1}-a_n).$$
|
stackexchange-math
|
{
"answer_score": 5,
"question_score": 1,
"tags": "real analysis, sequences and series, limits, convergence divergence"
}
|
Check if element of linked list exists
I am trying to determine if the value is a member in the link. if it is a member, it will return true otherwise it returns false. I try to do this
public boolean member(Integer val){
if(node.val.equals(val) || node.next.val.equals(val)){
System.out.println("true");
return true;
}
return false;
}
However, it only check the value of the head and value of the next of the head. What would be other way to check the value of all node?
|
Just pass the root node and loop through your linkedList:
public boolean member(Node root, Integer val){
Node currentNode = root;//keep track of current node
while(currentNode != null){
//switched currentNode.val and val to avoid null pointer exceptions
if(val.equals(currentNode.val)){
//if you're looking for nulls...still with the original
//if(currentNode.val.equals(val)){
System.out.println("true");
return true;
}
currentNode = currentNode.next();//update current node
}
return false;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "java, linked list, nodes"
}
|
change property of doc, if the view was requestet in CouchDB
I have a view where I get all customers and save them with curl as a json file. Now I would like to change a property of each document that where found in this view, how could I do this?
before I requested the view:
{
"name": "somebody"
"changed": true
}
after I requested the view:
{
"name": "somebody"
"changed": false
}
I tried to put it in my Design / View doc but that did not work:
function(doc) {
if (doc.type === "customer" && doc.changed === true) {
doc.changed = false;
emit(doc._id, doc);
}
}
|
Its not possible to alter docs within a view.
A doc can be altered when it gets requested with the help of an update handler but thats limited to single doc scenarios.
The client side must be included. E.g. the response of the view can be altered client-side and send back to the `_bulk_docs` path. Another way could be to provide an update handler for altering `doc.changed` \- then the client-side logic must send an empty POST to the update handler for every doc from the view response.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "nosql, couchdb"
}
|
Plone4 - I need an idea
I need to build a system around a concept as follows:
Users have their objects, which are created by managers and by users themselves. Their objects are visible only to themselves. How to do it in broad way? What logic and mechanism I should choose?
I know this question is perhaps too broad but I am quite novice to development.
|
Your requirements can be easily solved by using the built-in user-folders of Plone.
You need to enable them in the security-part of the controlpanel via yourhost:8080/sitename/@@security-controlpanel ( _Note_ : If you are logged in and trying to see the change of the config afterwards, looking for your own urserfolder, you need to logout and login again, because the foldercreation-trigger is the 'first' login).
Every user gets its own folder then, where other users but Managers don't have have access to and additionally have access themselves to items Managers created in their folder, because the ownership of the user-folder belongs to the user.
Preferably set this configuration in your own product (plone-add-on/plugin), to make it reproducable programatically.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "plone, roles, zope"
}
|
EF 4.3 - Update entity and sub entities
I have an entity Order with a sub entity OrderDetail. I want to update the Order and add a new OrderDetail. How should i do this?
I've tried setting the state of the Order to modified but i get this error:
A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship.
Update: After i've added the new OrderDetail, i want to update the order type which is part of primary key. I've tried to set the state of OrderDetail to modified but i get a new error:
Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.
|
Try to put the new `OrderDetail` into `Added` state first before you set the `Order` to `Modified`:
var newOrderDetail = order.OrderDetails.First();
context.Entry(newOrderDetail).State = EntityState.Added;
context.Entry(order).State = EntityState.Modified;
This might work - or not, depending on the details of your model and scenario...
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "entity framework, entity framework 4.3"
}
|
How to lock a file with C#?
I'm not sure what people usually mean by "lock" a file, but what I want is to do that thing to a file that will produce a "The specified file is in use" error message when I try to open it with another application.
I want to do this to test my application to see how it behaves when I try to open a file that is on this state. I tried this:
FileStream fs = null;
private void lockToolStripMenuItem_Click(object sender, EventArgs e)
{
fs = new FileStream(@"C:\Users\Juan Luis\Desktop\corte.txt", FileMode.Open);
}
private void unlockToolStripMenuItem_Click(object sender, EventArgs e)
{
fs.Close();
}
But apparently it didn't do what I expected because I was able to open the file with Notepad while it was "locked". So how can I lock a file so it cannot be opened with another application for my testing purposes?
|
As per <
FileStream s2 = new FileStream(name, FileMode.Open, FileAccess.Read, FileShare.None);
|
stackexchange-stackoverflow
|
{
"answer_score": 56,
"question_score": 41,
"tags": "c#, io"
}
|
Python writing to a json
Ive been working on an address book in python, and I need to make a function that can write to a json file. The function needs to be able to add/append to this specific json layout
Json Layout Example -
{"addresses":
[
{"name": "example", "town": "example", "address": "example"}
]
}
The Problem - I only know how to write to a json file, not how to write to a json object...
Can someone please show me an example of how to add/append to a json object
|
JSON is just a string in Python. You can `load` and `dump` the json whenever you need to return it or change it respectively. For example:
import json
py_dict = {'a': 'b'}
# Convert dict to string
json_obj = json.dumps(py_dict)
# oops need to make a change -> convert from string to dict
py_dict = json.loads(json_obj)
# append to dict
py_dict['hello'] = 'world'
# Convert dict to string
json_obj = json.dumps(py_dict)
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "python, json"
}
|
graded modules have enough projectives
In the bottom of page 32 in Bruns and Herzog, Cohen-Macaulay Rings, the authors write that if $R$ is a $\mathbb{Z}$-graded ring and $M$ a $\mathbb{Z}$-graded $R$-module, then $M$ is the homomorphic image of an $R$-graded module of the form $\oplus_{i \in \mathbb{Z}} R(i)$. Could someone please explain how we see that? In particular, how can we construct such an epimorphism? Note that $M$ need not be finite.
|
This is not correct (perhaps you have a misquote?), we need $\oplus_{i \in \mathbb{Z}} R[i]^{\oplus B_i}$ for sets $B_i$. These graded modules are called _graded-free_. They are easily seen to be projective.
In order to write every graded module $M$ as a quotient of a graded free module, just pick a generating system $B_{-i}$ of $M_i$. Every element $b \in B_{-i}$ corresponds to a homomorphism of graded $R$-modules $R[-i] \to M$, the image of $1 \in R = R[-i]_{i}$ is exactly $b \in M_i$. These extend to homomorphisms $R[-i]^{\oplus B_{-i}} \to M$, and then to a homomorphism $\oplus_i R[-i]^{\oplus B_{-i}} \to M$, which is an epimorphism by construction.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 2,
"tags": "commutative algebra"
}
|
Android/Jitpack: Unable to import submodule
I'm trying to import a submodule of an android library I'm creating. The sub-module is called **progressbar**
<
<
dependencies {
implementation 'com.github.SomeKoder:Essentials:0.1.0'
}
I've tried this and many other variations without success.
dependencies {
implementation 'com.github.SomeKoder.Essentials:progressbar:0.1.0'
}
Can someone help me figure out what I'm doing wrong please? Thanks in advance
|
Adding this to the modules **build.gradle** led to the artifacts actually building:
plugins {
id 'com.android.library'
id 'kotlin-android'
id 'maven-publish'
}
afterEvaluate {
publishing {
publications {
release(MavenPublication) {
from components.release
groupId = 'com.somekoder.Essentials.progressbar'
artifactId = 'progressbar'
version = '0.1.4'
}
debug(MavenPublication) {
from components.debug
groupId = 'com.somekoder.Essentials.progressbar'
artifactId = 'progressbar-debug'
version = '0.1.4'
}
}
}
}
It seems you must add a variant of this code in every module you wish to create an artifact for. Then importing through JitPack works fine.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "android, import, module, jitpack"
}
|
Exposing OData on a MVC application
I want to offer my users a rich query functionality so they can dynamically add Where clauses, change sort orders and groupings. oData seems to be the best technology for the job, but I don't know how to implement it correctly in a MVC application.
1) How can I connect a feature rich client that supports oData with a MVC architecture?
2) Must I expose IQueryable on my repository?
3) Can anyone explain how to Create, Update, or Delete when using 2 joined tables in MVC? (in the service layer?)
|
A good place to start learning about OData is here: <
In General OData and Web Services should be used if they are required because 1) You physical tiers need to be separated for security or performance reasons or 2) Multiple applications or consumers need to use the same API. There are of course other reasons but generally if you have to ask if OData makes sense you don't have those requirements. ;)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 4,
"tags": "asp.net mvc, model view controller, data access layer, crud, odata"
}
|
Mean, Median, Mode,…, Sum?
Five test scores have a mean of $91$, a median of $93$, and a mode of $95$. The possible scores on the tests are from $0$ to $100$. a) What is the sum of the lowest two test scores? b) What are the possible values of the lowest two test scores?
* so i came up with the numbers $82,90,93,95,95$
* I know that $95$ will appear more than once because its the mode
* however, I do not know how to prove my answer, as I got these answers through the use of an average calculator
* what would be a way to prove my answer, what equation should I use? -thanks
|
We know the median is $93$ and there are $5$ numbers. So we can arrange the numbers in increasing order $a,b,93,c,d$ because $93$ is the median.
Now we know the mode is $95$, which means it should occur more than once. If it only appears one time, $93$ would have also been the mode. So we have $a,b,93,95,95$.
Now the mean is $\frac{a+b+93+95+95}{5} = 91$, so $a+b=172$. That is part a). Now $b=172-a$ and $b ≥a$ and $b<93$. $b$ cannot be $93$ because then $93$ would also be the mode. So $b$ can take values from $92$ to $86$ and $a$ will range from $80$ to $86$ correspondingly.
$$80,92,93,95,95$$
$$81,91,93,95,95$$
$$\cdots$$
$$\cdots$$
$$86,86,93,95,95$$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "average"
}
|
Sci-fi story: they put humans in missiles/rockets
Its a short sci-fi story from 50s/60s/70s where two factions are fighting.
They try to outdo one another by constantly putting more advanced weapon guidance systems on their missiles.
Eventually their tech becomes so advanced that their defense systems can predict the point of attack and no offensive attacks are successful.
This leads to putting humans into rockets for kamikaze attacks as humans remain unpredictable in flight.
|
This resembles the plot of "The Feeling of Power", a short story by Isaac Asimov, first published in 1958. In the story, the Terrestrial Federation is at war with Deneb:
> a war of computer against computer. Their computers forge an impenetrable shield of anti-missiles against our missiles, and ours forge one against theirs. If we advance the efficiency of our computers, so do they theirs, and for five years a precarious and profitless balance has existed.
In this society the skill of doing mathematics has been lost; computers do all computations. A minor technician, Myron Aub, rediscovers the ancient art of pencil-and-paper mathematics, which they term "graphitics". This has a possibility of revolutionising the war since as well as leap-frogging the Denebian development of computers,
> a missile with a man or two inside... would be lighter, more mobile, more intelligent... A man is much more dispensable than a computer.
The story is available at the Internet Archive.
|
stackexchange-scifi
|
{
"answer_score": 33,
"question_score": 14,
"tags": "story identification, short stories"
}
|
Managing SQL Server logins and database users
I am getting a little further into the database administration side of things and starting to set up security access to SQL server databases for users. I have a question about server logins and database users in the following scenario:
We have 30 database users that require the same permissions, each with their own AD accounts.
When setting up SQL server access for these SQL writers what is the most performant approach for giving a group of users with the same permissions access to a server/database?
I appreciate that this could be achieved via several approaches but am keen to learn the performant approach to managing relationships between server logins/database users/database roles.
Thanks :)
|
The easiest and most manageable way to achieve this is using Active Directory groups.
Have your ad administrator create a security group called SQL_Writers (or something similar) for those users and add them (and any new users to that group).
Then in SQL Server, simply grant that security group the appropriate permissions to the server / databases.
If you want the permissions to be inherited to any newly created database on your instance, remember to grant the security role to the _model_ database as well.
|
stackexchange-dba
|
{
"answer_score": 1,
"question_score": 1,
"tags": "sql server, ssms"
}
|
Read message body (raw xml) from MSMQ using Nservice bus before Handle() is called
Is There any way I can read raw xml message from MSMQ using NService bus before it parses it to corresponding class object. I am getting message in Handle(Class obj). This is working fine but I want to log the xml from raw message body which NService parses to class object .
|
Have a look at transport message mutators. You'll be able to inspect both the Body and Headers of the message
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "c#, xml, msmq, nservicebus"
}
|
Foreigner registration in Belarus?
Are the foreigners required to register at police/immigration office on arrival if they are visiting Belarus for less than 5 days?
|
No. From GOV.UK:
> Anyone staying for more than 5 working days in Belarus must register with the local police office (OVIR) in the district in which they are staying. Registration will normally be arranged by your hotel. If you are not staying in a hotel registration must be organised by your host. There are fines for not registering in time. If you arrive at the weekend, the earliest you will be able to register is Monday (but offices are only open until 1pm).
|
stackexchange-travel
|
{
"answer_score": 5,
"question_score": 6,
"tags": "belarus, minsk"
}
|
Inverse cot in C#
We know that the inverse of `tan` is `Math.Atan`, what about the inverse of cot? `cot(x)` is defined as
cot(x)=1/tan(x)
|
See Inverse Cotangent. For some values, the inverse would be `atan(1/x)`.
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 5,
"tags": "c#, math"
}
|
Ruby on Rails CMS with multiple languages
I'm currently working on a project with Ruby on Rails. I need a CMS and multiple language integration. As of right now, I need the site to be shown only in English and Spanish.
Is there any Ruby on Rails CMS that handles this easily? If not, which Ruby on Rails CMS would you recommend that allows this to be implemented.
|
Of course, use Refinery, it's straight.
* * *
In spite of @tadman answers success, beware of community support:
* Sofa: 390 followers on github
* Refinery: 1728.
There is a sign here, even if there is no truth...
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 1,
"tags": "ruby on rails, ruby, ruby on rails 3, content management system"
}
|
Free action of a smooth variety is smooth
Let $X$ be a smooth complex algebraic variety and $G$ a finite group acting freely (i.e. $g.x=x\Rightarrow g=e$) on $X$, is the quotient $X/G$ a smooth algebraic variety again? I saw it be applied in e.g. page 171 of FGA explained.
It should be super obvious but I somehow failed to see it clearly.
|
There's one extra piece of information here that's missing which is super important. By proposition 1.8 in SGA I, Exposé V, a necessary and sufficient condition for a quotient scheme $X/G$ to exist for a scheme $X$ and a finite group $G$ acting on $X$ is that the orbit of every point of $X$ be contained in an affine open subset. This is automatically satisfied if $X$ is quasi-projective, for instance.
Once you know that the quotient exists, it may be quickly concluded that $X/G$ is smooth as well: the quotient of a smooth manifold by a finite group acting freely is again a manifold, and since a variety over $\Bbb C$ is smooth iff it's complex points form a smooth manifold (and the complex points of the quotient are the quotient of the complex points), there you go. There are other arguments as well, depending on your level of sophistication.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 2,
"tags": "algebraic geometry"
}
|
Modified vendor files, Laravel
I'm currently using Laravel 7.xx, and during working on my project, I change some vendor files, modify it
Because few things doesn't work for me, so without any option left, I have to modify some vendor files.
In case if I ever want / need to update my laravel / packages version, will the modified vendor files revert back to original state and I lost all my modified code?
Thanks in advance
|
Yes! whenever you do composer install or composer update, your modified vendor files will revert back. So, you never should edit any vendor files. What you can do is extend those specific classes to new files of your own
1. Make a new file of the class that you are overriding : (e.g : app/Overrides/MyClass.php)
2. in your composer.json
"exclude-from-classmap": [
"vendor/pathtotheYourVendorFileThatYouAreOverriding.php"
],
"psr-4": {
"App\\": "app/",
"Illuminate\\": "app/Overrides/"
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "laravel"
}
|
Как сделать кнопку "меню" в телеграм боте..? Пишу на Python, наткнулся на такую кнопку в другом боте. Фотографию приложил
,
]
# Команды для админов
admin_commands = [
BotCommand("start", "Старт"),
BotCommand("stat", "Статистика"),
]
async def set_commands(dp: Dispatcher):
await dp.bot.set_my_commands(user_commands, scope=BotCommandScopeDefault())
for admin in ADMIN_ID:
await dp.bot.set_my_commands(admin_commands,scope=BotCommandScopeChat(chat_id=admin))
Соответственно при запуске бота нужно исполнять set_commands()
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "python, telegram bot, telegram, bot"
}
|
Use of undeclared type 'WKNavigationDelegate'
I'm trying to make a web view to load an URL.
import UIKit
class ViewController: UIViewController, WKNavigationDelegate{
@IBOutlet weak var webView: WKWebView!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func loadButtonPressed(_ sender: UIButton) {
if let url = URL(string: " {
let urlRequest = URLRequest(url: url)
webView.load(URLRequest)
}
}
}
It shows `Use of undeclared type 'WKNavigationDelegate'`. I can't find what's go wrong. How can I fix it? Do I miss something?
|
OK I fix it.
I have to do `import WebKit` first
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "swift, webview"
}
|
Transfer a huge directory between servers (one of them has no ssh)
So we switched from some crappy shared hosting provider to a dedicated server and I'm trying to transfer a 250+ GB directory from the old crappy server (which I don't have ssh access to), to the new server (which i have root access to).
so RSYNC, SCP, etc. are out of the question.
I'm trying to figure out how i can do this without downloading all the files and re-uploading them. I would like to just set it in motion, go home for the weekend, and come back to it.
How would i FTP into my old server from my new server?
|
Install and use ncftp or ncftpget from the new server recursively to get the whole directory structure and files
ncftpget -R yourremotehost . /
check <
|
stackexchange-serverfault
|
{
"answer_score": 1,
"question_score": -1,
"tags": "linux, ssh, ftp"
}
|
Use an anchor tag in url after load with knockout
I am working on a knockout page and I have a list of items. For each item I need them to have an anchor tag to scroll to. The problem I'm having is the anchor tag is being loaded from knockout bindings so, when you click on the url from an external page you would have a problem with it actually scrolling to the item. The page with the hash is a separate page. So in you can't scroll to the hash on page load simply because it doesn't exist until knockout loads the bindings.
For example...
My url = `mysite.com/page1#thisItem`
It should link to page1 with an anchor tag like...
<a name="thisItem"></a>
The problem is that the name gets added after the knockout bindings. I would prefer to do this without javascript checking if it has an id to link to and changing the window.location, however if that's my only choice then I will do it. Does anyone have a more elegant solution to this problem?
|
If you usecase is simple enough, you could simply check for the target onload, after your KO has initialized, and then just send the user there. Using something like scrollIntoView should work:
if (location.hash) {
document.scrollIntoView(document.getElementByName(location.hash)[0]);
}
(not tested, adjust for syntax errors, etc!)
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "javascript, jquery, html, knockout.js"
}
|
change to random subdirectory in batch
Im trying to change to a random subdirectory in a folder with batch
cd c:\*
doesnt work, in fact takes you to the recycle bin each time
if exist * (
cd *
)
didnt work
for %d in (*) do cd %d
didnt work
so im at a loss, is there any way to do this in batch?
|
@echo off
setlocal EnableDelayedExpansion
rem Create an array of dir. names
set n=0
for /D %%a in (c:\*) do (
set /A n+=1
set dir[!n!]=%%a
)
rem Select a random element from the array
set /A d=%random%*n/32768+1
rem And CD to it
cd "!dir[%d%]!"
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "windows, batch file, cmd"
}
|
Block Connections From Other Devices
I have a website and I just want mobile devices to enter the site.So my question is how can I block connections from other devices.
I'm able to use node.js html and php in my website.
|
You can use mobile detect class in PHP and then use a code like this :
// if visitor is not using any mobile device (phones or tablets).
if ( !$detect->isMobile() ) {
die("access denied")
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "php, html, node.js"
}
|
Getting count of foreign keys and joining to another list?
I have two tables, `lists` and `items`
`Lists` table looks like this and
 as count
from items
group by list_id
when joining the list to this query, the counts are getting wrong. What can be the query to get the correct results? my database is sqlite.
|
looking to your sample seems you need a join between the tables
SELECT list.name, count(items.list_id) as count
from list
inner join items on list.id = items.list_id
group by list.name
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sql, database, sqlite, foreign keys"
}
|
algorithm for working with ratios using decimal type
What technique would you use to make the test below pass?
Cheers,
Berryl
[Test]
public void PercentageToSplit() {
for (int i = 1; i < 20; i++) {
decimal ratio = 1m / i;
Console.WriteLine(ratio);
var splitCount = (int)Math.Floor(1 / ratio); // *** this won't do
Console.WriteLine(splitCount );
Assert.That(splitCount, Is.EqualTo(i));
}
1 becomes 1
0.5 becomes 2
0.3333333333333333333333333333 becomes 3
0.25 becomes 4
0.2 becomes 5
0.1666666666666666666666666667 becomes 5
Test 'PercentageToSplit' failed:
Expected: 6
But was: 5
|
Your test passes if you change `Math.Floor` to `Math.Round`.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c#, algorithm, decimal, rounding"
}
|
Java MyBatis Freemarker Dynamic SQL
i use MyBatis (with Freemarker driver) in a spring boot application, accessing to query with the @Mapper and @Select annotations.
@Mapper
public interface DataRepository {
@Lang(FreeMarkerLanguageDriver.class)
@Select("/sqlMappers/module/findList.ftl")
public List<DomainDto> findItemsMatchingFilter(
@Param("entityId") Long entityId,
@Param("commonSearch") CommonSearch commonSearch);
I have some particular queries that I would like to be saved in databases and run by MyBatis at runtime (the idea is to modify the queries to dynamically generate some XLSX reports).
Is it possible with MyBatis (I'd like to use it to not have to worry about sql injection and other similar aspects)?
Thanks, Gabriele
|
So, with mybatis-freemarker is not possible.
I think i will save it in a DB table with freemarker format, so i will execute them as native query.
The business requirement is to create a little engine to execute custom query on DB and export them as excel file.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "java, mybatis, freemarker, dynamic sql"
}
|
What version of RHEL am I using?
From the shell and without root privileges, how can I determine what Red Hat Enterprise Linux version I'm running?
Ideally, I'd like to get both the major and minor release version, for example RHEL 4.0 or RHEL 5.1, etc.
|
You can use the `lsb_release` command on various Linux distributions:
lsb_release -i -r
This will tell you the Distribution and Version and is a little bit more accurate than accessing files that may or may not have been modified by the admin or a software package. As well as working across multiple distros.
For RHEL, you should use:
cat /etc/redhat-release
|
stackexchange-serverfault
|
{
"answer_score": 154,
"question_score": 152,
"tags": "linux, redhat, rhel5, rhel6, rhel4"
}
|
Embedding Resource in C# without Visual Studio
I have a question similar to this. However, I am not using Visual Studio (yeah, I know I should but I don't want to, so don't just say use Visual Studio). How would you embed a text file into an exe using only notepad and csc.exe?
|
According to this website: building embedded resources using csc
> Using this KB article and the docs for vs.net's csharp compiler options I arrived at this:
csc.exe /out:Resources.dll /target:library /res:image.png,Resources.image.png Resources.cs
> The tricky thing here is that the ms docs for the /res option only mention using it with .resources files, which are compiled resx files. But in fact you can embed any sort of file in there. The "Resources.image.png" part identifies the resource and puts it under the Resources namespace, which is what vs.net will do when specify a default namespace for the project.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 3,
"tags": "c#, embedded resource"
}
|
Ionic Ion-checkbox change color in Typescript
I want to change the color of the ion-checkbox in the typescript
<ion-item >
<ion-label id="check1">No</ion-label>
<ion-checkbox color="blue" id="box1" [(ngModel)]="todo.check1" name="check1"></ion-checkbox>
</ion-item>
I try this:
document.getElementById("box1").color = "dark";
but it doesn't work
I also try to change the class: doesn't work
Thanks for you help
|
try:
document.getElementById("box1").setAttribute("color", "dark")
or
document.getElementById("box1").style.color = "dark"
The first will change the color attribute of the element, while the second changes the css style for color of the element.
For typescript to be happy, you may also have to cast the result of your `getElementById` call. I.E.
(document.getElementById("box1") as HTMLElement).style.color ...
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "typescript, ionic framework, checkbox, colors, ion checkbox"
}
|
AWS Lambda: access the invocation parameters from error handler
Using AWS Lambda, how can I get the invocation parameters that the lambda was called with, inside the lambda error handling? i.e.:
lambda.invoke(lambda_params, function(err, obj) {
if(err){
// how do I access lambda_params from here?
}
}
|
What you're really asking is irrelevant to AWS Lambda, if I am understanding correctly, you want to access a variable called 'lambda_params' within the scope of the callback function. If so, then this is a question aimed towards how to access variables within the scope of a callback function in the specific language you're talking about.
Am not sure which language you're referring to in the above code but I believe you should be able to access `lambda_params` directly within the scope of the function
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "error handling, parameters, invoke, aws lambda"
}
|
$\sum \frac{a_k}{p^k}$ converges to a real number in $[0,1]$
Given $p \geq 2$, $$ \sum_{k=1}^{\infty} {\frac{a_k}{p^k}} , a_k \in \\{0,1,...,p-1\\}$$
converges to a real number in $[0,1]$
I was thinking maybe using geometric series the above series can written as $(p-1) \sum{a_k} $. But then again, how can we show this series actually belong to $[0,1]$ ? thanks
|
Note that $a_k\leq p-1$ for each $k$. Thus...? Relate this to $$\left( {p - 1} \right)\sum\limits_{k \leqslant N} {{{\left( {{p^{ - 1}}} \right)}^k}} =\sum\limits_{k \leqslant N} {{{\left( {{p^{ - 1}}} \right)}^{k - 1}} - {{\left( {{p^{ - 1}}} \right)}^k}} = 1 - {\left( {{p^{ - 1}}} \right)^N}\to 1$$ Recall a sum of positive terms converges if, and only if, it is bounded above.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "calculus, real analysis, sequences and series"
}
|
How to increase the volume for an avi file
I have one or two .avi files for which the sound is simply too low. I like to play them in vlc, and enabling the graphic equalizer helps somewhat, but is there any other (easy and quick!) way of increasing the volume? Thanks!
|
You could use VirtualDub for this. This guide has a short and straight-forward explanation.
Brief:
-
1. Start VirtualDub and load in your converted DivX file.
2. From the "Video" menu, select "Direct Stream Copy".
3. From the "Audio" menu, select "Full Processing Mode".
4. From the "Audio" menu, select "Volume", check the "Adjust volume of audio channels" option, and you can use the slider to change the level of audio.
5. Press the "Preview Output" button and listen to the audio - if it isn't loud enough, go back to the previous step and increase the amplification level.
6. From the "Audio" menu, select "Compression" and select "MPEG Layer-3" and the same or lower bitrate/attributes (eg. 128 kBit/s, 48000 Hz, Stereo) you used earlier to make the DivX movie.
7. From the "File" menu, select "Save AVI" to save the AVI to include the normalized audio. This shouldn't take too long as only the audio is re-encoded/compressed - the video will be left alone.
|
stackexchange-superuser
|
{
"answer_score": 5,
"question_score": 15,
"tags": "audio, avi"
}
|
Getting text from a textfield
I am trying to get username and password from the textfield. This is the HTML code:
<form class="navbar-form pull-left">
<input type="text" class="span2">
<input type="text" class="span2">
<button type="submit" class="btn">Submit</button>
</form>
How can I get this username & password in the LoginController to check for authentication?
|
First, you need to add a `name` property to your input fields. Then specify the `action` and `method` attributes for the `form`. The form would look like this then:
<form action="your_route_goes_here" method="post" class="navbar-form pull-left">
<input name="username" type="text" class="span2">
<input name="password" type="password" class="span2">
<button type="submit" class="btn">Submit</button>
</form>
In your LoginController, you can then access the username and password like so, respectively:
params[:username]
params[:password]
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": -3,
"tags": "ruby on rails, ruby"
}
|
How to reference a Web Service from an ASP.NET MVC project?
I want to add a web service to my `ASP.NET MVC 5` project.
I do that by right click on the project in solution explorer > `add` > `service reference`.
Then I add a web service url like this and it creates a new file in `Service References` folder called `ServiceReference1`
Then I'm able to call web service methods in C# by using `ServiceReference1` namespace and VS intellisense works.
The problem is that when I add this web service url, it adds a new namespace (`ServiceReference2`) to that folder, but I can't call the new namespace and it says `ServiceReference2 namespace could not be found`.
Is it me doing something wrong or the web service has a problem?
|
After you open your service window, click on the advanced button like below.
In general, I agree it's best not to use the older versions of web-services like I'm showing here, but in real life people have deadlines and such.
Saying that though, there is no huge drawback to using this tech, as long as performance isn't an issue.
!enter image description here
Then, click 'add Web Reference' like the picture below.
!enter image description here
Then enter URL and click on the little arrow button. Name your reference and click 'Add Reference'. see pic below
!enter image description here
|
stackexchange-stackoverflow
|
{
"answer_score": 13,
"question_score": 7,
"tags": "c#, asp.net, asp.net mvc, web services"
}
|
Attribution when deriving from a W3C Software Notice and Document License work
I am creating a reimplementation for a different language of a software library that is licensed under the W3C Software Notice and Document License. The original library contains a NOTICE file. As my project is heavily influenced by the original I would assume that it constitutes a derived work (which I want to publish under the MIT license).
I therefore wanted to ask for some advice on how to properly attribute the original library. Is it enough to include the text `This software or document includes material copied from or derived from [title and URI of the W3C document]. Copyright © [YEAR] W3C® (MIT, ERCIM, Keio, Beihang).` from the license in my README and the license text in the LICENSE file? Or do I have to create a NOTICE file myself (containing the text from the original NOTICE) and/or add the above mentioned copyright statement to every source code file in my library?
|
The W3C license you linked to does not mention a NOTICE file, so there is no requirement to have or keep such a file.
The best way to attribute the original library is to have the text `This software includes material copied from <original library> (<link to repository>). Copyright © [YEAR] W3C® (MIT, ERCIM, Keio, Beihang).` in both your README and LICENSE files.
You put it in your README to have the attribution in a location where it will be almost certainly seen.
You _also_ put it in your LICENSE file, just before the copy of the W3C Software Notice and Document License itself to make it clear why that license text is placed there and to avoid any possible confusion if your code might be dual-licensed or not.
|
stackexchange-opensource
|
{
"answer_score": 2,
"question_score": 1,
"tags": "licensing, mit, derivative works"
}
|
list-style-type with YUI reset.css?
I am using yui reset:
<link rel="stylesheet" href="
and I'm having a hard time getting my ordered lists to show with `decimal`.
So far I'm using this, but it still seems to be overwritten to be blank?
ol, ol li{
list-style-type: decimal;
list-style-position: outside;
}
|
You can un-reset these styles. See: <
What I prefer to do it have a wrapping class for my un-reset items. This way the reset remains universal everywhere else.
/* un-reset bullets */
.bullets ul {
margin:0 1.5em 1.5em 1.5em;
}
.bullets ul li {
list-style-type:disc;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "css, yui, yui reset"
}
|
How to configure 'uiGmapgoogle-maps' API key after bootstrap?
So, I am using uiGmapgoogle-maps in my angular project. I need to specify the API key, According to their documentation is needs to be done in the bootstrap process as a config:
.config(function(uiGmapGoogleMapApiProvider) {
uiGmapGoogleMapApiProvider.configure({
key: 'your api key',
v: '3.20', //defaults to latest 3.X anyhow
libraries: 'weather,geometry,visualization'
});
})
However, my issue is I don't have the API until later on in the applications life. To be specific, the api key is in the database and is specific to a user. The user would need to login and then we can access the api key.
I did some research into lazy loading angularjs controllers but I couldn't get my head around how to sort this specific issue.
So, how would I run this configuration after the boostrap process? Specifically from a controller.
|
I am answering my own question after fixing this issue.
I created a provider:
provider('GmapsKey', class GmapsKey {
constructor() {
this.uiGmaps = null;
}
set key(key) {
this.uiGmaps.configure({key});
}
$get() {
return this;
}
});
and
config(['uiGmapGoogleMapApiProvider', 'GmapsKeyProvider', (uiGmapGoogleMapApiProvider, GmapsKeyProvider) => {
GmapsKeyProvider.uiGmaps = uiGmapGoogleMapApiProvider;
}]);
Once I had my key ready, I injected `GmapsKey` and set the key:
GmapsKey.key = userConfig.uGMapAPIKey;
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "angularjs"
}
|
is there a bijection for $f: \mathbb R \to \mathbb C$?
I imagine no since the dimensions do not match
but they have the same cardinality $|\mathbb R |= |\mathbb C|$?
|
If you just want a bijection as sets, the answer is yes. That’s exactly what it means for two sets to have the same cardinality. If you’re looking for a bijection that preserves some structure, that will depend on precisely what you’re trying to preserve but the answer is very probably no.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 2,
"tags": "relations"
}
|
Create new lists of the shortest and longest words in an existing list - Python
I know there is a better way to do this but I can't seem to find it. As you can see below I am getting the longest and shortest results but only because I know what the longest and shortest words are and I then input a condition....but what if I didn't know the longest and shortest words... hope I am making myself clear. Just started with programming so have no prior experience. Many thanks for any help!
names = [ "Brian", "jake", "Jason", "Brad", "Tony", "jimmy", "Bobby", "Stevie"]
long = []
short = []
for name in names:
if len(name) <= 4:
short.append(name)
print "Short names: ", short
for name in names:
if len(name) >=6:
long.append(name)
print "long names: ", long
|
You can find the len of the shortest and longest name with
len_short = min([len(x) for x in names])
len_long = max([len(x) for x in names])
These variables can then replace `4` and `6` in your code
* * *
names = [ "Brian", "jake", "Jason", "Brad", "Tony", "jimmy", "Bobby", "Stevie"]
long = []
short = []
len_short = min([len(x) for x in names]) # this will be 4
len_long = max([len(x) for x in names]) # this will be 6
for name in names:
if len(name) <= len_short:
short.append(name)
print "Short names: ", short
for name in names:
if len(name) >= len_long:
long.append(name)
print "long names: ", long
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "python, list, loops, for loop"
}
|
Can I write Component inside Component in React?
I have come across many sources which talk about how to do `Component` nesting. However, whenever I try to create a `Component` inside another `Component` my code fails.
class parent extends React.Component{
class child extends React.Component{
render(){
return <div><h1>Hiiii</h1></div>;
}
}
render(){
return <div><DEF /></div>;
}
}
|
Comoponent nesting means rendering react components inside other components. Like
<ParentComponent property={value}>
<div>
<ChildComponent />
...
</div>
</ParentComponent>
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 4,
"tags": "reactjs"
}
|
Grammar is LL(1) or not?
S -> AS | b
A -> SA | a
I get FIRST of S = {a,b} for S->AS and FIRST of S = {b} for S->b
Hence FIRST(AS) ∩ FIRST (b) is not a disjoint This is not LL(1)
But I checked this site < and this shows the grammar is LL(1).  or not?
|
That website uses a different notation than what you assumed. This would be the correct input:
S -> A S | b.
A -> S A | a.
You entered `AS` (and `SA`) which it does not recognize as `A` followed by `S`, but as a single nonterminal named `AS`.
With that input it correctly says that the language is not $\text{LL}(1)$.
|
stackexchange-cs
|
{
"answer_score": 1,
"question_score": 0,
"tags": "compilers, parsers"
}
|
Dokku identifies rails application as node application
I'm new to Dokku, and got a mature Heroku project running for 3 years, I got this annoying issue that Dokku thinks my rails app is a node app probably because I got the package.json file that I use for client side tests. What should I do (currently I renamed this file to trick Dokku but this is kind of hacky) to tell Dokku I have a rails app? What is the proper buildpack I should specify and how.
|
You can specify a custom buildpack as noted here.
For your application, you'll probably want to use the ruby buildpack.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "ruby on rails, dokku"
}
|
What is the difference between a popup and a popover (i.e. NSPopupButton vs UIPopoverController)?
Why was the name popover chosen as opposed to a hypothetical UIPopupController.
|
It's popping over the UI at a non-deterministic location depending on available space. It's not popping up at a certain location.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "cocoa touch, ipad"
}
|
Limit Total Results with Pagination
Easy question. How do I set a limit on the _total_ results for a page that has pagination? I have a site that displays 16 entries per-page, but would like to limit the total results to 200. Is this possible?
|
Pretty easy to do using Stash.
First, make a list of the 200 entries you want to be shown in pages. This line should have no white-space or line returns in it to prevent parsing errors.
{exp:stash:set name="entry_ids" parse_tags="yes"}{exp:channel:entries channel="pages" limit="200" disable="categories|category_fields|custom_fields|member_data|pagination" dynamic="off"}{entry_id}|{/exp:channel:entries}{/exp:stash:set}
Then load the entries for each 16 entry page as normal:
{exp:channel:entries entry_id="{exp:stash:get name='entry_ids' backspace='1'}"
parse="inward" paginate="bottom" limit="16" dynamic="off"}
{title}<br/>
{/exp:channel:entries}
|
stackexchange-expressionengine
|
{
"answer_score": 10,
"question_score": 6,
"tags": "channel entries, pagination"
}
|
camel-spring.xsd is missing in camel-spring-3.10.0.jar
I have upgraded the camel version to latest and found that xsd is missing in the jar file. The xsd file is available in camel-spring-3.8.0.jar. Due to this am getting exception in spring camel application.
Is this a bug?
|
I have figured it out finally. The camel-spring component has been modularized into:
camel-spring - Core module for Camel Spring support
camel-spring-xml - XML DSL when using Spring XML (eg )
The xsds are defined in camel-spring-xml. Added the dependency fixed the issue.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "java, apache camel, spring camel"
}
|
how do I create records using mvc ef with json?
I know how to get data in json format from my MVC application (see below)
public JsonResult Index()
{
return Json(db.Publications, JsonRequestBehavior.AllowGet);
}
What would the create method look like? Edit?
I'm guessing it would look something like the following
[HttpPost]
public void Create(Publication publication)
{
try
{
db.Publications.Add(publication);
db.SaveChanges();
}
catch
{
// what do I catch?
}
}
If that is the case, what would my JSON call look like?
(Assuming the Publication class looks like the following)
public class Publication
{
public int Id { get; set; }
public String Title { get; set; }
}
Any help is appreciated.
|
For the Index, you will probably get some exceptions since the EF objects have a lot of properties that you won't need in the client side and will throw circular references exceptions.
You will have to either create a new POCO class to "wrap" the entities returned by the repository or simply use an anonymous object as suggested here:
Serialize Entity Framework objects into JSON
i.e.:
return Json(db.Publications.Select(p => new {Id = p.Id, Title = p.Title}), JsonRequestBehavior.AllowGet);
Then, the call using Json from the client will have to look like this (assuming you are using JQuery):
$.post('/controller/create', {id:$('#idField').val(), name:$('#nameField').val()}, function(){alert('Publication created');});
Hope this helps
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "asp.net mvc, json, entity framework"
}
|
Django testing model with ImageField
I need to test the Photo model of my Django application. How can I mock the ImageField with a test image file?
**tests.py**
class PhotoTestCase(TestCase):
def test_add_photo(self):
newPhoto = Photo()
newPhoto.image = # ??????
newPhoto.save()
self.assertEqual(Photo.objects.count(), 1)
|
For future users, I've solved the problem. You can mock an `ImageField` with a `SimpleUploadedFile` instance.
**test.py**
from django.core.files.uploadedfile import SimpleUploadedFile
newPhoto.image = SimpleUploadedFile(name='test_image.jpg', content=open(image_path, 'rb').read(), content_type='image/jpeg')
|
stackexchange-stackoverflow
|
{
"answer_score": 113,
"question_score": 65,
"tags": "python, django, testing, mocking"
}
|
Lebesgue measure on set difference
While studying a book on measure theoretic probability (by KR Parthasarthy), I came across a proof which employs the following equality:
$ L((A + x) \Delta (A + y)) = L(A \Delta [A + (y - x)]) $
where $L$ is the Lebesgue measure on real line.
I am not able to see how this equality holds. Any ideas? Thanks in advance.
|
$A+x$ is the set $A$ translated by $x$, and $A+y$ is the set $A+(y-x)$ translated by $x$, so $(A+x)\mathop{\triangle}(A+y)$ is just the set $A\mathop{\triangle}\big(A+(y-x)\big)$ translated by $x$. Translation preserves Lebesgue measure.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 0,
"tags": "measure theory, lebesgue measure"
}
|
Best way to model freindship relationship in couchdb
I am writing a social networking web app with couchdb as backend. Currently I am maintaining user profiles as JSON docs.
My app has a friendship feature when one user will request other user and upon acceptance the friendship is solemnized. Besides friendship there is one way relationship called "follow" relationship as well.
I thought of creating a connection doc
{
source_user:'',
target_user:'',
source_follows_target:'',
target_follows_source:'',
..Similarly for friendship...
}
This doesn't look right to me at all. Since the relationship exists between two exactly similar entities (users in this case) I dont thin the model should try to distinguish between source and target.
|
The fact that the relationship can be (or is always) symmetric doesn't mean it necessarily has to be modelled as one logical relationship. I think it might more general to model the possibility of either, and then prevent one-way friendships in your application if you so desire.
In which case for each user you might have a set of users that they consider their friend (One -> Many). You could store a copy (or cache) of whether it is symmetric or not on each of these relationship objects to make it a bit more scalable.
A rough example of how a user object might look:
{
"userId": 1,
"friends": [{"userId": 2, "friendsBack": true | false}, ...]
}
Operations on these sets of users, e.g. intersections (friends in common), would then be a lot easier since they are accessed directly from the user object.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "nosql, couchdb"
}
|
Result code 0 for Camera Intent
Code:-
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
try{
imageUri = Uri.fromFile(File.createTempFile("image", ".jpg"));
}catch (Exception ex){
ex.printStackTrace();
}
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, REQUEST_CAMERA);
I am using all permissions related to this in android manifest file... that above intent is working fine in mot g3 turbo and many more devices but in the case of only nexus 5 the resultCode is coming 0.. why?
|
With the guidance of CommonsWare Sir, I resolved my problem by doing the following changes...
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
destination = Environment.getExternalStorageDirectory().getPath() + "/image.jpg";
outputUri= Uri.fromFile(new File(destination));
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP) {
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
} else {
List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
grantUriPermission(packageName, outputUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
startActivityForResult(intent, REQUEST_CAMERA);
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 3,
"tags": "android, android camera"
}
|
How to embed a browser object, other than IE<n>, in a Delphi application
Using the default TWebBrowser makes things easy to embed a web browser. Unfortunately the one that comes in by default is IE<n>.
I'm wondering how does one integrate a Gecko or WebKit one.
1. Are there VCL examples somewhere?
2. If not, how would one go about doing it?
3. Where's the best place to find the core for Gecko and/or WebKit in an embeddable format?
|
TWebBrowser **is** IE. It is not a plugable construction for browsers. You can have other browsers integrated in your application. See
* <
* <
* <
## Time has moved on
This answer is from '08 and since then time has moved on. The links don't work anymore and there are probably better alternatives now.
|
stackexchange-stackoverflow
|
{
"answer_score": 21,
"question_score": 36,
"tags": "delphi, webkit, gecko, browser, embedded control"
}
|
Why are php files coming up 404 from IIS6 when they work OK the default site?
Usually php on iis will thow 404 errors if the install doesn't go right. However, danielcooper.dyndns.org/u.php works OK, but u.danielcooper.dyndns.org/u.php (different site in IIS, different folder) gives a 404 error. However u.danielcooper.dyndns.org/test.php
Been using this instance on the default site for some time OK, but php does't seem to work (other than the test file) on a new site.
Am I going crazy?
|
They all work for me.
danielcooper.dyndns.org/u.php = 'test'
u.danielcooper.dyndns.org/u.php = 'test'
u.danielcooper.dyndns.org/test.php = 'browserinfo..'
test.php includes phpinfo.. you might not want to publish that..
|
stackexchange-serverfault
|
{
"answer_score": 0,
"question_score": 1,
"tags": "iis, php, http status code 404"
}
|
color Hex to imagefilledrectangle
I am having problems with filling in the correct color:
$bgColor = '9EA5FF';
imagefilledrectangle($im, 0, 0, 11, 214,'0x' . $bgColor);
**OR**
$bgColor = '0x9EA5FF';
imagefilledrectangle($im, 0, 0, 11, 214,$bgColor);
Seems that the code(s) above does not fill in the square as it should (its just black) but this code:
imagefilledrectangle($im, 0, 0, 11, 214,'0x9EA5FF');
Does.
What am i doing incorrect?
|
function html2rgb($color)
{
if ($color[0] == '#')
$color = substr($color, 1);
if (strlen($color) == 6)
list($r, $g, $b) = array($color[0].$color[1],
$color[2].$color[3],
$color[4].$color[5]);
elseif (strlen($color) == 3)
list($r, $g, $b) = array($color[0].$color[0], $color[1].$color[1], $color[2].$color[2]);
else
return false;
$r = hexdec($r); $g = hexdec($g); $b = hexdec($b);
return array($r, $g, $b);
}
$theRGB = html2rgb($bgColor);
$background = imagecolorallocate($im, $theRGB[0], $theRGB[1], $theRGB[2]);
imagefilledrectangle($im, 0, 0, 11, 214,$background);
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "php, image"
}
|
What to use instead of Promise.all() when you want all results regardless of any rejections
I'm using the Bluebird promise library in a node.js project. I have two operations that both return promises and I want to know when both are done, whether resolved or rejected and I need the return values from both. I'm reading the contents of multiple files and some of the files may not exist and that's an OK condition, so though `fs.readFileAsync()` will fail if the file doesn't exist, I still need the results of the other read operation.
`Promise.all(p1, p2)` will reject if either p1 or p2 rejects and I don't think I'll necessarily get the data from the other one.
Of all the other Bluebird operations (`.some()`, `.any()`, `.settle()`, etc...) which is most appropriate to this situation? And, how is the data passed back such that you can tell which ones succeeded and which ones didn't?
|
That would be indeed be `.settle`. Settle takes an array of promises and returns `PromiseInspection` instances for all of them when they _resolve_. You can then check if they're fulfilled or rejected and extract their value.
For example:
Promise.settle(['a.txt', 'b.txt'].map(fs.readFileAsync)).then(function(results){
// results is a PromiseInspetion array
console.log(results[0].isFulfilled()); // returns true if was successful
console.log(results[0].value()); // the promise's return value
});
Your use case is pretty much what `Promise.settle` exists for.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "javascript, promise, bluebird"
}
|
Is there a way in django to update the same page with the response without totally rendering it?
Is there a way in django to update the same page with the response without totally rendering it. I am trying to create a code editor to test. But when I am returning the results my contents are removed. I understand it is because I am rendering the page . I need the contents to retain. How can I do it using redirect? I am including the render statement I used and a screenshot of how it looks here:
Steps:
1. Handle post request
2. Program execution code
3. Save the result in a variable called "message". Then I used
`return render(request, 'editor.html', {'message': message})`
I want to redirect the message to the same page without rendering a new page.
[Before submission][1] [After submission][2] [1]: [2]:
Any help will be appreciated. Thank you.
|
it is possible. using `ajax` in front-end and `render` or `render_to_string` in back-end(`Django`). using ajax you're able to call a `url` (with/without data you want to send), then in the `views.py` you can do anything needed and `return render(request,'template.html, context)`. then in ajax you have `success: function (res) { $('#id_of_element').append(res)}`. this function in ajax will append the recived response which is a rendered HTML template to the target element.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "django"
}
|
Raku (née Perl 6) reduce function and reduction metaoperator give different results
my @s=<1 2 3 2 3 4>;
say reduce {$^a < $^b}, @s;
say [<] @s;
# --------
# True
# False
My question is two fold: Firstly, why does the reduction metaoperator processes the `<` operator differently? It looks like the reduction metaop is estimatedly using a variable which, at the first change of true to false, retains that change because:
say [\<] @s;
# ----------
# (True True True False False False)
Secondly, I'd like to use this inside the reduce function, too, i.e. introducing some code inside the curly brackets of reduce function so that it gives the same result as the reduction meta operator. How can I do it? Thank you.
|
Both the meta-operator and `reduce` take into account the associativity of the operator passed to them; in the case of `<`, the operator is chaining.
When passing a custom block, `reduce` cannot see inside of it, and so it falls back to the default of left-associative; it then compares the later values against the boolean returned from the reducer, which numifies to `0` or `1`, which is why the result ends up as `True` in the end.
You can get the semantics you desire by declaring your reduction function as having chaining associativity:
my @s1 =<1 2 3 2 3 4>;
my @s2 =<1 2 3 4>;
sub my-reducer($a, $b) is assoc('chain') {
$a < $b
}
say reduce &my-reducer, @s1; # False
say reduce &my-reducer, @s2; # True
|
stackexchange-stackoverflow
|
{
"answer_score": 18,
"question_score": 13,
"tags": "raku, reduction"
}
|
What could cause an earthy flavour in beer?
I've just tried the first bottle from a batch of APA I brewed and it has a very distinct (and unpleasant) earthy / peaty flavour. Reminiscent of healthy soil. The beer also finishes with a very sharp acidic bitterness (also unpleasant).
What could have caused this? Is it a process error somewhere? Infection / mishandling? Just a poor recipe?
Is it likely to disappear with age or should I flush the lot?
> Fermentables:
>
> * 3kg Light malt extract (syrup)
> * 0.5kg Dextrose
>
>
> 23L batch, 10L boil
>
> Hops:
>
> * 50g Willamette @ 30min
> * 50g Amarillo @ 20 min
> * 15g Amarillo @ 10 min
>
>
> Hops left in the tub during primary (2 weeks) & cold crashed for a week. Racked into a bottling bucket to keep the crap out of the bottles.
>
> Fermented with Nottingham yeast
|
I've often gotten that flavor from Willamette hops. That might not be your problem, but it's something to consider.
|
stackexchange-homebrew
|
{
"answer_score": 5,
"question_score": 6,
"tags": "beer, flavor, off flavor, partial boil"
}
|
Solid state circuit to charge caps in parallel then discharge in series?
Do there exist a solid state design circuit to do the following:
Charge multiple capacitors in parallel for a certain amount of time from a low voltage DC source, then disconnect them completely from the DC source and rearrange them in series to allow them to be discharged in series?
What I want is to charge about 10 capacitors in parallel with 12 V, then discharge them at 120 V in pulses.
|
I think this is how you could do it in relays: -
!schematic
simulate this circuit - Schematic created using CircuitLab
All the switches operate together so if you could use MOSFET SSRs I guess you'd be just about there. 2 Single SSRs can be made to form a c/o contact and you'll therefore need four per capacitor. Or just use relays.
R1 is the discharge load (whatever it may be) and you can step and repeat for as many capacitors as you wish but watch the relay contact open-circuit voltage ratings. A simpler version is this (I believe): -
!enter image description here
And if you were prepared to suffer a couple of diode drops it could look like this: -
!schematic
simulate this circuit
(Well I think I'm sure!!)
|
stackexchange-electronics
|
{
"answer_score": 3,
"question_score": 2,
"tags": "capacitor, mosfet, solid state relay"
}
|
How to "disconnect" an accelerator , key-press-event or mouse-press-event in a GTK+ Widget?
Say I have a custom GTK+ widget obtained from a third party library. It has an accelerator, e.g it hides itself when I press 'h' or click it, and shows itself when I press 'h' again or double-click it. I want disable this _particular_ functionality of the GTK+ widget. How can I do this without changing the source code of the Library and rebuilding it?
Note: You can also give your solution in c++ , in fact it would be better that way because I am using C++ for my project.
|
I'm guessing now, but how about gtk_widget_can_activate_accel () ?
<
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 3,
"tags": "c++, c, custom controls, gtk"
}
|
Какая процедура уменьшает переменную на единицу?
Какая процедура уменьшает переменную на единицу?
|
Dec()
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "delphi, процедуры"
}
|
Would Falcon 9 sink on gentle splashdown?
Let's say the guidance system fails, and Falcon 9 first stage _gently_ touches down on surface of water before switching the engine off (and plummeting into the water).
Will it sink or will it float?
At that moment it's a huge, mostly empty tube, although rather heavy on itself, I'm not sure if it's durable enough to survive a splashdown from 0 altitude, and how much fuel is left after the landing. And while I could find the landing mass, I'm really unsure how to discover the landing volume.
|
Past events demonstrate that it will sink. Following the ORBCOMM launch in 2014, the first stage performed a soft landing in the Atlantic Ocean, and the water impact caused loss of hull integrity:
> After landing, the vehicle tipped sideways as planned to its final water safing state in a nearly horizontal position. The water impact caused loss of hull integrity, but we received all the necessary data to achieve a successful landing on a future flight.
(Source: SpaceX press release)
|
stackexchange-space
|
{
"answer_score": 14,
"question_score": 7,
"tags": "spacex, falcon 9"
}
|
how to say "to go viral"?
I can see from an internet search that виральный (edit: вирусный) has the meaning of "viral", but what is the translation of the phrase " _to go_ viral", e.g., "that video has gone viral"?
|
We use the word `вирусный`. There are Russian expressions like `вирусный маркетинг`, `вирусная реклама`, `вирусное видео`.
> That video has gone viral. - Это видео стало вирусным. / Это видео превратилось в вирусное.
The English Wiki article on viral marketing has a counterpart in the Russian Wiki called "Вирусный маркетинг".
This marketing-related meaning of the Russian word `вирусный` is quite new, but quite established and widely used.
|
stackexchange-russian
|
{
"answer_score": 6,
"question_score": 4,
"tags": "перевод"
}
|
Staging redirecting to live site (under construction page)
I created a staging environment from my customers live wordpress website. now when I try to access it without being logged in as an admin, it redirects to the live "under construction" live site. Only on desktop. On mobile we can access it.
I've been working this way for a long time and it is the first time I encounter this problem. I am using ELementor Pro builder and Jupiter X theme.
I turned off Simple SSL plugin keeping the https active. Didn't work. I also double checked that I didn't have Seedprod's coming soon plugin installed.
Any idea how to fix this?
thanks!
|
It sounds like a caching issue as mobile is the same domain. Try a different browser or if you use Chrome.
Open Inspection Tool > Network Tab > then check Disable Cache
;
print "$test";
You can also prevent the interpolation by using single quotes as the delimiter to `qx`:
$test = qx' pkginfo | awk \'/TestPackage/{print $2}\' ';
Note that `$test` will have a trailing newline unless you `chop` it.
But, invoking `awk` from `perl` is not very perlish. Although using `awk` feels a lot cleaner, it may be better to do something like:
@test = map { m/^\S+\s+(\S+)/; $_ = $1 } grep { /TestPackage/ } qx( pkginfo );
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 0,
"tags": "perl, shell"
}
|
logplot for negative valued function
I would like to plot the following function
Plot[(1/x (0.01/(0.01 + x^2) - (10/(10 + x^2))^2)), {x, 0, 10},
Frame -> True, PlotRange -> All]
which is very peaked at 0.01 in log scale, to show it up to higher values, i.e.:
LogPlot[-(1/x (0.01/(0.01 + x^2) - (10/(10 + x^2))^2)), {x, 0, 100},
Frame -> True, PlotRange -> {10^-9, 10}]
However, since function is negative, I must add a minus sign to the function. I would like to get something like the log plot above, but with the y-axis going downwards and with negative values, looking similar to the plot below
LogPlot[-(1/x (0.01/(0.01 + x^2) - (10/(10 + x^2))^2))^-1, {x, 0, 10},
Frame -> True, PlotRange -> {0.1, 10^3}]
but with the right scaling for log axis and negative value sin stead of positive ones, is it possible?
Thanks in advance
|
It seems something like this does the work. Taking the inverse, just produce the negative value for the log. Then, relabeling the ticks (but using also the inverse, solves the work)
myTicks =
N[Table[{10^-i, -10^i}, {i, -9, 1}]]; LogPlot[-f[x], {x, 0, 100},
Frame -> True, PlotRange -> {10^-9, 10}]
LogPlot[-f[x]^-1, {x, 0, 100}, Frame -> True,
PlotRange -> {1/10, 10^9},
FrameTicks -> {Automatic, myTicks, None, None}]
Thanks to Boson which helped here.
!enter image description here
|
stackexchange-mathematica
|
{
"answer_score": 3,
"question_score": 1,
"tags": "plotting"
}
|
Reading HKEY CURRENT USER from the registry in Python, specifying the user
In my application I run subprocesses under several different user accounts. I need to be able to read some of the information written to the registry by these subprocesses. Each one is writing to HKEY_CURRENT_USER, and I know the user account name that they are running under.
In Python, how can I read values from HKEY_CURRENT_USER for a specific user? I assume I need to somehow load the registry values under the user's name, and then read them from there, but how?
edit: Just to make sure it's clear, my Python program is running as Administrator, and I have accounts "user1", "user2", and "user3", which each have information in their own HKEY_CURRENT_USER. As Administrator, how do I read user1's HKEY_CURRENT_USER data?
|
According to MSDN, `HKEY_CURRENT_USER` is a pointer to `HKEY_USERS/SID of the current user`. You can use pywin32 to look up the SID for an account name. Once you have this, you can use open and use the registry key with the _winreg module.
import win32security
import _winreg as winreg
sid = win32security.LookupAccountName(None, user_name)[0]
sidstr = win32security.ConvertSidToStringSid(sid)
key = winreg.OpenKey(winreg.HKEY_USERS, sidstr)
# do something with the key
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "python, windows, registry"
}
|
How do I run a function from my .py file in the command?
I have a .py file with a function that calculates the gradient of a function at a point and returns the value of that gradient at the point. The function takes a np.array([2,]) as input and outputs another np.array([2,]). I am confused as to how I can call the function from the cmd line and run the function with a specified input.
Here is a code snippet:
import numpy as np
def grad(x):
x_1 = x[0]
x_2 = x[1]
df_dx_1 = 6*x
df_dx_2 = 8*x_2
df_dx = np.array([df_dx_1, df_dx_2])
return np.transpose(df_dx)
I would really appreciate your help!
EDIT: This question differs from the popular command line thread because I have a specific issue of not being able to recognise the `numpy` input
|
You can have more than one command line argument:
import sys
import numpy as np
def grad(x):
# your grad function here
arr = np.array([int(sys.argv[1]), int(sys.argv[2])])
print(grad(arr))
Usage:
python gradient.py 10 5
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python, function, file, command line"
}
|
Защита формы без капчи
Посоветуйте, хотелось бы сделать защищенную форму на сайте без использования капчи. Что я сделал:
1. Ввел сессионную переменную с генерированным закодированным значением, которое помещается в поле формы. При получении формы поле hidden сравниваю с этим значением. При несоответствии, естественно, выводится соответствующее сообщение и форма не попадает под обработку.
2. Ввел еще одну сессионную переменную, которая следит, чтобы форму невозможно было отправить чаще 1 раза в час. То есть после отправки формы при обновлении страницы, ее html-разметка вообще не появляется на странице в течение часа.
Вопрос: какие подводные камни содержит мой скрипт и что можно ожидать от веселых хакеров? В частности интересует возможность или невозможность отправки данной формы со стороннего ресурса.
|
Сделайте так, чтобы поля содержали рандомные имена, причем все были типа "text", или подобных, которые заполняют боты. И одно-несколько полей сделайте visibility:hidden. Если бот их заполнит, то форма не проходит.
От ручного спама так-то и капча не спасет.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "php, форма, защита, captcha"
}
|
Best way to maintain and develop 3 similar sites
It would kind of be like S[OFU] except there will be more differences between the site.
What are good ways to develop 3 site at once with a different look and different functionality? I believe with the look i may only change the CSS and some backend data for different categories. I also need some functionality and options to be specific to one or two but not all sites.
Whats the easiest way to develop, maintain and test the sites during the development process? I am hoping something simple like changing the root directory in the visual studio IDE can be enough and have site specific features enabled through config files in the site specific root directory.
|
You might want to consider developing in a somewhat modular manner. That way, common elements can be shared between the sites completely (just 2 deployments of the same code), while elements that vary are their own independent modules.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "asp.net mvc, testing, web, build process"
}
|
REGEX in mysql query
I won't found data from table who start following by CR and one space and 4 to 6 number
Query
SELECT `order_det_ref_no` FROM `manufacturers_order` WHERE
`order_det_ref_no` REGEXP '%^CR\s+\b\w{4,6}$%'
, `\s`, `\w` regex shorthand classes. Use
REGEXP '^CR[[:space:]]+[[:alnum:]_]{4,6}$'
Note that `[[:space:]]` matches both horizontal and vertical whitespace, you may use `[[:blank:]]` if you also need to only match horizontal whitespace.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php, mysql, regex"
}
|
Left shift on an unsigned short without overflow into an integer
if I've a ushort variable which is 0xFFAA and I'll left shift this with 8 bits, I'll get an integer not an unsigned short, why? Here a picture to make you more clear, what I mean:
 & 0xFFFF;
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "c#, bit manipulation, overflow, bit shift"
}
|
All nodes getting selected with deep-equal in xquery
I want to find all movies which don't have styles of anthology and art. To achieve this I am using the following query
for $movie in db:open("movies","movies.xml")/movies/movie
where not(deep-equal(($movie/styles/style),("anthology","art")))
return $movie
However, all nodes are getting selected instead of filtering them. What is going wrong?
|
You query doesn't make much sense and deep-equal isn't useful here at all. The following will return all movies with a style not equal to anthology or art:
db:open("movies", "movies.xml")/movies/movie[not(styles/style = ("anthology", "art"))]
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "xquery, basex"
}
|
Why Bibliography and References appears in Latex TOC?
I am using these commands for including references:
\addcontentsline{toc}{chapter}{References}
\bibliographystyle{agsm}
\bibliography{dissrefs}
The problem is that in the table of contents both `References` and `Bibliography` appear, while I just want one to appear. Why is this happening? Can I customise the table of contents entry to be just one of them?
I am using MikTex 2.8 and TexMaker 2.1.
|
I dont think that you need to use `\addcontentsline{toc}` bibtex should do it automatically. At least I don't recall ever needing it...
Have you tried commenting out that line?
**Edit** regarding OPs comment on changing the title of the bibliography:
The bibliography's title can be changed by (to for instance "New Title") using `\renewcommand\refname{New Title}` for articles and `\renewcommand\bibname{New Title}` for books.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "latex, biblatex"
}
|
Google+ Sharing in iframe
I am developing a web application for PC/Tablet/Mobile phones, and I want to integrate Google+ Sharing onto it.
But seems that the url < has blocking iframes...
prove that it doesn't work: <
isn't there any other way to do that?
P.S The server side of my application is ASP.NET MVC and the client side is jQuery Mobile.
|
I have found that there are some pages on google servers which allow iframes, but they are not complete . (for example, if user is not logged in, again we have another problem)
So, the best choice is **not using iframes!**
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, html, css, iframe, google plus"
}
|
OpenVPN access control
Using OpenVPN, I can enable 2-way authentication with certificates, private keys and a CA-certificate.
In my understanding, this only provides authentication (the client is, who he says he is) but not authorization (access control). OpenVPN just assumes that a valid authentication is also an access authorization.
If I now run a second VPN server, using the same CA, will the clients of the first also have access to the second VPN?
If I want to avoid this - clients with keys/certs for the first VPN server should not be able to access the second VPN server (and reverse) - what are my options?
* use a different CA for each server (ugly in my opinion)
* use an access control list based on the common name (CN) (not so practical)
* use firewall / iptables (not so practical)
Am I missing a way to somehow limit access of a certain client to a certain server?
|
Citing Jan Just Keijser from the OpenVPN forum
> openvpn provides authentication, not access control (authorization), nor should it, in my opinion. The options you mention are the only options you have, unless you also want to throw in username+password control.
>
> you could use a sub-CA (intermediary CA) ; each client cert would be signed by a specific sub-CA ; the clients need only the "root" CA to connect to a server, but the servers can allow access based on the sub-CA used for a client.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "authentication, authorization, access control, openvpn"
}
|
Make sure a service is running with specific arguments using puppet
I have an application that I'm installing to all my VMs, it requires a specific arguments passing to it when it gets run and it should always be running.
I want to ensure that mailcatcher is running with the parameter --ip="0.0.0.0"
What's the best way to go about this?
|
My colleague kindly provided me with a new puppet module for this - <
|
stackexchange-superuser
|
{
"answer_score": 0,
"question_score": 0,
"tags": "puppet"
}
|
Is it possible to get rid of these shading artifacts for a smooth shaded flat surface?
I am modeling a logo and want beveled edges that will be smooth shaded to look rounded but a flat surface that looks flat do you have any sugestions? This is the result after beveling edges:
![enter image description here](
|
Proper Topology
Having a proper topology depending on the kind of work you are doing solves this problem
as here blender doesn't have enough info to shade the front face correctly
you can check the CGCookie guide for clean topology here
|
stackexchange-blender
|
{
"answer_score": 3,
"question_score": 1,
"tags": "modeling, artifacts"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.