INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Serializing a LinqtoNh filter/order clause
I've got a REST web service that uses LinqtoNh to query entities and return them as DTO, plain classical stuff. I want the service to apply some filter/order clause on the returned entities, and I'm asking if there is some way of serialize the linqtonh expression in order to send it an the wire without creating some custom strategy. A plus would be not having a NH reference on the client. Any suggestion?
|
Take a look at WCF Ria Services: It expose a WCF Rest service that supports the LINQ filtering, sorting, paging e grouping. Server side the DomainService will create a LINQ query with "Where", "Order*", "Take", "Skip"...
Avoiding the NH reference it's a great idea, implement your own IQueryable, link it to NHibernate (maybe you want to use an IoC engine to do so) and return it in the exposed queries! You're almost done, most of the LINQ2NH call are standard LINQ extensions method, you would have to write somethign else if you need to use the eager fetching extension method (Fetch*) or other pretty NHibernate-stuff.
As far the client, WCF Ria is initially designed for SL but supports _everything_ , they have even JS client called RIA/JS
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "linq, nhibernate, rest, linq to nhibernate"
}
|
How to pass checkbox value 0 or 1 in ajax?
**ajax**
$.ajax({
url: $('#MAINURL').val() + "admin/ajax/ajax_homedisplay.php",
data: [
{name: 'mode', value: 'update'}
, {name: 'slider', value: htmlEncode($('#slider').val())}
, {name: 'welcomebox', value: htmlEncode($('#welcomebox').val())}
, {name: 'servicebox', value: htmlEncode($('#servicebox').val())}
],
here slider,welcomebox, servicebox is a checkbox i want to pass 0 or 1 value if checkbox is checked thn insert 1 or else 0.
Currently it is insert only 1 weather it is checked or not it is insert only 1.
I want to insert 1 when checkbox is checked and when checkbox is unchecked thn insert 0.
|
You can use this,
$.ajax({
url: $('#MAINURL').val() + "admin/ajax/ajax_homedisplay.php",
data: [
{name: 'mode', value: 'update'}
, {name: 'slider', value: htmlEncode($('#slider').val())}
, {name: 'welcomebox', value: htmlEncode($('#welcomebox').attr('checked'))}
, {name: 'servicebox', value: htmlEncode($('#servicebox').attr('checked'))}
],
Thanks Amit
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, php, ajax"
}
|
How to convert UIColor value to a named color string?
I need to convert `UIColor` to an `NSString` of the color name.
I tried:
NSString *colorString = NSStringFromClass([[UIColor redColor] class]);
But `colorString` did not give @"redColor".
|
What do you want to do that for? Have a look at generic `-desciption` method for a start
UIColor* someColor = ...//Initialize color
NSString* colorString = [someColor description];
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 17,
"tags": "ios, iphone, cocoa touch"
}
|
Diferencias entre SetCursorPosition y CursorTop, CursorLeft en C#
Tengo una duda con el siguiente ejemplo, no entiendo qué hace exactamente `CursorTop` y `CursorLeft` que no esté haciendo `SetCursorPosition`.
using System;
class Sample
{
protected static int origRow;
protected static int origCol;
protected static void WriteAt(string s, int x, int y)
{
try{
Console.SetCursorPosition(origCol+x, origRow+y);
Console.Write(s);
}catch (ArgumentOutOfRangeException e){
Console.Clear();
Console.WriteLine(e.Message);
}
}
public static void Main()
{
Console.Clear();
origRow = Console.CursorTop;
origCol = Console.CursorLeft;
WriteAt("+", 0, 1);
}
}
|
En este ejemplo `CursorTop` y `CursorLeft` es utilizado para establecer los valores iniciales de los atributos `origRow`y `origCol` para posteriormente con `SetCursorPosition` ir cambiando la posición del cursor basado en los valores iniciales (de `origRow`y `origCol`) más los valores de los argumentos `x` y `y`.
|
stackexchange-es_stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "c#"
}
|
Notepad++ remove character 10 to 20 for example
the title says it all, I can't find a option in notepad+ for removing for example character 10 to 20.
Do I miss something or is there a other option for it?
Example:
original line:
<div id="dot"><a id="69149d5ac2-70" href="
must look like:
<div id="dot"><a href="
|
I'm not sure this is what you're asking, but if you need to delete chars 10 to 20 of **each** line, a fast way of doing this is block selection.
You just keep `ALT` pressed while dragging to select a rectangular block of characters. Then hit `DEL` to delete them.
|
stackexchange-superuser
|
{
"answer_score": 1,
"question_score": 0,
"tags": "notepad++, find and replace"
}
|
Kafka consuming same messge multiple times
I am queuing a single message in kafka queue.
Kafka Prop :
enable.auto.commit=true
auto.commit.interval.ms=5000
max.poll.interval.ms=30000
Processing of my message was taking around 10mins. So message was keep on processing after every 5 mins.
Then I have changed the prop `max.poll.interval.ms` to 20 mins. Now the issue is fixed. But my question is this : why is this happening. Since I already have auto commit enabled and it should happen every 5sec, then why my messages are not marked committed in the former case
|
When `enable.auto.commit` is set to `true`, then the largest offset is committed every `auto.commit.interval.ms` of time. However, this happens only whenever `poll()` is called. In every poll and in your case every 20mins (`max.poll.interval.ms`), the `enable.auto.commit` is checked. Whenever you `poll()`, the consumer checks if it is time to commit the offsets it returned in the last poll.
Now in your case, `poll()` is called every 20 minutes which means that it might even take up to additional 20 minutes (+5000ms) before committing the offset.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "apache kafka, kafka consumer api"
}
|
Sort list of objects in python using custom sort logic function with cmp_to_key
I have a list of objects in python, where a single object has 2 attributes ie. `a` and `b`, `a` can be either `None` or `dict` and b is an `int` or `None`, I want the resultant list to be sorted like:
1. It should have first all objects with `a equal to None`.
2. Then it should have all objects with `a not equal to None`.
3. In 1, 2 if those objects have `b` (`b is int`) then sort them with b.
Example result:
[
Obj(a=None, b=2),
Obj(a=None, b=5),
Obj(a=None, b=None),
Obj(a=dict, b=1),
Obj(a=dict, b=4),
Obj(a=dict, b=None)
]
|
This will do it using `sorted()`, and a similar approach would work with the `sort()` method of the `list` datatype:
class Obj:
def __init__(self, a, b):
self.a = a
self.b = b
input = [
Obj(a=dict(), b=1),
Obj(a=dict(), b=None),
Obj(a=None, b=5),
Obj(a=None, b=None),
Obj(a=dict(), b=4),
Obj(a=None, b=2),
]
output = sorted(input, key=lambda x: (x.a is not None, x.b is None, x.b))
[print(f"Obj(a={'dict' if x.a is not None else 'None'}, b={x.b})") for x in output]
Output:
Obj(a=None, b=2)
Obj(a=None, b=5)
Obj(a=None, b=None)
Obj(a=dict, b=1)
Obj(a=dict, b=4)
Obj(a=dict, b=None)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, python 3.x, sorting"
}
|
write access violation when inserting array
I am defining a structer for my class. Basicly i want take an input and write it to member variable(array).
class DynArray
{
int m_size;
int* m_p_array;
public:
DynArray(){
std::cout << "Please enter size\n";
std::cin >> m_size;
m_p_array[m_size];
for (int i{ 0 }; i < m_size; i += 1) {
std::cout << "Please enter element " << i << "\n";
std::cin >> m_p_array[i]; //"Exception thrown" message shows in this line
}
}
}
VS2019 shows me as a warning code : C26495 Variable 'DynArray::m_p_array' is uninitialized. Always initialize a member variable
I just searched like 1 hour but didn't figgure out the what is my mistake. Is pointer i used for "m_p_array" problem? Thanks in advance.
|
This is not how you allocate memory for the array:
m_p_array[m_size];
You need to do this:
m_p_array = new int[m_size];
later you need to free the memory in your destructor:
delete[] m_p_array;
but consider using `std::vector` instead because it is better.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "c++, arrays"
}
|
Python CGI - Change data based on user time zone
I have a Python CGI program which prints datetime values. The timestamps are all formatted to the server's time which is way off from the local time of some of the users. How can I format it automatically for all users based on their time zone?
Here is one of the formatted string:
2011-09-25 02:04:54
That string was created by using a datetime.datetime object.
-Sunjay03
|
You will have to have a way to find the timezone of the user. One way to do this is by having them set it in a preference page, and storing it in the database, and looking it up when you render the page. Another way is to have the browser include its current time in the request, so that you can adjust your times.
One you know the user's offset from your server time, you can use `timedelta` methods to adjust the datetime object.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "python, datetime, timezone, cgi"
}
|
Code128 barcode language independent
I'm using this code128 barcode font. It works fine, but when I have an underscore (_) my usb barcode reader automatically transforms it in a minus (-). I tryed to switch the keyboard language and I get a slash (/). So, I suppose there's a problem with the language. I'd like to have a barcode that is language independent. Is this possible? How?
The code I used to generate the barcode representation is like the one stated here.
|
I solved. The problem was the setting of my barcode scanner (a Datalogic HeronG). I set the USB interface to `USB-KBD - ALT-mode`. In the `USB-KBD` mode, the scanner simulates the national keyboard.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "barcode"
}
|
What does the word "lines" mean in the phrase "tenure track lines"?
> The resources in the language department of most major research universities were assigned to different languages a very long time ago; resources such as budget, space, and _tenure track **lines_**.
My guess is that, there are several candidates for a tenure, and they have to reach all sorts of required standards, so the lines refer to the standards of all aspects the candidates must reach. Is my guess right?
|
At many American universities, every department is allotted a fixed number of slots for professors on the tenure track (assistant professors without tenure, associate professors, full professors with tenure). Each of these slots is called a _tenure track line_.
We can also say a department has 20 tenure track _positions_ or 20 tenure track _slots_ instead of 20 tenure track _lines_. We would not say that the department has 20 tenure tracks.
I believe the word _line_ refers to the progression from assistant professor without tenure to (eventually) full professor with tenure. This is also exactly what _track_ in _tenure track_ refers to, but they are used differently, as described above.
|
stackexchange-english
|
{
"answer_score": 5,
"question_score": 1,
"tags": "meaning"
}
|
Unusual function format and its partial derivatives.
I came across a function of this format:
$z = f(u,v)$ where $u = x^2y^2$ and $v = 5x + 1$
Because this function is not in the same format of the ones I've seen before (explicit or implicit), I don't know how to find (or even to do a single solving step!) its partial derivatives.
Basically, I need to show that:
$\frac{\partial^2z}{\partial x\partial y} = 4xy\frac{\partial f}{\partial u} +4x^3y^3\frac{\partial^2f}{\partial u^2} +10x^2y\frac{\partial^2f}{\partial v \partial u}$
Anyone could tell me how I should approach this type of problem?
Thanks!
|
Yes this is a function. You can think of this as a composition of two functions
$z=f(u,v)=f(x^2y^2,5x+1)=g(x,y)$
and to answer your question, you need the chain rule for multivariable functions...applied twice. The chain rule in this case is
$\frac{\partial z}{\partial x}=\frac{\partial z}{\partial u}\frac{\partial u}{\partial x}+\frac{\partial z}{\partial v}\frac{\partial v}{\partial x}$
and then similarly
$\frac{\partial z}{\partial y}=\frac{\partial z}{\partial u}\frac{\partial u}{\partial y}+\frac{\partial z}{\partial v}\frac{\partial v}{\partial y}.$
So first take the partial w.r.t $y$
$\frac{\partial z}{\partial y}=\frac{\partial z}{\partial u}\frac{\partial u}{\partial y}+\frac{\partial z}{\partial v}\frac{\partial v}{\partial y}=\frac{\partial f}{\partial u}\cdot2x^2y+\frac{\partial f}{\partial v}\cdot0=2x^2y\cdot\frac{\partial f}{\partial u}$
and then apply $\frac{\partial}{\partial x}$ to this quantity using the product and the chain rule and then simplify.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 3,
"tags": "multivariable calculus, coordinate systems"
}
|
SQL Server insert Top nchar +1 that could start by 0
I have to develop an insert query on sql server which inserts a nchar value from another nchar value, but I have to increment it by 1. I have to preserve the left 0 (not always be a 0). How can I make the conversion? This is my code:
DECLARE @CIG int;
SET @CIG = (SELECT MAX([VALUE1]) FROM [DB].[dbo].[TABLE]) +1;
For example If I have:
0761600002511
the result will be:
0761600002512
if I have:
1761600002511
the result will be:
1761600002512
I have tried with something like this: (with the same conversion error and with the same problem with the possible starting 0)
SET @CIG =
CAST
(
(CAST
(
(
SELECT MAX([VALUE1])FROM [DB].[dbo].[TABLE]
)
as int)+1)
as nchar(100))
Thanks
|
Assuming That you have set NCHAR(10) length for your column, to preserve zero if there
DECLARE @tmp NCHAR(100) ='0761600002511';
SELECT LEFT(@tmp ,3)+CAST((CAST(RIGHT(@tmp ,97)AS INT)+1) AS NCHAR(10))
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "sql, sql server"
}
|
How many times does ConstraintLayout measure each of its children?
RelativeLayout measures all its children twice. This can cause performance issues. Does constraint layout only measure its children once each?
|
`ConstraintLayout` requires up to two measure passes.
If you look at the `ConstraintLayout`'s source, you'll see that its `onMeasure()` method first measures its children inside an `internalMeasureChildren()` utility method. Next, it evaluates some constraints. Finally, `ConstraintLayout` calls `child.measure()` on its children a second time inside a loop.
Source: decompiled the class files, since the source isn't available at this time.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 6,
"tags": "android, android layout, android view, android constraintlayout"
}
|
2 dynamic size divs + float:left
Sorry for the bad title.
So I have 2 divs both with `float:left` property inside a container with fixed size. Each div can have optional size. Problem is if I fill div2 with a lot of text it goes below div1, but they should be next to each other. I want div2 just become smaller, not go below div1.
Check example on JS Fiddle:
|
Try
.div2 {
float: none; /* default value */
overflow: hidden;
}
**Demo**
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "html, css"
}
|
Run scalafmtCheck in an sbt assembly
I would like to run a `scalafmtCheck` in `sbt assembly`. I tried to add:
(compile in Compile) := ((compile in Compile) dependsOn scalafmtCheck).value
I got that error :
[error] References to undefined settings:
[error]
[error] submissions / scalafmtCheck from submissions / Compile / compile (/home/yass/Documents/Invenis/iss/build.sbt:45)
[error] Did you mean submissions / Compile / scalafmtCheck ?
[error]
[error] scalafmtCheck from Compile / compile (/home/yass/Documents/Invenis/iss/build.sbt:45)
[error] Did you mean Compile / scalafmtCheck ?
[error]
Any idea ?
|
You were almost there. `scalafmtCheck` is a task as well, therefore needs scope. What you need to do is:
Compile / compile := (Compile / compile).dependsOn(Compile / scalafmtCheck).value
If you want to add it to the assembly stage, you can do:
assembly := assembly.dependsOn(Compile / scalafmtCheck).value
If you want the format to apply this to your tests as well you can do:
Compile / compile := (Compile / compile).dependsOn(Test / scalafmtCheck).value
Or only at the assembly stage:
assembly := assembly.dependsOn(Test / scalafmtCheck).value
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "scala, sbt, scalafmt"
}
|
How to detect if a user exists in a database
I would like to have some php code detect if a user exists in a database or not, and execute specific code according to the condition. This is what I have tried:
$query = "SELECT * FROM users WHERE
username='$username'
OR email='$email'
LIMIT 1";
$result = mysqli_query($db, $query);
while ($row = mysqli_fetch_assoc($result)) {
if(count($row) > 0) {
echo "The user exists";
} else {
echo "The user does not exist";
}
}
It echos "The user exists" when the user exists but not "the user does not exist" when the user doesn't exist. Why is this?
|
You don't need a loop, since the query returns at most one row. If the user exists it will return that row, otherwise there won't be any rows, and your loop is never entered.
$row = mysqli_fetch_assoc($result);
if ($row) {
echo "The user exists";
} else {
echo "The user does not exist";
}
If you don't actually need the information about the user, there's no need to fetch it at all. Just fetch the count of existing rows.
$query = "SELECT COUNT(*) AS count FROM users WHERE username = ? OR email = ?";
$stmt = $db->prepare($query);
$stmt->bind_param("ss", $username, $email);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if ($row['count'] > 0) {
echo "The user exists";
} else {
echo "The user does not exist";
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -3,
"tags": "php"
}
|
Why are React keys limited to strings?
In React, when rendering a mapping from elements of a list/array/iterable to React elements, we're required to attach a locally-unique key to each element. Generally this is so that if an element changes or is removed, React only needs to rerender that specific element rather than the whole list. This key is required to be a string, and if an element-specific key is not forthcoming, there is an npm package* (shortid) for generating them.
Why did the React designers set this requirement rather than allowing any immutable value? In particular, it makes sense to me to be able to use a `Symbol`, which cannot be converted to a unique string. (Upon re-examining my specific case where I wanted to use a `Symbol`, I realized it was unnecessary, but the question still stands in general.)
* * *
* There also used to be a package specifically designed for this called `react-key-index` but it seems to have disappeared from github.
|
React writes the key to the HTML and reads it back when parsing the DOM.
Since the HTML attribute is a string, whatever value you give it must be serialised to a string.
If you wanted to use non strings you would require a de/serialiser and possibly a second attribute in the HTML element to indicate the type of the key value.
Also remember this is essentially an optimisation so we don't have to re generate the entire HTML on every change. So anything that would slow the process down would be undesirable.
|
stackexchange-softwareengineering
|
{
"answer_score": 5,
"question_score": 3,
"tags": "javascript, reactjs"
}
|
When should I rotoscope in the compositting proces?
I already made my animation and I’m going to composite it in a videoclip. I’m currently tracking the clip, but there are going to be some occlusions in front of the animation that I need to rotoscope. My question is, when in the compositting proces should I rotoscope those things? Should I do this in blender?
|
When to rotoscope?
Whenever you need to evaluate the integration of the video element you want to composite.
Can rotoscoping be done in blender?
Yes.
You can draw and animate masks that can be used in the compositor. Mask drawing tools are quite robust in blender, allowing you to add, subtrac or intersect different masks and layers, and it allows you to create sharp or feathered edges.
Advanced and semi-automated rotoscoping can be done by parenting masks to tracking points on the video clip editor.
|
stackexchange-blender
|
{
"answer_score": 1,
"question_score": 1,
"tags": "animation, objects, tracking, compositing nodes"
}
|
Grease pencil drawing is fully on top of my 3D object after rendering while in Camera view it looks different
I was trying out the Grease Pencil on a 3D object. I made some layers, they all looked perfect in viewport. But when I rendered the image the Grease Pencil drawing came fully above my 3D object while I had set it up that some parts are hidden in some dimensions.
|
please try checking "combined" and "z":
 How to add a User Interace like many installers have that asks if to launch the app now?
