text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Он обвиняет в этом жену?
«Когда русскому человеку особенно плохо живется, он обвиняет в этом
жену, соседа, погоду, Бога - всех, кроме самого себя.»
Этом - prepositional,
Жену - accusative.
Why don't they match?
Этом - masculine,
Жена - feminine.
Why not Этой?
Большое спасибо!
A:
The relevant part of the phrase translates as "he accuses his wife of this".
Обвинять is a polyvalent verb which accepts up to two objects (one direct and one prepositional): обвинять кого? (acc.) в чём? (prep.)
Compare English verb "to accuse someone of something".
So those are two different objects and they don't have to agree with each other.
| {
"pile_set_name": "StackExchange"
} |
Q:
AngularJS v1.2.16 bug when using IE?
This piece of code :
if (window.angular.bootstrap) {
//AngularJS is already loaded, so we can return here...
console.log('WARNING: Tried to load angular more than once.');
return;
}
is contained in AngularJS version 1.2.26 and causing an issue for IE. Error message is "console is undefined". My fix is just to remove console.log ?
What is meaning of window.angular.bootstrap ?
A:
As others have said in the comments, support of the console object and specifically console.log is not good for some versions IE, so that is why you are getting that error. There are many polyfills for logging, such as this one. Although, that is not your issue.
The reason you are even running this code in the first place, is because window.angular.bootstrap is not null or undefined, which implies you are loading Angular JS more than once.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a way to see all the references of a method in netbeans similar to the newer version of visual studio
I was using a fresh installed visual studio when i noticed you can now quickly see the reference above the methods. I was wondering if there is a similar way to do this in netbeans ? Because sometimes when i refactor my code i'm losing a lot of time searching where all the references are .
A:
Place the cursor on any method / variable / etc. and press [left Alt]+[F7] or just right-click on it and select "Find usages".
| {
"pile_set_name": "StackExchange"
} |
Q:
I keep coming up with the wrong calculation when using the vincenty formula
I'm trying to use the formula from (www.movable-type.co.uk/scripts/latlong.html) to return a destination point giving a starting point, distance and bearing. These are my values:
int radius_km = 6371;
double d = 74.02;
double st_lat = 39.4450;
st_lat = Math.toRadians(st_lat);
double bearing = 106.1607;
bearing = Math.toRadians(bearing);
double end_lat = Math.asin( Math.sin(st_lat)*Math.cos(d/radius_km) +
Math.cos(st_lat)*Math.sin(d/radius_km)*Math.cos
(bearing) );
end_lat = Math.toDegrees(end_lat);
When I enter the d, st_lat and bearing at the website, I get this: 39°33′28″N.
When I use the above code (that I copied from the website) I get this: 39.25679699255662.
I looked around more and somebody said the division may not return the decimal amount, so I replaced the division with:
BigDecimal distance = new BigDecimal("74.02");
BigDecimal strradius = new BigDecimal("6371");
BigDecimal d2 = distance.divide(strradius, 6, RoundingMode.HALF_EVEN);
double d = d2.doubleValue();
and changed the formula to:
end_lat=Math.asin(Math.sin(st_lat)*
Math.cos(d)+Math.cos(st_lat)*Math.sin(d)*Math.cos(bearing));
The answer I get now is 39.25680143864117.
I'm sure I'm missing something but I'm not able to go through each step of the calculation to see where I'm off at. Does anybody have step-by-step instructions on how to do this? I would greatly appreciate it.
Thanks.
A:
Are you sure you are doing the correct conversion from minutes/seconds to decimals?
There are 60 minutes in a degree, 60 seconds in a minute. If the starting latitude is 39.4450; assuming that positive means north of the equator. If the bearing of 106.1607 is assumed to be measured from north going clockwise; would mean you are traveling southeast.
You said the website is telling you the answer is 39°33′28″N, but if I convert this to decimal, that is equal to 39+(33+28/60)/60 = 39.5578. This result is greater than your starting point, i.e., you are traveling southeast, but ending up north of your point.
I haven't looked at the math in your code yet, but off hand I would say your problem lies in the conversion from minutes/seconds to decimals and back.
| {
"pile_set_name": "StackExchange"
} |
Q:
Serializing JSON data in PHP / CodeIgniter
I have a User table that has serialized data in one of the tables.
When the user logs in, that row for the user gets loaded into a session object. The issue is that the entire user object is then serialized by CI's Session library. This causes issues when unserializing. Digging down into the Session.php library, it looks like unserialize returns false.
Has anyone come across this or know of any way to better serialize serialized objects?
EDIT
Correct, it's not serialized in my User table. It's saved as JSON. Which still breaks the unserialize
A:
well if you data is saved as in json format then to bring it back to life (usable form) you should use json_decode function
| {
"pile_set_name": "StackExchange"
} |
Q:
What solid foods to give a picky toddler to make her satisfied?
I'm a teen mom and my 19-month-old baby girl is so picky she barely eats baby foods. Everytime she sleeps during the day or night when she wakes up all she wants is milk. I’ll have to wait when she’s hungry later to give her real food which sometimes she doesn’t eat. I need help and suggestions on what to give her as solids that she might like as a baby please...
A:
I transitioned my son off "baby foods" by giving him the baby cereal mixed with vegitable beef soup (concentrate). He got a variety of (soft) vegitables with well cooked meat. If your daughter is full from solid foods, she is less likely to be dependant on milk. I would like to add, when she wakes and you think she only wants milk, she might really want to be held so she can wake up slowly. Distract her with a pacifier, bottle of water, or some milk that's thinned with water, even a saltine, while calming her. Then make her something that will fill her up. Some of it should be finger foods that she can explore and eat on her own. You will (both) get through this.
| {
"pile_set_name": "StackExchange"
} |
Q:
Convert table cell text to array
<tr>
<td>a</td>
<td>b</td>
</tr>
I know that I can create an array manually and loop over each td and push them in to the array.
But is there any way to make a jquery one-liner that results in an array with the texts?
Desired result:
['a', 'b']
A:
You can use .map with .get as given below to solve this.
var values = $('td').map(function(index, item){
return $(item).text()
}).get()
console.log(values)
Demo: Fiddle
| {
"pile_set_name": "StackExchange"
} |
Q:
calculate address from array syntax in c
I know that the title is not clear at all , but i use this code to tell what i want to ask
assume the following simple code :
void example(int *a)
{
for(i = 0 ; i < 20 ; i++)
{
printf(" %d number is %d \n " , i , a[i]);
}
}
int main()
{
int a[20] ;
// assume that the array is filled
example(a);
return 0 ;
}
so my question is ,what is the 'addresing mode' that c language follow , if we write a[i] ? if we just follow the rules of pointer or syntax of pointer we must write this in this way *a[i] , since we need to show the value that *a point on it , and not the address ?
A:
About the array subscript operator [], the C99 standard §6.5.2.1¶2 says -
A postfix expression followed by an expression in square brackets []
is a subscripted designation of an element of an array object. The
definition of the subscript operator [] is that E1[E2] is identical to
(*((E1)+(E2))). Because of the conversion rules that apply to the
binary + operator, if E1 is an array object (equivalently, a pointer
to the initial element of an array object) and E2 is an integer,
E1[E2] designates the E2-th element of E1 (counting from zero).
So a[i] in the function example evaluates to *(a + i). You could write it either way. Please note that arrays and pointers are different types. Arrays are not first-class objects in C unlike integers, floats, structures etc. This means you can't pass array to or return an array from a function.
In the function main, a is an array type - its type is int[20], i.e., an array of 20 integers. When you pass a to the function example in the statement
example(a);
in main, then the array a evaluates to a pointer to its first element which is assigned to function parameter a which is of type int *. You can access the elements in the array a in main by either syntax - a[i] or *(a + i) - they are equivalent as described in the standard. However, remember that the there is a difference in the way the array elements are accessed when using the array itself (a[i] in main) and using a pointer to the first element in the array (a[i] in example). For more details, please look here - Difference between dereferencing pointer and accessing array elements
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding dropdowns to each row in a column of a dataview
I have a dataview with the following columns:
<Columns>
<asp:BoundField DataField="report_type" HeaderText="Report Type" ReadOnly="True" SortExpression="report_type"/>
<asp:BoundField DataField="progress" HeaderText="Progress" SortExpression="progress"/>
</Columns>
This works fine, it displays records from the database.
How do I replace the progress column and make it contain a dropdown for each row? Where the dropdown contains complete and incomplete?
A:
You can use Template column in order to customize your render
<asp:TemplateField HeaderText="..">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
| {
"pile_set_name": "StackExchange"
} |
Q:
Why are my Macbook's internal speakers not available?
My Macbook (the unibody aluminum version) has lost its internal speakers. When I open System Preferences -> Sound -> Output, all I see is "Digital Out". If I plug in a pair of headphones, this switches to "Headphones". I don't see "Internal Speakers" at all any more. Headphones seem to work fine.
In System Profiler -> Audio -> Available Devices, I do see "Speaker: Connection: Internal".
I just clean-installed Snow Leopard, so it appears to be a hardware problem.
Is there anything I can do to fix this, short of taking it back to Apple? It's out of warranty.
A:
If you look in your headphones jack, is there a red light on?
If yes, then you have Digital Out on, and this messes with the speaker configuration.
There is a thread here, which has some possible fixes.
Update
There is switch inside the jack that is stuck. Plug the speaker jack in and out several times while watching the Sound-output system preference panel. The internal speaker option will come on if the switch is unstuck.
Taking a toothpick and fiddling around inside the jack has solved the problem for some, you should try this. (Don't break the toothpick inside :) )
From: http://forums.macrumors.com/showthread.php?t=239287
The problem is actually caused by a little switch inside the jack that gets stuck. When you stick in an audio cable, it pushes the switch down. If it's an analog cable, the end is made of metal. If it's optical, the end is made of plastic. If the switch is pressed down, the computer checks to see if the plug inside is metal or plastic based on conductivity. When it gets stuck and nothing is in there, it thinks an optical cable is plugged in since the switch is down but nothing conductive is in there. That's why it works with headphones or external analog speakers.
A:
Samething here, I plugged in my headphones and jiggled them a little bit while inside and then pulled them out halfway. Once I did that I could see the volume slider appear and the volume could be adjusted up and down. I pulled them out all the way and they volume went grey again. Pushed the headphones back in and then pulled them out and now everything is fine.
A:
I had this problem and solved it by plugging in (and then unplugging) my iPod headphones.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to update specific row using inner join?
I need to update a specific row in a table, to select this row i need to use inner join, I wrote this:
UPDATE Items
SET [Seq] = '0'
WHERE EXISTS
(SELECT *
FROM Items
inner join Dictionary on items.Member = Dictionary.Member WHERE
Items.ID = '1' and Items.Member ='23')
All rows in Items table were updated, not the specific row (the select statement works fine and I get the row I need)
Do I miss something?
A:
Sql Server
UPDATE Items
SET Items.[Seq] = '0'
FROM Items inner join Dictionary
on items.Member = Dictionary.Member
WHERE Items.ID = '1' and Items.Member ='23'
Mysql
UPDATE Items
INNER JOIN Dictionary
ON items.Member = Dictionary.Member
SET Items.[Seq] = '0'
WHERE Items.ID = '1' and Items.Member ='23'
| {
"pile_set_name": "StackExchange"
} |
Q:
Inserting element to hash of hashes in perl
I have an array. The elements in the array are containing semi colon in between them.
Array looks something like this:
@Array = { "AUT;E;1",
"AUT;E;2",
"CHE;A;1",
"CHE;C;4"
};
I want to split the array elements using ';' (semicolon) as delimiter.
By using hash of hashes I want to store 'AUT' as key and under that want to store E => 1 and E => 2.
i.e I needed the hash as
%HashOfElem = (
'AUT' => {
'E' => 1,
'E' => 2
},
'CHE' => {
'A' => 1,
'C' => 4
}
)
For that purpose I wrote the following code which is not behaving as expected :(
foreach(@Array)
{
my @TmpArray = split(/;/,$_);
%HashOfElem = (
$TmpArray[0] => {
$TmpArray[1] => $TmpArray[2]
}
);
}
If my approach is wrong then which data structure in perl can be used to achieve above purpose?
Please help..
A:
Note that you're doing wrong assignement to @Array, it should be (parenthesis instead of braces):
updated according to comment:
my @array = (
"AUT;E;1",
"AUT;E;2",
"CHE;A;1",
"CHE;C;4"
);
so your script becomes:
my @array = (
"AUT;E;1",
"AUT;E;2",
"AUT;E;2",
"CHE;A;1",
"CHE;C;4"
);
my %hash;
my %dups;
foreach (@array) {
next if exists $dups{$_}; # skip this line if already stored
$dups{$_} = 1;
my @tmp = split/;/;
push @{$hash{$tmp[0]}{$tmp[1]}}, $tmp[2];
}
say Dumper\%hash;
output:
$VAR1 = {
'CHE' => {
'A' => [
'1'
],
'C' => [
'4'
]
},
'AUT' => {
'E' => [
'1',
'2'
]
}
};
| {
"pile_set_name": "StackExchange"
} |
Q:
Como permitir obter dados via API do Wordpress
Queria começar a aprender React.js e para isso decidi fazer um tema escrito em React para o meu wordpress, usando a 'nova' funcionalidade WP API. Como faço para ter acesso ao API a partir do meu computador? Eu sei que tenho de autorizar a chamada à API, mas não sei como fazer. Veja como estou a tentar buscar as informações:
componentDidMount() {
let dataURL = "http://meusite.com/wp-json/wp/v2/books?_embed";
fetch(dataURL)
.then(res => res.json())
.then(res => {
this.setState({
movies: res
})
})
}
Recebo o erro 425 (visivel do chrome devTools) quando faço a chamada para o Url que devolve Json.
Como posso permitir o acesso?
A:
As rotas de leitura sempre serão públicas no wordpress a não ser que você aplique um filtro para protegê-las.. Ler a lista de posts por exemplo, seja para custom post type ou não você não precisa de autenticar..
as rotas para adicionar novos conteúdos no banco, vc precisa de autenticação..
Usando o oauth2 você vai ter bastante trabalho pra compreender se você não estiver familiarizado.. Você pode optar em usar o JWT para fazer essa autenticação.. Seja qual for o modo de autenticação que você utilizar, você vai precisar instalar o plugin..
| {
"pile_set_name": "StackExchange"
} |
Q:
How to rank records within each group and also checking other variable to assign rank if two records had same rank within the group in SQL Server?
I have a data set which basically tells you how many coupons were sent for each retailers, and how many responded, their corresponding response rate for each dealer and for each coupons.
I am looking to rank each coupons within each dealer based on response rate and if two coupons had same response rate, then I need to assign better rank to the coupons which was sent the most
This is the script that I have tried but it is not ranking properly
SELECT
DealerCode, Coupon_name, emailsent, responders, responserate,
RN = RANK() OVER (PARTITION BY DealerCode, Coupon_name, responserate
ORDER BY DealerCode, responserate, emailsent)
FROM
table123
This is the expected result
RetailerCode Coupon_name emailsent responders responserate RN
----------------------------------------------------------------------
A1 Coupon 1 6 1 0.166666667 1
A1 Coupon 2 10 1 0.1 2
A1 Coupon 7 50 2 0.04 3
A1 Coupon 9 25 1 0.04 4
A2 Coupon 1 28 3 0.10714 2
A2 Coupon 4 12 0 0 3
A2 Coupon 3 1217 131 0.1076 1
A3 Coupon 2 63 10 0.1587 1
A3 Coupon 6 9 1 0.11111 2
A3 Coupon 7 3 0 0 3
A3 Coupon 8 2 0 0 4
A4 Coupon 4 174 22 0.1266782 3
A4 Coupon 3 1118 244 0.2182869 1
A4 Coupon 6 3091 420 0.135877 2
A5 Coupon 3 1227 78 0.06356962 2
A5 Coupon 2 780 50 0.064104 1
A5 Coupon 1 164 6 0.0365866 3
A:
Looking to your sample you should only use PARTITION BY DealerCode
SELECT DealerCode, Coupon_name, emailsent, responders, responserate,
RN = RANK()OVER(PARTITION BY DealerCode
ORDER BY DealerCode,responserate,emailsent)
FROM table123
| {
"pile_set_name": "StackExchange"
} |
Q:
ScheduledThreadPoolExecutor threads remain when completed
The routine myProcessToRun() needs to be executed 100 times but there needs to be about a second delay between each execution.
The following FOR Loop is used in conjunction with the ScheduledThreadPoolExecutor object.
for (int n=0; n<100; n++)
{
final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
executor.schedule(new Runnable() {
@Override
public void run() {
myProcessToRun();
}
}, (n+2), TimeUnit.SECONDS);
}
This actually works fine but the threads still remain.
Using JVisualVM the number of Threads increases by 100 threads when the routine is executed. When the routine finishes, the 100 threads still remain.
Clicking the "Perform GC" button doesn't clean them up so Java still believe they should exist.
How do these threads get cleaned up using an example like above?
---Edited---
I noticed the ScheduledThreadPoolExecutor was being instantiated within the Loop which was a terrible idea. After moving it outside the LOOP the threads created weren't so bad.
After attempting to implement the solution there was unexpected behavior.
final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10);
for (int n=0; n<100; n++)
{
//final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(2);
executor.schedule(new Runnable() {
@Override
public void run() {
doAddNewCondSet();
}
}, (n+2), TimeUnit.SECONDS);
}
try
{
executor.shutdown();
if (!executor.awaitTermination(400, TimeUnit.SECONDS))
executor.shutdownNow();
} catch (InterruptedException e1)
{
e1.printStackTrace();
}
With the modified code, it would immediate stop all the processes with the shutdown and nothing was executed.
With the executor.shutdown(); commented out and just using the awaitTermination(), the program just hung and after a few minutes, all the processes kicked off at the same time without delay which resulted in errors.
I suspect my implementation was wrong.
A:
There are a number of ways that you can do this. You can view some of them here:
https://www.baeldung.com/java-executor-wait-for-threads
My personal favorite is the CountDownLatch:
Next, let’s look at another approach to solving this problem – using a
CountDownLatch to signal the completion of a task.
We can initialize it with a value that represents the number of times
it can be decremented before all threads, that have called the await()
method, are notified.
For example, if we need the current thread to wait for another N
threads to finish their execution, we can initialize the latch using
N:
ExecutorService WORKER_THREAD_POOL
= Executors.newFixedThreadPool(10);
CountDownLatch latch = new CountDownLatch(2);
for (int i = 0; i < 2; i++) {
WORKER_THREAD_POOL.submit(() -> {
try {
// ...
latch.countDown();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
// wait for the latch to be decremented by the two remaining threads
latch.await();
| {
"pile_set_name": "StackExchange"
} |
Q:
Netty Decoder for specific Xml Tags
I'm trying to make a TCP server using netty that runs a TCP Server, listens for incoming xml strings and sends any received xml to all open Connections.
The xml is always formatted the same way (beginning and ending with ).
In addition to handling it's own server connections, it also open a connection with a second server that does the same thing and pools all xml between the two.
So basically there's a ServerBootstrap that listens for incoming XML data from any Connection that it listens for as well as one pre-defined connection that the application manages itself.
The two major issues I'm having is
a.) properly listening for data and deliminating incoming strings based on the xml tag.
I've tried using XmlDecoder in my pipeline but that doesn't seem to be doing anything. In fact my ServerBootstrap just ends without doing anything, is it supposed to block for listening purposes?
Here's my Server Bootstrap
try {
ServerBootstrap bootstrap = new ServerBootstrap()
.group(listenGroup, speakingGroup)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress("127.0.0.1", mListeningPort))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline()
//.addLast("string-decoder", new StringDecoder())
.addLast("xml-decoder", new XmlDecoder())
.addLast(new ServerHandler());
}
});
ChannelFuture channelFuture = bootstrap.bind().syncUninterruptibly();
} finally {
listenGroup.shutdownGracefully();
speakingGroup.shutdownGracefully();
}
The other issue im having is establishing a connection to the mirror server and adding it to the list of outputs for the ServerBootstrap. I've done less testing on this myself, and theoretically an interface leading back to a regular ol' Bootstrap should work, but I'm not sure how to keep the Bootstrap connection alive or whether or not it's better to take the Channel somehow and add it to the ServerBootstraps group.
Any thoughts? Sorry if it's a little confusing what i'm trying to do.
A:
My guess is that your parenthesis that you are using to delimit your messages isn't supported by the xml decoder. (i.e. you aren't actually sending valid xml) Is there a reason that you can't just use an outermost xml group that holds the entire message?
| {
"pile_set_name": "StackExchange"
} |
Q:
C Splitting Strings
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
char *strArray[40];
void parsing(char *string){
int i = 0;
char *token = strtok(string, " ");
while(token != NULL)
{
strcpy(strArray[i], token);
printf("[%s]\n", token);
token = strtok(NULL, " ");
i++;
}
}
int main(int argc, char const *argv[]) {
char *command = "This is my best day ever";
parsing(command); //SPLIT WITH " " put them in an array - etc array[0] = This , array[3] = best
return 0;
}
Here it is my code, is there any simply way to solve it? By the way my code is not working. Im new at coding C language and i dont know how can i handle it :( Help
A:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *strArray[40];
void parsing(const char *string){//Original does not change
int i = 0;
strArray[i++] = strdup(string);//make copy to strArray[0]
char *token = strtok(*strArray, " ");
while(token != NULL && i < 40 - 1){
strArray[i++] = token;
//printf("[%s]\n", token);
token = strtok(NULL, " ");
}
strArray[i] = NULL;//Sentinel
}
int main(void){
char *command = "This is my best day ever";
parsing(command);
int i = 1;
while(strArray[i]){
printf("%s\n", strArray[i++]);
}
free(strArray[0]);
return 0;
}
int parsing(char *string){//can be changed
int i = 0;
char *token = strtok(string, " ");
while(token != NULL && i < 40){
strArray[i] = malloc(strlen(token)+1);//Ensure a memory for storing
strcpy(strArray[i], token);
token = strtok(NULL, " ");
i++;
}
return i;//return number of elements
}
int main(void){
char command[] = "This is my best day ever";
int n = parsing(command);
for(int i = 0; i < n; ++i){
printf("%s\n", strArray[i]);
free(strArray[i]);
}
return 0;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Sequence $(x_n)_{n \in \mathbb{N}}$ that is not a cauchy-sequence, but $(x_{n+1}-x_n)$ a null sequence
I'm learning about cauchy sequences which is why I want to know if someone could give me a sequence $(x_n)_{n \in \mathbb{N}}$ that is not a cauchy-sequence, but $(x_{n+1}-x_n)_{n \in \mathbb{N}}$ a null sequence?
A:
Classic example
$$ x_n = \sum_{j=1}^n \frac{1}{j}.$$
It does not converge, is thus not a Cauchy-sequence, but $x_{n+1}-x_n=\frac{1}{n+1}$ is a Cauchy sequence.
| {
"pile_set_name": "StackExchange"
} |
Q:
I need some good expressions for someone who has just been back from a cemetery
It was almost two years ago where I first met Bob (nickname). Bob was my new classmate. He looked very sad and I tried to ask him what had happened. He told me that someone in his family passed away.
so, I said "I am very sorry to hear that".
He is a good man, becasue he often goes to the cemetery to clean the headstone. on the other hand, it often made me helpless and nervous when I met him, because my English is weak. I was afraid of asking him where he had just been, because he would definitely tell me he had just went back from the cemetery.
I want to comfort him, but What could I say to him when he told me he had just been back from the cemetery?
I would probably not say, "oh, Bob, you are a good man.", this would make him think I as an ironic speaker.
Can you help me?
A:
There is nothing wrong with saying You are a good man.
After he's told you he's been to the cemetery, you could open up the conversation by saying I see you've gone there often. You must really miss whomever. What were they like? Sometimes it is good to get the bereaved to recount the good memories.
What's most important is he will feel what your intention is when you talk with him. Be of good heart and good intentions.
I realize this is a sensitive subject, it's just a suggestion, please no flaming...
| {
"pile_set_name": "StackExchange"
} |
Q:
Angularjs: loop $http.post
script.js
for(var i = 0;i<$scope.data_acc_lv.length;i++)
{
var input3 = {
"_id": $scope.accLvID + i,
"acc_id":$scope.accLvID,
"name": $scope.data_acc_lv[i].names,
"read": $scope.data_acc_lv[i].read,
"execute": $scope.data_acc_lv[i].execute,
}
$http.post("http://localhost:1234/access_menu",input3)
.success(function(res){
if(res.error == 0)
{
}
});
}
script.js
app.post('/access_menu',function(req,res){
var IDMenu = req.body._id;
var Forein = req.body.acc_id;
var Name = req.body.name;
var Read = req.body.read;
var Execute = req.body.execute;
var data = {"error":1,"Access_menu":""};
if(!!Name && !!Read && !!Execute)
{
db.collection("access_menu").insert({_id:IDMenu,acc_id:Forein,name:Name,read:Read,execute:Execute},function(err,req){
if(!!err)
{
data['Acess_menu'] = "input error";
}
else
{
data['error'] = 0;
data['Access_menu'] = "input berhasil"
}
res.json(data);
});
data = {"error":1,"Access_menu":""};
}
});
so I trying to input data from table to database but I always got the value from the last index (all previous value replace by the last index value), so what the cause the problem. Thank you
A:
You can wrap the code inside the for loop in an immediately invoked function
(function( i ) {
var input3 = {
"_id": $scope.accLvID + i,
"acc_id":$scope.accLvID,
"name": $scope.data_acc_lv[i].names,
"read": $scope.data_acc_lv[i].read,
"execute": $scope.data_acc_lv[i].execute,
}
$http.post("http://localhost:1234/access_menu",input3)
.success(function(res){
if(res.error == 0)
{
}
});
})(i);
Hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
Помогите удалить класс js
Переделываю модальное окно. Есть одна кнопка с одним классом и 4 кнопки с другим классом, которые открывают одно и тоже модальное окно и добавляют себе новый класс. Открытие модального окна и присвоение класса проходит нормально. Но когда пытаюсь закрыть модалку, то модалка закрывается, а класс не удаляется. Возникает конфликток между этими строчками
if (target.className == 'popup-close') {
target.classList.remove('more-splash');
Как мне при нажатии на кнопку закрыть (close) найти кнопку с присвоенным классом и удалить его.
let overlay = document.querySelector('.overlay'),
close = document.querySelector('.popup-close');
document.addEventListener('click', function(event) {
let target = event.target;
if (target.className == 'description-btn' || target.className == 'more')
{
target.classList.add('more-splash');
overlay.style.display = "block";
document.body.style.overflow = 'hidden';
}
if (target.className == 'popup-close') {
target.classList.remove('more-splash');
overlay.style.display = "none";
document.body.style.overflow = '';
}
});
https://codepen.io/Pavlenkovik/pen/qyGopo
A:
Вероятнее всего, так:
document.getElementsByClassName('more-splash')[0].classList.remove('more-splash').
У Вас этот класс вешается не на кнопку, а на div по которому кликнули, следовательно при нажатии на Close он не может удалиться, поскольку его попросту нет.
Правленный пример:
let overlay = document.querySelector('.overlay'),
description = document.querySelectorAll('.description-btn'),
more = document.querySelector('.more'),
close = document.querySelector('.popup-close');
document.addEventListener('click', function(event) {
let target = event.target;
if (target.className == 'description-btn' || target.className == 'more') {
target.classList.add('more-splash');
overlay.style.display = "block";
document.body.style.overflow = 'hidden';
console.dir(target);
console.log(target.className);
console.log(target.classList);
}
if (target.className == 'popup-close') {
document.getElementsByClassName('more-splash')[0].classList.remove('more-splash');
overlay.style.display = "none";
document.body.style.overflow = '';
}
});
.content .info-tabcontent .description-btn {
width: 180px;
height: 45px;
line-height: 43px;
margin-top: 30px;
border: 1px solid #c78030;
font-size: 14px;
color: #c78030;
text-transform: uppercase;
font-weight: bold;
text-align: center;
font-weight: 300;
cursor: pointer;
}
.overlay {
position: fixed;
display: none;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 3;
}
.overlay .popup {
position: fixed;
z-index: 4;
left: 50%;
top: 150px;
width: 752px;
-webkit-transform: translateX(-50%);
-ms-transform: translateX(-50%);
transform: translateX(-50%);
}
.overlay .popup-close {
position: absolute;
right: -20px;
top: -35px;
cursor: pointer;
font-size: 35px;
color: #fff;
font-weight: 300;
}
.overlay .popup-title {
display: block;
width: 100%;
height: 71px;
line-height: 71px;
margin: 0;
background-color: #c78030;
color: #ffffff;
text-transform: uppercase;
font-size: 21px;
font-weight: 500;
text-align: center;
}
<div class="content">
<div class="container" id="about">
<div class="info">
<div class="info-header">
<div class="info-header-tab"></div>
<div class="info-header-tab"></div>
<div class="info-header-tab"></div>
<div class="info-header-tab"></div>
</div>
<div class="info-tabcontent fade">
<div class="description">
<div class="description-title"></div>
<div class="description-text">
</div>
<div class="description-btn">
Узнать подробнее
</div>
</div>
<div class="photo">
</div>
</div>
<div class="info-tabcontent fade">
<div class="description">
<div class="description-title"></div>
<div class="description-text"></div>
<div class="description-btn">
Узнать подробнее
</div>
</div>
<div class="photo">
</div>
</div>
<div class="info-tabcontent fade">
<div class="description">
<div class="description-title"></div>
<div class="description-text"></div>
<div class="description-btn">
Узнать подробнее
</div>
</div>
<div class="photo">
</div>
</div>
<div class="info-tabcontent fade">
<div class="description">
<div class="description-title"></div>
<div class="description-text"></div>
<div class="description-btn">
Узнать подробнее
</div>
</div>
<div class="photo">
</div>
</div>
</div>
<button class="more"> Узнать больше</button>
</div>
</div>
<div class="overlay fade">
<div class="popup">
<div class="popup-close">×
</div>
<div class="popup-title">
</div>
</div>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Which issues have you encountered due to sequence points in C and C++?
Below are two common issues resulting in undefined behavior due to the sequence point rules:
a[i] = i++; //has a read and write between sequence points
i = i++; //2 writes between sequence points
What are other things you have encountered with respect to sequence points?
It is really difficult to find out these issues when the compiler is not able to warn us.
A:
A variation of Dario's example is this:
void Foo(shared_ptr<Bar> a, shared_ptr<Bar> b){ ... }
int main() {
Foo(shared_ptr<Bar>(new Bar), shared_ptr<Bar>(new Bar));
}
which might leak memory. There is no sequence point between the evaluation of the two parameters, so not only may the second argument be evaluated before the first, but both Bar objects may also be created before any of the shared_ptr's
That is, instead of being evaluated as
Bar* b0 = new Bar();
arg0 = shared_ptr<Bar>(b0);
Bar* b1 = new Bar();
arg1 = shared_ptr<Bar>(b1);
Foo(arg0, arg1);
(which would be safe, because if b0 gets successfully allocated, it gets immediately wrapped in a shared_ptr), it may be evaluated as:
Bar* b0 = new Bar();
Bar* b1 = new Bar();
arg0 = shared_ptr<Bar>(b0);
arg1 = shared_ptr<Bar>(b1);
Foo(arg0, arg1);
which means that if b0 gets allocated successfully, and b1 throws an exception, then b0 will never be deleted.
A:
There are some ambigous cases concerning the order of execution in parameter lists or e.g. additions.
#include <iostream>
using namespace std;
int a() {
cout << "Eval a" << endl;
return 1;
}
int b() {
cout << "Eval b" << endl;
return 2;
}
int plus(int x, int y) {
return x + y;
}
int main() {
int x = a() + b();
int res = plus(a(), b());
return 0;
}
Is a() or b() executed first? ;-)
A:
Here is a simple rule from Programming principles and practices using c++ by Bjarne Stroustup
"if you change the value of a variable in an expression.Don't read or
write twice in the same expression"
a[i] = i++; //i's value is changed once but read twice
i = i++; //i's value is changed once but written twice
| {
"pile_set_name": "StackExchange"
} |
Q:
How to detach firestore listener
I'm new to FireStore. I created a ListenerRegistration to update my Recycler View. I know my implementation may not be perfect, but every time my activity got destroyed, my app throws an error on the lines that are inside this Listener. I don't know why, but mt registration.remove() is not working before on destroy or after finish() activity. Can someone help?
public class MainActivity extends AppCompatActivity {
private ListenerRegistration registration;
private com.google.firebase.firestore.Query query;
private void requestPacienteList(){
FirebaseFirestore db = FirebaseFirestore.getInstance();
progress.setVisibility(View.VISIBLE);
query = db.collection("Hospital");
registration = query.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
for(DocumentSnapshot documentSnapshot : documentSnapshots){
if(documentSnapshot.get("nome").equals("Santa Clara")){
hospital = documentSnapshot.toObject(Hospital.class);
hospital.setHospitalDocumentKey(documentSnapshot.getId());
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("Hospital")
.document(hospital.getHospitalDocumentKey())
.collection("Pacientes")
.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
homeModelList.clear();
for(DocumentSnapshot documentSnapshot : documentSnapshots){
final Paciente paciente = documentSnapshot.toObject(Paciente.class);
paciente.setPacienteKey(documentSnapshot.getId());
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("Pessoa")
.document(paciente.getProfissionalResponsavel())
.addSnapshotListener(new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(DocumentSnapshot documentSnapshot, FirebaseFirestoreException e) {
Profissional profissional = documentSnapshot.toObject(Profissional.class);
int[] covers = new int[]{R.drawable.ic_person_black};
HomeModel p = new HomeModel(paciente.getNome()+" "+paciente.getSobrenome(),paciente.getBox(),paciente.getLeito(),
covers[0],profissional.getNome()+ " "+profissional.getSobrenome(),paciente.getPacienteKey());
homeModelList.add(p);
homeAdapter.notifyDataSetChanged();
prepareListaPacientes();
}
});
}
}
});
}
}
}
});
switch (id){
case R.id.logout:
if(FirebaseAuth.getInstance().getCurrentUser()!=null)
FirebaseAuth.getInstance().signOut();
Intent it = new Intent(HomeActivity.this, MainActivity.class);
startActivity(it);
if(registration!=null)
registration.remove();
finish();
drawerLayout.closeDrawers();
break;
}
}
}
My onDestroy method:
@Override
protected void onDestroy() {
super.onDestroy();
registration.remove();
}
When I remove this if:
if(FirebaseAuth.getInstance().getCurrentUser()!=null)
FirebaseAuth.getInstance().signOut();
My problem is gone. But if I don't, I get the following error:
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.Object
com.google.firebase.firestore.DocumentSnapshot.toObject(java.lang.Class)'
on a null object reference
at santauti.app.Activities.Home.HomeActivity$4$1$1.onEvent(HomeActivity.java:200)
at santauti.app.Activities.Home.HomeActivity$4$1$1.onEvent(HomeActivity.java:197)
at com.google.firebase.firestore.DocumentReference.zza(Unknown Source)
at com.google.firebase.firestore.zzd.onEvent(Unknown Source)
at com.google.android.gms.internal.zzejz.zza(Unknown Source)
at com.google.android.gms.internal.zzeka.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
A:
When you use addSnapshotListener you attach a listener that gets called for any changes. Apparently you have to detach those listeners before the activity gets destroyed. An alternative is to add the activity to your call to addSnapshotListener:
db.collection("Pessoa").document(paciente.getProfissionalResponsavel())
.addSnapshotListener(MainActivity.this, new EventListener<DocumentSnapshot>() {
You'll need to update MainActivity.this to match your code.
By passing in the activity, Firestore can clean up the listeners automatically when the activity is stopped.
Yet another alternative is to use get() to get those nested documented, which just reads the document once. Since it only reads once, there is no listener to clean up.
A:
use registration.remove(); for Stop listening to changes
Query query = db.collection("cities");
ListenerRegistration registration = query.addSnapshotListener(
new EventListener<QuerySnapshot>() {
// ...
});
// ...
// Stop listening to changes
registration.remove();
see more about this : https://firebase.google.com/docs/firestore/query-data/listen#detach_a_listener
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL Social - Online Users
I've got a table
CREATE TABLE `tbl_users` (
`user_id` int(11) NOT NULL auto_increment,
`user_username` tinytext NOT NULL,
`user_password` tinytext NOT NULL,
`user_email` tinytext NOT NULL,
`user_enabled` tinyint(4) NOT NULL default '1',
`user_verified` tinyint(4) NOT NULL default '0',
`user_verified_date` datetime NOT NULL default '0000-00-00 00:00:00',
`user_signup_date` datetime NOT NULL default '0000-00-00 00:00:00',
`user_login_date` datetime default NULL,
`user_status` mediumtext NOT NULL,
`user_online` tinyint(4) NOT NULL default '0',
PRIMARY KEY (`user_id`)
)
Every time a user visits the website user_login_date updates and user_online is set to 1, which means he's online.
What query can I send to switch user_online to 0 (offline) if user's last visit was 10 minutes ago?
I've already done like that
UPDATE tbl_users SET user_online = '0' WHERE (NOW() - user_login_date) > INTERVAL 10 minute
But that didn't help.
A:
You should do the calculations on the constants so that an index on user_login_date can be used:
UPDATE tbl_users
SET user_online = '0'
WHERE NOW() - INTERVAL 10 MINUTE > user_login_date
| {
"pile_set_name": "StackExchange"
} |
Q:
Reading from multiple Db's with same Persistence Unit?
I need some help to configure several connection's to multiple db's using the same Persistence unit.
They all have the same schema. Therefore I want to use the same Persistence unit/ DAO's etc and dont want to have to setup 10 EntityManagers, 10 Persistence xml's etc. Is there a way to do this? Here is my current config:
<persistence-unit name="PersistenceUnit-c1" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.show_sql" value="${hibernate-show-sql}"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.SybaseDialect" />
<property name="hibernate.c3p0.min_size" value="${hibernate-c3p0-min-size}" />
<property name="hibernate.c3p0.max_size" value="${hibernate-c3p0-max-size}" />
<property name="hibernate.c3p0.timeout" value="${hibernate-c3p0-timeout}" />
<property name="hibernate.c3p0.max_statements" value="${hibernate-c3p0-max-statements}" />
<property name="hibernate.c3p0.idle_test_period" value="${hibernate-c3p0-idle-test-periods}" />
</properties>
<class>com.domain.TktOrder</class>
<exclude-unlisted-classes/>
</persistence-unit>
I am also using Spring/hibernate to set up my context:
<bean id="EntityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:persistenceUnitName="PersistenceUnit-c1"
p:dataSource-ref="DataSource">
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:showSql="${hibernate-show-sql}"
p:generateDdl="false"
p:databasePlatform="org.hibernate.dialect.SybaseDialect" />
</property>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
</bean>
<bean id="DataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"
p:driverClass="net.sourceforge.jtds.jdbc.Driver"
p:jdbcUrl="jdbc:jtds:sybase://url.net:port;DatabaseName=db_1"
p:user="user"
p:password="password"
/>
and finally I use:
@PersistenceContext(unitName="PersistenceUnit-c1")
public void setEntityManager(EntityManager entityManager)
{
this.entityManager = entityManager;
}
to inject my EntityManager into my DAO
How can I extend this model to be able to use db1 then change the data source and execute again for db2 etc?
Many thanks for any help in advance!
A:
After a few attempts I have found a solution that seems to fit the bill.
Please first have a look at this: dynamic-datasource-routing
This uses a few custom classes which you will need and the key class is AbstractRoutingDataSource.
This reconfigures my datasource bean like so:
<bean id="dataSource" class="com.domain.etc.etc.recon.utils.RoutingDataSource">
<property name="targetDataSources">
<map key-type="com.domain.etc.etc.recon.utils.DbType">
<entry key="C1" value-ref="C1" />
<entry key="C2" value-ref="C2" />
</map>
</property>
<property name="defaultTargetDataSource" ref="C3" />
</bean>
Where Connection one C1, C2 look like:
<bean id="parentDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
abstract="true">
<property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver" />
<property name="username" value="*******" />
<property name="password" value="*******" />
</bean>
<bean id="C1" parent="parentDataSource">
<property name="url"
value="jdbc:jtds:sybase://URL:PORT;DatabaseName=dbname" />
</bean>
<bean id="C2" parent="parentDataSource">
<property name="url"
value="jdbc:jtds:sybase://URL:PORT;DatabaseName=dbname2" />
</bean>
<bean id="C3" parent="parentDataSource">
<property name="url"
value="jdbc:jtds:sybase://URL:PORT;DatabaseName=dbname3" />
</bean>
you can inject this into the EntityManager as I have in the original Question;
<bean id="EntityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:persistenceUnitName="PersistenceUnit"
p:dataSource-ref="dataSource">
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence-.xml" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:showSql="${hibernate-show-sql}"
p:generateDdl="false"
p:databasePlatform="org.hibernate.dialect.SybaseDialect" />
</property>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
</bean>
After this you need to use your own implementation of the java classes in the link above to be able to switch between data sources. This is nothing more than renaming the classes to ones that are more meaning full to you. Linking the Enum up to C1,C2,C3 etc and finally pointing to your own dao to carry out the work.
Good Luck!
| {
"pile_set_name": "StackExchange"
} |
Q:
Ubuntu 20.04 Network printer works but scanner not detected
Samsung SCX-3405W Laster Multifunction Printer On Ubuntu 20.04.
The printer works but scanner is not detected by Document Scanner (simple-scan).
A:
I am answering my own question (which is similar to this question)
In order to make your Samsung SCX-3405W network printer print and scan, follow these steps:
;tldr
Install the Linux driver from hp.com and add tcp <printer ip> <port> to xerox_mfp.conf
FIND & DOWNLOAD THE LINUX DRIVER FOR SCX-3405W
visit https://support.hp.com/gb-en/drivers/printers
look for SCX-3405W
change OS to Linux and Ubuntu
download the basic drivers
the filename should be something like uld_V1.00.39_01.17.tar.gz
UNPACK & INSTALL THE DRIVERS
tar -zxvf uld_V1.00.39_01.17.tar.gz
cd uld
sudo ./install.sh
ADD THE PRINTER AT THE CUPS ADMIN PAGE
go to http://localhost:631/admin
click Add Printer
Under the Discovered Network Pritners there should be multiple options for the Samsung SCX-3400 Series. Choose one and click Continue.
If the Connection starts with ipp:// you have chosen the correct one. In case it does not, go back in your browser and choose another until you find the one with ipp connection. Adjust the name, location, etc. and then click continue.
In the next step review the config and click Add printer
The printer should now be available in the Settings>Printers
PRINTING TEST PAGE
Go to Settings > Printers
Click the gear icon next to the printer
Click Printing options, set what you want and click Test page in the upper left corner. It should print a page.
CHECK IF SCANNER WORKS
Open Document Scanner and see if it finds your scanner.
IF SCANNER IS NOT DETECTED
Find the IP of your printer in the Settings > Printers > Your printer > Gear icon > Printer details
Edit this config sudo nano /etc/sane.d/xerox_mfp.conf and add the following lines (I found this tip here: http://www.sane-project.org/man/sane-xerox_mfp.5.html):
# Samsung SCX-3405W, network mode
# tcp HOST_ADDR PORT
tcp <ip.of.your.printer> 9400
Log out & Log in (not sure if this is necessary)
The scanner should now be detected.
Even after all this, the simple-scan seems to be very slow in scanning. Much slower than on to what I was used to on Ubuntu 16.04. Will investigate.
| {
"pile_set_name": "StackExchange"
} |
Q:
Updating test case as PASS/FAIL in TFS using java SDK
How to update a test case as PASS/FAIL in TFS given the test case ID and suite ID using java SDK? I have searched and found out I need to use the rest API. But could anyone share the code or share a link from where I can learn how to use it? Thanks a lot in advance.
A:
After go through the latest version of JAVA SDK (Download page for TEE 2015), there's no related method and API by using Java SDK to modify tests and update the test results in TFS.
To use Rest Api for updating Test Case results. You need to use
Update test results for a test run
You could call TFS rest API using postman for a test. Sample request fail a case as below:
PATCH https://fabrikam-fiber-inc.visualstudio.com/Defaultcollection/Fabrikam-Fiber-TFVC/_apis/test/runs/26/results?api-version=3.0-preview
Content-Type: application/json
[
{
"id": 100000,
"state": "Completed",
"outcome": {
enum { Failed}
},
]
If you haven't already with Rest API, look at the information on getting started with these APIs.
To use REST API to connect to TFS from Java code, you need to use HttpClient
A sample list git repos using Java Client code call rest api:
private void getRequest() throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY,
new NTCredentials("user", "password", "workstation", "domain"));
HttpHost target = new HttpHost("tfs.web.com", 8080, "http");
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
HttpGet httpget = new HttpGet("/tfs/CollectionName/ProjectName/_apis/git/repositories/repo-name");
CloseableHttpResponse response1 = httpclient.execute(target, httpget, context);
try {
HttpEntity entity1 = response1.getEntity();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
response1.close();
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Issue with android development kit
I installed the ADK (android development kit) in eclipse. The install went perfect for me.
When I try to set the SDK path I get the following message:
Unable to create the selected preference page.
An error occurred while automatically activating bundle com.android.ide.eclipse.adt (1182).
I installed the adk 5 times already, and installed it again with the same result.
Previously I installed an older ADK version, but Eclipse told me to update my ADK to develop for android 4.1.
Anyone know what is going on?
A:
Does your Eclipse installation contain the necessary parts of the JDT (for Java editing) and WST (for XML editing)? I guess so from your update story, but just making sure.
Are you on a 64 bit version of Windows or are you on Linux and use a non Sun JRE? In both cases you might run into trouble with the keystore that is used by the ADT. You might want to try a 32 bit JRE on Windows or the Sun6 JRE on Linux.
Besides that, could you please open the error log view, search the entry with the error message from your posting and double click it. It should then show a stack trace indicating what went wrong in the Eclipse code in more detail. If you have more error entries with the same time stamp (+/- 1 second) directly below or above that one, those might also be interesting.
Last thing: Are you sure that Eclipse itself is executed on a reasonable new Java version? (Some older version of the ADT broke if run on Java 1.4). You can check this in the About dialog.
| {
"pile_set_name": "StackExchange"
} |
Q:
HighCharts Stock Chart error code 18
I am trying to add series to my chart application using gwt-highchart (using the latest gwt-highchart 1.6.0 and Highstock 2.3.4 versions). Everything seems fine until the third series. When I try to add the third one I got this error:
com.google.gwt.core.client.JavaScriptException: (String)
@org.moxieapps.gwt.highcharts.client.BaseChart::nativeAddSeries(Lcom/google/gwt/core
/client/JavaScriptObject;Lcom/google/gwt/core/client/JavaScriptObject;ZZ)([JavaScript
object(4953), JavaScript object(5135), bool: true, bool: true]): Highcharts error #18:
www.highcharts.com/errors/18
And here is my code (runs within a loop):
// Create a new serie with a new yAxis
Series newSeries = chart.createSeries().setYAxis(index).setPlotOptions(new LinePlotOptions().setColor(tag.getColor()));
// Set new yAxis options
chart.getYAxis(index).setPlotLines(chart.getYAxis(index).createPlotLine().setValue(0).setWidth(1).setColor(tag.getColor())).setLabels(new YAxisLabels().setEnabled(false)).setTickLength(0).setOffset(60).setStartOnTick(false)
.setEndOnTick(false).setGridLineWidth(0).setMaxPadding(DEFAULT_YAXIS_MAX_PADDING).setMinPadding(DEFAULT_YAXIS_MIN_PADDING)
.setAxisTitle(new AxisTitle().setText(null).setStyle(new Style().setColor(tag.getColor())));
// Add the serie to the chart
chart.addSeries(newSeries.setName("Test " + index));
First two series are OK as I said before but third one throws the above exception (when I debug the application, I can see the newly created yAxis references).
Here is the line which throws the exception:
chart.addSeries(newSeries.setName("Test " + index));
Thanks
A:
I've figured it out finally!
GWT-HighCharts seems to be the problem. It does not add the new YAxis to the Chart at all. So you must add YAxis via native calls like this;
private static native void nativeAddAxis(JavaScriptObject chart, JavaScriptObject axisOptions, boolean isX, boolean redraw, boolean animationFlag) /*-{
chart.addAxis(axisOptions, isX, redraw, animationFlag);
}-*/;
Just call this native method before adding the new series.
// Create new series
Series newSeries = chart.createSeries().setYAxis(index);
newSeries.setPlotOptions(new LinePlotOptions().setColor(tag.getColor()));
newSeries.setName(index + 1 + ") ");
// Create a new YAxis
YAxis yAxis = chart.getYAxis(index).setPlotLines(chart.getYAxis(index).createPlotLine().setValue(0).setWidth(1).setColor(tag.getColor())).setLabels(new YAxisLabels().setEnabled(false)).setTickLength(0).setOffset(60)
.setStartOnTick(false).setEndOnTick(false).setGridLineWidth(0).setPlotLines().setMaxPadding(DEFAULT_YAXIS_MAX_PADDING).setMinPadding(DEFAULT_YAXIS_MIN_PADDING)
.setAxisTitle(new AxisTitle().setText(null).setStyle(new Style().setColor(tag.getColor())));
// IMPORTANT!: New YAxis must be added to the chart via native calls since gwt-highcharts wrapper doesn't do that properly!
nativeAddAxis(chart.getNativeChart(), yAxis.getOptions().getJavaScriptObject(), false, false, false);
// Physical attach
chart.addSeries(newSeries);
| {
"pile_set_name": "StackExchange"
} |
Q:
Testing list equivalency by including properties in nested lists using Fluent Assertions
Is there a way to assert the equivalency of two lists of objects by properties located in a nested list? I know you can test equivalency with ShouldAllBeEquivalentTo() and Include() only certain properties, but I would like to call Include() on a property defined in a nested list:
class A
{
public B[] List { get; set; }
public string SomePropertyIDontCareAbout { get; set; }
}
class B
{
public string PropertyToInclude { get; set; }
public string SomePropertyIDontCareAbout { get; set; }
}
var list1 = new[]
{
new A
{
List = new[] {new B(), new B()}
},
};
var list2 = new[]
{
new A
{
List = new[] {new B(), new B()}
},
};
list1.ShouldAllBeEquivalentTo(list2, options => options
.Including(o => o.List.Select(l => l.PropertyToInclude))); // doesn't work
A:
Currently there isn't an idiomatic way to achieve this, but the API is flexible enough to do it, albeit in a more clumpsy way.
There is an open issue about this problem, which also lists some solutions.
With the current API (version 5.7.0), your posted example can be asserted by only including the property List, and then excluding properties ending with "SomePropertyIDontCareAbout".
var list1 = new[]
{
new A
{
SomePropertyIDontCareAbout = "FOO",
List = new[]
{
new B()
{
PropertyToInclude = "BAR",
SomePropertyIDontCareAbout = "BAZ"
},
}
},
};
var list2 = new[]
{
new A
{
SomePropertyIDontCareAbout = "BOOM",
List = new[]
{
new B()
{
PropertyToInclude = "BAR",
SomePropertyIDontCareAbout = "BOOM"
},
}
},
};
// Assert
list1.Should().BeEquivalentTo(list2, opt => opt
.Including(e => e.List)
.Excluding(e => e.SelectedMemberPath.EndsWith(nameof(B.SomePropertyIDontCareAbout))));
| {
"pile_set_name": "StackExchange"
} |
Q:
Not showing coredata framework in linked frameworks and libraries in Xcode 6.3
I am trying to add CoreData.Framework to my application but it is not showing in in linked frameworks and libraries.
please some one help me to get coreDta back to my Xcode 6.3
A:
Xcode 6 uses modules, so Apple frameworks do not need to be explicitly linked. You can just import the framework to use it.
Modules are much better than old frameworks where an import statement copies the entire header over.
| {
"pile_set_name": "StackExchange"
} |
Q:
I'm trying to sort and set a string to see if it matches the alphabet. If yes i want to return True but it returns False
import string
def ispangram(str1, alphabet=string.ascii_lowercase):
return ''.join(sorted(set(str1.lower()))) == alphabet
ispangram("The quick brown fox jumps over the lazy dog")
the output of the ''.join(sorted(set(str1.lower()))) is 'abcdefghijklmnopqrstuvwxyz '
there is a space in the end and this is why it's not matching the alphabet string and returning false.
how can i fix it ? i'm new to this language so I probably don't have the skillset to solve it, it might be very simple so thanks for the helpers :)
A:
The thing it seems that you really want to know is if every element in alphabet is in the string. If the string can contain punctuation and spaces, you probably don't want those interfering with your test. What you can do is a set of the test string and alphabet and see if the test string set is a superset of the alphabet using the >= operator
import string
def ispangram(str1, alphabet=string.ascii_lowercase):
return set(str1.lower()) >= set(alphabet)
ispangram("The brown quick fox jumps over the lazy dog")
# true
ispangram("The brown (quick) fox jumps over the lazy dog?")
#true
ispangram("The quick fox jumps over the lazy dog")
#false
This has the added benefit of avoiding the sort.
| {
"pile_set_name": "StackExchange"
} |
Q:
groovy script to delete artifacts on nexus 3 (not nexus 2)
i have nexus 3 server that i save artifacts on it, and it has been filled to max.
i wish to create a task to delete the old artifacts every day but always remain with at least 50 artifacts. the problem is that the default task that should do it, does't work.
so i read that it can be done with a groovy script that i schedule to run inside tasks.
can anyone help me with it? i can't find anything useful on the internet.
A:
based on @daniel-schröter answer you could add a Scheduled Task following this example:
Go to System -> Tasks and click Create Task. Create a script task:
Set the language to groovy and copy this script modified to fit to scheduled task (you should provide your own modifications to it, it's just an example):
import org.sonatype.nexus.repository.storage.Component
import org.sonatype.nexus.repository.storage.Query
import org.sonatype.nexus.repository.storage.StorageFacet
log.info("delete components for repository: my-repo")
def compInfo = { Component c -> "${c.group()}:${c.name()}:${c.version()}[${c.lastUpdated()}]}" }
def repo = repository.repositoryManager.get("my-repo")
StorageFacet storageFacet = repo.facet(StorageFacet)
def tx = storageFacet.txSupplier().get()
tx.begin()
Iterable<Component> components = tx.findComponents(Query.builder().where('last_updated < ').param('2190-01-01').build(), [repo])
tx.commit()
tx.close()
log.info("about to delete " + components.flatten(compInfo))
for(Component c : components) {
log.info("deleting " + compInfo(c))
tx2 = storageFacet.txSupplier().get()
tx2.begin()
tx2.deleteComponent(c)
tx2.commit()
tx2.close()
}
log.info("finished deleting " + components.flatten(compInfo))
| {
"pile_set_name": "StackExchange"
} |
Q:
setting java classpath for Libre Office Base in Fedora 16
using Fedora 16 OS. i want to use Libre Office Base to connect to MySQL. when i set up the JDBC connection, it asks me for the driver, however, it cannot be loaded (because it doesn't see it in the classpath).
does anybody know how to set the classpath for Libre Office? is there like a config util tool for that?
e.g. my driver is [B]com.mysql.jdbc.Driver [/B]situated in[B] /usr/share/java/mysql-connector-java-5.1.17.jar[/B]. it works fine when i connect from other JDBC clients, like straight Java or Eclipse Quantum plugin. the problem is that Libre Office does not ask me for the (class)path of where it can find the driver and i do not know where and how to set it so that it becomes visible.
thanks
A:
This is old but Libre Office does not honor CLASSPATH. You have to close Base, open writer and add the /usr/share/java/mysql-connector-java-5.1.17.jar jar file on menu:
Tools > Options > Java, hit the "Class Path" button and add the jar in the dialog that pops up.
Close writer, open Base and your driver have to be recognized.
| {
"pile_set_name": "StackExchange"
} |
Q:
Prove that $\lim_{L\rightarrow\infty} P\left(\sup_{0\leq s\leq t}|B(s)|>L\right)=0$, for each $t\geq0$, where $B$ standard Brownian motion.
Let $B(t)$, $t\geq0$, be a standard Brownian motion. I would like to prove that
$$\lim_{L\rightarrow\infty} P\left(\sup_{0\leq s\leq t}|B(s)|>L\right)=0,$$
for each $t\geq0$.
In my class notes, I have the following proof: since $\sup_{0\leq s\leq t}|B(s)|$ has the same probability distribution as $|B(t)|$, then
$$P\left(\sup_{0\leq s\leq t}|B(s)|>L\right)=P(|B(t)|>L), $$
and by Chebyshev's inequality, that probability is bounded by $L^{-1} E(|B(t)|)$, which tends to $0$ as $L\rightarrow\infty$.
I do not understand why $\sup_{0\leq s\leq t}|B(s)|$ has the same probability distribution as $|B(t)|$. I know that $\sup_{0\leq s\leq t}B(s)$ (with no absolute value) possesses the same probability distribution as $|B(t)|$, but this is not the same statement. Could you please elaborate on this? Thank you!
A:
You are correct in your doubts. $\sup_{s<t}|B_s|$ does not have the same distribution as $|B_t|$, so your notes have a mistake.
One way around this; you can write
$$
\sup_{0<s<t}|B_s|=\max\left(\sup_{0<s<t}B_s,\sup_{0<s<t}-B_t\right)
$$
and then the event the LHS is more than $L$ is the union of the events that both arguments of the RHS are more than $L$. Therefore, $P(\sup_{0<s<t}|B_s|>L)\le 2P(|B_t|>L)$.
However, there is an even easier proof. For any (finite) random variable $X$, we have $\lim_{L\to\infty}P(X>L)=0$. This follows from continuity of probability, since the events $\{X>L\}$ decrease to the empty set as $L\to\infty$.
| {
"pile_set_name": "StackExchange"
} |
Q:
"Aquí" and "acá" regional differences
In Spain I learned aquí, allí, allá, but in Costa Rica it all seems to become acá. Am I not remembering the Castellano correctly or does this differentiation not exist in Latin America?
A:
"Aquí" and "Acá" have the same meaning. The same for "Allí" and "Allá".
We use "Aquí/Acá" when you're talking about a position near to you, or maybe your own position. In the other hand, "Allí/Allá" is for pointing a position far from you.
For example:
Aquí/Acá fue donde lo vi por última vez.
Esta silla de aquí/acá es de hace 5 años.
Vamos a comer allá/allí
Ese de allá/allí es a quien buscas
A:
In Spain acá is not typically used. So you probably learned the Spanish from Spain where we use aquí, allá and allí as you said.
I believe the word acá is very common in Latin America countries, and has the same meaning as aquí.
| {
"pile_set_name": "StackExchange"
} |
Q:
How does the effect "Counter target spell" work?
There is an instant card called "Cancel" with this effect and also a creature whose name I forgot. I don't really understand the effect of "counter target spell" and how (and when) to use this card.
I tried to use it against an instant card from my opponent, but apparently "counter target spell" doesn't destroy the enemy instant which I thought would happen...
Could someone please explain how this card is used?
A:
When you "Counter" a spell it essentially never happens. This can only be done during the time the spell is being cast.
A spell that is countered is put into the graveyard instead of doing its effect.
In Magic the Gathering, everything but land is a spell. So whether your opponent is playing a creature, instant, sorcery, enchantment, etc. it can be countered.
As far as why your specific counter did not work, perhaps you targeted the wrong card? Or maybe your opponent used a counter on your Cancel (countering your counter). Another reason could be that the spell specifically cannot be countered. It is also possible that you attempted to counter first and the instant was play on the stop of the stack, meaning it resolves first. In order to know for sure, we would need to know what spell the opponent was playing as well as anything on the field.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unreachable statement instantiating an instance of a fragment class inside of fragment
I have a fragment called ProfilePicBtn and Im trying to load it in my fragment class called HomeFragment. But when I try and instantiate an instance of ProfilePicBtn I get an error saying unreachable statement. Note Im trying to follow the developer docs here.
package com.example.adam.hilo;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.app.Fragment;
import android.view.View;
import android.view.ViewGroup;
public class HomeFragment extends Fragment {
public HomeFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home, container, false);
Fragment profileBtnFragment = new ProfileBtnFragment();
}
}
A:
This code has an unconditional return statement before the line which allocates the new ProfileBtnFragment. So the second line is unreachable.
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP fwrite error
I'm stuck. Been trying to fix this. The example is almost identical to the teachers... I don't get it.... The html is here. Its simple setup for a schedule. It won't write to the file correctly. Help?
EDIT: It won't write the variables to the file. I can get it to write text, just not the variables. Hope that clarifies.
<?php
/* Create folder for data */
if (is_dir('schedule'))
chdir('schedule');
else
{mkdir('schedule');
chdir ('schedule');}
/* Variable Declaration */
/* Employee 1 */
$sunStart1=$_POST['sunStart1'];
$sunEnd1=$_POST['sunEnd1'];
$monStart1=$_POST['monStart1'];
$monEnd1=$_POST['monEnd1'];
$tuesStart1=$_POST['tuesStart1'];
$tuesEnd1=$_POST['tuesEnd1'];
$wedStart1=$_POST['wedStart1'];
$wedEnd1=$_POST['wedEnd1'];
$thurStart1=$_POST['thurStart1'];
$thurEnd1=$_POST['thurEnd1'];
$friStart1=$_POST['friStart1'];
$friEnd1=$_POST['friEnd1'];
$satStart1=$_POST['satStart1'];
$satEnd1=$_POST['satEnd1'];
/* Employee 2 */
$sunStart2=$_POST['sunStart2'];
$sunEnd2=$_POST['sunEnd2'];
$monStart2=$_POST['monStart2'];
$monEnd2=$_POST['monEnd2'];
$tuesStart2=$_POST['tuesStart2'];
$tuesEnd2=$_POST['tuesEnd2'];
$wedStart2=$_POST['wedStart2'];
$wedEnd2=$_POST['wedEnd2'];
$thurStart2=$_POST['thurStart2'];
$thurEnd2=$_POST['thurEnd2'];
$friStart2=$_POST['friStart2'];
$friEnd2=$_POST['friEnd2'];
$satStart2=$_POST['satStart2'];
$satEnd2=$_POST['satEnd2'];
/* Make data file */
$schedule = fopen('schedule.txt', 'w');
fwrite($schedule, "$sunStart1\n");
fwrite($schedule, "$sunEnd1 \n");
fwrite($schedule, "$monStart1 \n");
fwrite($schedule, "$monEnd1 \n");
fwrite($schedule, "$tuesStart1 \n");
fwrite($schedule, "$tuesEnd1 \n");
fwrite($schedule, "$wedStart1 \n");
fwrite($schedule, "$wedEnd1 \n");
fwrite($schedule, "$thurStart1 \n");
fwrite($schedule, "$thurEnd1 \n");
fwrite($schedule, "$friStart1 \n");
fwrite($schedule, "$friEnd1 \n");
fwrite($schedule, "$satStart1 \n");
fwrite($schedule, "$satEnd1 \n");
fwrite($schedule, "$sunStart2 \n");
fwrite($schedule, "$sunEnd2 \n");
fwrite($schedule, "$monStart2 \n");
fwrite($schedule, "$monEnd2 \n");
fwrite($schedule, "$tuesStart2 \n");
fwrite($schedule, "$tuesEnd2 \n");
fwrite($schedule, "$wedStart2 \n");
fwrite($schedule, "$wedEnd2 \n");
fwrite($schedule, "$thurStart2 \n");
fwrite($schedule, "$thurEnd2 \n");
fwrite($schedule, "$friStart2 \n");
fwrite($schedule, "$friEnd2 \n");
fwrite($schedule, "$satStart2 \n");
fwrite($schedule, "$satEnd2 \n");
fclose ($schedule);
?>
A:
Your forms method is not syntaxed correctly...
You have
<form action="lab5.php" method"POST">
It should be
<form action="lab5.php" method="POST">
Plus your form structure is also not correct...
I would place the <form> before the <table> and subsequenctly end </form> after </table>
| {
"pile_set_name": "StackExchange"
} |
Q:
Toggle instead of Hover function jQuery
I want to repeat the same process everytime I click on the class specified in the code. It was working on hover function but when I switched to click function, it does the job one time only. and it's not repeatable.
Also I switched to clickToggle and it does not work. Any thoughts?
var sidebarFloat = $('.sidebar').css('float');
$('.sidebar').hover(function() {
sidebarFloat = $(this).css('float');
if (sidebarFloat == 'right') {
$(this).stop().animate({
left: "0px"
}, 500)
} else if (sidebarFloat == 'left') {
$(this).stop().animate({
left: "0px"
}, 500)
}
}, function() {
var width = $(this).width() - 10;
if (sidebarFloat == 'right') {
$(this).stop().animate({
left: +width
}, 500);
} else if (sidebarFloat == 'left') {
$(this).stop().animate({
left: -width
}, 500);
}
});
A:
The jquery hover() function takes two functions as parameters: handleIn and HandleOut.
Click does not.
As a result you will have to track the state of the click using a separate variable.
For example:
var sidebarFloat = $('.sidebar').css('float');
var toggled = false;
$('.sidebar').click(function() {
if (toggled) {
sidebarFloat = $(this).css('float');
if (sidebarFloat == 'right') {
$(this).stop().animate({
left: "0px"
}, 500)
} else if (sidebarFloat == 'left') {
$(this).stop().animate({
left: "0px"
}, 500)
}
} else {
var width = $(this).width() - 10;
if (sidebarFloat == 'right') {
$(this).stop().animate({
left: +width
}, 500);
} else if (sidebarFloat == 'left') {
$(this).stop().animate({
left: -width
}, 500);
}
}
toggled = !toggled;
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Cannot add providers in Hermes JMS
Following the guide here I have added the Active Mq Jars to providers list:
But Hermes Jms does not show the Active Mq connection factory:
I have tried restarting Hermes Jms but that doesn't help.
A:
I believe your problem is that you need to change the Loader dropdown in the middle section of the Session screen from System to ActiveMQ. I have the setup steps documented in a word doc and can send them to you if you send me your email address. (my id is [email protected]) The instructions were originally written for Weblogic, but you can take basically the same steps and modify slightly for ActiveMQ.
The gist is
create your context for ActiveMQ
then when you create the session, the ConnectionFactory loaded needs to be switched to ActiveMQ from System. This allows Hermes to find the active mq connection factory. By doing that, now Hermes can find the ActiveMQ connection factory options. See my screenshot below.
Hope this helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
Cmd+Tab does not work on hidden or minimized windows
When I want to switch between windows using ⌘ Cmd + ⇥ Tab it does not work with hidden or minimized windows. I can see the icons of these windows in the application switcher but choosing them does nothing. How can I get this to work again?
A:
This one is a bit tricky :
press ⌘ Cmd + ⇥ Tab to show your running apps. Keep holding ⌘ Cmd.
press ⇥ Tab until you've selected the app
press the ⌥ Option, and let go of the ⌘ Cmd. ( You must release ⌘ Cmd after pressing ⌥ Option ! )
A:
Use ⌘ Cmd-Tab to cycle to the desired application and then, while still holding down ⌘ Cmd, press the ↑ or ↓ arrow. This will show the application's windows in Expose. Select the desired window with the arrow keys and press Return to activate it.
http://www.macworld.com/article/1152366/commandtabminimizedwindows.html
A:
Try this:
On your Mac,
Navigate to System Preferences
Go to Mission Control
Uncheck "When switching to an application, switch to a Space with open windows for the application"
Try using the cmd+tab now.
| {
"pile_set_name": "StackExchange"
} |
Q:
Bit rate in function of radio frequency
I would like to transmit data over the ionosphere with a specific frequency (that will enable the radio waves to bounce on the ionosphere), this frequency might be about 30 MHz. I am wondering how much data will I be able to transfer with this frequency ?
A:
To calculate this you can use the Shannon–Hartley theorem.
$$C = B \log_2 \left( 1+\frac{S}{N} \right) $$
where
C is the channel capacity in bits per second; B is the bandwidth
of the channel in hertz (passband bandwidth in case of a modulated
signal); S is the average received signal power over the
bandwidth (in case of a modulated signal, often denoted C, i.e.
modulated carrier), measured in watts (or volts squared); N is the
average noise or interference power over the bandwidth, measured in
watts (or volts squared); and S/N is the signal-to-noise ratio
(SNR) or the carrier-to-noise ratio (CNR) of the communication signal
to the Gaussian noise interference expressed as a linear power ratio
(not as logarithmic decibels).
In a simple case, your maximum bandwidth will be the frequency you use. More likely it will be whatever frequency you modulate your signal at.
If your system were perfect, that would also be your channel capacity. But, it won't be perfect, ever. There will be noise and signal loss, more than you want.
You'll have to give more information about your system before you can get a reasonable first cut of your actual channel capacity.
To address your follow up question:
As an engineer, I like to draw straight lines and pretend they're close enough to the real world. For a situation like this, where a whole mess of small (and a few large) losses come into play, I would make a Fermi estimate.
I understand that's not easy. One of the biggest problems for aspiring engineers is they're not willing to just guess. This prevents them from moving forward, likely failing, and returning to make a better guess. Just get some paper and sit down in a place where you can make some noise and say "eehhuuhhhmm, fifty-six... ish?". Write that down. Now calculate it. Does it make any sense? Use whatever information you have; if your calculations show that you can set up your own radio station with some AA batteries then get a new piece of paper.
In the end the system you're trying to model is really complex; clearly, it depends on undulating ionospheric plasma and the time of day. You'll likely be able to guess your values within an order of magnitude, which might be enough information to get you to start building something.
A:
I can't tell you how much the ionosphere will reflect back your signal so you'll need to do some digging to find that out. What I can help you with is the generally accepted formula for free-space transmissions namely link loss - this is how many dBs of attenuation you could expect theoretically if two antennas were communicating in free-space. The formula is: -
Link Loss (dB) = 32.5 + 20\$log_{10}\$(F) + 20\$log_{10}\$(d)
where F is MHz and d is distance between the two antennas (kilo metres).
Your transmit distance is 8000 km (at 30 MHz) and these numbers give a link loss of 32.5dB + 29.5dB + 78dB = 140dB. Put another way, if your transmitter power is 1 watt (30 dBm), you could expect a power of -110 dBm at your receiving antenna.
How much power does your receiver require? There is another generally accepted formula that states: -
Power required in dBm is -154dBm + 10\$log_{10}\$(data rate) dBm
So, if your data rate is 1k bits/second, you should be able to adequately receive (with reasonably low error rates) a power of -124 dBm.
So far, at 8000 km you should be able to receive -110 dBm from a 1 watt transmitter and for a 1kbps transmission your receiver needs a minimum of -124 dBm. This implies you have 14dB in-hand but, anyone working in radio will tell you that's not enough for continued all day long reception and that something like 30dB margin is more acceptable.
However, you are targeting ionospheric conditions being right and are probably not 100% bothered about really decent continuous data at low bit error rates so maybe it's enough.
Improvements can be made by using directional antennas but at 30 MHz you are probably going to use dipoles at each end and these will give you a slight increase in margin of about 3dB. Higher power transmissions are also one area that could improve things.
Good luck.
| {
"pile_set_name": "StackExchange"
} |
Q:
Database per tenant approach, single or multiple database server(s)?
I'm tasked with investigating the different approaches for multitenancy.
Currently I'm expanding my demo application to use the database per tenant approach.
Now where I'm getting unsure is that in a single database server application you're able to create multiple database structures with their own schemas and now I'm wondering what the database per tenant refers to:
Actual database servers running on different ports.
or
Database structures within a single database server.
A:
I'm wondering what the database per tenant refers to
It can refer to both, there is nothing like "one and only" correct definition of that term.
But if you ask which if the two approaches to prefer, my recommendation is to design your client application in a way the database name and server it connects to is freely configurable. Then start with the most simple solution which the chosen DBMS stack allows, on a single server hardware, and when it turns out this does not meet your requirements any more (in performance or security), then you pick a more complex solution.
TLDR; don't overthink this - think big, start small.
| {
"pile_set_name": "StackExchange"
} |
Q:
Neat alternatives to __defineGetter__?
Getters and setters are a beauty in VB.Net:
Get
Return width
End Get
Set(ByVal value As Integer)
width = value
End Set
In Javascript, this is probably what we would do:
function Test() {
var width = 100;
this.__defineGetter__("Width", function() {
return width;
});
this.__defineSetter__("Width", function(value){
width = value;
});
}
It looks like a plate of spaghetti ransacked by a kuri. What are some neater alternatives we have?
Note: The new code should access the value using new Test().Width and not new Test().Width().
A:
With ES5 you'll be able to do:
function Test() {
var a = 1;
return {
get A() { return a; },
set A(v) { a = v; }
};
}
The getter/setter functions can of course do anything you want them to.
A:
Here's a clean(er) alternative (also for older script engines):
function Test() {
var a=1;
return { A: { toString: function(){return a;} } };
}
alert(Test().A); //=> 1
Mind you, you can't use it to define private/static complex structures. You can only 'get' strings or numbers (so immutable variables) with this pattern. Maybe the pattern can be enhanced using json.
[edit] Using json, you can also create a getter this way for objects:
function Test() {
var a=1,
b = {foo:50, bar:100};
return {
A: { toString: function(){return a;} }
foobar: { toString: function(){return JSON.stringify(b);} }
};
}
var foobar = JSON.parse(Test().foobar);
alert(foobar.foo); //=> 50
A:
In Ecmascript5, the 'clean' (and standards compliant) way of doing this is with defineProperty.
function Test() {
var a = 1;
Object.defineProperty(this, "A", {get : function() {
return a;
},
enumerable : true});
}
This assumes that you just want to see how to define a getter. If all you want to do is make instances of Test immutable (a good thing to do where you can), you should use freeze for that:
function Test() {
this.a = 1;
Object.freeze(this);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Ошибка «No SLF4J providers were found» при установке SLF4J в Maven
Пытаюсь через Maven подключить это логирование!
Вот мой pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>groupId</groupId>
<artifactId>projekt1</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.0-alpha1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.3</version>
</dependency>
</dependencies>
</project>
Вылетает постоянно эта ошибка:
SLF4J: No SLF4J providers were found.
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#noProviders for further details.
Может что то еще нужно подключить помимо в Maven?
A:
В сообщении об ошибке дается ссылка на документацию: http://www.slf4j.org/codes.html#noProviders
Там написано, что нужно обязательно подключить реализацию логгера:
Placing one (and only one) of slf4j-nop.jar slf4j-simple.jar, slf4j-log4j12.jar, slf4j-jdk14.jar or logback-classic.jar on the class path should solve the problem.
Раз у Вас уже используется log4j-api, то, думаю, нужно добавить зависимость slf4j-log4j12 в POM:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>2.0.0-alpha1</version>
</dependency>
Для того чтобы работал log4j нужно будет создать файл конфигурации (log4j.properties).
| {
"pile_set_name": "StackExchange"
} |
Q:
What is wrong with this Fourier transform? (in python)
As people who have read my previous posts on this site could tell, I have been trying to implement a PDE solver that uses FFT in Python. The programming part is mostly worked out, but the program produces an (very suitable for this site) overflow error (basically it grows very much until it becomes a NaN).
After ruling out all other possibilities, I pinned down the problem to the FFT and the way I am trying to do the derivatives, so I decided to test two different FFT's (numpy's fft module and the pyFFTW package) with the following code:
import pyfftw
import numpy as np
import matplotlib.pyplot as plt
def fftw_(y: np.ndarray) -> np.ndarray:
a = pyfftw.empty_aligned((N, N), dtype=np.float64)
b = pyfftw.empty_aligned((N, N//2+1), dtype=np.complex128)
fft_object = pyfftw.FFTW(a, b, axes=(0, 1), direction='FFTW_FORWARD', flags=('FFTW_MEASURE',), threads=12)
y_hat = fft_object(y)
return y_hat
def ifftw_(y_hat: np.ndarray) -> np.ndarray:
a = pyfftw.empty_aligned((N, N//2+1), dtype=np.complex128)
b = pyfftw.empty_aligned((N, N), dtype=np.float64)
fft_object = pyfftw.FFTW(a, b, axes=(0, 1), direction='FFTW_BACKWARD', flags=('FFTW_MEASURE',), threads=12)
y = fft_object(y_hat)
return y
def func(x: np.ndarray, y: np.ndarray) -> np.ndarray:
return np.exp(x)*np.sin(y)
dx = 0.02
x = np.arange(-1, 1, dx)
y = np.arange(-1, 1, dx)
X, Y = np.meshgrid(x, y)
N = len(x)
kxw, kyw = np.meshgrid(np.fft.rfftfreq(N, dx), np.fft.fftfreq(N, dx))
Lapw = -4*np.pi**2*(kxw**2+kyw**2)
kxnp, kynp = np.meshgrid(np.fft.fftfreq(N, dx), np.fft.fftfreq(N, dx))
Lapnp = -4*np.pi**2*(kxnp**2+kynp**2)
z = func(X, Y)
lap_z_w = ifftw_(Lapw*fftw_(z))
lap_z_np = np.fft.ifft2(Lapnp*np.fft.fft2(z))
lap_z_np_mag = np.abs(lap_z_np)
lap_z_np_ang = np.angle(lap_z_np)
plt.imshow(z, cmap='plasma')
plt.colorbar()
plt.savefig("f.png", dpi=200)
plt.clf()
plt.imshow(lap_z_w, cmap='plasma')
plt.colorbar()
plt.savefig("Lap_fftw.png", dpi=200)
plt.clf()
plt.imshow(lap_z_np_mag, cmap='plasma')
plt.colorbar()
plt.savefig("Lap_np_mag.png", dpi=200)
plt.clf()
plt.imshow(lap_z_np_ang, cmap='plasma')
plt.colorbar()
plt.savefig("Lap_np_ang.png", dpi=200)
plt.clf()
Here the np.ndarray's named Lapw and Lapnp are what I thought should do the discrete Laplacian. And the function I chose, eˣsin(y), is a harmonic function, so its Laplacian should be zero.
But the results from the program are very far from this expected value. In Particular I get:
The original function f
The "Laplacian" of f with pyFFTW
The magnitude and phase of the "Laplacian" of f with Numpy
Looking at the values of these plots (please do note the range in the colorbar and the fact that 20000 is not any kind of decent approximation to 0) makes it clear why the program I made is giving an overflow, but I don't know how to correct this. Any help would be greatly appreciated.
A:
The mistake here is that your assumptions about your function are not correct. e^x sin(y) might seem harmonic, but you only calculated it for -1 < x,y < 1. The fft will implicitly continue it periodically, i.e. you get discontinuities at all the edges of your function. If the function is not continuous, it's not harmonic and especially you get divergences in the Fourier transfom. This is what makes your FFT diverge at the edges. Besides that, "far away" from the edges, the results look as expected.
| {
"pile_set_name": "StackExchange"
} |
Q:
Change meta tags according to current route in Aurelia app
I'm just learning Aurelia and I was wondering if there's something equivalent to ngMeta for Aurelia or maybe I can just put the aurelia-app custom attribute on the html tag instead of the body so meta tags can be changed according to the current route?
Something like:
<html aurelia-app>
<head>
<meta name="description" value="${site_description}">
<title>${site_title}</title>
</head>
<body>
</body>
</html>
A:
In aurelia you can change page title by special command on activate event:
activate(params, routeConfig){
routeConfig.navModel.setTitle(this.someData);
}
If you want to change meta tags then you can use jquery
import $ from 'jquery';
export class SampleModel{
attached(){
$('meta[name=description]').remove();
$('head').append( '<meta name="description" content="this is new">' );
}
}
More solutions in javascript: Is it possible to use javascript to change the meta-tags of the page?
| {
"pile_set_name": "StackExchange"
} |
Q:
Change color of a Flex 4 spark Button
Is there an easy way to change the background color of a Flex 4 spark Button without messing with skins?
UPDATE: ok, figured it out, simply set the chromeColor attribute of the Button mxml.
A:
For spark components, you can use chromeColor style:
<s:Button chromeColor="0xff0000" label="chrome red"/>
| {
"pile_set_name": "StackExchange"
} |
Q:
How would someone implement mathematical formulae in Java?
How would someone implement mathematical formulae in Java?
What I mean, the user inputs a string with multiple variables. Like a simple quadratic formula: x^2 + 5x + 10. Or in Java: (Math.pow(x,2)) + (x * 5) + 10. The user would then enter that and then the program would solve for x. I will be using the BeanShell Interpreter class to interpret the string as an equation. But how would I solve for x?
A:
This is a hard problem, unless you restrict yourself to simple equation types.
Here are some links for you to chase:
Wikipedia page on Computer Algebra Systems
Wikipedia Comparison of Computer Algebra Systems.
Trawling through the second link, I spotted 3 open-source Java systems.
| {
"pile_set_name": "StackExchange"
} |
Q:
Windows CE, .NET - how to get CPU ticks or current time in (micro) milliseconds?
I would like to test how difficult are lines of code I wrote. I need to know how long (or how many CPU ticks) it takes to complete them.
I use Windows CE, compact .NET framework 2, VB.NET 2005
On Google and here I found only solutions that work on desktop Windows, not mobile. I tried following:
Private Declare Function GetTickCount Lib "kernel32" () As Long
'and
Private Declare Function GetTickCount Lib "coredll.lib" () As Long
Dim lngStart As Long = GetTickCount() 'did not work
System.Diagnostics.Stopwatch ' does not exist
System.DateTime.Now() ' resolution only seconds I need at least milliseconds
System.Environment.TickCount ' same as Now()
(DateTime.Now-new DateTime(1970,1,1)).TotalMilliseconds ' only seconds
... and much more. Nothing worked.
Can you help please?
A:
The GetTickCount API returns a DWORD, which is a 32-bit integer. That corresponds to a managed Integer not a Long so that's explains the P/Invoke failure.
DateTime.Now just calls the GetSystemTime API which, in every CE device I've used since back in the 2.0 days, did not have millisecond resolution. Now the OEM of any device could give it ms resolution, but I've never seen it (well I saw it once in an OS that I built for a customer who specifically wanted it). A resonable workaround can be found here.
Environment.TickCount calls the GetTickCount API, which typically returns milliseconds since the processor started, with a wrap at something like 22 days. It is not processor ticks. It is much slower.
Some devices support a higher-resolution counter, which can be queried by P/Invoking QueryPerformanceFrequency and QueryPerformanceCounter to get (obviously) the frequency and current value. This often has a hns (hundreds of nanoseconds) resolution. Though if you're concerned about things at this level, I might begin to question your choice of managed code. At any rate, an example for this can be found here.
If you're looking at code performance and the CF then this article, while a bit old, is still valid and informative.
EDIT
Since you mentioned the Stopwatch class in your question:
There's an implementation of the Stopwatch class that works with CF 1.0 and CF 2.0 in the old 1.x SDF source code. You can download the full (free) 1.4 source here (bottom middle of the page).
| {
"pile_set_name": "StackExchange"
} |
Q:
Programatically select a node in a SmartGWT treegrid
I have a smartgwt treegrid, which, when expanding a group, I need to automatically select the first childnode of that group. I can get to the child, but I fail to see how to select the node.
TreeGrid moduleTree = new TreeGrid();
final Tree tree = new Tree();
moduleTree.addFolderOpenedHandler(new FolderOpenedHandler() {
public void onFolderOpened(FolderOpenedEvent event) {
TreeNode[] children = tree.getChildren(event.getNode());
if (children.length > 0) {
// TODO
}
}
});
Any Ideas?
Thanks!
A:
you can select a particular TreeNode using this property of TreeGrid:
treeGrid().selectRecord(record);
treeGrid().selectRecords(records);
Here record is the TreeNode you want to be selected. You can select multiple TreeNodes using the second property.
| {
"pile_set_name": "StackExchange"
} |
Q:
\footnote doesn't work with \twocolumn
I am writing an article and need footnotes to write author affiliations. I am writing in a two-column format, and using \twocolumn, but adding \footnote inside this environment doesn't produce a footnote at the bottom. See this example:
\documentclass[10pt,twocolumn]{article}
\begin{document}
\twocolumn[
\begin{center}
Author\footnote{This doesn't work.}
\end{center}
]
Text\footnote{This works.}
\end{document}
What am I doing wrong?
A:
You can use \footnotemark and \footnotetext{}:
\documentclass[10pt,twocolumn]{article}
\begin{document}
\twocolumn[
\begin{center}
Author\footnotemark
\end{center}
]\footnotetext{Now this works.}
Text\footnote{This works.}
\end{document}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to handle pre-set value in Flex Combobox as selected item
I'm facing a pretty basic but irksome problem with my Flex program.
To make the long story short, I've a DataGrid where in every row (you can already add and remove rows dinamically) there's a Combobox based on an ArrayCollection of elements (responsabili), every change to the Combobox already stores changes to the db.
I want the Combobox to show the value loaded from the db as the selected value.
<s:Panel title="qqq" width="100%" height="100%" styleName="light">
<s:layout>
<s:VerticalLayout paddingBottom="10" paddingLeft="10" paddingRight="10" paddingTop="10" />
</s:layout>
<s:VGroup width="100%" height="100%">
<mx:Text text="www" />
<components:GraphicButton styleName="add" toolTip="Aggiungi elemento" id="aggCompito" click="aggCompito_clickHandler(event)"/>
<s:DataGrid width="100%" height="100%" dataProvider="{MyModel.instance.compiti}" editable="true" gridItemEditorSessionSave="changeHandler(event)">
<s:columns>
<s:ArrayList>
<s:GridColumn headerText="Responsabile" editable="false" width="180">
<s:itemRenderer>
<fx:Component>
<s:GridItemRenderer>
<fx:Script>
<![CDATA[
import it.aaa.frontend.model.MyModel;
import mx.binding.utils.ChangeWatcher;
import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.core.FlexGlobals;
import mx.events.CloseEvent;
import mx.events.IndexChangedEvent;
import spark.events.IndexChangeEvent;
protected function changeHandler(event:IndexChangeEvent):void {
data.responsabile = myResponsabile.selectedItem;
// TODO Auto-generated method stub
data.tipo = event.newIndex;
dispatchEvent(new Event("compitiChange", true));
}
protected function responsabililabelFunc(item:Object):String {
return String(item.cognome) + " " + String(item.nome);
}
protected function guessSelectedItem(item:Object):int {
return item.responsabile.id;
}
]]>
</fx:Script>
<s:HGroup>
<s:ComboBox id="myResponsabile"
dataProvider="{MyModel.instance.responsabili}"
change="changeHandler(event)"
labelFunction="responsabililabelFunc"
selectedItem="{data.responsabile}"
/>
</s:HGroup>
</s:GridItemRenderer>
</fx:Component>
</s:itemRenderer>
</s:GridColumn>
</s:ArrayList>
</s:columns>
</s:DataGrid>
</s:VGroup>
</s:Panel>
MyModel.as
public var responsabili:ArrayCollection; //initialized with actual ArrayCollection of "responsabili", with id, cognome, nome.
A:
It will only work with selectedItem="{data.responsabile}" if you are using some actionscript classes as your data object and the property resposabile is marked as bindable:
[Bindable] public var responsabile:Object;
If you have just some generic objects as data, you will need to catch this up where data is set in your itemrenderer. So your GridItemRenderer needs another method:
override public function set data(value:Object):void
{
super.data = value;
// only do something if the data is set. When the renderer is destroyed the data will be null
if (data)
{
myResponsabile.selectedItem = data.responsabile;
}
}
I don't remember though if the data is set after all components (including your combobox) has been created or before that. So in case you will get a null pointer exception because myResponsabile is null at this point, it will get more complicated:
private var _myResponsabile:Object;
private var _myResponsabileChanged:Boolean;
override public function set data(value:Object):void
{
super.data = value;
// only do something if the data is set. When the renderer is destroyed the data will be null
if (data)
{
_myResponsabile = data.responsabile;
_myResponsabileChanged = true;
invalidateProperties();
}
}
override protected function commitProperties():void
{
super.commitProperties();
if(_myResponsabileChanged)
{
_myResponsabileChanged = false;
myResponsabile.selectedItem = _myResponsabile;
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Enumerator behavior changes based on how we reference it?
Wrapping a reference to the list's enumerator inside a class seems to change its behavior. Example with an anonymous class:
public static void Main()
{
var list = new List<int>() { 1, 2, 3 };
var an = new { E = list.GetEnumerator() };
while (an.E.MoveNext())
{
Debug.Write(an.E.Current);
}
}
I would expect this to print "123", but it only prints zero and never terminates. The same example with a concrete class:
public static void Main()
{
var list = new List<int>() { 1, 2, 3 };
var an = new Foo()
{
E = list.GetEnumerator()
};
while (an.E.MoveNext())
{
Debug.Write(an.E.Current);
}
}
public class Foo
{
public List<int>.Enumerator E { get; set; }
}
What's going on?
A:
I tested it and for me it does not work with your concrete class either.
The reason is that List<T>.Enumerator is a mutable struct and an.E is a property.
The compiler generates a backing field for each auto-property like this:
public class Foo
{
private List<int>.Enumerator _E;
public List<int>.Enumerator get_E() { return E; }
public void set_E(List<int>.Enumerator value) { E = value; }
}
A struct is a value-type, so every-time you access an.E you get a copy of that value.
When you call MoveNext() or Current, you call it on that copy and this copy is mutated.
The next time you access an.E to call MoveNext() or Current you get a fresh copy of the not-yet-iterated enumerator.
And an.E.Current is 0 instead of 1 because - again - you get a fresh enumerator that MoveNext() was not yet called upon.
If you want to store a reference of the list's enumerator you could declare your class Foo with a property of type IEnumerator<int>:
public class Foo
{
public IEnumerator<int> E { get; set; }
}
If you assign E = list.GetEnumerator(); now, the enumerator gets boxed and a reference instead of a value is stored.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why am I getting jinja2.exceptions.TemplateSyntaxError: unexpected '}'
I can't figure-out why this error occuring,
{% block body %}
<!-- Content -->
<div class="container">
<div class="row">
<div class="col-lg-12">
<br>
<div class="header"><h3>Ongoing Matches</h3></div>
<br>
<h3>{{ datestring_today }}</h3>
<br>
<script src="//www.cricruns.com/widget/widget_livebar.js" type="text/javascript"></script>
<! --summary---->
<div class="list-group">
{% for game in gamest %}
{% if game[]}
<a class="score-size text-xs-center nounderline list-group-item list-group-item-action" >
<div class="row">
<div class="col-xs-4">
{% if game["Batting_team_img"] %}
<img class="team-logo" src="/static/{{ game["Batting_team_img"] }}">
{% endif %}
{{ game["Batting team"] }} {{ game["runs10"] }}
</b>
<br>
{{ game["wickets10"] }}
</div>
<div class="col-xs-4 broadcast-column">
<div class="final-text">
{{ game["status2"] }}
</div>
<div class="broadcaster">
{{ game["series2"] }}
</div>
</div>
<div class="col-xs-4">
{% if game["Bowling_team_img"] %}
<img class="team-logo" src="/static/{{ game["Bowling_team_img"] }}">
{% endif %}
{{ game["Bowling team"] }} {{ game["runs20"] }}
</b>
<br>
{{ game["wickets20"] }}
</div>
</div>
</a>
{% endfor %}
</div>
</div>
</div>
<br></br>
<div class="row">
<div class="col-lg-12">
<table class="standings-datatable table table-sm">
<thead>
<tr class="bg-primary text-white">
<th class="text-lg-center">Match Type</th>
<th class="bg-danger text-lg-center">Series</th>
<th class="bg-dark text-lg-center">Team vs Team</th>
<th class="bg-info text-lg-center">Status</th>
<th class="bg-light text-lg-center">Batting </th>
<th class="bg-primary text-lg-center">Runs</th>
<th class="bg-secondary text-lg-center">Wickets</th>
<th class="bg-success text-lg-center">Overs</th>
<th class="bg-transparent text-lg-center">Batsman Name</th>
<th class="bg-warning text-lg-center">Batsman Score</th>
<th class="bg-transparent text-lg-center">Batsman Name</th>
<th class="bg-warning text-lg-center">Batsman Score</th>
<th class="bg-transparent text-lg-center">Bowler Name</th>
<th class="bg-warning text-lg-center">Bowler Wickets</th>
<th class="bg-transparent text-lg-center">Bowler Name</th>
<th class="bg-warning text-lg-center">Bowler Wickets</th>
</tr>
</thead>
<tbody>
{% for game in gamest %}
<tr class="table table-bordered">
<td >{{ game['matchtype2'] }}</td>
<td>{{ game['series2'] }}</td>
<td>{{ game['teams2'] }}</td>
<td>{{ game['status2'] }}</td>
<td>{{ game['Batting team'] }}</td>
<td>{{ game['runs10'] }}</td>
<td>{{ game['wickets10'] }}</td>
<td>{{ game['overs10'] }}</td>
<td>{{ game['name1'] }}</td>
<td>{{ game['runs1'] }}</td>
<td>{{ game['name2'] }}</td>
<td>{{ game['runs2'] }}</td>
<td>{{ game['name5'] }}</td>
<td>{{ game['wickets5'] }}</td>
<td>{{ game['name6'] }}</td>
<td>{{ game['wickets6'] }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<br></br>
<table class="standings-datatable table table-sm">
<thead class="thead-inverse">
<tbody>
<tr>
<th class="bg-dark text-lg-left">TEAM</th>
<th class="bg-dark text-lg-center">M</th>
<th class="bg-dark text-lg-left">W</th>
<th class="bg-dark text-lg-left">L</th>
<th class="bg-dark text-lg-left">T</th>
<th class="bg-dark text-lg-left">N/R</th>
<th class="bg-dark text-lg-left">PT</th>
<th class="bg-dark text-lg-left">NRR</th>
<th class="bg-dark text-lg-left">FOR</th>
<th class="bg-dark text-lg-left">AGAINST</th>
</tr>
</thead>
{% for key in tabledata %}
<tr>
<td>{{ key['Sydney image'] }}</td>
<td>{{ key['Sydney Thunder M'] }}</td>
<td>{{ key['Sydney Thunder For'] }}</td>
<td>{{ key['Sydney Thunder PT'] }}</td>
<td>{{ key['Sydney Thunder W'] }}</td>
<td>{{ key['Sydney THunder AGAINST'] }}</td>
<td>{{ key['Sydney THunder N/R'] }}</td>
<td>{{ key['Sydney THunder L'] }}</td>
<td>{{ key['Sydney THunder T'] }}</td>
<td>{{ key['Sydney THunder NRR'] }}</td>
</tr>
<tr>
<td>{{ key['Brisbane image'] }}</td>
<td>{{ key['Brisbane Heat M'] }}</td>
<td>{{ key['Brisbane Heat For'] }}</td>
<td>{{ key['Brisbane Heat PT'] }}</td>
<td>{{ key['Brisbane Heat W'] }}</td>
<td>{{ key['Brisbane Heat AGAINST'] }}</td>
<td>{{ key['Brisbane Heat N/R'] }}</td>
<td>{{ key['Brisbane Heat L'] }}</td>
<td>{{ key['Brisbane Heat T'] }}</td>
<td>{{ key['Brisbane Heat NRR'] }}</td>
</tr>
<tr >
<td>{{ key['Adelaide strikers image'] }}</td>
<td>{{ key['Adelaide Strikers M'] }}</td>
<td>{{ key['Adelaide Strikers For'] }}</td>
<td>{{ key['Adelaide Strikers PT'] }}</td>
<td>{{ key['Adelaide Strikers W'] }}</td>
<td>{{ key['Adelaide Strikers AGAINST'] }}</td>
<td>{{ key['Adelaide Strikers N/R'] }}</td>
<td>{{ key['Adelaide Strikers L'] }}</td>
<td>{{ key['Adelaide Strikers T'] }}</td>
<td>{{ key['Adelaide Strikers NRR'] }}</td>
</tr>
<tr >
<td>{{ key['Horbat Hurricanes image'] }}</td>
<td>{{ key['Horbat Hurricanes M'] }}</td>
<td>{{ key['Horbat Hurricanes For'] }}</td>
<td>{{ key['Horbat Hurricanes PT'] }}</td>
<td>{{ key['Horbat Hurricanes W'] }}</td>
<td>{{ key['Horbat Hurricanes AGAINST'] }}</td>
<td>{{ key['Horbat Hurricanes N/R'] }}</td>
<td>{{ key['Horbat Hurricanes L'] }}</td>
<td>{{ key['Horbat Hurricanes T'] }}</td>
<td>{{ key['Horbat Hurricanes NRR'] }}</td>
</tr>
<tr >
<td>{{ key['Melbourne Renegades image'] }}</td>
<td>{{ key['Melbourne Renegades M'] }}</td>
<td>{{ key['Melbourne Renegades For'] }}</td>
<td>{{ key['Melbourne Renegades PT'] }}</td>
<td>{{ key['Melbourne Renegades W'] }}</td>
<td>{{ key['Melbourne Renegades AGAINST'] }}</td>
<td>{{ key['Melbourne Renegades N/R'] }}</td>
<td>{{ key['Melbourne Renegades L'] }}</td>
<td>{{ key['Melbourne Renegades T'] }}</td>
<td>{{ key['Melbourne Renegades NRR'] }}</td>
</tr>
<tr >
<td>{{ key['Melbourne stars image'] }}</td>
<td>{{ key['Melbourne stars M'] }}</td>
<td>{{ key['Melbourne stars For'] }}</td>
<td>{{ key['Melbourne stars PT'] }}</td>
<td>{{ key['Melbourne stars W'] }}</td>
<td>{{ key['Melbourne stars AGAINST'] }}</td>
<td>{{ key['Melbourne stars N/R'] }}</td>
<td>{{ key['Melbourne stars L'] }}</td>
<td>{{ key['Melbourne stars T'] }}</td>
<td>{{ key['Melbourne stars NRR'] }}</td>
</tr>
<tr >
<td>{{ key['Perth Scorchers image'] }}</td>
<td>{{ key['Perth Scorchers M'] }}</td>
<td>{{ key['Perth Scorchers For'] }}</td>
<td>{{ key['Perth Scorchers PT'] }}</td>
<td>{{ key['Perth Scorchers W'] }}</td>
<td>{{ key['Perth Scorchers AGAINST'] }}</td>
<td>{{ key['Perth Scorchers N/R'] }}</td>
<td>{{ key['Perth Scorchers L'] }}</td>
<td>{{ key['Perth Scorchers T'] }}</td>
<td>{{ key['Perth Scorchers NRR'] }}</td>
</tr>
<tr >
<td>{{ key['Sydney Sixers image'] }}</td>
<td>{{ key['Sydney Sixers M'] }}</td>
<td>{{ key['Sydney Sixers For'] }}</td>
<td>{{ key['Sydney Sixers PT'] }}</td>
<td>{{ key['Sydney Sixers W'] }}</td>
<td>{{ key['Sydney Sixers AGAINST'] }}</td>
<td>{{ key['Sydney Sixers N/R'] }}</td>
<td>{{ key['Sydney Sixers L'] }}</td>
<td>{{ key['Sydney Sixers T'] }}</td>
<td>{{ key['Sydney Sixers NRR'] }}</td>
</tr>
{%endfor%}
</tbody>
</table>
<div class="row">
<div class="col-lg-6">
<a class="twitter-timeline" href="https://twitter.com/nikilr14/lists/hot-cric-tweets?ref_src=twsrc%5Etfw"data-aria-polite="assertive"data-chrome="noheader nofooter noborders scrollbar"data-width="500"
data-height="500">A Twitter List by nikilr14</a>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
</div>
<div class="col-lg-6">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<iframe id="youtube_video" width="600" height="340" frameborder="0" allowfullscreen></iframe>
<script>
var channelID = "UCSRQXk5yErn4e14vN76upOw";
$.getJSON('https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fwww.youtube.com%2Ffeeds%2Fvideos.xml%3Fchannel_id%3D'+channelID, function(data) {
var link = data.items[0].link;
var id = link.substr(link.indexOf("=")+1);
$("#youtube_video").attr("src","https://youtube.com/embed/"+id + "?controls=0&showinfo=0&rel=0");
});
</script>
</div>
<div class="row">
<!-- Bballbreakdown -->
<div class="col-lg-6">
{% for title, link in cricinfo_posts.items() %}
<a class="reddit-boxes nounderline list-group-item list-group-item-action" href="{{ link }}">
{{ title }} <img class="team-logo" src="/static/images/espncricinfo.png">
</a>
<br>
{% endfor %}
</div>
<!-- Fansided Nylon Calculus -->
<div class="col-lg-6">
{% for title, link in cricbuzz_posts.items() %}
<a class="reddit-boxes nounderline list-group-item list-group-item-action" href="{{ link }}">
{{ title }} <img class="team-logo" src="/static/images/cricbuzz.png">
</a>
<br>
{% endfor %}
</div>
</div>
<div class="col-lg-6">
{% for title, link in yahoonews_posts.items() %}
<a class="reddit-boxes nounderline list-group-item list-group-item-action" href="{{ link }}">
{{ title }} <img class="team-logo" src="/static/images/yahoocricnews.png">
</a>
<br>
{% endfor %}
</div>
<div class="col-lg-6">
{% for title, link in bigbash_posts.items() %}
<a class="reddit-boxes nounderline list-group-item list-group-item-action" href="{{ link }}">
{{ title }} <img class="team-logo" src="/static/images/bbl.png">
</a>
<br>
{% endfor %}
</div>
</div>
<!-- Reddit -->
<div class="row">
<div class="col-lg-6">
{% for i in range(1, 10, 2) %}
<a class="reddit-boxes nounderline list-group-item list-group-item-action" href="https://reddit.com{{ hot_Cricket_posts[i].permalink }}">
{{ hot_Cricket_posts[i].title }} <img class="team-logo" src="/static/images/reddit.png">
</a>
<br>
{% endfor %}
</div>
<div class="col-lg-6">
{% for i in range(2, 11, 2) %}
<a class="reddit-boxes nounderline list-group-item list-group-item-action" href="https://reddit.com{{ hot_Cricket_posts[i].permalink }}">
{{ hot_Cricket_posts[i].title }} <img class="team-logo" src="/static/images/reddit.png">
</a>
<br>
{% endfor %}
</div>
</div>
</div>
{% endblock %}
sorry for irregular in code structure, any improvement in the code will be appreciated, I looked every '}' in code but I didn't find any wrong syntax.I looked into jinja2 documentation, my code followed every syntax rules as mentioned in documentation yet I'm getting template syntax error, If you want to know more about the code feel free to ask, thanks.
A:
Check out these lines:
{% for game in gamest %}
{% if game[]}
...
You are missing the closing % character.
You might receive an error about game[] as well.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can Lorentz-Boosts reach every phase space point?
Given a particle with mass $m$ and four momentum $p=\left(p_x,p_y,p_z,\sqrt{|\vec{p}|^2+m^2}\right)$. Is it possible to reach every point in phase space, i.e. every combination of values $p_x,p_y,p_z\in\mathbb{R}$, by a simple Lorentz-Boost?
I'm guessing no, but don't know why.
A:
Two boosts in orthogonal directions give you a boost and a rotation, so you are free to include rotations. But actually the answer is even simpler. Since the particle is massive, start in its rest frame where $p = (0,0,0,m)$ (note that we usually put time first, but I'm using your notation). Obviously you can boost this in any direction, so by rotational symmetry we can just consider the boosts along $x$. And it should be easy to convince yourself that boosts along $x$ can give you a momentum $p = (p_x,0,0,\sqrt{p_x^2 + m^2})$ for any $p_x \in \mathbb{R}$. So the answer to your question is yes.
Note also, be careful how you use words like "phase space". Since by definition, phase space is the space of states available, the answer to your question is trivially yes. The more interesting question is whether the phase space is all of $\mathbb{R}^3$, or just a subset.
A:
Let $\vec{p}$ be the original spatial part of the four-momentum, and let $\vec{p}'$ be the desired spatial part of the four-momentum. Let us assume that for any $\vec{p}'$, there exists a boost vector $\vec{\beta}$ under which $\vec{p}$ maps to $\vec{p}'$. This will lead to a contradiction.
We can choose our coordinate system such that $\vec{\beta}$ points in the $x$-direction. We can then rotate our coordinate system about this $x$-axis such that $\vec{p}$ points in the $xz$-plane (i.e., $p_y = 0$.) Under the action of the boost $\vec{\beta}$, we must have $p'_y = 0$ as well. (Remember, we defined our coordinates such that $\vec{\beta}$ was in the $x$-direction.) But we assumed that $\vec{p}'$ could be any vector in $\mathbb{R}^3$; we therefore have a contradiction.
We conclude that a single pure boost cannot map an arbitrary spatial momentum $\vec{p}$ to another arbitrary spatial momentum $\vec{p}'$.
| {
"pile_set_name": "StackExchange"
} |
Q:
IntegrityError at /person/create/ UNIQUE constraint failed: member_person.user_id
my model:
class Person(models.Model):
name = models.CharField(max_length=250)
slug = AutoSlugField(populate_from='name')
birth_date = models.DateField(null=True, blank=True)
blood_group = models.CharField(max_length=5)
present_address = models.CharField(max_length=250, blank=True)
permanent_address = models.CharField(max_length=250, blank=True)
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
related_name='member_persons')
my views:
@require_authenticated_permission(
'member.add_person')
class PersonCreate(CreateView):
template_name = 'member/person_form.html'
model = Person
success_url = '/person/'
form_class = MemberForm
def get_form(self, form_class=None):
form = super().get_form(form_class)
form.request = self.request
return form
my form is:
class MemberForm(ModelForm):
class Meta:
model = Person
exclude = ('user',)
def clean_user(self):
user = self.cleaned_data['user']
if Person.objects.filter(user=user).exists():
raise forms.ValidationError("You already submitted data")
return user
def save(self, commit=True):
person = super().save(commit=False)
if not person.pk:
person.user = get_user(self.request)
if commit:
person.save()
self.save_m2m()
return person
It worked fine for first instance of person but when I tried to submit member form again with different data it gives following integrity error:
Traceback:
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/db/backends/utils.py" in execute
64. return self.cursor.execute(sql, params)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py" in execute
337. return Database.Cursor.execute(self, query, params)
The above exception (UNIQUE constraint failed: member_person.user_id) was the direct cause of the following exception:
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapper
67. return bound_func(*args, **kwargs)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/utils/decorators.py" in bound_func
63. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapper
67. return bound_func(*args, **kwargs)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/utils/decorators.py" in bound_func
63. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/views/generic/base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/views/generic/edit.py" in post
217. return super(BaseCreateView, self).post(request, *args, **kwargs)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/views/generic/edit.py" in post
183. return self.form_valid(form)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/views/generic/edit.py" in form_valid
162. self.object = form.save()
File "/home/ohid/test_venv/persontest/member/forms.py" in save
37. person.save()
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/db/models/base.py" in save
796. force_update=force_update, update_fields=update_fields)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/db/models/base.py" in save_base
824. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/db/models/base.py" in _save_table
908. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/db/models/base.py" in _do_insert
947. using=using, raw=raw)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/db/models/manager.py" in manager_method
85. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/db/models/query.py" in _insert
1045. return query.get_compiler(using=using).execute_sql(return_id)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in execute_sql
1054. cursor.execute(sql, params)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/db/backends/utils.py" in execute
79. return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/db/backends/utils.py" in execute
64. return self.cursor.execute(sql, params)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/db/utils.py" in __exit__
94. six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/utils/six.py" in reraise
685. raise value.with_traceback(tb)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/db/backends/utils.py" in execute
64. return self.cursor.execute(sql, params)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py" in execute
337. return Database.Cursor.execute(self, query, params)
Exception Type: IntegrityError at /person/create/
Exception Value: UNIQUE constraint failed: member_person.user_id
I know it is the causes of my model's field:
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
related_name='member_persons')
I want to show messages of "You already submitted data" in member creation form rather than getting this error. Could anybody suggest the way how could I achieve this.
Edit:
form template:
{% extends parent_template|default:"member/base_member.html" %}
{% load crispy_forms_tags %}
{% load i18n %}
{% block body %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-md-7">
<div class="panel panel-default">
<div class="panel-body">
<form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form|crispy }}
<div class="form-group">
<div class="col-sm-offset-6 col-sm-6">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
person-list template:
{% extends parent_template|default:"member/base_member.html" %}
{% load crispy_forms_tags %}
{% block body %}
{% if perms.member.add_person %}
<div class="page-header">
<div class="row">
<div class="col-sm-3 ">
<a class="btn btn-primary" href="{% url 'member:person-list' %}">View All Member</a>
</div>
<a class="btn btn-primary pull-right" href="{% url 'member:person-create' %}"><i class="icon-plus icon-white"></i> Add New Member</a>
</div>
</div>
{% endif %}
<div class="container-fluid">
<div class="row ">
<div style="overflow-x:auto;">
<div class="col-sm-8 col-md-9">
<h3>Members List</h3>
{% if persons %}
<table>
<tr>
<th>sl.</th>
<th>Name and Position</th>
<th>Photo</th>
<th>Organisation & Address</th>
<th>Contact</th>
</tr>
{% for person in persons %}
<tr>
<td>{{forloop.counter}}.</td>
<td><a href="{{person.get_absolute_url}}">
{{person.name}}
</a></td>
<td>{{person.birth_date}}</td>
<td>
{{person.blood_group}}<br>
{{person.present_address}}
</td>
{% if user.pk == person.user.pk or user.is_superuser %}
<td>
<a href="{{person.get_update_url}}">
<button type="button" class="btn btn-primary btn-sm">
<span class="glyphicon glyphicon-pencil">Update</span>
</button></a>
</td>
{% endif %}
<td><a href="{{person.get_delete_url}}">
<button type="submit" class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-trash">Delete</span>
</button>
</a></td>
</tr>
{% endfor %}
</table>
{% else %}
<p>No person in the list.</p>
{% endif %}
</div>
</div>
</div>
</div>
{% endblock %}
A:
Because you excluded user from fields it doesn't run your clean_user method. You can use clean form method instead. And field error
class MemberForm(ModelForm):
class Meta:
model = Person
exclude = ('user', )
def clean(self):
user = get_user(self.request)
if Person.objects.filter(user=user).exists():
self.add_error('name', "You already submitted data")
return self.cleaned_data
def save(self, commit=True):
...
| {
"pile_set_name": "StackExchange"
} |
Q:
Use water or milk in a tart crust?
I'm making a toffee apple tart that has a shortbread pastry as its crust, and the author of the recipe says you can use milk or water in the crust. Which would be better? Or do they each have their own strengths and weaknesses?
A:
They are technically two different pastries. Shortcrust pastry made with water is called pâte a foncer, 'lining pastry'. Shortcrust pastry made with milk is called pâte brisée. Pâte brisée typically contains a bit more butter, and is generally lighter and flakier than pâte a foncer, which is conversely crisper and firmer.
So it's up to you really; both are very similar. The pâte brisée is more delicate, so if you have a 'heavy' filling, say, lots of fruits, it might be better to go with the foncer.
| {
"pile_set_name": "StackExchange"
} |
Q:
React Hooks to Implement Counter
I'm trying to use React hooks (useState & useEffect) in a component to show a vote count. After the user clicks up/down the 'vote' state should be increment or decremented and then the app makes an API call to PATCH the "votes" count in the database. The original vote count is coming from props passed from the parent component. But for some reason, the initial state for the votes is always 0 -- even though when I console.log the props it shows the correct number of votes?
PATCH request seems to be working fine, but something with hooks I think is wrong. Thanks in advance for any help I can get on this!
export default function Votes(props) {
const { item, voteCount, itemType } = props
const [votes, setVotes] = useState(voteCount || 0)
useEffect(() => {
if (itemType == 'question') {
questionApiService.updateQuestionFields({
questionId: item.id,
questionFields : { votes: `${votes}` }
})
} else if (itemType === 'answer') {
console.log('answer')
// questionApiService.updateAnswerFields({
// answerId: item.id,
// answerFields: { votes: votes }
//})
}
}, [votes])
const handleClick = e => {
e.currentTarget.id === "increment"
? setVotes(prevCount => prevCount + 1)
: setVotes(prevCount => prevCount - 1)
}
return (
<div className="QuestionPage__votes-count">
<button id="increment" onClick={handleClick}>
<FontAwesomeIcon icon={faCaretUp} size="2x" />
</button>
{votes}
<button id="decrement" onClick={handleClick}>
<FontAwesomeIcon icon={faCaretDown} size="2x" />
</button>
</div>
)
}
A:
You need to add itemType to the dependencies of useEffect, since you can't expect the prop to be available on the very first render, or to remain static throughout the component lifecycle. With your current example, the itemType referenced will always refer to its value at the very first time this function was run.
Also as others have mentioned, setting state initial value from props is a no-no. You can solve this by using a separate Effect to set state once your component receives its props:
...
const [votes, setVotes] = useState(0);
...
useEffect(() => {
setVotes(voteCount);
}, [voteCount]);
| {
"pile_set_name": "StackExchange"
} |
Q:
I am using Authorize.net payment gateway and doing transaction through Direct Post Method,is it possible to just validate card information
I am using Authorize.net payment gateway and doing the transaction through Direct Post Method where I don't get Credit card details on my server.Is there anyway where I can just validate the credit/debit card details ,I don't want to charge a customer or even if I charge minimal cost say $1 it should be refunded automatically after validation.
Following is my code :
<form id='secure_redirect_form_id' action='https://test.authorize.net/gateway/transact.dll' method='POST'>
<br />
<input type='hidden' name='x_invoice_num' value='<%=System.currentTimeMillis()%>' />
<input type='hidden' name='x_relay_url' value="${relayResponeURL}" />
<input type='hidden' name='x_login' value="${paymentModel.paymentLoginId}" />
<input type='hidden' name='x_fp_sequence' value="${sequence}" />
<input type='hidden' name='x_fp_timestamp' value="${timestamp}" />
<input type='hidden' name='x_fp_hash' value="${fingerPrint}" />
<input type='hidden' name='x_version' value='3.1' />
<input type='hidden' name='x_method' value='CC' />
<input type='hidden' name='x_type' value='AUTH_CAPTURE' />
<input type='hidden' name='x_amount' value="${paymentModel.amount}"/>
<input type='hidden' name='x_show_form' value='PAYMENT_FORM' />
<input type='hidden' name='x_test_request' value='FALSE' />
<input type='hidden' name='notes' value="${paymentModel.description}" />
<input type="hidden" name="x_address" value="${location.address1} ${location.address2}" >
<input type="hidden" name="x_city" value="${location.city}" >
<input type="hidden" name="x_state" value="${location.state}" >
<input type="hidden" name="x_email" value="${user.email}" >
<input type="hidden" name="x_email_customer" value="true" >
<input type="hidden" name="x_first_name" value="${user.firstName}" >
<input type="hidden" name="x_last_name" value="${user.lastName}" >
<input type="hidden" name="x_phone" value="${merchant.phoneNumber}" >
<input type="hidden" name="x_zip" value="${location.zipcode}" >
<input type="hidden" name="x_company" value="${merchant.companyName}" >
<input type='submit' name='buy_button' value='BUY' />
</form>
A:
You can do an AUTH_ONLY which will get authorization for the charge but never actually charge it unless you then run a CAPTURE transaction.
<input type='hidden' name='x_type' value='AUTH_CAPTURE' />
Keep in mind that effectively freezes those funds on the user's card so you need to either do it for a small amount ($0.00 if your processor supports it, or $0.01) or VOID the transaction immediately after running it.
| {
"pile_set_name": "StackExchange"
} |
Q:
click handler remains after deleting element and perform its actions multiple times
I am dynamically adding a custom component with buttons this way
function showPopup(){
var comp = '<div id="alert"><input type="button" id="proceed"><input type="button" id="close"></div>';
$('#body').append(comp);
}
To these buttons I have handlers like this
$('#close').live('click',function(){
$(this).parent().remove();
});
$('#proceed').live('click',function(){
//ajax-call
});
Now the issue is when I call the function say n times and close it and when i do a proceed now it does n ajax calls.
Any solution to this ?
Thank you
A:
You are adding multiple elements with the same id which is invalid markup. This will be causing problems for jQuery when it comes to delegating the event to the correct element. jQuery matches exactly one element when querying for an ID - see Does duplicate id's screw up jquery selectors?
Also, this demo seems to be working for me in Chrome 14.
| {
"pile_set_name": "StackExchange"
} |
Q:
Writing to SD Card in android always returning False
Hi guys i have to copy my sqlite db to downloads with the code bellow. But if (sd.canWrite()) always returning false... Im stuck on this , and yes im already added to my manifest. Im debuging on real device not the virtual one. Ty for help
private void copyDbToExternal(Context context) {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()){
String currentDBPath = "//data//data//" + context.getApplicationContext().getPackageName() + "//databases//"
+ "qamatrisdb";
String backupDBPath = "qamatrisdb";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
A:
Did you try using tutorial on Dev.Android?
http://developer.android.com/training/basics/data-storage/files.html
Example for accessing external storage:
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
$C ([1,2] \times [0,1] \to \mathbb R)$ dense in $C ( [1,2] \rightarrow L^{2} ([0,1] \to \mathbb R))$?
Let $[0,1] \subset \mathbb R$ be a the compact interval in the real numbers $\mathbb R$.
We know that $C([0,1] \to \mathbb R)$ (the continuous function on $[0,1]$ with values in $\mathbb R$) are dense in $L^{2} ([0,1] \to \mathbb R)$ (the usual Lebesgue space).
Now consider the space of continuous functions on $[1,2]$ taking values in $L^{2} ([0,1] \to \mathbb R)$ , i.e. $C ( [1,2] \rightarrow L^{2} ([0,1] \to \mathbb R))$.
Is the space $C ([1,2] \times [0,1] \to \mathbb R)$ dense in $C ( [1,2] \rightarrow L^{2} ([0,1] \to \mathbb R))$?
In other words:
Fix an arbitrary $f \in C ( [1,2] \rightarrow L^{2} ([0,1] \to \mathbb R))$.
Can we find a sequence $f_{n} \in C ([1,2] \times [0,1] \to \mathbb R)$, such that
$$\sup_{z \in [1,2]} \int_{[0,1]} ( f_{n} -f )^{2} (z,x) d x \rightarrow 0
?
$$
This question is related to this question, by a different order of the spaces.
A:
Yes. Say $f_t\in L^2[0,1]$ for $t\in[1,2]$ and $f_t$ depends continuously on $t$. Then $K=\{f_t:t\in[1,2]\}$ is a compact subset of $L^2[0,1]$.
Define $T_n:L^2[0,1]\to L^2[0,1]$ by, say, letting $T_n=f*\phi_n$, where $\phi_n$ is an approximate identity. It's easy to see that for each $n$ the function $g_n(s,t)=T_nf_t(s)$ is continuous on $[0,1]\times[1,2]$. We know $T_nf\to f$ in $L^2$ for every $f\in L^2$. And since $||T_n||\le||\phi_n||_1=1$ the family $(T_n)$ is equicontinuous on compact subsets of $L^2$. Hence $T_nf\to f$ uniformly on $K$.
??? Since the downvoter doesn't see fit to show the courtesy of explaining what he or she thinks the problem is I have to guess. There are all sorts of things above that could be read incorrectly. Take the conclusion, "Hence $T_nf\to f$ uniformly on $K$", for example. A person could think that said that a certain sequence of continuous functions on $[0,1]\times[1,2]$ converged uniformly to a discontinuous function, which would of course be absurd. But that's not what it says. $K$ is a metric space, being a subset of the metric space $L^2$. $T_n$ is a sequence of mappings from this metric space into another metric space, again $L^2$ as it happens. So saying $T_nf\to f$ uniformly on $K$ says precisely that $\sup_{t\in[0,1]}||T_nf_t-f_t||_2\to0$.
Not that I have any reason to think that that's the problem, but I suspect that whatever the problem is is based on a similar sort of incorrect reading. Can't explain the actual problem without being told what it is...
| {
"pile_set_name": "StackExchange"
} |
Q:
how to get binded drop down list while users pagging and sorting in asp.net 3.5
i have grid view which have two drop down list. so user can change drop down list value at run time. here is my grid view design code :
<asp:TemplateField HeaderText="Status" SortExpression="status_id">
<asp:TemplateField HeaderText="Status" SortExpression="status_id">
<HeaderTemplate>
<asp:LinkButton ID="lbut_sortstatus1" runat="server"
CommandArgument="status_id" CommandName="Sort" CssClass="normaltext"
Font-Bold="true" Text="Status"></asp:LinkButton>
<asp:PlaceHolder ID="placeholderstatus1" runat="server"></asp:PlaceHolder>
</HeaderTemplate>
<ItemTemplate>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:DropDownList ID="DDL_StatusList1" runat="server"
DataTextField="status_name" DataValueField="Id" AppendDataBoundItems="true"
AutoPostBack="True"
onselectedindexchanged="DDL_StatusList1_SelectedIndexChanged">
</asp:DropDownList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID ="DDL_StatusList1"
EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
</ItemTemplate>
<HeaderStyle CssClass="headinglist_bg" HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
how ever this is my Page_Load code :
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Panel_View.Visible = false;
Session["SearchtText"] = null;
Session["ColumnName"] = null;
this.FillGrid((String)Session["ColumnName"] ?? null, (String)Session["SearchtText"] ?? null);
Bind_DDL_Column_List();
Bind_DDL_Title();
Bind_DDL_Status();
Bind_DDL_Group();
Bind_DDL_Countries();
}
this.GetData();
}
and here is my one of drop down list bind method that shows how i binding grid view drop down list.
public void Bind_DDL_Group()
{
using (DataClassesDataContext db = new DataClassesDataContext())
{
var query = db.Groups.Select(g=>g).OrderBy(g=>g.Group_name).ToList();
DataSet myDataset = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Group_name", typeof(string));
foreach (var item in query)
{
DataRow dr = dt.NewRow();
dr["Id"] = item.Id.ToString();
dr["Group_name"] = item.Group_name.ToString();
dt.Rows.Add(dr);
}
myDataset.Tables.Add(dt);
DDL_GroupList.DataSource = myDataset;
DDL_GroupList.DataBind();
DropDownList bind_dropdownlist;
foreach (GridViewRow grdRow in GV_ViewUserList.Rows)
{
bind_dropdownlist = (DropDownList)(GV_ViewUserList.Rows[grdRow.RowIndex].Cells[8].FindControl("DDL_GroupList1"));
bind_dropdownlist.DataSource = myDataset;
bind_dropdownlist.DataBind();
}
}
}
however at Page load first time it's works successfully but when user clicks sorting or pagging then drop down list get empty. how ever i binds them in (!Page.IsPostBack) of Page_Load.
what I'm doing wrong here..
please help me...
A:
Please put dropdown binding code out of if(!Page.IsPostBack) condition
Because when go to another page in gridview Page will be posted back to server
and if(!Page.IsPostBack) condition will return false.
Change your code to
if (!Page.IsPostBack)
{
Panel_View.Visible = false;
Session["SearchtText"] = null;
Session["ColumnName"] = null;
this.FillGrid((String)Session["ColumnName"] ?? null, (String)Session["SearchtText"] ?? null);
Bind_DDL_Column_List();
Bind_DDL_Title();
Bind_DDL_Countries();
}
Bind_DDL_Status();
Bind_DDL_Group();
this.GetData();
| {
"pile_set_name": "StackExchange"
} |
Q:
how to concatenate string from query sql server 2005 but datatype is integer
(WATCHDOGACIDT.COMASCALEE + WATCHDOGACIDT.COMASCALEV +
WATCHDOGACIDT.COMASCALEM) AS EVM --not work
(PATIENT_NAME.FIRSTNAME +' '+ PATIENT_NAME.LASTNAME) AS Fullname --work great
but this code return summary
ex 1 + 2 + 3 i would like return 123 but return 6 thank
A:
Like this:
CAST(myIntegerVar AS varchar(50)) + ' some text etc'
so:
(CAST(WATCHDOGACIDT.COMASCALEE as varchar(1)) + CAST(WATCHDOGACIDT.COMASCALEV AS varchar(1)) + CAST(WATCHDOGACIDT.COMASCALEM AS varchar(1)) ) AS EVM
| {
"pile_set_name": "StackExchange"
} |
Q:
WebDriverWait is deprecated in Selenium 4
I'm getting a
Warning: (143,13) 'WebDriverWait(org.openqa.selenium.WebDriver, long)' is deprecated
in Selenium 4.0.0-alpha-3.
But official Selenium page lists only
WebDriverWait(WebDriver driver, Clock clock, Sleeper sleeper, long timeOutInSeconds, long sleepTimeOut)
as deprecated.
What is wrong? I'm using IntelliJ, could it be their issue?
A:
It doesn't appear in the docs, but if you look at the source code you will see @Deprecated annotation
@Deprecated
public WebDriverWait(WebDriver driver, long timeoutInSeconds) {
this(driver, Duration.ofSeconds(timeoutInSeconds));
}
In the constructor description you have the solution
@deprecated Instead, use {@link
WebDriverWait#WebDriverWait(WebDriver, Duration)}.
Which is the constructor being called from the deprecated one in any case.
new WebDriverWait(driver, Duration.ofSeconds(10));
| {
"pile_set_name": "StackExchange"
} |
Q:
Comparing and removing elements not present in a List and array java
I have one String array and one List<String>. What I want to do is to use the variable with a larger size and use that as the basis of the values removal of the smaller variable. I also want to get the values of the larger sized variable not present in the other. Note that the reason why the two variables differ on datatype is because the String[] group variable is a checkbox group from a jsp page and the List<String> existingGroup is a ResultSet from the database. For example:
String[] group contains:
Apple
Banana
Juice
Beef
List<String> existingGroup contains:
Apple
Beef
Lasagna
Flower
Lychee
And since the size of the two variables vary, it should still correctly remove the values.
What I have so far is
if(groupId.length >= existingGroup.size()) {
for(int i = 0; i < groupId.length; i++) {
if(! existingGroup.contains(groupId[i])) {
if(existingGroup.get(existingGroup.indexOf(groupId[i])) != null) {
// I'm unsure if I'm doing this right
}
}
}
} else {
for(int i = 0; i < existingGroup.size(); i++) {
// ??
}
}
Thanks.
A:
Ok, I would start with converting your array into the List too. So do
List<String> input = Arrays.asList(array);
//now you can do intersections
input.retainAll(existingGroup); //only common elements were left in input
Or, if you want elements which are not common, just do
existingGroup.removeAll(input); //only elements which were not in input left
input.removeAll(existingGroup); //only elements which were not in existingGroup left
Choice is yours:-)
A:
You can use the methods the List interface provides.
list.removeAll(Arrays.asList(array)); // Differences removed
or
list.retainAll(Arrays.asList(array)); // Same elements retained
based on your needs.
| {
"pile_set_name": "StackExchange"
} |
Q:
Remove Duplicates from List of String
I have the following List of String:
{
"Name1,Name2",
"Name2,Name1",
"Name3,Name4",
"Name4,Name3"
}
Without using any Java/C/Python/C++/C# library, I want to remove the duplicates in a way that, it prints:
Name1,Name2
Name3,Name4
One way to remove duplicates would be this:
private static boolean checkIfEquals(String str, String str1) {
HashSet<String> set1 = new HashSet<>(Arrays.asList(str.split(",")));
HashSet<String> set2 = new HashSet<>(Arrays.asList(str1.split(",")));
return set1.equals(set2);
}
A:
Using your same approach, assuming your list of strings is in a variable List<String> strings:
List<String> unique =
strings.stream()
.map(str -> new LinkedHashSet<>(Arrays.asList(str.split(","))))
.distinct()
.map(set -> set.stream().collect(Collectors.joining(",")))
.collect(Collectors.toList());
| {
"pile_set_name": "StackExchange"
} |
Q:
How to install nodejs modules in a local app directory?
I'm taking a node.js course on frontendmasters.com. In this course, which appears to be at least one or two years old, the instructor creates an application directory called 'express', cds into it, and then runs the command "npm install express". According to him, since I didn't specify the '-g' option (which would cause npm to install it globally), a node_modules directory should be created inside the express folder. And when he ran the command on his laptop, that's what happened. He says this is done so that if, for instance, you had two different apps which needed different versions of express, you could run a different version in each app's directory. This makes perfect sense.
However, when I ran the 'npm install express' command, I discovered that npm created a $HOME/node_modules/express directory rather than creating that node_modules directory below my express project directory. When I created a second app, basic2, at the same directory level as basic, I found that I didn't need to re-run the 'npm install express' command as express is still accessible via the $HOME/node_modules directory. This now means that both apps, basic and basic2 will be using the same version of express which contradicts what the instructor said.
So my question is, how does one install express (or any other module, for that matter) using npm so that the node_modules directory is created locally in one's local app directory (i.e. on a per-app basis) rather than in my $HOME directory? It appears that something about npm has changed since this video was created.
A:
Create a new folder for the app
mkdir my-app
cd my-app
Then creating a nodejs app with npm init this will ask you several kind of information like the app name version etc... This command will generate package.json
After that you can run the command npm i --save express which will add express to the package.json of your app
| {
"pile_set_name": "StackExchange"
} |
Q:
mongodb + node connection string
I'm having trouble connecting mongodb to my local machine. I'm new at this and can't seem to figure it out from the docs or other stackoverflow posts.
I have a database.js file, and I think my connection string is wrong:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost');
// I've tried this too:
// mongoose.connect('mongodb://localhost/test');
// mongoose.connect('mongodb://localhost:8080/test');
module.exports = {
'url' : 'mongodb://localhost:27017/test'
}
I've got mongod running in one tab and shows 4 connections open - I don't know if it's this or the connection string.
Then in a 2nd tab, I've connected to a db called "test".
Lastly there's a very simple view. When I navigate to localhost:8080 (where process.env.PORT || 8080 is pointing to in server.js), it doesn't connect.
A:
Here is configuration file
{
"db": {
"connection": "mongodb://localhost",
"name": "testdb"
}
}
Here is usage in code:
var dbUrl = config.get('db:connection') + '/' + config.get('db:name');
var db = mongoose.connection;
mongoose.connect(dbUrl, function(err) {
//your stuff here
});
Hope, it helps.
P.S. Could you please provide how you catch no connection to db?
| {
"pile_set_name": "StackExchange"
} |
Q:
R - convert JSON to desired format
My dataframe currently looks like this:
df$name <- c("Person A","Person B","Person C")
df$count <- c(50,100,150)
Using toJSON from the jsonlite package produces an array that does not preserve the numeric class of the count variable.:
toJSON(as.matrix(df))
[["Person A","50"],["Person B","100"],["Person C","150"]]
I fully recognize this is because converting df to a matrix requires all data to be of the same class. Instead, I would like the classes preserved such that name is preserved as a string and count is preserved as numeric, like so:
[["Person A",50],["Person B",100],["Person C",150]]
For some context, I'd like to be able to feed the JSON output externally to Google Charts (not through googleVis). Suggestions and help are so greatly appreciated- I've tried a number of things and can't quite seem to yield the product I need. Thanks!
A:
You should transform your data.frame to a paired list before transforming it to a json string. :
library(RJSONIO)
## use cat for better print
cat(toJSON(Map(function(x,y)list(x,y),df$name,df$count)))
[
[
"Person A",
50
],
[
"Person B",
100
],
[
"Person C",
150
]
]
| {
"pile_set_name": "StackExchange"
} |
Q:
Best Way to add group totals to a dataframe in Pandas
I have a simple task that I'm wondering if there is a better / more efficient way to do. I have a dataframe that looks like this:
Group Score Count
0 A 5 100
1 A 1 50
2 A 3 5
3 B 1 40
4 B 2 20
5 B 1 60
And I want to add a column that holds the value of the group total count:
Group Score Count TotalCount
0 A 5 100 155
1 A 1 50 155
2 A 3 5 155
3 B 1 40 120
4 B 2 20 120
5 B 1 60 120
The way I did this was:
Grouped=df.groupby('Group')['Count'].sum().reset_index()
Grouped=Grouped.rename(columns={'Count':'TotalCount'})
df=pd.merge(df, Grouped, on='Group', how='left')
Is there a better / cleaner way to add these values directly to the dataframe?
Thanks for the help.
A:
df['TotalCount'] = df.groupby('Group')['Count'].transform('sum')
Some other options are discussed here.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to hide FAB from subfragment?
Well, i have an Activity(with ViewPager and FAB)
In ViewPager there is a NotesFragment(fragment contains only RecyclerView)
And I have a Fragment calls AddNoteFragment which do the job of Adding and Showing existing Note:
1) From Activity fab opens AddNoteFragment to add note, which is logical,
2) And from RecyclerView, clicking item opens AddNoteFragment with details of clicked item
Question: how to hide FAB on Activity, when i'm opening AddNoteFragment to show exciting note correctly? The only way I know is a using interface and transfering it up, but this will look like RecyclerViewAdapter -> NotesFragment -> ViewPagerAdapter -> Activity, it looks weird..
A:
While I think using interface it's a good way to do it, you might want to take a look at EventBus (https://github.com/greenrobot/EventBus), it works similary as BroadcastReceiver, all you have to do is to wait for the event on your Activity, and hide/show it whenever you want. Below is the code you have to put on your activity:
@Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(Boolean show) {if (show){
fab.show()
}else{
fab.hide()
}};
then, whenever you want, you just have to call this
EventBus.getDefault().post(/* true or false*/);
| {
"pile_set_name": "StackExchange"
} |
Q:
Templatefield in gridview
how can i get the values stored in one column of the gridview? this is the code:
<asp:TemplateField HeaderText="Document Code" HeaderStyle-BackColor="#000099" HeaderStyle-Width="150px">
<ItemTemplate>
<asp:LinkButton runat="server" ID="doc_code" Text='<%# Eval("doc_code")%>' CommandArgument='<%#Eval("doc_id") %>'
OnCommand="editDocument" CausesValidation="false">
<span class='glyphicon glyphicon-remove'></span>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
i always get a blank value from this column i dont know how to get its values. Please help. Thanks
A:
Use Bind in place of Eval as shown in below solution.
<asp:LinkButton runat="server" ID="doc_code" Text='<%# Bind("doc_code")%>' CommandArgument='<%# Bind("doc_id") %>' OnCommand="editDocument" CausesValidation="false">
| {
"pile_set_name": "StackExchange"
} |
Q:
Linking CalendarView To Device Calendar
Is there a way to link the CalendarView widget to the built in Calendar on a mobile device? For example, when I click on any date in my CalendarView, it brings up the device's google calendar so I could set reminders and so forth.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar_date);
calendarView = (CalendarView)findViewById(R.id.calendar);
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
@Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
//Could I place the code in here?
}
});
}
A:
Try this:
// Convert your year/month/day into date-time specified in milliseconds since the epoch.
long startMillis = ...
Uri.Builder builder = CalendarContract.CONTENT_URI.buildUpon();
builder.appendPath("time");
ContentUris.appendId(builder, startMillis);
Intent intent = new Intent(Intent.ACTION_VIEW)
.setData(builder.build());
startActivity(intent);
Using intents to view calendar data | Calendar Provider | Android Developers
| {
"pile_set_name": "StackExchange"
} |
Q:
How to serve RoR JS/CSS out of nginx passenger sub_uri?
Here is my config:
user nobody nobody;
worker_processes 2;
error_log /rails/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
passenger_root /usr/local/lib/ruby/gems/1.8/gems/passenger-2.2.15;
passenger_ruby /usr/local/bin/ruby;
include mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" -- "$cookie_YBY" ';
access_log /rails/nginx_access.log main;
sendfile on;
tcp_nopush on;
keepalive_timeout 65;
client_header_timeout 10m;
client_body_timeout 10m;
send_timeout 10m;
connection_pool_size 256;
client_header_buffer_size 1k;
# large headers needed for FF
large_client_header_buffers 4 8k;
request_pool_size 4k;
gzip on;
gzip_http_version 1.0;
gzip_comp_level 2;
gzip_min_length 1100;
gzip_buffers 4 8k;
gzip_types text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;
output_buffers 1 32k;
postpone_output 1460;
server {
listen 80;
server_name optisol.s0hoo.com;
client_max_body_size 50M;
#access_log /rails/access.log;
error_log /rails/smart_error.log;
root /rails/smart_ads_archive/public;
passenger_enabled on;
location ~* \.(ico|css|js|gif|jp?g|png)(\?[0-9]+)?$ {
expires max;
access_log off;
break;
}
}
}
and im running on the latest nginx, ruby on rails 2.3.5, and the latest passenger. The problem I am having is that I want to deploy to a sub_uri, so i modify the server config to have:
root /websites/rails;
passenger_base_uri /smart_ads_archive; # <--- been added.
but when I visit the page all of the css that links to /images/etc/etc/ are coming up with 404 because the rails app is sitting in the sub uri. On my shared host w/ Apache I am able to deploy rails app to sub directories in public_html without a problem and with no configuration to my rails app and with css files pointing to /images... and it just looks at the rails public/images folder.
The question: is there a setting I am missing in Rails or in Nginx? Or do I need to go find all of the /images/ references and /css/ and /js/ and manually prepend /smart_ads_archive/js.. etc.
Thanks for the help!
A:
Please read the documentation for how to use a Sub URI in Nginx/Passenger.
Short version: you need a symlink in your root to the Rails /public/ folder. Passenger_base_uri takes the name of that symlink as its parameter.
| {
"pile_set_name": "StackExchange"
} |
Q:
Redis .service file
На Ubuntu 16.04 поставил Redis по этой инструкции. Собирал через make, сконфигурил, всё работает, НО: при запуске/перезапуске через sudo service redis restart вывод строки "повисает" на некий таймаут, то есть, насколько я могу предположить, "изнутри" это работает так - после успешного запуска/перезапуска возвращается некий статус типа true, и в консоли появляется приглашение к вводу новой команды. У меня этот статус, условно говоря, не возвращается. Вывод команды sudo service redis status:
root@ubuntu-xenial:~# service redis status
● redis-server.service - Redis In-Memory Data Store
Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; vendor preset: enabled)
Active: activating (start-post) since Ср 2017-06-28 07:17:09 UTC; 14s ago
Docs: http://redis.io/documentation,
man:redis-server(1)
Process: 15864 ExecStopPost=/bin/run-parts --verbose /etc/redis/redis-server.post-down.d (code=exited, status=0/SUCCESS)
Process: 15882 ExecStartPost=/bin/run-parts --verbose /etc/redis/redis-server.post-up.d (code=exited, status=0/SUCCESS)
Process: 15878 ExecStart=/usr/local/bin/redis-server /etc/redis/redis.conf (code=exited, status=0/SUCCESS)
Process: 15874 ExecStartPre=/bin/run-parts --verbose /etc/redis/redis-server.pre-up.d (code=exited, status=0/SUCCESS)
Tasks: 3
Memory: 10.2M
CPU: 89ms
CGroup: /system.slice/redis-server.service
└─15881 /usr/local/bin/redis-server 127.0.0.1:6379
июн 28 07:17:09 ubuntu-xenial systemd[1]: Starting Redis In-Memory Data Store...
июн 28 07:17:09 ubuntu-xenial run-parts[15874]: run-parts: executing /etc/redis/redis-server.pre-up.d/00_example
июн 28 07:17:09 ubuntu-xenial redis-server[15878]: 15878:C 28 Jun 07:17:09.164 # systemd supervision requested, but NOTIFY_SOCKET not found
июн 28 07:17:09 ubuntu-xenial run-parts[15882]: run-parts: executing /etc/redis/redis-server.post-up.d/00_example
июн 28 07:17:09 ubuntu-xenial systemd[1]: redis-server.service: PID file /var/run/redis/redis-server.pid not readable (yet?) after start-post: No such file or directory
Статус activating т.е. условно говоря вот тот статус, о котором я говорил, он видимо не возвращается-таки, а без него не ставится статус active.
Как починить?
A:
Нашёл PPA для Ubuntu, из которого можно поставить корректно работающую версию Redis. Вопрос закрыт.
| {
"pile_set_name": "StackExchange"
} |
Q:
WebAudioAPI: Trigger envelope based on input
Context: I'm trying to make a 100% modular synthesizer on the web
So far, the tutorials I've seen for making envelopes used functions to trigger the different stages of the envelope, but what if I want to trigger an envelope based on the output of an AudioNode?
For example, attack on the rising edge of a square wave oscillator, and release on the falling edge?
Will I have to resort to using a script processor node (and suffer in performance) or is there a better way to do this that I haven't found out yet?
Thanks in advance
Clarification:
The input is a simple binary gate. 1 when the key is held down, 0 when it isn't.
There should be a few parameters that are AudioParams that will allow for control over attack time, decay time, sustain level and release time. It is assumed that the decay level (the peak of the ADSR envelope) is 1
The output is the ADSR envelope signal itself.
A:
Here's an alternative approach. If you had analog circuitry, you could differentiate your square wave to get a positive impulse at the leading edge and a negative impulse at the trailing edge. Feed this impulse train into an RC circuit. This would produce an attack and release phase.
In WebAudio, you can do a simple differentiator by delaying the signal one sample and subtracting it from the original. For the RC circuit, you can use a BiquadFilterNode or an IIRFilterNode to produce the desired result.
I'm not exactly sure what to do if you want a more complicated ADSR response.
| {
"pile_set_name": "StackExchange"
} |
Q:
Keyboard keeps blocking my view... how to fix it?
my keyboard keeps blocking my view. Is there anyway to fix this?
When I click the Description 2 to insert something, But the keyboard so annoying... I can't see what I'm typing... Actually This isn't one page. Others page also like this. I can't see what I'm typing, Only when I close the keyboard then okay can see the things.
Here is the code
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center|top">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="300dp"></ListView>
</LinearLayout>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="60dp"
android:layout_height="wrap_content"
android:text="DATE:" />
<TextView
android:id="@+id/Select_Date"
android:layout_width="60dp"
android:layout_height="38dp"
android:text="SELECT DATE"
android:textSize="19dp"
/>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="60dp"
android:layout_height="wrap_content"
android:text="TXN NO:" />
<TextView
android:id="@+id/D_Txn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="60dp"
android:layout_height="wrap_content"
android:text="NAME:" />
<EditText
android:id="@+id/D_Name"
android:layout_width="273dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="72dp"
android:layout_height="wrap_content"
android:text="AMOUNT:" />
<EditText
android:id="@+id/D_Amount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="110dp"
android:layout_height="wrap_content"
android:text="DESCRIPTION1:" />
<Spinner
android:id="@+id/D_Description"
android:layout_width="match_parent"
android:layout_height="35dp"
android:background="@android:drawable/btn_dropdown"
android:spinnerMode="dropdown" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="60dp"
android:layout_height="wrap_content"
android:text="DESCRIPTION2:" />
<EditText
android:id="@+id/Ds_Description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" />
</TableRow>
</TableLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:gravity="center|bottom"
android:orientation="horizontal">
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableRow>
<Button
android:textColor="@color/my_color_state"
android:id="@+id/Db_New"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="NEW" />
<Button
android:textColor="@color/my_color_state"
android:id="@+id/Db_Save"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:enabled="false"
android:text= "SAVE" />
</TableRow>
<TableRow>
<Button
android:textColor="@color/my_color_state"
android:id="@+id/Db_Print"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="PRINT" />
<Button
android:textColor="@color/my_color_state"
android:id="@+id/Db_Back"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="BACK" />
</TableRow>
</TableLayout>
</LinearLayout>
A:
In your manifest, add this line to your activity:
android:windowSoftInputMode="adjustResize"
It adjusts your activity when the available layout size changes.
EDIT:
You'll also have to add a ScrollView over the main container in your case.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I get the Rails Application controller to run a function when the server starts up?
I am working on a feature to limit the number of pages a user can access in a day. My plan is to create a class variable in the ApplicationController which is instantiated on startup. One of the features I want though is for this value to be changed by an administrator without having to worry about changing the config file, hence the class variable.
How can I have rails call a function in the application controller when rails starts up?
A:
You can't do it this way. You must operate on the presumption that your Rails application will consist of multiple independent processes with entirely arbitrary lifetimes, that is they may be spawned if needed and killed if they're idle at any time.
You're stuck having to persist this somewhere. A flat file can work if you're using a single server, but a database of some sort, SQL or otherwise, is also viable. For light loads, that is less than dozens of requests per second, SQL won't be a problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
I try to save a photo every 30 secs to temporary dir with a different name each,but it only save once
I try to save a photo every 30 secs to temporary dir with a different name each,but it only save once and give me an error
this is my error
A generic error occurred in GDI+.
stacktrace
at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
at System.Drawing.Image.Save(String filename, ImageFormat format)
at WindowsApplication1.Form1.savetempfoto() in Form1.vb:line 372
and the line error is
PB1.Save(path, System.Drawing.Imaging.ImageFormat.Bmp)
this is my code
Public Function temdirx()
My.Computer.FileSystem.CreateDirectory(tempdir)
End Function
Public Function timesavetemp()
Timer2.Start()
End Function
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
timetosavetemp = timetosavetemp + 1
If timetosavetemp >= 30 Then
savetempfoto()
timetosavetemp = 0
End If
End Sub
Public Function savetempfoto()
Dim PB1 As New Bitmap(PictureBox1.Image)
'Dim frame As Long 'individual frames
'Dim strings As String
'strings = frame
'Dim path As String = String.Format("C:\Mediamemebuilderpro\MDAL1Image{0}.jpg", nametosave)
'PB1.Save(path, System.Drawing.Imaging.ImageFormat.Bmp)
'PB1.Save("C:\Mediamemebuilderpro\MDAL1Image" & strings & ".jpg", System.Drawing.Imaging.ImageFormat.Bmp)
'frame += 1
Dim filename As String = "MDAL1Image" 'Change as needed
Dim path As String = String.Format("C:\Mediamemebuilderpro\{0}{1}.jpg", filename, nametosave)
PB1.Save(path, System.Drawing.Imaging.ImageFormat.Bmp)
timetosavetemp = 0
End Function
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
For Each file As String In IO.Directory.GetFiles("C:\Mediamemebuilderpro", "*.*")
ListBox1.Items.Add(file)
Next
End Sub
Private Sub Button20_Click(sender As Object, e As EventArgs) Handles Button20.Click
ListBox1.Items.Clear()
End Sub
A:
There are any number of reasons why you would get that error. Start here:
Saving image: A generic error occurred in GDI+. (vb.net)
Often times it's something simple.
| {
"pile_set_name": "StackExchange"
} |
Q:
What does "They have been backed at short odds to win thousands of pounds" mean?
How should I analyse the following sentence?
They have been backed at short odds to win thousands of pounds.
Which of the following versions is the most accurate understanding (or would there be a more accurate version)?
They have been backed (by someone or some wish) to win money at short odds.
They have been supported by short odds to win the money
They have been very likely to win the money.
A:
It means that
- a gambler (perhaps more than one) has backed them (a team?) to win
- the bet was placed at 'short' odds (which means that the team is reasonably likely to win, as opposed to long odds, which would mean that a win is perceived as rather unlikely)
- the size of the bet was sufficiently large that if the bet was successful, the profit for the gambler would be thousands of pounds.
| {
"pile_set_name": "StackExchange"
} |
Q:
Haskell Maybe/Parametric Polymorphism
I have this code :
getLengthOfMissingArray :: Maybe [Maybe [Int]] -> Maybe Int
getLengthOfMissingArray maybelist = do
ns <- maybelist
getMissing ns
getMissing :: [Maybe [Int]] -> Maybe Int
getMissing maybelist
| any (==Nothing) maybelist = Nothing
| any (==Just []) maybelist = Nothing
| otherwise = Just (sumn mx - sumn (mn - 1) - sum l0)
where
l0 = map length (catMaybes maybelist)
(mn,mx) = (minimum l0, maximum l0)
sumn n = n * (n + 1) `quot` 2
Which is a Haskell translation of this :
https://www.codewars.com/kata/length-of-missing-array
Now it works, however I have two issues :
it is kind of fugly
it should work on any list, not just int's
I would like to have getMissing just be :
getMissing :: [[Int]] -> Int
And then just use that function inside of the other one, but I don't know how to utilize that function on the Maybe of a Maybe.
Second, I tried simply doing :
getMissing :: Eq a => [Maybe [a]] -> Maybe Int
getLengthOfMissingArray :: Eq a => Maybe [Maybe [a]] -> Maybe Int
But then Haskell generates errors when I try to use QuickCheck on test cases like :
getLengthOfMissingArray (Just [ Nothing, Just [ 4, 5, 1, 1 ], Just [ 1 ],
Just [ 5, 6, 7, 8, 9 ] ]) `shouldBe` Nothing
That works, but this generates type errors :
getLengthOfMissingArray (Just [Just []]) `shouldBe` Nothing
I guess without an actual a there there's an issue because if I just try to run it on a Nothing it also generates the same type error:
"Ambiguous type variable ‘a0’ arising from a use of ‘getLengthOfMissingArray’
prevents the constraint ‘(Eq a0)’ from being solved."
A:
sequence :: [Maybe a] -> Maybe [a] will help you adapt your [Maybe [Int]] to [[Int]].
join :: Maybe (Maybe a) -> Maybe a might also be useful.
Both sequence and join have more general types - I wrote them as I expect you will use them here.
You will see "Ambiguous type variable" errors when you pass a polymorphic value to a function that is polymorphic in its argument. To actually run the function GHC needs to use a specific type, and it won't choose - you need to. Since you want getLengthOfMissingArray to remain polymorphic, you can add a type signature to the test case to specify how the tests should run.
| {
"pile_set_name": "StackExchange"
} |
Q:
Passing data to another view controller, using custom struct datatype, initialiser needed?
How do I pass data to another view controller when a custom structure datatype is used? The problem I think I'm having is defining the variables in the second view controller.
This is how I'm passing data to the next view controller:
let sessionDetailsViewController = segue.destination as! SessionDetailsViewController
let indexPathRow = sender as! Int
sessionDetailsViewController.session = myFeed[indexPathRow]
Where session is of the structure datatype, Feed.
Then in my SessionDetailsViewController I'm trying to set the session variable like so:
var session: Feed
However if I do this, I get an error about no initialisers. So I tried implementing an initialiser like so:
init(session: Feed) {
self.session = session
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented, SessionDetailedViewController")
}
The app compiles, then when I trigger the segue to this class, it crashes on the fatalError call.
Previously before I was using the Feed structure datatype, I had been using NSDictionary, which I defined like so:
var session = NSDictionary()
This worked fine. If I try and take the same approach for Feed, Xcode tries to make me create a new Feed object will all its parameters (as expected, as I'm aware () creates a new instance).
So how do I pass the required parameters to this view controller? Also, is there a way to make sure this controller is always instantiated with these parameters (as I assume this would be good coding practice)?
A:
You can declare session to be an implicitly unwrapped optional (which will be set in prepare(for:sender:) of the view controller from which the segue was initiated). No custom init is needed.
var session: Feed!
To be clear, Feed! is an optional. It's just an "implicitly unwrapped" optional (where it's implicitly unwrapped wherever you use it). It's used in cases where the logic in your app dictates that it might not be set by the time init is complete, but once it's time to actually use it, it will always be set, which is the case here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Dragging an event with url always follow the url after the drop
I'm having some troubles while dragging an event with an url assiociated.
If you try to do that, you'll see that the event correctly moves, but also the click event is fired, so you'll visit the linked url (and that's bad).
I tried playing around with the eventClick callback, but with no luck.
Here you can find my code:
// calendar setup
eventDragStart : function(event, jsEvent, ui, view){
event.dragging = true;
},
eventDragStop : function(event, jsEvent, ui, view){
event.dragging = false;
},
eventClick : function(event, jsEvent, view){
//even if I try to return always false, the link is still active
if(event.dragging === true) return false;
},
Then i tried to manipulate the event link:
eventRender : function(event, element, view){
$('a').click(function(){
// custom function that checks if the event is being dragged or not
//return dragCheck(event);
return false;
});
},
but still no luck. I think that while dragging, a new element is created, so every custom value is wiped out...
Any ideas?
A:
- Doctor, when I punch my stomach I feel bad
- So, don't punch it!
I found a solution following the previous motto.
Instead of using the original url property, I created another one custom_url.
This will prevent fullcalendar from creating the a element, so the problem is gone.
Here you can find my code.
Server side code for fetching the events:
foreach($this->items as $row)
{
$event = array();
$event['id'] = $row->id_calendars;
$event['title'] = $row->cal_title;
$event['start'] = $row->cal_start;
$event['end'] = $row->cal_end;
$event['allDay'] = (bool) $row->cal_all_day;
$event['custom_url'] = $row->url;
$events[] = $event;
}
echo json_encode($events);
Then the javascript part:
eventDragStart : function(event, jsEvent, ui, view){
event.dragging = true;
},
eventDragStop : function(event, jsEvent, ui, view){
event.dragging = false;
},
eventClick : function(event, jsEvent, view){
if(event.dragging === true) return false;
if(event.custom_url){
window.location = event.custom_url;
}
},
And you're done!
| {
"pile_set_name": "StackExchange"
} |
Q:
Conditional code based on generic type parameter with C#
I have a method in C# which receives a generic type as argument:
private void DoSomething<T>(T param)
{
//...
}
I need to perform different things depending on what type is param of. I know I can achieve it with several if sentences, like this:
private void DoSomething<T>(T param)
{
if (param is TypeA)
{
// do something specific to TypeA case
} else if (param is TypeB)
{
// do something specific to TypeB case
} else if ( ... )
{
...
}
// ... more code to run no matter the type of param
}
Is there a better way of doing this? Maybe with switch-case or another approach that I'm not aware of?
A:
Just use overloading instead of generics.
A:
If project/logic structure allows it would be nice to move DoSomething into T and describe it with IDoSomething interface. This way you can write:
private void DoSomething<T>(T param) where T:IDoSomething
{
param.DoSomething()
}
If that's not an option then you can setup dictionary of rules
var actionsByType = new Dictionary<Type, Action<T /*if you neeed that param*/>(){
{ Type1, DoSomething1 },
{ Type2, DoSomething2 },
/..
}
and in your method you can call:
private void DoSomething<T>(T param){
//some checks if needed
actionsByType[typeof(T)](param/*if param needed*/);
}
A:
You can create a specific method for a particular type.
private void DoSomething<T>(T param)
{
//...
}
private void DoSomething(int param) { /* ... */ }
private void DoSomething(string param) { /* ... */ }
| {
"pile_set_name": "StackExchange"
} |
Q:
Using multiple LINQ "Include" to get 2nd depth data
I have the following model (simplified)
public partial class Fault
{
public int FaultID { get; set; }
...
public virtual ICollection<FaultComment> FaultComments { get; set; }
public virtual User FaultCreatorUser { get; set; }
}
public partial class FaultComment
{
public int CommentID { get; set; }
public int FaultID { get; set; }
public string CommentContent { get; set; }
public Nullable<System.DateTime> CommentCreationDate { get; set; }
public int CommentCreatorUserID { get; set; }
public bool IsDeleted { get; set; }
public virtual User User { get; set; }
public virtual Fault Fault { get; set; }
}
So there is a fault.. it has a navigation property to get the collection of comments for a fault and each commend has a navigation property for the user that created the comment.
is it possible to create a LINQ statement that will retrieve the fault all of its comments and the users information for the comment ?
something like
var faultsWithComments = _context.Fault.Include("FaultComments").include("???FaultComments>>User???")
A:
var faultsWithComments = _context.Fault.Include("FaultComments.User");
Or with EF >= 4.1 you can use a strongly typed version:
var faultsWithComments = _context.Fault
.Include(f => f.FaultComments.Select(fc => fc.User));
(You need using System.Data.Entity; in your code file to have the Include extension method available that accepts a lambda expression as parameter.)
EF will include all related entities on the specified navigation path, so you don't need to include FaultComments explicitly when you include FaultComments.User.
| {
"pile_set_name": "StackExchange"
} |
Q:
In scenario, where only stored procedures are used for ASP.NET MVC 4 application - is better ADO.NET or EntityFramework 5?
I want to know your opinion.
In scenario, where only stored procedures are used for data manipulation - is better to use standard ADO.NET or Entity Framework 5.
The only (and main) reason for using EF are strongly typed classes (generated complex classes), that can be used as a model in ASP.NET MVC 4. Updating complex types could be simpler in EF compare to ADO.NET.
Reason for using ADO.NET is making communication with database more simply.
Thank you for your opinion.
A:
You could also look at e.g. Dapper-Dot-Net (or some of the other "micro-ORM") which is based off "raw" ADO.NET, but also offers conversion to nice .NET objects (the main EF benefit in your case, I believe) from stored procedure results
| {
"pile_set_name": "StackExchange"
} |
Q:
Every group as full symmetry group of points in $\mathbb R^d$
Does every finite group $G$ have the property that it is isomorphic to a full symmetry group of some set of points in $\mathbb R^n$ for some $n$
A:
Yes. The construction is not delicate; you just have to make something which is as generic as possible while still having $G$-symmetry. It could easily be possible to do something cleverer and shorter than what I'm about to do, but I want to emphasize that all I'm about to do below is to enforce genericity in what seems to me like the most obvious way to get the argument to work at each step.
Start with any faithful orthogonal linear representation of $G$ on a real inner product space $V = \mathbb{R}^n$ containing no trivial subrepresentation. A good example to visualize is the action of the cyclic group $C_k, k \ge 3$ of order $k$ on $\mathbb{R}^2$ by rotation because the most obvious version of this construction will not work in this case; if you just pick a vector and act on it you'll produce dihedral symmetry, and all the work I'm about to do is geared towards avoiding this sort of thing. In general you can take the action of $G$ on the set of functions
$$\left\{ f : G \to \mathbb{R} \mid \sum_{g \in G} f(g) = 0 \right\}.$$
Pick a collection of points $R$ in $V$ whose properties we'll specify later. We'll take our set of points to have the form
$$GR = \bigcup_{g \in G} gR.$$
By construction, the isometry group certainly contains $G$. The game is to figure out what we need to ask of $R$ for the isometry group of $GR$ to be exactly $G$.
So, suppose $\varphi : V \to V$ is some isometry of $GR$. For starters, we'd like to guarantee $\varphi(0) = 0$. This is guaranteed if the "center of mass" of $GR$ is $0$, which is in turn guaranteed if $\sum_{g \in G} g$ acts by $0$ on $V$. But this is equivalent to the condition that $V$ has no trivial subrepresentations.
Now pick a point $r_0 \in R$. We'd like to guarantee $\varphi(r_0) = g r_0$ for some $g \in G$. We can do this by requiring
Property 1: Every point in $R$ has a unique distance from the origin.
Then the only points in $GR$ the same distance away from the origin as $r_0$ are the points $g r_0, r \in G$, so $\varphi(r_0)$ must be such a point.
Pick some other point $r_1 \in R$. We'd now like to guarantee $\varphi(r_1) = g r_1$ for the same $g \in G$ as above. To do this we'll require
Property 2: There is some constant $D$ such that any two points in $R$ are less than $D$ apart, but any point in $R$ is greater than $D$ away from any point in $gR, g \neq e$.
Now, since $d(\varphi(r_1), \varphi(r_0)) = d(r_1, r_0) < D$, it follows that $\varphi(r_1)$ must lie in the same copy $gR$ of $R$ as $r_0$ does. To force $\varphi(r_1) = g r_1$, we'll require
Property 3: Every point in $R$ has a unique distance from every other point in $R$.
This uniquely forces $\varphi(r_1) = g r_1$ as desired. Since $r_1$ was arbitrary, we've shown that $\varphi(r) = gr$ for every $r \in R$. We'd like to conclude from this that $\varphi = g$. Since $\varphi$ is an isometry fixing the origin, it is linear, and so to guarantee this it suffices to require
Property 4: The vectors in $R$ span $V$.
Every property we've asked for is guaranteed by the following construction. Say that a vector $v \in V$ is generic if its stabilizer under the action of $G$ is the identity. Since the action of $G$ on $V$ is faithful, the subset of non-generic vectors in $V$ is a finite union of subspaces of strictly lower dimension, and hence a vector is generic with probability $1$.
If $v$ is a generic vector, let $2D$ be the minimum distance between $v$ and any $gv, g \neq e$, and take $R$ to be a random finite set of at least $\dim V$ points all of which are strictly less than $\frac{D}{2}$ away from $v$. This satisfies all of the properties above with probability $1$, so we're done.
Example. Take $G = C_k, k \ge 3$ acting on $V = \mathbb{R}^2$ by rotation. If we pick $R$ to be a single nonzero vector we get something with dihedral symmetry (Property 4 is not satisfied). But we can fix this by picking $R$ to be a pair of vectors very close together with different distances from the origin.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using GPL 3rd party code for internal closed source project
If I use GPL software in my internal/closed source app do I have to make the source publicly available? say on the Internet?
A:
This question is specifically addressed in the GPL FAQ, and it says you're allowed to use GPLed software inside a company without legally distributing it. You have no obligation to release either source or binary outside the company.
You're talking about what Richard Stallman (the person behind the Gnu movement) calls "private software". For private software, any license that allows you to use the code works, because you're not distributing it. Both the Free Software Foundation and the Open Source Initiative maintain that it should always be possible to use software privately.
A:
Loosely speaking, the GPL requires that you offer to make the source code available to whoever you make the binary available to. If the application is only for internal use, then this is probably not a problem, since you are presumably not worried about your internal users requesting or using the source.
Edit: Note that, to comply with the GPL, you're still obligated to offer the source code (even if no one takes you up on your offer), and you could conceivably get into dicey territory if an internal user insists on getting a copy of your source and you're not ready to give them one.
Edit: I did not realize that the GPL FAQ specifically excludes internal use from being considered distribution, which makes David Thornley's answer much better than mine. I guess I'll leave my answer since it covers the broader issue of limited distribution.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why my server is loading these PHP variables?
I'm migrating my server to a new dedicated, and after the migration my main website shows 500 Internal Error message, on error_log I see
[28-Feb-2014 22:29:14 America/New_York] PHP Warning: PHP Startup: Unable to load dynamic library '/usr/local/lib/php/extensions/no-debug-non-zts-20090626/suhosin.so' - /usr/local/lib/php/extensions/no-debug-non-zts-20090626/suhosin.so: cannot open shared object file: No such file or directory in Unknown on line 0
[28-Feb-2014 22:29:14 America/New_York] PHP Warning: PHP Startup: Unable to load dynamic library '/usr/local/lib/php/extensions/no-debug-non-zts-20090626/pdo.so' - /usr/local/lib/php/extensions/no-debug-non-zts-20090626/pdo.so: cannot open shared object file: No such file or directory in Unknown on line 0
[28-Feb-2014 22:29:14 America/New_York] PHP Warning: PHP Startup: Unable to load dynamic library '/usr/local/lib/php/extensions/no-debug-non-zts-20090626/pdo_sqlite.so' - /usr/local/lib/php/extensions/no-debug-non-zts-20090626/pdo_sqlite.so: cannot open shared object file: No such file or directory in Unknown on line 0
[28-Feb-2014 22:29:14 America/New_York] PHP Warning: PHP Startup: Unable to load dynamic library '/usr/local/lib/php/extensions/no-debug-non-zts-20090626/sqlite.so' - /usr/local/lib/php/extensions/no-debug-non-zts-20090626/sqlite.so: cannot open shared object file: No such file or directory in Unknown on line 0
[28-Feb-2014 22:29:14 America/New_York] PHP Warning: PHP Startup: Unable to load dynamic library '/usr/local/lib/php/extensions/no-debug-non-zts-20090626/phar.so' - /usr/local/lib/php/extensions/no-debug-non-zts-20090626/phar.so: cannot open shared object file: No such file or directory in Unknown on line 0
[28-Feb-2014 22:29:14 America/New_York] PHP Warning: PHP Startup: Unable to load dynamic library '/usr/local/lib/php/extensions/no-debug-non-zts-20090626/pdo_mysql.so' - /usr/local/lib/php/extensions/no-debug-non-zts-20090626/pdo_mysql.so: cannot open shared object file: No such file or directory in Unknown on line 0
[28-Feb-2014 22:29:14 America/New_York] PHP Fatal error: Directive 'allow_call_time_pass_reference' is no longer available in PHP in Unknown on line 0
I don't know why it is loading this many libraries, any way I can find out?
Should I just google them all and install them?
A:
Look at your php.ini file; it refers to each of these libraries, or it wouldn't be trying to load them.
| {
"pile_set_name": "StackExchange"
} |
Q:
Doing serialization in c++
I was reading this page about serialization in c++.
http://www.parashift.com/c++-faq-lite/serialize-binary-format.html
Third bullet got me confused (the one that starts with: "If the binary data might get read by a different computer than the one that wrote it, be very careful about endian issues (little-endian vs. big-endian) and sizeof issues") which also mentions: "header file that contains machine dependencies (I usually call it machine.h)".
What are these endiannes and sizeof issues? (sizeof probably being that on one machine int can be 4 bytes while on another for example less bytes right?).
How would that machine.h file look like?
Is there some tutorial on internet which explains all these things, in an understandable way?
Sometimes in some source codes I also encounter typedefs like:
typedef unsigned long long u64_t;
is it related somehow to that machine.h file?
A:
sizeof: on one architecture long is 64 bits on another 32 bits.
endianness: let's assume that 4-byte long. The 4 bytes can be placed in different order in memory, say on intel the least significant bits are at the lowest address, on motorola or sparc the order is the opposite, but there can be processors with 2301 order too.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to restore the table window in ArcMap 10.2 (stuck in maximized view)
I've somehow managed to maximize the table window in ArcMap 10.2 (after choosing > Open Attribute Table from the TOC).
Whenever this window opens, it's maximized, and I can't see an option to restore it so it doesn't take up the full screen - the only option is to close it.
(A possible complication is that I'm running this in Windows 7 via Bootcamp on a Mac).
A:
I think this is the same thing that happens to me now and again with 10.1. If you have a laptop and open the attribute table on an external monitor that is a different size than your laptop display it throws things out of whack when you open it when you are just on the laptop. This could also happen frequently if you use remote desktop from different computers.
If that is the case, you should be able to either connect the monitor that you were using or remote in with a higher resolution.
If that isn't the case, another thing you can do is reset all of your settings to default (which includes window positions). To do that, rename your 'Normal.mxt' to something else and ArcGIS will create a new one next time it is started. Unfortunately, that will also reset all of your toolbar settings and default toolboxes that are loaded as well.
For 10.1 on Windows 7, your Normal.mxt file is located at C:\Users\<username>\AppData\Roaming\ESRI\Desktop10.1\ArcMap\Templates. I would expect 10.2 to be very similar although I can't speak to your Mac setup.
| {
"pile_set_name": "StackExchange"
} |
Q:
mouseover on text html
In my javascript file there is,
var htm = '<div style="overflow:hidden;height:24px;width:150px;" onmouseover="tooltip(this)">' ;
function tooltip(sp)
{
sp.title = sp.innerHTML;
}
So on mouse over a text the tooltip is displayed.But the tool tip does not stay longer. meaning the position is not fixed.
Can the code be modified such that mouse over should be done on the text and the tool tip also........
A:
If all you want is a "built-in" tooltip, there's no need at all to do it dynamically. Just code the HTML element with a "title" attribute containing the text you want. The browser will show the tooltip on mouseover. If you want something fancier, you should probably look at a jQuery add-on (or some other framework).
| {
"pile_set_name": "StackExchange"
} |
Q:
can there be any problems with building full featured jquery file manager for asp.net?
I m building a file manager...and i m doing that in jquery instead of using asp.net server controls. until now everything is going just fine and the file manager looks cool and works well.
I m concerned if there are any possible bottlenecks with using jquery for file management when switched to production environment???
thnks in advance for your replies....
A:
well, as I can find when googling this, no worries of using jQuery to handle file management.
in my previous company, we built such one using ExtJS , and comparing that ExtJS is HUGE and not as fast as jQuery, we found the file manager to work very fine, and the customer was very happy.
go on, and tell us about the result.
| {
"pile_set_name": "StackExchange"
} |
Q:
Which is the best way to find element in array column in spark scala?
I have a array column on which i find text from it and form a dataframe. Which is the better way among the below 2 options?
Option 1
val texts = Seq("text1", "text2", "text3")
val df = mainDf.select(col("*"))
.withColumn("temptext", explode($"textCol"))
.where($"temptext".isin(texts: _*))
And since it has added and extra column "temptext" and increased duplicate rows by exploding
val tempDf = df.drop("temptext").dropDuplicates("Root.Id") // dropDuplicates does not work since I have passed nested field
vs
Option 2
val df = mainDf.select(col("*"))
.where(array_contains($"textCol", "text1") ||
array_contains($"textCol", "text2") ||
array_contains($"textCol", "text3"))
Actually I wanted to make a generic api, If I go with option 2
then the problem is for every new text i need to add array_contains($"textCol", "text4") and create new api every time
and in option 1 it creates duplicate rows since I explode the array and also needs to drop the temporary column
A:
Use arrays_overlap (or) array_intersect functions to pass array(<strings>) instead of array_contains.
Example:
1.filter based on texts variable:
val df=Seq((Seq("text1")),(Seq("text4","text1")),(Seq("text5"))).
toDF("textCol")
df.show()
//+--------------+
//| textCol|
//+--------------+
//| [text1]|
//|[text4, text1]|
//| [text5]|
//+--------------+
val texts = Array("text1","text2","text3")
//using arrays_overlap
df.filter(arrays_overlap(col("textcol"),lit(texts))).show(false)
//+--------------+
//|textCol |
//+--------------+
//|[text1] |
//|[text4, text1]|
//+--------------+
//using arrays_intersect
df.filter(size(array_intersect(col("textcol"),lit(texts))) > 0).show(false)
//+--------------+
//|textCol |
//+--------------+
//|[text1] |
//|[text4, text1]|
//+--------------+
2.Adding texts variable to the dataframe:
val texts = "text1,text2,text3"
val df=Seq((Seq("text1")),(Seq("text4","text1")),(Seq("text5"))).
toDF("textCol").
withColumn("texts",split(lit(s"${texts}"),","))
df.show(false)
//+--------------+---------------------+
//|textCol |texts |
//+--------------+---------------------+
//|[text1] |[text1, text2, text3]|
//|[text4, text1]|[text1, text2, text3]|
//|[text5] |[text1, text2, text3]|
//+--------------+---------------------+
//using array_intersect
df.filter("""size(array_intersect(textcol,texts)) > 0""").show(false)
//+--------------+---------------------+
//|textCol |texts |
//+--------------+---------------------+
//|[text1] |[text1, text2, text3]|
//|[text4, text1]|[text1, text2, text3]|
//+--------------+---------------------+
//using arrays_overlap
df.filter("""arrays_overlap(textcol,texts)""").show(false)
+--------------+---------------------+
|textCol |texts |
+--------------+---------------------+
|[text1] |[text1, text2, text3]|
|[text4, text1]|[text1, text2, text3]|
+--------------+---------------------+
| {
"pile_set_name": "StackExchange"
} |
Q:
Finding an entire function such that $|f(z)| > e^{Im f(z)}$ and $f(0)=2$ & an analytic function that has an essential singularity at $z=0$
Here are my problems:
Find an entire function $f(z)$ such that $|f(z)| > e^{\operatorname{Im} f(z)}$ for all $z \in \mathbb{C}$ and $f(0)=2$.
I am trying to guess $2\cos(z), 2e^z$, etc, but they are all failed in the end.
Let $f(z)$ be analytic in the punctured disk $0<|z|<1$, and $f(\frac 1n)=\sqrt{n}$ for every integer $n>1$. Prove that $f(z)$ has an essential singularity at $z=0$.
I am trying to use the definition of essential singularity to prove. But I don't know how to express the $f(z).$
A:
You ask a lot: $2=|f(0)|< e^{Im f(0)}=e^0=1$.
(For the new version: Have you tried $e^z+e^{-z}$?)
It would be a better idea to show that the singularity is neither removable nor a pole and then use the classification of singularities.
A:
2) if there were a pole at zero
$$
f(z)=\sum_{k=-N}^{\infty}a_kz^k, N>0
$$
then $f(1/n)\sim a_{-N}n^N$ but the assumption is $f(1/n)\sim n^{1/2}$
| {
"pile_set_name": "StackExchange"
} |
Q:
Order/Sort text and numbers works in Firefox and Chrome, but not Safari
I wrote a jQuery script to sort the results by year which works fine in most browsers. In the case safari browsers the results are listed like this:
2006
ALL
2007
2008
2009
etc.
Of course the list should apear like this.
ALL
2006
2007
2008
2009
etc.
I don't understand why the results vary.
var li = $('#filter .milo-filter');
li.sort(function(a, b) {
if(parseInt($(a).text()) > parseInt($(b).text()))
return 1;
else return -1;
});
$('#filter').empty().html(li);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="milo-portfolio-filters clearfix">
<ul data-option-key="filter" id="filter">
<li class="milo-filter">
<a class="selected " title="All" data-option-value="*" href="#">All</a>
</li>
<li class="milo-filter">
<a title="2015" data-option-value=".2015" href="#">2015</a>
</li>
<li class="milo-filter">
<a title="2011" data-option-value=".2011" href="#">2011</a>
</li>
<li class="milo-filter">
<a title="2006" data-option-value=".2006" href="#">2006</a>
</li>
<li class="milo-filter">
<a title="2007" data-option-value=".2007" href="#">2007</a>
</li>
<li class="milo-filter">
<a title="2008" data-option-value=".2008" href="#">2008</a>
</li>
<li class="milo-filter">
<a title="2013" data-option-value=".2013" href="#">2013</a>
</li>
<li class="milo-filter">
<a title="2010" data-option-value=".2010" href="#">2010</a>
</li>
<li class="milo-filter">
<a title="2009" data-option-value=".2009" href="#">2009</a>
</li>
<li class="milo-filter">
<a title="2014" data-option-value=".2014" href="#">2014</a>
</li>
<li class="milo-filter">
<a title="2012" data-option-value=".2012" href="#">2012</a>
</li>
</ul>
</div>
Here is a Codepen for better understanding.
http://codepen.io/scooma/pen/yJKxPJ
A:
When there is no absolute equality status between two members the browser is not required to give them in the order that you think it should (since you don't really know the exact order the browser send the members of your array to the sort function).
As for the problem in your code, if you will check parseInt("All") < parseInt(2015) and parseInt("All") > parseInt(2015) you will see that both return false.
Here is an example with the exact same code, but the returned value is different in chrome and firefox (due to the exact "problem"):
a = [1, 2, 3, 41, 42]
a.sort(function(a, b) {
if (a == 41) {
a = 4;
}
if (b == 41) {
b = 4;
}
if (a == 42) {
a = 4;
}
if (b == 42) {
b = 4;
}
if (a > b) {
return 1;
}
return -1;
})
console.log(a)
Return value in Chrome: [1, 2, 3, 41, 42 ]
Return value in Safari: [1, 2, 3, 42, 41 ]
The solution
The solution for that is to check if the value you have is a text, and depends on that to return the relevant value (1/-1):
var li = $('#filter .milo-filter');
li.sort(function(a, b) {
if(isNaN(parseInt($(a).text()))) {
// If we can't parse the first element as a number, it is probably text, and it should appear first
return -1;
}
if(isNaN(parseInt($(b).text()))) {
// If we can't parse the second element as a number, it is probably text, and it should appear last
return 1;
}
if (parseInt($(a).text()) > parseInt($(b).text())) {
return 1;
}
return -1;
});
$('#filter').empty().html(li);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="milo-portfolio-filters clearfix">
<ul data-option-key="filter" id="filter">
<li class="milo-filter">
<a class="selected " title="All" data-option-value="*" href="#">All</a>
</li>
<li class="milo-filter">
<a title="2015" data-option-value=".2015" href="#">2015</a>
</li>
<li class="milo-filter">
<a title="2011" data-option-value=".2011" href="#">2011</a>
</li>
<li class="milo-filter">
<a title="2006" data-option-value=".2006" href="#">2006</a>
</li>
<li class="milo-filter">
<a title="2007" data-option-value=".2007" href="#">2007</a>
</li>
<li class="milo-filter">
<a title="2008" data-option-value=".2008" href="#">2008</a>
</li>
<li class="milo-filter">
<a title="2013" data-option-value=".2013" href="#">2013</a>
</li>
<li class="milo-filter">
<a title="2010" data-option-value=".2010" href="#">2010</a>
</li>
<li class="milo-filter">
<a title="2009" data-option-value=".2009" href="#">2009</a>
</li>
<li class="milo-filter">
<a title="2014" data-option-value=".2014" href="#">2014</a>
</li>
<li class="milo-filter">
<a title="2012" data-option-value=".2012" href="#">2012</a>
</li>
</ul>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
How to align perfectly the logo and the navbar and the logo
after make many researches, I didn't figure out how I could align the logo of my web application and the nav items. I created a logo image, but I can't align it the right way!
Hopefully some of you could help me out.
Here are the Haml code
%header
.header_inner
= link_to image_tag('loo.png'), root_path, id: "logo"
%nav
- if user_signed_in?
= link_to "New Note", new_note_path
= link_to "Sign Out", destroy_user_session_path, method: :delete
- else
= link_to "Log In", new_user_session_path
Here the Sass code
header {
background: $dark_gray;
position: fixed;
top: 0;
width: 100%;
padding: 1.75rem 0;
border-bottom: 7px solid $green;
.header_inner {
width: 90%;
margin: 0 auto;
#logo {
float: left;
padding: 1px 0;
}
nav {
display: inline-block;
width: 10px;
float: left;
a {
text-decoration: none;
color: white;
font-size: 1.1rem;
line-height: 1.5;
margin-left: 1rem;
&:hover {
color: $green;
}
}
}
}
and the result of the navbar styling
Navbar Styling Result - Application Image
A:
B'coz of you have give some css like: float:left, margin-left:1rem etc..etc.
Do something
float:none
margin:0 auto;
display:inline-block;
width:100%
hope this help...
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.