2) Can I create a custom action that runs the app with user privileges?
|
You can either create a js custom dialog described here: Run exe after msi installation?
or you can make a custom action at commit that calls [TARGETDIR]\YourApp.exe
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "visual studio 2008, windows installer"
}
|
XCode warnings go away after subsequent Build calls
In XCode, let's say I call a method that doesn't exist. Well, XCode gives me a nice little warning when I click "Build." Then, if I immediately click "Build" again, that warning goes away mysteriously! How do I fix this? I don't want my warnings to ever go away :)
|
Try selecting the All option for your build information
!Screenshot
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "iphone, ios, xcode"
}
|
Domain of a legend in D3.js
I am a beginner in D3 charts and working to pick it up fast. I was working on a heatmap chart with legend, which looks perfect at the moment. As I have hard-coded the domain values in legend, what will happen when the domain changes, or its dynamic? How can we link the domain in a d3 chart to a variable dataset?
|
You want to use the `scale` functions of d3 to map minimum/maximum bounds to domains/ranges:
Setting Scales Domains and Ranges in d3.js
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "d3.js"
}
|
Since static member functions can't modify non-static member variables, why should we still use it?
I know static class member function don't need to be instantiated. But, since class member functions' manipulation are always based on its' own member variables, why we still use the static member functions? can someone tell me by some detail examples? Thanks in advance.
P.S. I am writing a program that in one class member function create two threads, so that I need to pass the thread callback function address to when create the two threads. I want the thread callback function also be the same class's member function. According to some references, if a callback function is a class's member, it should be static. There comes the question: in the static callback, I can't call other non-static function in the same class, and can't modify it's non-static member variables. (English is my secondary language, so I'am not good at it. hope some help me describe it more succinctly:-)
|
I will just give you an example. If you want to calculate how many instances you have declared about your class, you may have a static member like
int instance_count;
and in the class constructor you can add the instance_count like:
instance_count++;
and in your destructor :
instance_count--;
As a result, you can get how many instances you have currently in your program.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -2,
"tags": "c++, multithreading"
}
|
Getting error on installing a plugin in wordpress
Getting fatal error when installing a woocommerce theme in wordpress. The error is:
> Fatal error:Maximum execution time of 30 seconds exceeded...
|
May your plugin's loop endless. If it is not, you could extend the maximum execution time like this:
ini_set('max_execution_time', 0);
Or,
At the top of the file set the timeout:
set_time_limit(0);
Or,
I had the same problem and solved it by changing the value for the param max_execution_time in php.ini, like this:
max_execution_time = 360 ; Maximum execution time of each script, in seconds (I CHANGED THIS VALUE)
max_input_time = 120 ; Maximum amount of time each script may spend parsing request data
;max_input_nesting_level = 64 ; Maximum input variable nesting level
memory_limit = 128M ; Maximum amount of memory a script may consume (128MB by default)
Thanks
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "wordpress"
}
|
adding more textviews for every xml tag on android
i'm pretty new to android programming and i'm try to read an xml file. that all works fine, and i can see in the logCat that he is receiving all the data but the app only shows 5 of the tag from the xml file. so i was wondering if i could add some sort of string that will add a new textView/listView or what ever view i need.
|
There is a good Android API guide on this: <
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "java, android, xml, eclipse, sax"
}
|
Using .values.max() for arrays
I use the following code to get a row from a dataframe and then find the max value.
def find_max(a):
return a.values.max()
row = df.iloc[0].astype(int)
max_value = find_max(a)
That works fine. However, if I pass an array like
ar = [1,2,3]
max_value = find_max(ar)
it doesn't work and I receive `AttributeError: 'list' object has no attribute 'values'`. How can I use that function for both types?
|
def find_max(a):
if isinstance(a, list):
return max(a)
elif isinstance(a, pd.DataFrame):
return a.values.max()
else:
print("No max method found for the input type")
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "python, pandas"
}
|
Как в Golang узнать реальное имя системной папки?
Как в Golang узнать реальное имя системной папки?
Нужно создать файл в каталоге программных файлов Windows
Например %ProgramFiles% - не работает.
Как узнать папку програмных файлов / операционной системы и др. ?
|
`os.getenv` вам поможет - _golang.org/pkg/os/#Getenv_
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "golang"
}
|
Let $T : \mathcal{D}(\mathbb{R}) \to \mathbb{R}$ be given by $T(\phi) = |\phi(0)|$. Show that $T$ is not a distribution.
As the title states, I wish to show that $T(\phi) = |\phi(0)|$ is not a distribution. I assume I need to show that the bound $|T(\phi)| \leq C \sum_{|\alpha| \leq n} ||D^{\alpha}\phi||_{L^{\infty}}$ fails to hold.
I am confused since the dirac distribution is defined as $\delta_0(\phi) = \phi(0)$ which means that $T(\phi) = |\phi(0)| = |\delta_0(\phi)|$, right?
What am I missing?
|
You have only to check that $\langle T, \varphi_1 + \varphi_2\rangle=\langle T, \varphi_1 \rangle +\langle T, \varphi_2\rangle$ is false in general with the definition of $\langle T,\varphi\rangle=|\varphi(0)|$.
Briefly said: the absolute value blocks the linearity.
Your last question deals implicitely with the meaning of $|\delta|$ ; but we have precisely shown that this definition of $|T|$ is faulty...
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "functional analysis, distribution theory"
}
|
Submit an app to app-store build with ios 8.4 SDK and run it on a device with iOS 9
I know that it's possible to build an app with xcode 6.4 and then deploy it on a device running iOS 9 with TestFlight or any other deployment tool. The question is if it's possible with apples app store. Or more precisely, when will apple force us to switch to the iOS 9 SDK when submitting to the app store? Will it be September? Octobre? 2015?
Many thanks! TK
|
Over time, Apple sets the minimum version of XCode that you can submit with, but the "SDK" requirement is dependent on the APIs that you are actually using.
The Deployment Target version is the minimum iOS version that your app supports, and you can set the target version less than the latest version. This affects the user at download/install time. If their device does not meet the minimum, they won't be able to download and install the app.
The minimum Deployment Target that you can set in XCode also increases over time with new releases of XCode. In that case, you may have some deadlines to beat to provide updates for the app that support older iOS versions. According to wikipedia, XCode 7 will allow a minimum iOS 5.1.1 deployment target, though you may have to set it manually.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "ios, ios9"
}
|
Finding out the current Identity Provider in Windows Identity Foundation
I have a web site which allows multiple ways of authenticating a user (e.g. facebook, twitter, windows etc.) Each of this provides a different identity name when the user logs in. I need to find out who provided the identity (ClaimsIdentity) and accordingly select the unique id for the user to add application specific claims to the users claims set. I created a table to associate all the entities with users primary profile table. This table contains name of the identity provider, unique id provided by the identity provider and unique user id from the profile table.
My question is how can I find the name of the identity provider when the user signs into my site using these logins? The problem is if the user has same email address used for both facebook and twitter, I am not able to find out that information in the incoming principal as used in the authentication manager's authenticate method.
|
You typically use the `Issuer` and `OriginalIssuer` properties in each claim that you get.
If you use `e-mail` as the unique identifier:
var u = this.User as IClaimsPrincipal;
var c = (u.Identity as IClaimsIdentity)
.Claims
.First( c => c.ClaimType == ClaimTypes.Email );
var issuer = c.Issuer;
var originalIssuer = c.OriginalIssuer;
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "c#, wif, claims based identity"
}
|
Place button to the center oh the toolbar ionic 2
I need to put a button in the center of my toolbar, and i have a menutoggle to the left. Here is my code :
<ion-toolbar>
<button ion-button icon-only menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-buttons end>
<button ion-button icon-only class="button-navbar">
<ion-icon name="ios-refresh"></ion-icon>
</button>
<button ion-button icon-only class="button-navbar button-right">
<ion-icon name="ios-cart-outline"></ion-icon>
</button>
</ion-buttons>
</ion-toolbar>
With this i have my togglemenu and the two icons on the right, i would like one in the middle of the toolbar :

|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "css, ionic framework, ionic2"
}
|
What is a Serre-smooth algebra?
Let $A$ be an $R$-algebra. In the book "Noncommutative Geometry and Cayley-smooth Orders" by Le Bruyn one can find the notion of "Serre-smooth" in the introduction. But no formal definition seems to be given in this (very long) introduction. It is just mentioned that $A$ is Serre-smooth if $A$ has finite global dimension together with some extra features such as Auslander regularity or the Cohen-Macaulay property.
Then it is refered to the article < but there I can not find the word "Serre" (searching with Strg+F).
> Question: Is there a reference for the complete definition of being Serre-smooth?
|
No, there is no such reference. The introduction to that book is based on a couple of lectures I gave in Luminy and there I had to distinguish between several notions of 'smoothness', formal smoothness a la Kontsevich-Rosenberg, Cayley-smoothness, and Artin-Schelter- or Auslander-Gorenstein-regularity as used by people working in NAG. For the later category I then used the term 'Serre-smoothness' as it is the noncommutative equivalent of smoothness for commutative affine algebras (finite global dimension) to the noncommutative world. If one only considers (maximal) orders in central simple algebras which are finite modules over their centers then one can do with less than the full repertoire of these homological conditions, I think. Please read 'Serre-smoothness of A' as 'A is an Auslander-Gorenstein regular ring'. My apologies for the confusion this ad-hoc terminology may have caused.
|
stackexchange-mathoverflow_net_7z
|
{
"answer_score": 5,
"question_score": 5,
"tags": "reference request, rt.representation theory, ra.rings and algebras, homological algebra"
}
|
Undo Changes with collection of images
I'm trying to create a undo functionality to a picture box by saving the image right before the paint take place into a array or something. I tried with List but i get the same image all the time, with Image List the size is to small for my porpoises. What are the best practices for saving undo data or how can i store images into memory right before every paint take place? Thank you !
|
You have to clone the image contents every time. I think you are adding always the reference of the image to the list.
If you want to get undo functionality done properly have a look at the Command Pattern.
Another way would be to calculate the difference of the original image and the image after the operation and then store the difference to save memory.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "c#"
}
|
toggle effect in jQuery for 2 div
I have make a jquery toggle efect. When I click one div it toggles and when I click another div it also toggles but both are open. So my question if I open one of them then the second div will be close automatically. My demo link is here
$(document).ready(function() {
$('.top').each(function(index) {
$(this).on("click", function(){
$('.read:eq(' + index + ')').slideToggle("fast");
});
});
});
$('.box').click(function (e) {
$( '#' + $(this).data('toggleTarget') ).slideToggle(300);
});
|
Don't try to bind events inside a loop structure.
Try,
$(document).ready(function () {
$('.top').on('click', function () {
$('.read').not($('.read:eq(' + $('.top').index(this) + ')').slideToggle(300)).slideUp(300);
});
});
## DEMO
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "jquery"
}
|
Are $f\sqrt{1+g^2}$ and $fg\sqrt{1+g^2}$ smooth if $f,fg,fg^2$ are smooth?
Suppose that $f$ and $g$ are functions from $\mathbb R$ to $\mathbb R$ such that the functions $f,fg,fg^2$ are smooth, that is, are in $C^\infty(\mathbb R)$. Does it then necessarily follow that the functions $f\sqrt{1+g^2}$ and $fg\sqrt{1+g^2}$ are smooth?
Of course, the problem here is that the function $g$ does not have to be smooth, or even continuous, at zeroes of the function $f$.
One may also note that the continuity of the functions $f\sqrt{1+g^2}$ and $fg\sqrt{1+g^2}$ (at the zeroes of $f$ and hence everywhere) follows easily from the inequalities $|f\sqrt{1+g^2}|\le|f|+|fg|$ and $|fg\sqrt{1+g^2}|\le|fg|+|fg^2|$.
|
**No.**
Set $$ f(x) = \exp(-2/|x|^2) \operatorname{sign} x, \qquad g(x) = \exp(1/|x|^2) \sqrt{|x|} \operatorname{sign} x $$ for $x \ne 0$, and, of course, $f(0) = g(0) = 0$. Then clearly $$ \begin{aligned} f(x) & = \exp(-2/|x|^2) \operatorname{sign} x , \\\ f(x) g(x) & = \exp(-1/|x|^2) \sqrt{|x|} , \\\ f(x) (g(x))^2 & = x \end{aligned} $$ are infinitely smooth, but $$ f(x) g(x) \sqrt{1 + (g(x))^2} = \sqrt{|x| \exp(-2/|x|^2) + |x|^2} = |x| (1 + o(1)) $$ is not even differentiable at $0$.
|
stackexchange-mathoverflow_net_7z
|
{
"answer_score": 15,
"question_score": 7,
"tags": "reference request, real analysis"
}
|
How to create dependencies in statechart?
Example StateChart
I've got a system, that is depending on another system. I want to display this in a statechart.
System 1: **microwave_state** with two states: **On** and **Off**
When microwave_button is pressed AND system 2 current state is true, then ON else Off
System 2: **electricity_state** with two states: **True** and **False**. When electricity bill is payed then True else False
How can I display that dependency in a statachart?
|
You would do it like this:
, I would set the Grid.Row values to 10, 20, 30, 40, and 50. In this case, if I wanted to insert a row after the first row, I would set its Grid.Row value to 15. I wouldn't need to change any other rows. The layout engine would know to put the rows in ascending order. Is there some reason that the Grid.Row values don't act this way?
_HTML Z-Index values work like this_
|
> Is there some reason that the Grid.Row values don't act this way?
This would require the Grid to determine _every_ possible row (by iterating all of it's children) during it's layout, and then placing the items. This would slow down and complicate the layout pass.
By making the grid row's explicit, this is avoided, and it helps the overall performance of the layout pass when the Grid arranges it's children.
> HTML Z-Index values work like this
FYI - the `Canvas` class, in WPF, also uses this approach for Z indexing.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 3,
"tags": "wpf, grid"
}
|
Can I enter the US with a Green Card about to expire?
My Green Card expired in April, however in February I applied for renewal, and it was extended through November. I am travelling overseas and returning on November 28th. Since I have not yet received the new Green Card, could I have problems entering the US with a Green Card that is about to expire two days later?
|
I just realised this question had no answer. Since I returned with no problem, I am going to post as an answer my own experience.
Yes, returning caused no problem, my green card was still valid (albeit for just a couple more days) and I came in with no issue. A month later I finally received the replacement.
|
stackexchange-travel
|
{
"answer_score": 7,
"question_score": 10,
"tags": "usa, residency, visa expiration"
}
|
How to filter alphabetic values from a String column in Pyspark Dataframe?
I have a string column that I need to filter. I need to obtain all the values that have letters or special characters in it.
Initial column:
id
---
12345
23456
3940A
19045
2BB56
3(40A
Expected output:
id
---
3940A
2BB56
3(40A
TIA
|
Just the simple digits regex can solve your problem. `^\d+$` would catch all values that is entirely digits.
from pyspark.sql import functions as F
df.where(F.regexp_extract('id', '^\d+$', 0) == '').show()
+-----+
| id|
+-----+
|3940A|
|2BB56|
|3(401|
+-----+
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "python, validation, pyspark, apache spark sql"
}
|
How can you get the calling ip address on an ejb call?
If a java client calls a remote EJB on a different server, how can you get the client IP address? Note that it is important to get it from the server, because the client is likely behind a NAT firewall, and in this case we need the public IP address.
NOTE: Although it would preferably be a generic solution, at a minimum I could use one that retrieves the IP address from an EJB2 call on JBoss 4.2.2
|
This article on the JBoss community wiki addresses exactly your issue. Prior to JBoss 5 the IP address apparently has to be parsed from the worker thread name. And that seems to be the only way to do it on earlier versions. This is the code snippet doing it (copied from the above link):
private String getCurrentClientIpAddress() {
String currentThreadName = Thread.currentThread().getName();
System.out.println("Threadname: "+currentThreadName);
int begin = currentThreadName.indexOf('[') +1;
int end = currentThreadName.indexOf(']')-1;
String remoteClient = currentThreadName.substring(begin, end);
return remoteClient;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "java, ip address, ejb"
}
|
media:thumbnail w/ BeautifulSoup
What is the correct way to parse the `url` attribute of `media:thumbnail` tags using BeautifulSoup? I have tried the following:
doc = BeautifulSoup(urlopen(' 'xml')
items = doc.findAll('item')
for item in items:
title = item.title.text
link = item.link.text
image = item.find('media:thumbnail')[0]['url']
However, I get the `'NoneType' object is not subscriptable` error.
|
Don't include the namespace prefix:
>>> doc.find('thumbnail')
<media:thumbnail height="51" url=" width="90"/>
The `element.find()` method returns **one** element, so there is no need for subscription here; you can access the `url` attribute on the element directly:
>>> doc.find('thumbnail')['url']
u'
There currently isn't any support for searching by a specific namespace; the namespace _URL_ is stored (in the `.namespace` attribute) but not used by `.find()` or `.find_all()`.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "python, rss, beautifulsoup"
}
|
Testing binary stream
I am building a binary file importer using Python. The specific file structure is defined in a specification. This looks like:
File
* Map Block
String, Short Integer, Long Integer, String, Short Integer, Long Integer...
* Block1
String, String, Long Integer, String, Short Integer, String, Long Integer, Long Integer....
* Block2
* Block3
etc
I have proved the concept of collecting and decoding the binary data and I can access each block of data individually by collecting the Map Block first.
However I can't figure out the best way to Test it. The current tests I have are: test_get_string test_get_short test_get_long
Can you suggest what suite of tests I might build next? Would I be best testing with an actual file or create long binary strings to test with?
|
If you work with a stream to import (as suggested by Killian) then you can test each of the functions to get individual values by mocking that stream. Mocking the stream means that you setup the next few bytes before calling the to be tested function and let the test fail when it requests more than the needed number of bytes. After the function all those bytes should have been read.
Part of the correctness assertion would be that it doesn't read more or less than the amount of bytes it needs to decode and the correctness of the value.
You can also test getting each block individually again with ensuring it only reads exactly as many bytes it needs and correctness of the read in values.
For testing the map block decoding you can construct one and then query the offsets of some blocks using that map block.
|
stackexchange-softwareengineering
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python, unit testing"
}
|
Copying the macros and modules from one workbook to another and have all the VBA work in one master workbook
I need to know how to copy the VBA modules with the corresponding sheets with buttons and macros (that are assigned to the buttons) to an another workbook that also has VBA code in it.
Thank you so much!
|
You must define you're variables (inputs) in the worksheet. You can define your variables to that worksheet or the whole entire workbook. It depends on what you are doing. Each variable must be unique and if you made a mistake just define it something else. This all relates to the VBA code so the names defined and arguments must match.
The variables are usually defined in the code where you are seeing an error. Define the variables in the worksheet by right clicking on the input and then you can call it by its name that is related to the code.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "vba, excel, copy paste"
}
|
why do I first get undefined in the console then it prints the numbers I want?
Why do I first get undefined in the console then it prints the numbers I want? How can I solve the code so that it does not write undefined in the beginning?
var rangeStart;
var rangeStop;
var sum1;
function printRange(rangeStart, rangeStop) {
for (rangeStart = 23; rangeStart < rangeStop; rangeStart++) {
sum1 += rangeStart + ',';
}
}
printRange(23, 47);
var sum1 = sum1.slice(0, -1);
console.log(sum1);
|
var rangeStart;
var rangeStop;
var sum1;
Your first 3 variables declarations are unnessecary. rangeStart and rangeStop don't need to be declared as they are gonna be arguments of yourfunction printRange.
sum1 , you declare it two times, the first time it initialize it to undefined, and then later, instead of assigning a value to an already declared variable, you redeclare it. That's why you have those 2 logs in the console. The code below should do what you want to achieve.
function printRange(rangeStart, rangeStop) {
let sum = "";
for (var i = rangeStart; i < rangeStop; i++) {
sum += i + ',';
}
return sum;
}
var sum1 = printRange(23, 47).slice(0, -1);
console.log(sum1);
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript"
}
|
Determining the probability of having over a dollar amount based on defined bills.
Good day,
I am having difficulty solving the following problem from a leisure math activity:
### Problem
> [] has a money bag containing a \$20 bill, two \$10 bills, two \$5 bills, and a \$1 bill. If he randomly draws out three bills, what is the probability that the sum of the bills is greater than $25?
### Answer Choices
The possible answer choices are 25%, 40%, 44%, 50%, & 61%. The answer key included states that the correct answer is 50%, but I do not understand why.
### What I know
I know the total number of permutations of bill combinations is 6!, and I believe that it is reduced to 6!/3! due to the three-bill draw. I attempted to write out the possible permutations over $25 by hand, but I know there must be a better way.
|
The bills have been carefully chosen so having more than $\$25$ is equivalent to having the $\$20$ bill. If you do have the $\$20$, the least you can have is $20+5+1=26$. If you don't have the $\$20$, the most you can have is $10+10+5=25$. You draw three bills out of six, so the chance you get the $\$20$ is $50\%$.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": -1,
"tags": "probability"
}
|
output for System.out.println gives strange number
System.out.println("1 + 2 = " + 1 + 2);
output: 12
can you explain why this is ? I tried to look through some documentation but did not find anything...
|
Because the `+` operator works from left to right, it adds the string `"1 + 2 = "` to `1` first, and gets `"1 + 2 = 1"`, then adds `2` to get `"1 + 2 = 12"`.
It's equivalent to
System.out.println(("1 + 2 = " + 1) + 2);
Try this instead.
System.out.println("1 + 2 = " + (1 + 2));
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "java"
}
|
Which process is using port 4000 (identified as remoteanything by nmap)?
I've run `nmap -sS [computer ip]` and see that i only have one service running:
PORT STATE SERVICE
4000/tcp open remoteanything
What service is this? Should i close it? I've googled and only found some shady stuff: < Maybe it is used by some of my other programs?
|
`nmap` just makes a guess at the service here, as basically any application can bind to any port. To see which specific application it is in your case, run
lsof -i :4000
|
stackexchange-apple
|
{
"answer_score": 5,
"question_score": 3,
"tags": "tcp"
}
|
timer complete start repeatCount flex 4
Just a quick question about the Timer class of Flex 4. I have a timer object with a set repeatCount. At the end of the set number of cycles, the TIMER_COMPLETE event is triggered and the timer.running changes to false. Now I can call the timer.start() function again.
My question is that at this stage, does it also set the repeatCount property back to zero. Or does one have to explicitly call the timer.reset() function.
Thanks.
|
No it doesn't reset the repeatCount property
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "apache flex, flex4, timer"
}
|
how to capture wget command output inside groovy
I am execution a **wget** command inside my groovy code, the command is like this:
cmd /c C:/wget.exe -q -O - <my-URL>
When i actually run this command from **cmd** or windows run util, it works fine. But when i try to run this from within my groovy code, I don't see the output. How can i capture the output of this within groovy.
Thanks!
|
"cmd /c C:/wget.exe -q -O - <my-URL>".execute().text
But `new URL("<my-URL").text` might be a better way to load an url without relying on wget.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "groovy, cmd, wget, outputstream"
}
|
What can a pregnant woman do if she already stepped on nails?
A pregnant women is advised by the gemara (Nidda 17a) to avoid stepping on cut human nails out of fear of miscarriage. What can she do if she has already stepped on them? Is there a way to "fix" things to avoid a miscarriage (chalilah)?
Related
|
One source for the two approaches everyone is talking about is in the Ri MiLunel here (second column third paragraph). He writes that some say it is because of her fragility and some say it is because of sorcery. Interestingly, the way he formulates the second option - because of _sorcery_ , not simply spiritual dangers - it would appear that he would hold that this does not apply in an era where we are generally not concerned about sorcerers. Couple that with the fact that (as others pointed out) according to the first option it doesn't seem logical that the danger should last longer than the moment she steps on the nails anyway, and we can basically conclude that according to the Ri MiLunel the answer to the question is she has nothing to worry about.
|
stackexchange-judaism
|
{
"answer_score": 4,
"question_score": 10,
"tags": "pregnancy birth, health safety shmira, nail cutting"
}
|
Enable pin with maximum 3.0v
I've an Enable pin active-high that have maximum voltage rating of 3.0v, but I use a 3.3v MCU outputs. I've also a 3.0v voltage regulator on board.
Should I use resistor voltage divider or there is a possibilty to use 3.0v voltage regulator? And how should I connect it?
|
Yes, you could just use a simple voltage divider. However, if you wanted to do it in a more fancy way with the 3.0V supply, you could use a simple resistor and transistor (NPN or N-channel logic level MOSFET) arrangement which inverts the pin so it becomes active low:
!schematic
simulate this circuit - Schematic created using CircuitLab
So to activate your enable pin you would output a logic LOW, and to disable it a logic HIGH. It then also becomes the same as most other "Chip Enable" pins which are active low.
|
stackexchange-electronics
|
{
"answer_score": 3,
"question_score": 1,
"tags": "voltage, voltage regulator, voltage divider, input"
}
|
How to return the generic type of an object inside generic class?
I'd like to write a generic service that should work with an object of a specific type. When I write custom implementation of that service, I'd like to object to be variable. Therefore I wanted to override the method that creates that object.
But it won't work. Is it impossible in java to achieve the following?
class MyService<T extends Foo> {
//Type mismatch: cannot convert from Foo to T
public T createObject() {
return new Foo();
}
public void run() {
T t = createObject();
//work with the object
}
}
class Bar extends Foo;
class CustomService<Bar> {
@Override
public Bar createObject() {
return new Bar();
}
}
|
class NewArrayList extends ArrayList {
}
abstract class MyService<T> {
public abstract T createObject();
public void run() {
T t = createObject();
//work with the object
}
}
class CustomService extends MyService<NewArrayList> {
@Override
public NewArrayList createObject() {
return new NewArrayList();
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "java, generics"
}
|
How to add object as attribute using javascript?
I am trying to add object to attribute using javascript but it is passing as object object.
var choice = {'name':'one',id:1}
COde
return '<a href="/users?userId='+
choice.id+'" class="tool-tip" title="'+
choice.name+'"><span data-desc="'+
choice+'">'+this.label(choice)+'</span></a>';
it is creating as
<a href="/users?userId=1" class="tool-tip" title="userName">
<span data-desc="Object Object"></span></a>
Where i am dong wrong?
|
When manipulating the DOM via Javascript, there is absolutely no need to go through the intermediary simplified HTML representation. Create DOM objects directly with arbitrary properties:
var link = document.createElement('a');
link.href = '/users?userId=' + choice.id;
link.classList.add('tool-tip');
link.title = choice.name;
var content = document.createElement('span');
content.desc = choice;
content.textContent = this.label(choice);
link.appendChild(content);
return link;
And then `appendChild` this `link` to some other DOM element…
If you absolutely need `choice` to be part of `dataset` (`data-*="…"`) because some other component depends on it… well, `dataset` can only hold strings, not objects, so you would have to at least agree that the value is a JSON string:
link.dataset.desc = JSON.stringify(choice);
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -1,
"tags": "javascript, html, object"
}
|
Database schema considerations for a dynamic form creation/survey web application
I'm building a web application that will essentially allow 'admins' to create forms with any number and combination of form elements (checkboxes, combo-boxes, text-fields, date-fields, radio-groups, etc). 'Users' will log into this application and complete the forms that admins create.
We're using MySQL for our database. Has anyone implemented an application with this type of functionality? My first thoughts are to serialize the form schema has JSON and store this as a field in one of my database tables, and then serialize the submissions from different users and also store this in a mysql table. Another thought: is this something that a no-sql database such as MongoDB would be suited for?
|
Yes, a document-oriented database such as MongoDB, CouchDB, or Solr could do this. Each instance of a form or a form response could have a potentially different set of fields. You can also index fields, and they'll help you query for documents if they contain that respective field.
Another solution I've seen for implementing this in an SQL database is the one described in How FriendFeed uses MySQL to store schema-less data.
Basically like your idea for storing semi-structured data in serialized JSON, but then _also_ create another table for each distinct form field you want to index. Then you can do quick indexed lookups and join back to the row where the serialized JSON data includes that field/value pair you're looking for.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "database, database design, web applications, serialization, database schema"
}
|
Firebase Firestory query where stored timestamp is in the past
I need to delete all Documents which have a timestamp (stored in a field) prior to today.
The timestamp is created in the Firestore GUI. The following query doesnt return any docs.
collectionRef
.where('timestampFieldName', '<', Date.now())
.get()
What exactly is a timestamp, created in the GUI and how to compare it with any date?
|
Whenever passing a date to Firestore, you should pass in an actual `Date` object. `Date.now()` returns a timestamp, which is just a number and not a `Date` object itself. To get the actual `Date` for the same value, use `new Date()`. So:
collectionRef
.where('timestampFieldName', '<', new Date())
.get()
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, firebase, google cloud firestore"
}
|
How does PHP scandir work?
I need to scan directory `/home/user/www/site/public_html/application` (full path by root).
scandir does perform it with even just `'application'` part of full path as argument and that's all going to be ok, I got now list of files and directories as result.
I am interesting how scandir does work with that path `'application'`? Ain't the argument should be a `full path by root`?
I did not found any explanation to this behavior on official php.net, unfortunately.
Any idea, how it works? Thanks.
P.S. My `DOCUMENT_ROOT` is set to `/home/user/www/site/public_html`
|
For relative paths it bases them on the script's current working directory, which you can find with `getcwd`.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php, file, directory, scandir"
}
|
Error in edit button "Only assignment, call, increment, decrement, and new object expressions can be used as a statement"
private void button1_Click(object sender, EventArgs e)
{
string StudentNo = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value.ToString();
frmEdit EditForm = new frmEdit();
EditForm.StudentNo;
EditForm.ShowDialog();
}
|
You probably meant to write
EditForm.StudentNo = StudentNo;
instead of just
EditForm.StudentNo;
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -4,
"tags": "c#"
}
|
How to get the length of a formula in R?
I am trying to get the length of the following formula:
myformula <- ~ (1 | Variable1) + (1|Sex) + Age + Cells + Glucose
But for some reason, `R` doesn't recognize the real number of elements (which is 5)
str(myformula)
Class 'formula' language ~(1 | Variable1) + (1 | Sex) + Age + Neutrophils + Monocytes
..- attr(*, ".Environment")=<environment: R_GlobalEnv>
length(myformula)
[1] 2
(Note: I have variables like this (1|Variable) because I am working with the Variance Partition package (and categorical variables must be written in that format).
Does anyone know how to get the real length of a formula in `R`?
|
We may use `all.vars` to get the variables in the formula and then apply the `length`
length(all.vars(myformula))
[1] 5
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "r, formula, string length, variable length"
}
|
Clients getting sent wrong Term Serv CAL, getting Temp instead of installed CAL
I have Win Server 2008R2 with RDS role and then another 2008R2 DC that is also the license server. When I first installed the RDS server I did not have CAL licenses at the time so the users were getting temp per device CAL. A few days later I installed the PER USER CAL on the server. How can I move the users from the temp CAL to the ones I bought?
Screen shot of RD Licensing Manager
|
You can tell your terminal servers where the license server is in the Terminal server config, or better still there's a policy you can set (i cant remember where it is exactly) that you can use to set the info on mass.
Also for info we have had some issues in the past on XP machines where if a user has a temporary license, they don't always end up with a full one. We traced it down a a problem with a permission on a registry key, but to fix it you just have to logonto the machine as a local admin, then connect twice (it has to be twice, and you dont need to logon) to a terminal server.
|
stackexchange-serverfault
|
{
"answer_score": 0,
"question_score": 1,
"tags": "windows server 2008, licensing, remote desktop services"
}
|
Find out which radio button is selected using Selenium (implemented as li)
I have the below HTML. It's a small window with 3 radio buttons. Its implemented as a ul with 3 li elements. Below code clicks on the div inside the li and is selecting the radio button:
WebElement v = driver.findElement(By.xpath("/html/body/div[4]/div/div[2]/div/div[1]/div[2]/ul/li[2]/div[1]"));
JavascriptExecutor jsb = (JavascriptExecutor) driver;
jsb.executeScript("arguments[0].click();", v);
How do I find out which of the three radio button is clicked? I want to open this screen again and be able to tell which one of the radio buttons is selected.
[![HTML\[!\[\]\[1\]](
|
There aren't a lot of info in your question. I can suppose that the image with the interested html is when "none" is selected. If you notice, when a radio button is selected, the class name is **`"icon icon-dot-circle-o"`**.
Otherwise, the class name is "icon icon-circle-o".
You could use this info in order to understand which button is selected.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "java, selenium, xpath, selenium webdriver, css selectors"
}
|
Merge 2 SELECT statement in one result table
I have 2 different select statements, both of which generate similar tables. How can I put the result from both of them in one table? Example:
First SELECT generates
Col1 Col2 Col3
A X Y
B X Z
The second SELECT generates
Col1 Col2 Col3
A Z Z
C X X
And I want the result to be
Col1 Col2 Col3
A X Y
B X Z
A Z Z
C X X
|
You should use `UNION` or `UNION ALL` if you want duplicate data.
Remember that column name and type must be same in two queries.
For example
SELECT
col1,
col2
FROM table1
UNION
SELECT
col1,
col2
FROM table2
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "mysql, sql, select, merge"
}
|
SQL: List of users that meet a condition N times
I have data that looks something like:
Date UserID Visits
2012-01-01 2 5
...
I would like to output a list of users who have > x visits on at least y dates (e.g., the users who have >5 visits for at least 3 dates from January 3 to January 10).
|
Try this:
SELECT SUB.UserId, COUNT(*) FROM (
SELECT VL.UserId FROM VisitLog VL
WHERE VL.Visits > 5
AND VL.Date BETWEEN '2014-01-03' AND '2014-01-10') SUB
GROUP BY SUB.UserId
HAVING COUNT(*) >= 3
The sub query returns all rows where the number of `Visits > 5` between your sample date range. The results of this are then counted to return only users where this condition has been matched at least 3 times.
You don't give much information but if you have multiple records per date per user then use this query (exactly the same principal, just an inner grouping to sum by user and date):
SELECT SUB.UserId, COUNT(*) FROM (
SELECT VL.UserId, VL.Date FROM VisitLog VL
WHERE VL.Date BETWEEN '2014-01-03' AND '2014-01-10'
GROUP BY VL.UserId, VL.Date
HAVING SUM(VL.Visits) > 5) SUB
GROUP BY SUB.UserId
HAVING COUNT(*) >= 3
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 2,
"tags": "sql, postgresql"
}
|
Import data into R from access
I'm attempting to pull data into R from access which, I've successfully done.
Now what I'm looking to do is pull in all the needed tables with one line of code opposed to one at a time.
Example:
I have 5 tables: 3/15 Policy Details 6/15 Policy Details 9/15 Policy Details 12/15 Policy Details 3/16 Policy Details
As you can see, all the tables end with "Policy Details" but begin with a different date.
My orginal solution:
library(RODBC)
db<-file.path("C:\\Path\\To\\Database.accdb")
db
channel<-odbcConnectAccess2007(db)
sqlTables(channel,tableType = "TABLE")$TABLE_NAME ##List all table names
Q1.15<-sqlFetch(channel,"3/15 Policy Details")
Q2.15<-sqlFetch(channel,"6/15 Policy Details")
close(channel)
I had to use sqlFetch for each quater. What I'm looking to do is bring in all the tables with one string of code oppossed to doing a seperate line of code for each quarter.
|
Consider using `grep()` on returned list of table names. Then bind table fetches into a list with `lapply()` and then out to separate dataframe objects with `list2env`:
library(RODBC)
db <- file.path("C:\\Path\\To\\Database.accdb")
channel<-odbcConnectAccess2007(db)
accTables <- sqlTables(channel,tableType = "TABLE")$TABLE_NAME
accTables <- accTables[grep(".*Policy Details$", accTables)]
dfList <- lapply(accTables, function(t) sqlFetch(channel, t))
close(channel)
# NAME EACH DF ELEMENT THE SAME AS TABLE NAME
dfList <- setNames(dfList, accTables)
# OUTPUT EACH DF TO INDIVIDUAL OBJECT
list2env(dfList, envir=.GlobalEnv)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "mysql, r, ms access"
}
|
Oversized UI in Firefox (non-high DPI display)
When installing Firefox ESR on a fresh bare-bones Debian 10 net-install with the minimal components of Xfce, the UI appears somehow oversized (like it was a touch device, which is not the case). This and this show the issue.
Has anybody faced this issue? Is there a way to solve it rather than reinstalling the OS?
Thanks in advance.
EDIT: Worth to say that the UI components that are affected are mainly those which are part of the Firefox UI itself, not the webpages. I mean, right-click menus, Firefox top-right menu, as well as the cursor in the URL bar.
|
I've finally figured it out myself.
Booting my system in recovery mode and deleting the file `/home/<myUser>/.config/xfce4/xfconf/xfce-perchannel-xml/xsettings.xml` has returned Firefox's UI to its default state after I've rebooted normally.
EDIT: turns out it was a problem with the font I had set, changing it solves the issue without deleting any files.
|
stackexchange-unix
|
{
"answer_score": 0,
"question_score": 0,
"tags": "debian, xfce, firefox"
}
|
Replaying packets with pyusb does not have the expected output
Working on my Logitech G105 keyboard, to hopefully implement a userspace driver to activate some of its specialized features.
I've captured the usb traffic it outputs when using a windows vm with the official logitech drivers, output of starting the software and setting the m1 led active are in this gist (usbmon-boot and usbmon-m1 respectively).
Replaying the packets with in python with `dev.ctrl_transfer(0x21, 0x09, 0x0200, 0x0000, 0x0001) ` and so on results in almost the exact results, however, the data words after = in usbmon are all 00, and the led on the keyboard does not activate.
|
Ah, figured out my problem. I was doing
`dev.ctrl_transfer(0x21, 0x09, 0x0306, 0x0001, 0x0002)`
in response to
`ffff8800822bbcc0 1231215925 S Co:7:009:0 s 21 09 0306 0001 0002 2 = 0601`
but what I should have done is
`dev.ctrl_transfer(0x21, 0x09, 0x0306, [0x06, 0x01])`
Issue is resolved :D
|
stackexchange-reverseengineering
|
{
"answer_score": 0,
"question_score": 1,
"tags": "usb"
}
|
Cannot enter long commands in terminal
I am using putty (0.64.0.0 2015) to access the terminal on an AIX server. Normally typing long commands works just fine but somehow something weird happened and when I type long commands Linux cursor goes back on the same line even behind the 'bash' word.
In order to explain the problem I have a picture. Just to explain in the picture I start with capital 'ABC' then '1-10' and then small 'abc' and then repeat this sequence to simulate a long command.
 and how to solve it without restarting putty? Does it have to do with a buffer of some kind since the command runs just fine it is only that it looks like this in the picture.
|
It looks like your shell is no longer aware of its terminal's dimensions. Perhaps you've resized the PuTTY window after logging in?
Sometimes `resize` will fix such issues.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "linux, bash, terminal, putty"
}
|
How to access JavaScript variable in HTML tags?
I am trying to access JavaScript variable in the `href` attribute of anchor tag.
JavaScript Function:
<script type="text/javascript">
function fun(ReqTextbox)
{
var queueData =document.getElementById(ResTextbox).value;
//some more code
}
</script>
HTML code:
<body>
<input type="text" value="<%=dynamicValue%>" id="<%=dynamicId%>"/>
<a href="servlet?variablename="<%Eval(queueData)%>" onclick=fun('<%=dynamicvalue%>');>LINK</a>
</body>
I know that I am going to wrong at `variablename="<%Eval(queueData)%>"`.
Can someone please help me how to access and pass JavaScript variable as a query string parameter?
|
First, I think you made a typo :
function fun(ReqTextbox) {
var queueData = document.getElementById(ResTextbox).value;
//some more code
}
You get `ReqTextbox` parameter but you use `ResTextbox`. Then, since Javascript is client-sided, you have to manually update the href tag using `href` attribute. So your function would be like :
function fun(ReqTextbox) {
var queueData = document.getElementById(ReqTextbox).value;
document.getElementById('myAnchor').href = "servlet?variablename=" + queueData;
//some more code
}
And give your anchor tag an id, `myAnchor` in my example.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "javascript, html"
}
|
Connection string for a L2E web app
We have a class library (ProjA) which has L2E object context. This will be used in an Website (ProjB) and WCF Service (ProjC). How do I specify the connection string in the website (ProjB) web.config so that it uses the resource files from the class library project (ProjA).
connectionString="metadata=res://*/db.csdl|res://*/db.ssdl|res://*/db.msl;provider=System.Data.SqlClient;provider connection string="Data Source=localhost;Initial Catalog=db;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient"
I tried replacing the * with ProjA all name, but it cant load that dll
|
The * should work just fine. That means "search all loaded assemblies." So as long as the library assembly is loaded before you attempt to instantiate an ObjectContext (which, in my experience, is true almost by definition) then the EDMX will be found.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c#, .net, entity framework, linq to entities, connection string"
}
|
Spring Boot Gradle Tomcat 8
The Spring Boot reference guide provides instructions for upgrading to Tomcat 8 by setting a custom property in Maven:
<properties>
<tomcat.version>8.0.3</tomcat.version>
</properties>
What is the equivalent way to do the same in a Gradle build?
I have tried the following to no avail. It stays on version 7.0.52 at app startup.
buildscript {
...
ext['tomcat.version'] = '8.0.3'
...
}
|
Gradle has no equivalent of a "parent pom", so you have to call out the dependency explicitly. Because it's groovy you can probably do it programmatically, something like:
configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
if (details.requested.group == 'org.apache.tomcat.embed') {
details.useVersion '8.0.3'
}
}
}
We _could_ add some support for version properties to the Spring Boot Gradle plugin (feel free to open an issue in github) but it would probably have to be optional.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 9,
"tags": "tomcat, gradle, spring boot"
}
|
Switching values from 2 columns
I am writing a Python script that reads an Excel sheet.
In my excel sheet I have two columns, let's say A & B.
If column B's value is greater than column A I would like to switch it.
Example Sheet:
[A] [B]
1 6
10 2
3 11
Output Wanted:
[A] [B]
6 1
10 2
11 3
Right now I have this, but it is giving me completely different values:
s = (~(col['A'] < col['B'])).cumsum().eq(0)
col.loc[s, 'B'] /=2
col.loc[s, 'A'] = col.loc[s, ['A', 'B']].sum(1)
|
I'm assuming you're using Pandas based on your syntax. This would be a good situation for using the DataFrame.apply() method.
import pandas as pd
df = pd.DataFrame({'A': [1, 10, 3], 'B': [6, 2, 11]})
def switch(row):
if row['A'] < row['B']:
row['A'], row['B'] = row['B'], row['A']
return row
df = df.apply(switch, axis=1)
print(df)
gives:
A B
0 6 1
1 10 2
2 11 3
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python"
}
|
how secure is sending values through urls in PHP
I want to know how secure is about sending values through URLs. It will be a big mess I think. The good suggestion would be sending values by post method in php through pages. But if I get a better example of how usually the script would be in post format it would be great.. Or otherwise suggest your valuable comments to this to do how
|
**GET:** User can directly see the data in the browser location bar.
**POST:** Anyone in the intermediate network between client and server can still see the data.
**Solution:** If you want ultimate security, you need to use SSL (HTTPS). It's _not_ free, you need to buy the SSL certificate first.
* * *
**[EDIT]: OP Clarification:**
"Anyone in the intermediate network" means that suppose you are connected to your company's Internet Firewall that connects to to your Internet Service Provider (ISP) which connects to the server your website is hosted on.
Now, if you do not use SSL, then your company administrators can see the data through firewall and also ISP administrators can see it, if they want.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php"
}
|
Does Groovy have support for something like Ruby Modules?
Ruby modules make things like passing a database connection or other dependencies to various objects much easier while allowing for separation of concerns. Does Groovy support a similar functionality? And if so what is it called?
|
In ruby modules are used either as mixins or to namespace a class (e.g. `Net::HTTP`).
To mixin the behavior you can use @mixin annotation. like examples here <
To namespace, groovy uses same mechanism as java i.e. using packages (e.g. `groovy.sql.Sql`).
I am not sure if that answered your question or not. But for dependency injection, while its common to do it mixin way in ruby (or even in scala/play), I have not seen it done a lot using `@mixin` in groovy. Usually a DI container like spring is used.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "ruby, groovy, mixins, dynamic languages"
}
|
Deleting a notebook cell using only the keyboard
I am working on a laptop (thus I don't have the numeric pad). To erase a cell in Mathematica I always have to look on the right of the notebook window to find the bracket associated to the line, and then push del on my keyboard.
This is really inefficient because I always have to be carefull to erase the proper cell.
Isn't there a way to directly erase a cell by selecting its text and pushing a given key (selecting text + del will delete the text but not the cell).
Also, my keyboard is AZERTY (French keyboard).
|
You can move the cursor between cells, then press and hold SHIFT and select whole cells up or downwards with your arrow keys. If you press DELETE then this will delete the selected cells.
|
stackexchange-mathematica
|
{
"answer_score": 2,
"question_score": 3,
"tags": "front end, notebooks, keyboard"
}
|
Render escaped html in Rails
I'm pulling product descriptions from Amazon and they arrive escaped, looking like `<i>New York Times</i>`
When I use h, raw or html_safe it shows up in my application as <i>New York Times</i>
But I'd really like it to show up as _New York Times_
|
Try this:
<%= CGI.unescapeHTML("<i>New York Times</i>").html_safe %>
The issue is that the string contains html that has already been escaped. So, you need to 'unesacpe' it first.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "html, ruby on rails"
}
|
Using lambda if condition on different columns in Pandas dataframe
I have simple dataframe:
import pandas as pd
frame = pd.DataFrame(np.random.randn(4, 3), columns=list('abc'))
Thus for example:
a b c
0 -0.813530 -1.291862 1.330320
1 -1.066475 0.624504 1.690770
2 1.330330 -0.675750 -1.123389
3 0.400109 -1.224936 -1.704173
And then I want to create column “d” that contains value from “c” if c is positive. Else value from “b”.
I am trying:
frame['d']=frame.apply(lambda x: frame['c'] if frame['c']>0 else frame['b'],axis=0)
But getting “ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index a')
I was trying to google how to solve this, but did not succeed. Any tip please?
|
is that what you want?
In [300]: frame[['b','c']].apply(lambda x: x['c'] if x['c']>0 else x['b'], axis=1)
Out[300]:
0 -1.099891
1 0.582815
2 0.901591
3 0.900856
dtype: float64
|
stackexchange-stackoverflow
|
{
"answer_score": 50,
"question_score": 24,
"tags": "python, pandas, numpy, dataframe, lambda"
}
|
Convert selection to PDF in Google Chrome
There are Google Chrome plugins that convert entire web pages into PDF, but are there any plugins or other software that convert only the selected area in a web page to PDF?
|
You did not specify an operating system. While this answer should work across Windows/OSX/Linux, specific program recommendations will be for Windows because that's what I primarily use.
* * *
The most basic and program independent method is to install a PDF printer. I won't really recommend any specific one, but I have used Primo PDF on Windows in the past.
To convert a selected area, well, there's two ways, both generally program independent. You can select the text and print the selection to the PDF printer, or you can take a screenshot, crop it and print the result to PDF.
Chrome has been known to cause users to struggle with printing only a selection. There's a few ways to do so, for example `Ctrl``Shift``P` if you're on Windows. There's also a few plugins that allow printing only the selection.
|
stackexchange-superuser
|
{
"answer_score": 0,
"question_score": 3,
"tags": "google chrome, web, google chrome extensions, print to pdf"
}
|
find the longest word and the largest number in a text file
So im learning python right now and i really need your help. For example you do have random text file with words and numbers inside. You need to find the longest word and maximum number in this file. I managed to do the first half, i found the longest word:
def longest_word(word):
with open(word, 'r') as infile:
words = infile.read().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]
print (("the longest word is :"), longest_word ('text.txt'))
can you help me with the second part? how to find maximum number in a file?
|
You can implement error handling and try to parse the str as int: "2" --> 2
def longest_integer(word):
max_int = 0
with open(word, 'r') as infile:
words = infile.read().split()
for word in words:
try:
int_val = int(word)
if int_val > max_int:
max_int = int_val
except:
pass
return max_int
print (("the longest integer is :"), longest_integer ('text.txt'))
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "python, python 3.x, file"
}
|
Prove that $X_1 + ... + X_r \sim NB(r,p)$
Let $X_1,...,X_r$ be independent random variables with geometric distribution $X_i \sim Geometric(p)$. Then $$X_1 + ... + X_r \sim NB(r,p)$$
This is what I have tried:
$$\begin{eqnarray} P(X_1+...+X_r = k) &=& P(X_1 = k - X_2 -...-X_r) \\\&=& P(X_1 = k - j_2 -...-j_r, X_2 = j_2 , .., X_r=j_r) \\\&=& P(X_1 = k - j_2 -...-j_r) \cdot P(X_2 = j_2) \cdot ... \cdot P(X_r = j_r) \\\&=& (1-p)^k \cdot p^r \end{eqnarray}$$
which is not quite right since we're missing the factor $ {k+r-1 \choose k}$. But where did I go wrong?
|
When $r=2$ you have
$$\begin{align} \mathsf P(X_1+X_2=k) & =\sum_{j_2=0}^k \mathsf P(X_1=k-j_2)\mathsf P(X_2=j_2) \\\ & = \sum_{j_2=0}^k (1-p)^{k-j_2}p\cdot (1-p)^{j_2}p \\\ & = (k+1) (1-p)^kp^2 \end{align}$$
Now extend this to summation over $j_2, .., j_r$ for any $r\leq k$.
$$\begin{align} \mathsf P(\sum_{i=1}^r X_i=k) & = \sum_{j_2=0}^k\sum_{j_3=0}^{k-j_2}\cdots\sum_{j_r=0}^{k-\sum_{i=2}^r j_i} \left(\mathsf P\left(X_1=k-\sum_{i=2}^r j_i\right)\prod_{i=2}^r\mathsf P(X_i=j_i)\right) \\\ & = (1-p)^k p^r \left(\sum_{j_2=0}^k\sum_{j_3=0}^{k-j_2}\cdots\sum_{j_r=0}^{k-\sum_{i=2}^r j_i} 1\right) \end{align}$$
Now use a combinatorial argument on that summation. **Hint:** What is it counting?
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "probability, statistics, probability distributions"
}
|
Filter 2d-list(?) in R
I have this data structure in R:
>my2dlist
[,1] [,2] [,3] [,4] [,5]
[1,] 1.8911965 -0.5783678 1.125074 0.8213261 1.327800
[2,] 0.6354067 1.9959153 -0.571080 0.9250592 -1.668552
I want only those element where [1,] > [2,] but can't figure out how to do it, using Filter()
To clarify what I'm trying to do: in python:
[x for x in my2dlist if x[0]>x[1]]
|
Assuming that `my2dlist` is a `matrix`, we create a logical `vector` by comparing the first row with the second and subset the columns based on the logical vector
my2dlist[,my2dlist[1,] > my2dlist[2,], drop = FALSE]
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "r"
}
|
Database schema: User Team administration
I have **users** , who are members of **many teams** through a **membership** table. Each team has one administrator.
My question is:
Should the **admin column** be a boolean in the **membership** table, or an integer (id of user) in the **team** table?
|
Most simple is, yes: in membership table as that is the link between a User and a Team. In that case you would be more flexible to add for example 2 administrators. The other way around is also a valid one, considering it secures to have explicitly 1 administrator.
The disadvantage is for example that there is a relation which you should enforce so admin_id always links to a User which is really a member of the Team. So on delete you should check whether this admin is really still available.
A bit further thinking: Consider whether you have multiple roles, if that's the case you might use a more complex but flexible solution like ACL's and things.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "mysql, database design, ruby on rails 3.2"
}
|
if i release NSMutableArray is released, what happens to the objects in the array if their retainCount is greater then 1?
if i have a NSMutableArray with a retain count of 1 and this array has multiple class A objects that have variables with retain count greater then 1, what happens to this variables if i release the array? are they forced to release every retained count and release space or wil they stil occupy memory ?
|
Releasing the array has the same effect as removing all the items from the array. That is, the array no longer claims ownership of them. If anyone else has retained the objects, they'll continue to exist. If not, they'll be deallocated.
This is just the normal set of memory rules in effect. If you retain an object, you must release it. Conversely, other bits of code (like an array) are allowed to retain and release that object when they want to own it, too, but if everyone follows the rules, nobody gets surprised.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 1,
"tags": "iphone, objective c, ios"
}
|
Visual C++ 2010 - fatal error LNK1169: one or more multiply defined symbols found
this is a program :
#include <iostream>
using namespace std;
int main() {
cout << "Enter a number";
int i;
cin >> i;
try {
if( i == 0 ) throw 0;
if( i == 2 ) throw "error";
} catch( int i ) {
cout << "can't divide by 0";
}
catch( ... ) {
cout << "catching other exceptions";
}
}
On compiling (Microsoft visual C++ 2010 express on Windows 7), I get the error which says:
> fatal error LNK1169: one or more multiply defined symbols found
|
**Actually there is no error in this code**.
Number of source files could be the problem. Try this code as a new project in the same compiler or try deleting the files from the `source files` option in the left side of Text Area (i.e where you are writing your code)
This should compile then.
|
stackexchange-stackoverflow
|
{
"answer_score": 16,
"question_score": 5,
"tags": "c++, visual c++, exception, visual c++ 2010 express"
}
|
update SQLite data from tablet to mobile in android
I am creating an app that is for my grandmother as she suffers from Alzheimer. I would like to have a feature where I could remotely update the schedules from my mobile to her tablet .Now I am thinking of various possibilities to have the same set of data in both Tablet and Mobile for example:Authenticating the application with caretaker's username and password requires checking data from SQLite table.Now how is it possible to have same set of SQLite data in both mobile and tablet. Any update on SQLite table in tablet should also update the mobile SQLite database. -I don't want any cloud service or third party apis. -One way I think is have a PHP enabled server and have both devices integrated to it. -Is there a way to have the tablet send data directly to mobile through HTTP?(Of course mobile should be connected to Wifi but that is fine!)
|
As I see it there are two ways you can go.
Server based: You write a server and then post updates to it, the tablets periodically pulls any updates from it, you need to write a web server in language and framework of your choice communicating over JSON or XML with phone and tablet. This has the advantage that the phone can post multiple updates and the tablet can pull whenever it has net available.
Direct: Use (tcp) sockets to send commands from the phone to the tablet over the net. If you know that both will be connected to the internet or the same wifi all the time this will be more efficient, and you don't need to write a server.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "android, android asynctask, client server, android sqlite, asyncsocket"
}
|
Dojo: How to have different label and value on FilteringSelect widget when using JsonRest store?
I am using JsonRest store with FilteringSelect widget and would like to know how to have different label (human readable) and value(hidden input value). All examples are using ItemFileReaderStore for doing this and it is specified that ItemFileReaderStore will be deprecated in v2.0. Do I need to use ItemFileReaderStore for having value and label on FilteringSelect? Thank you for your help.
|
Don't switch to ItemFileReaderStore. You just need to define an idProperty for your JsonRest store.
var store = new JsonRest({
target: "/some/resource",
idProperty: "timeStamp"
});
There is an example JSfiddle, but with Memory.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "select, dojo, label"
}
|
Asignar cookies en pedido GET con XMLHttpRequest
Estoy tratando de asignar una cookie en una petición _GET_ , en un pedido `XMLHttpRequest`.
Mi código es el siguiente:
var pedido = new XMLHttpRequest()
pedido.open("GET","
pedido.setRequestHeader("Cookie","SSID=AbhcxIM8JMu")
Esto me tira una advertencia en _Firefox_ :
> El pedido de establecer un encabezado prohibido fue denegado: Cookie
Sospecho que la solución está en cambiar algo en la configuración de _Firefox_ , pero no sé exactamente cómo hacerlo.
¿Es posible hacer esto en _JavaScript_?
|
Crear una cookie en JS es muy sencillo:
document.cookie='SSID=AbhcxIM8JMu';
Puedes encontrar más información en MDN, pero realmente no hace falta mucho más: Una vez que hayas definido un valor, se añadirá automáticamente a cada petición que hagas al servidor al que pertenece la página actual.
|
stackexchange-es_stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "javascript, firefox, cookies, http get"
}
|
Will eggwhites clear my lobster broth
I'm planning to do a lobster broth for New-Years.
* Lobster shells, browned in oven
* Shallots, parsley root, carrots and other suitable veg
* Seasoning, tomato paste, I think I have a reasonable slurp of Cognac avaliable.
Boil for about 15 minutes.
When I strain this, it will be cloudy. I was thinking whisking in egg-whites and straining it again to make it clear. Is this possible? Will the procedure change the taste?
I have about 4 hours to make it on saturday. Any suggestions are welcome. I want it as consommé-like(clear) as possible.
|
Allow me to describe what happened. (TLDR; complete success)
I started out with

But I was wondering if anyone had an idea on how I might replace these values with a fixed value? Say `1900-01-01 00:00:00` (or maybe 1955-11-12 for anyone who gets the reference!)
Reason being that this data frame is part of a process that handles thousands and thousands of JSONs per day. I want to be able to see in the dataset easily the incorrect ones by filtering for said fixed date.
It is just as invalid for the JSON to contain any date before 2010 so using an earlier date is fine and **it is also perfectly acceptable to have a blank (NA) date value so I can't rely on just blanking the data**.
|
Replace missing values by some default datetime value in `Series.mask` only for missing values generated by `to_datetime` with `errors='coerce'`:
df=pd.DataFrame({"date": [np.nan,'20180101','20-20-0']})
t = pd.to_datetime('1900-01-01')
date = pd.to_datetime(df['date'], format='%Y%m%d', errors='coerce')
df['date'] = date.mask(date.isna() & df['date'].notna(), t)
print (df)
date
0 NaT
1 2018-01-01
2 1900-01-01
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "python, pandas, datetime"
}
|
Approximation of Lebesgue Measurable Sets by compact and G-delta?
Just to check if this is true:
Let $E$ be a Lebesgue measurable set on $\mathbb{R}^n$. Does there exists a sequence of open sets $G_m$, compact sets $K_m$, with $K_m\subset E\subset G_m$ and $\mu((\cap G_m)\setminus (\cup K_m))=0$?
I am aware of the usual approximation by $G_\delta$ and $F_\sigma$ sets, however here we need compactness which may not be true if the sets are not bounded?
Thanks for any help.
|
Yes. For $n\geq 0$ let $B_n=\\{x\in E: \|x\|<n\\}.$ Then $B_0=\emptyset$ and $$\mu (E)=\sum_{n=0}^{\infty}\mu ( B_{n+1}\backslash B_n)=$$ $$=\sup_{m\in N}\sum_{n=0}^m \mu (B_{n+1}\backslash B_n)=$$ $$=\sup_{m\in N}\mu (\cup_{n=0}^{m+1}( B_n)=\sup_{m\in N}\mu ( B_{m+1}).$$ Let $C_m$ be a compact subset of $B_m$ with $\mu (C_m)>\mu ( B_m)-2^{-m}.$ Then $\mu (E)=\sup_{m\in N}\mu (C_m).$
Let $D=\cup_{m\in N}C_m.$ For each $n\in N$ we have $\mu (B_n\backslash D)=0.$ So we have $$\mu(E\backslash D)=\sum_{n\in N}\mu (B_n\backslash D)=\sum_{n\in N}0=0.$$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "real analysis, analysis, lebesgue measure"
}
|
Finding The Minimal Polynomial Of Symmetric/Hermitian Matrix
Given a specific symmetric/hermitian matrix, one can easily find the characteristic polynomial, can the minimal polynomial can be found without testing out lower powers polynomials with as a normal operator can be unitary diagonalized, and a matrix is diagonalized $\iff$ the minimal polynomial is a product of linear elements?
|
For symmetric $A$, the eigenvalues are real, which is trivial for the real field, and not difficult to show over the complex field. If $\lambda$ is real, then $$ \mathcal{N}((A-\lambda I)^2)=\mathcal{N}(A-\lambda I) $$ because, if $(A-\lambda I)^2x=0$, then
$$ 0=\langle (A-\lambda I)^2 x,x\rangle = \langle (A-\lambda I)x,(A-\lambda I)x\rangle = \|(A-\lambda I)x\|^2. $$ Thus, the minimal polynomial of a symmetric $A$ has no repeated factors. So the minimal polynomial is obtained from the characteristic polynomial by eliminating repeated factors.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 3,
"tags": "linear algebra, diagonalization"
}
|
Огонь - огниво - огненный - огнь
Огонь - огниво - огненный - огнь
По сути - **огниво** \- **огненный** \- исходные от слова **огнь**!
Почему слово **огнь** вышло из употребления?
|
Древнерусская и старославянская форма слова **огнь** употреблялась в литературе до начала 19 века (Карамзин, Крылов). К тому времени уже более двух веков существовала и конкурировала с ней форма **огонь** : в сочетании согласных ГН развился дополнительный слоговый гласный О, под влиянием первого. Слово _огнь_ осталось в церковнославянском языке, в текстах библейских книг; также оно возможно в торжественной поэзии "под старину" ( _огнь священный_ ).
|
stackexchange-rus
|
{
"answer_score": 3,
"question_score": 2,
"tags": "словообразование"
}
|
How can I access lazy-loaded fields after the session has closed, using hibernate?
consider this scenario:
* I have loaded a Parent entity through hibernate
* Parent contains a collection of Children which is large and lazy loaded
* The hibernate session is closed after this initial load while the user views the Parent data
* The user may choose to view the contents of the lazy Children collection
* I now wish to load that collection
What are the ways / best way of loading this collection?
* Assume session-in-view is not an option as the fetching of the Children collection would only happen after the user has viewed the Parent and decided to view the Children.
* This is a service which will be accessed remotely by web and desktop based client.
Thanks.
|
I'm making some assumptions about what the user is looking at, but it seems like you only want to retrieve the children if the user has already viewed the parent and really wants to see the children.
Why not try opening a new session and fetching the children by their parent? Something along the lines of ...
criteria = session.createCriteria(Child.class);
criteria.add(Restrictions.eq("parent", parent));
List<Child> children = criteria.list();
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 11,
"tags": "java, hibernate, lazy loading"
}
|
Liquibase: Using sequence
I am using the `InsertStatement` class and I want to pass the sequence generation code. How do I do that? I tried following, but did not work.
InsertStatement statement1 = new InsertStatement("saas", "OAuth2AppTemplate");
statement1.addColumnValue("id",
new SelectSequencesStatement("saas.seq.nextval"));
Any inputs?
|
Okay, after lot of digging into the Liquibase documentation I found it.
InsertStatement statement1 = new InsertStatement("saas", "OAuth2AppTemplate");
final Sequence sequence = new Sequence();
sequence.setName("saas.OAuth2AppTemplate_id_seq.nextval");
statement1.addColumnValue("id", sequence);
And this then generates the query appropriately.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "java, oracle11g, liquibase"
}
|
My C++ program behaves strange with wrong output?
I want to view all solution for: X^12≡1(mod27) So I wrote the following C++ program which outputs only 1 even though 8 and 10 are possible values for x too.
Why is that?
#include <iostream>
#include <cmath>
int main() {
for (int i = 0; i <= 2700000; ++i) {
if (int(pow(i, 12))% 27 == 1) {
std::cout << i << std::endl;
}
}
std::cout << "Hello, World!" << std::endl;
return 0;
}
|
The inbuild `pow()` function is not capable of handling so large number. Rather we have to use custom function to achieve that.
Here it is
#include <iostream>
#include <cmath>
long long binpow(long long a, long long b, long long m) {
a %= m;
long long res = 1;
while (b > 0) {
if (b & 1)
res = res * a % m;
a = a * a % m;
b >>= 1;
}
return res;
}
int main() {
for (int i = 0; i <= 2700000; ++i) {
if (binpow(i, 12, 27) == 1) {
std::cout << i << std::endl;
}
}
std::cout << "Hello, World!" << std::endl;
return 0;
}
You can read more about that function from here: <
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "c++"
}
|
What properties can I use with event.target?
I need to identify elements from which events are fired.
Using `event.target` gets the respective element.
What properties can I use from there?
* href
* id
* nodeName
I cannot find a whole lot of info on it, even on the jQuery pages, so here is to hoping someone can complete the above list.
**EDIT:**
These may be helpful: selfHTML node properties and selfHTML HTML properties
|
`event.target` returns the DOM element, so you can retrieve any property/ attribute that has a value; so, to answer your question more specifically, you will always be able to retrieve `nodeName`, and you can retrieve `href` and `id`, provided the element _has_ a `href` and `id` defined; otherwise `undefined` will be returned.
However, inside an event handler, you can use `this`, which is set to the DOM element as well; much easier.
$('foo').bind('click', function () {
// inside here, `this` will refer to the foo that was clicked
});
|
stackexchange-stackoverflow
|
{
"answer_score": 51,
"question_score": 131,
"tags": "events, properties, jquery"
}
|
Installing Asp.Net SignalR error while installing
I am trying to install SignalR in Visual Studio 2010 professional project. But I am getting this error:
Could not install package 'Microsoft.Owin.Security 2.1.0'. You are trying to install this package into a project that targets '
.NETFramework,Version=v4.0', but the package does not contain any assembly references or content files that are compatible with that framework. F
or more information, contact the package author.
|
Try installing a different version of signal r with this command (via nuget package console) 'install-package Microsoft.AspNet.SignalR -Version 1.1.3'. Latest version of signalr requires .net4.5
|
stackexchange-stackoverflow
|
{
"answer_score": 12,
"question_score": 4,
"tags": "asp.net, .net, .net 4.0, signalr, nuget"
}
|
Can I somehow modify a '&' array?
So basically I have this:
let mut sortedNumbers = numbers.clone();
sortedNumbers.sort_by(|a, b| b.rational.cmp(&a.rational));
Where `numbers` is a `&[..]`
I want to somehow sort the `sortedNumbers` vector, but the reference is not mutable. Any ideas?
|
If `numbers` is a `&[T]`, then `numbers.clone()` is also a `&[T]`, referring to the same array. What you want is `numbers.to_vec()` or `numbers.to_owned()`, which give you a `Vec<T>`, which you can then modify.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "rust, ownership, borrowing"
}
|
Поиск значений массива в массиве
Имеем массив
$a = array("qwe","asd","zxc");
И массив
$b = array("zxc","qwe");
Нужно определить, имеются ли значения из массива `$b` в массиве `$a`.
Что-то тупняк навалился, не пойму, как сделать.
|
(bool) array_intersect($a, $b);
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "массивы, php"
}
|
Angular 9 routerLink resolving semi-colon to %3B
How can I prevent Angular 9 from rendering routerLink hrefs with URL encoding?
Here is a stackblitz example of the problem, of the below example:
<
**typescript:**
myurl = "/testing;parameter1=abc";
**template:**
<p>myurl = {{myurl}}<p>
<a [routerLink]="myurl">Testing</a>
**Simplified Output:**
<p>myurl = /testing;parameter1=abc</p>
<a href="/testing%3Bparameter1%3Dabc">Testing</a>
How do I prevent the href from rendering with %3B, %3D rather than semi-colon and equals?
Thank you!
|
Angular doesn't work that way to handle query params, you must declare them separatly :
<a routerLink="/testing" [queryParams]="{parameter1: 'abc'}">Testing</a>
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "angular, render, urlencode, routerlink"
}
|
Как получить доступ к Edit1, если ругается "undeclared identifier Edit1"
Есть функция. Во время своей работы функция должна запросить данные у пользователя через компонент TEdit и сохранить в виде целочисленных переменных. Выглядит это пока так.
function translate(): boolean;
var tx, ty: integer;
begin
tx := StrToInt(Edit1.Text);
ty := StrToInt(Edit2.Text);
end;
При этом компилятор говорит:
> undeclared identifier Edit1
При том что Edit1 и Edit2 инициализированны в самом начале. Что я делаю не так?
|
Чтобы иметь доступ к компонентам формы, функция должна быть членом класса формы:
function Form1.translate():boolean;
или получать ссылки на компоненты в виде параметров:
function translate(Edit1, Edit2: TEdit): boolean;
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 5,
"question_score": 2,
"tags": "delphi, vcl"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.