text:
Q: Como puedo hacer para que el programa regrese al menu? #include<stdio.h>
#include<conio.h>
#include<math.h>

void problema1(void);
void problema2(void);
void problema3(void);
void problema4(void);
void problema5(void);
void problema6(void);
void problema7(void);
void problema8(void);
void problema9(void);
void problema10(void);
int main(){

    int  opc=0;

    printf("================================\n");
    printf("selecione una opcion\n");
    printf("================================\n");
    printf("1).operacion y+b/a-b\n");
    printf("2).area y perimetro de un rectangulo\n");
    printf("3).calificiones aprovado/reprovado\n");
    printf("4).calculo de salario de trabajador\n");
    printf("5).operacion funcion 100\n");
    printf("6).calculo del factorial\n");
    printf("7).tabla de temperaturas\n");
    printf("8).calculo de potencia\n");
    printf("9).notas de un estudidiante\n");
    printf("10).cuadrados y cubos\n");
    printf("=================================\n");
    scanf("%d",&opc);
    printf("=================================\n");

    switch(opc)
    {

    case 1:
    problema1();
    break;

    case 2:
    problema2();
    break;

    case 3:
    problema3();
    break;

    case 4:
    problema4();
    break;

    case 5:
    problema5();
    break;

    case 6:
    problema6();
    break;

    case 7:
    problema7();
    break;

    case 8:
    problema8();
    break;

    case 9:
    problema9();
    break;

    case 10:
    problema10();
    break;

    }

    }

void problema1(){

        float y,b,a,r;

    bool system ;
    printf("dados 3 numeros enteros, realice la siguiente operación: y+b/a-b\n \n");

printf("introdusca el valor de  y\n ");
scanf("%f",&y);
printf("introdusca el valor de  b\n ");
scanf("%f",&b);
printf("introdusca el valor de  a\n ");
scanf("%f",&a);
r=(y+b)/(a-b);

printf("la respuesta de la operacion es %.2f\n",r);
getchar();
}

void problema2()
{
    int x,y,p,a;
    printf("dados como datos la base y la altura de un rectangulo, calcule e imprima el perimetro y el area. El a = base*altura y p = 2(base+altura).  Despliegue el area y el perimetro\n \n");
    printf("introduzca la medida de la altura del rectangulo\n");
    scanf("%d",&x);
    printf("introduzca la medida de la base del rectangulo\n");
    scanf("%d",&y);
    a=(y*x);
    p=2*(x+y);

    printf("la altura del rectangulo es %d\n",a);
    printf("el perimetro del rectangulo es %d\n",p);
    getchar();
}

void problema3(){
    int score1,score2,score3,score4,score5;
    printf("introduzca la calificacion 1\n");
    scanf("%d",&score1);
    if(score1>=71){
        printf("aprovado\n");
    }
    else{
        printf("reprovado\n");
    }
        printf("introduzca la calificacion 2\n");
    scanf("%d",&score2);
    if(score2>=71){
        printf("aprovado\n");
    }
    else{
        printf("reprovado\n");
    }
            printf("introduzca la calificacion 3\n");
    scanf("%d",&score3);
    if(score3>=71){
        printf("aprovado\n");
    }
    else{
        printf("reprovado\n");
    }
            printf("introduzca la calificacion 4\n");
    scanf("%d",&score4);
    if(score4>=71){
        printf("aprovado\n");
    }
    else{
        printf("reprovado\n");
    }
            printf("introduzca la calificacion 5\n");
    scanf("%d",&score5);
    if(score5>=71){
        printf("aprovado\n");
    }
    else{
        printf("reprovado\n");
    }
    getchar();
}
void problema4(){
        float ht,sh,d,sueldo,total,sueldoneto;
    printf("introduzca las horas trabajadas \n");
    scanf("%f",&ht);
    printf("introduzca el salario por hora\n");
    scanf("%f",&sh);
    printf("introduzaca la deducciones a realizarse\n");
    scanf("%f",&d);
    sueldo=ht+sh*30-d;
    sueldoneto=ht+sh*30;
    if(sueldo<=1000){
        total=sueldo*0.25;
    }
    else{
        total=sueldo*1;
    }
    if(sueldo>1000&sueldo<=1500){
        total=sueldo*0.21;
    }
    else{
        total=sueldo*1;
        }
        if(sueldo>1500){
            total=sueldo*0.18;
        }
    printf("el sueldo neto es %.2f\n",sueldoneto);
    printf("el saladio es %.2f\n",total);
    getchar();
}

void problema5(){
        int num, v;
    float r;
    printf("digite el numero 1 para multiplicar\n");
    printf("digite el numero 2 para sumar\n");
    printf("digite el numero 3 para dividir\n");
    scanf("%d",&num);
    printf("ingrese un valor para realizar a operacion\n");
    scanf("%d",&v);
    if(num=1){
        r=100*v;
    }else if(num=2){
        r=100+v;}
    else if(num=3){
        r=100/v;
    }
    printf("el resultado de la operacion es %.2f\n",r);
    getchar();
}
void problema6(){
        int fac=1,n,r;
    printf("introduzca el numero para calcular el factorial\n");
    scanf("%d",&n);
    for(r=1;r<=n;r++){
        fac=fac*r;
    }
    printf("\nel factorial del numero %d  es %d",n,fac);
    getchar();

}
void problema7(){
    float f,c;
    for(f=1;f <= 200; f++){
    c=(f -32) * 5/9;
    printf("\n fahrenheit %.1f | celcius %.1f",f,c);
    }
    getch();

}
void problema8(){
    int exp;
        float base, result;

        printf("introduzca un numero:\n");
        scanf("%f",&base);
        printf("la potencia de %.2f es: \n",base);
        for(int x=1;x<=9;x++){
            result=pow(base,x);
            if(result<=2000){
                printf("| %.2f",result);
            }
        else{
            x=9;
        }
        }

}
void problema9(){
int i,e;
    float p,total;
    printf("ingrese el numero de articulos que va a comprar\n");
    scanf("%d",&e);
    printf("introduzca el precio del articulo\n");
    scanf("%f",&p);
        total=p*e;
        total+=total*0.07;
        if(total>500){
            total-=total*0.10;
        }
    printf("el total de la compra es |%.2f|\n",total);
    getchar();

}
void problema10(){
    int dig,c,c2;
 printf("\n ===================================");
 printf("\n numeros 1 al 25 cubos y cuadrados ");
 printf("\n ===================================");
 for(dig=0;dig <= 25; dig++) {
       c=pow(dig,2);
       c2=pow(dig,3);
    printf ("\n %d|   %d   | %d", dig, c, c2);
    }
}

A: haces esto:
int main(){
char respuesta; (nueva variable para guardar respuesta)
int opc = 0;

do{

printf("----------- bla bla bla

problema 1 etc...
...

problema10(...){
...
}

printf("Desea realizar otra operacion(s/n)?\n");
fflush(stdin);
scanf("%c",&respuesta);

}while(respuesta=='s');

system("pause");

}

de esa manera va a preguntar si el usuario quiere seguir haciendo operaciones, si elige 's' va a seguir mostrando el menu, si elige 'n' sale. Ojo , siempre va a entrar al menu aunque sea 1 sola vez, si queres que pregunte la primera vez vas a tener que agregar la pregunta arriba de todo y abajo hacer un while.
Para el system("pause") necesitas importar la biblioteca stdlib.h
y eso es lenguaje C.


text:
Q: Address Sanitizer : heap use after free crash when iterating through map of shared_ptr and coming out of scope I am trying to create a map containing shared_ptr as values.In the function deleteB, I iterate through the map looking for a particular key value, when found, I erase the particular key, value pair and break out of the for loop, but as soon I come out of the deleteB function, the program crashes.I used address sanitizer and it shows heap use after free error.Not sure, where exactly this crash is happening.
struct MyObj{
  int val;
  void* ctx;
};

class A{
  private:
    MyObj obj;
    int countVal;
  public:
  A(int value){
     countVal = value;
     obj = (MyObj){countVal, this};
  }
  ~A(){}
   MyObj getObj(){
     return obj;
   }
};

class B{
  private:
  int count = 0;
  map<uint32_t, shared_ptr<A>> mB;

  public:
   void createB(MyObj &obj, int &getCount){
    ++count;
    mB[count] = make_shared<A>(count);
    obj = mB[count]->getObj();
    getCount = count;
   }

   void deleteB(int Val){
       if(!mB.empty()){
         for(auto &a : mB){
           if(a.first == Val){
              mB.erase(a.first);
              break;
           }
         }
       }
   }
};

int main(){
  B b;
  MyObj objVal;
  int count = 0;
  b.createB(objVal, count);
  b.deleteB(count);
  return 0;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to deploy a signal R self host server on azure web app I am new to azure and I have an web app running on Azure web app and I have my signal-R self host as an console application. I want to deploy the signal r self host conbsole app to azure. What are the steps I need to take?

A: @esther fang,
please reference below tutorial, one thing need to be aware is, you will need to manually enable web socket for you site.
http://www.asp.net/signalr/overview/deployment/using-signalr-with-azure-web-sites
Quote:

Deploying a SignalR Web App to Azure App Service
SignalR doesn't add any particular complications to deploying an
  application to Azure versus deploying to an on-premises server. An
  application that uses SignalR can be hosted in Azure without any
  changes in configuration or other settings (though for WebSockets
  support, see Enabling WebSockets on Azure App Service below.) For this
  tutorial, you'll deploy the application created in the Getting Started
  Tutorial to Azure.

A: You can host your console application on Azure as Web or Worker Role or even on a virtual machine managed by you.
Here is a blog post comparing Azure Web and Worker Roles.
You can find the steps you have to take in order to set it up in the following answer:
Hosting console application on Azure or Amazon, is it possible?


text:
Q: uuu wait for Wait for Known USB Device Appear I have just compiled my Yocto image for my board based on IMX.8.M plus. I need to flash my board using uuu (Universal Update Utility) for nxp imx chips. Each time i launch the following command :
uuu -b emmc_all imx-boot-tagged core-image-minimal-devboard.wic

I have this message :
uuu (Universal Update Utility) for nxp imx chips -- libuuu_1.4.243-0-ged48c51

Wait for Known USB Device Appear...

Note that my board is connected through my laptop with serial port communication.
How to use properly uuu in linux ? Do you have any hint ?

A: I had to set my board in recovery mode by setting correct switch boot pin. I also had to connect my board through usb type C instead.


text:
Q: Cisco 678 Will Not Work using PPPoE I am attempting to configure a Cisco 678 because I am totally sick on my Actiontec. However, I am running into some problems. It seems as though the Cisco is able to train the line, but I am unable to ping out.
It is almost like I am not correctly configuring the device to grab it's IP using PPPoA (like my Actiontec.) The output from "show running" (below) makes me think this too.
Below are the commands I ran in order to configure this:
# en
# set nvram erase
# write
# reboot
# en
# set nat enable
# set dhcp server enable
# set PPP wan0-0 ipcp 0.0.0.0
# set ppp wan0-0 dns 0.0.0.0
# set PPP wan0-0 login xxxxx // My actual login
# set PPP wan0-0 password yyyyy // My actual password
# set PPP restart enabled
# set int wan0-0 close
# set int wan0-0 vpi 0
# set int wan0-0 vci 32
# set int wan0-0 open
# write
# reboot

Here is the output from a few commands I thought could provide some useful information:
cbos#ping 74.125.224.113
Sending 1 8 byte ping(s) to 74.125.224.113 every 2 second(s)
Request timed out

cbos#show version

Cisco Broadband Operating System
CBOS (tm) 678 Software (C678-I-M), Version v2.4.9 - Release Software
Copyright (c) 1986-2001 by cisco Systems, Inc.
Compiled Nov 17 2004 15:26:29
DMT FULL firmware version G96
NVRAM image at 0x1030f000

cbos#show errors
- Current Error Messages -
## Ticks        Module     Level      Message
 0 000:00:00:00 PPP        Info       IPCP Open Event on wan0-0
 1 000:00:00:14 ATM        Info       Wan0 Up
 2 000:00:00:14 PPP        Info       PPP Up Event on wan0-0
 3 000:00:01:54 PPP        Info       PPP Down Event on wan0-0
Total Number of Error Messages: 4

cbos#show interface wan0
wan0   ADSL Physical Port
       Line Trained
Actual Configuration:
  Overhead Framing:           3
  Trellis Coding:             Enabled
  Standard Compliance:        T1.413
  Downstream Data Rate:       1184 Kbps
  Upstream Data Rate:         928 Kbps
  Interleave S Downstream:    4
  Interleave D Downstream:    16
  Interleave R Downstream:    16
  Interleave S Upstream:      4
  Interleave D Upstream:      8
  Interleave R Upstream:      16
  Modem Microcode:            G96
  DSP version:                0
  Operating State:            Showtime/Data Mode
Configured:
  Echo Cancellation:          Disabled
  Overhead Framing:           3
  Coding Gain:                Auto
  TX Power Attenuation:       0dB
  Trellis Coding:             Enabled
  Bit Swapping:               Disabled
  Standard Compliance:        T1.413
  Remote Standard Compliance: T1.413
  Tx Start Bin:               0x6
  Tx End Bin:                 0x1f
  Data Interface:             Utopia L1
Status:
  Local SNR Margin:           19.0dB
  Local Coding Gain:          7.5dB
  Local Transmit Power:       12.5dB
  Local Attenuation:          46.0dB
  Remote Attenuation:         31.0dB
Local Counters:
  Interleaved RS Corrected Bytes:         0
  Interleaved Symbols with CRC Errors:    2
  No Cell Delineation Interleaved:        0
  Out of Cell Delineation Interleaved:    0
  Header Error Check Counter Interleaved: 0
  Count of Severely Errored Frames:       0
  Count of Loss of Signal Frames:         0
Remote Counters:
  Interleaved RS Corrected Bytes:         0
  Interleaved Symbols with CRC Errors:    1
  No Cell Delineation Interleaved:        0
  Header Error Check Counter Interleaved: 0
  Count of Severely Errored Frames:       0
  Count of Loss of Signal Frames:         0

cbos#show int wan0-0
WAN0-0  ATM Logical Port
        PVC (VPI 0, VCI 32) is configured.
        ScalaRate set to Auto
        AAL 5         UBR Traffic
        IP Port Enabled

cbos#show running
Warning: traffic may pause while NVRAM is being accessed
[[ CBOS = Section Start ]]
NSOS MD5 Enable Password = XXXX
NSOS MD5 Root Password = XXXX
NSOS MD5 Commander Password = XXXX
[[ PPP Device Driver = Section Start ]]
PPP Port User Name = 00, "XXXX"
PPP Port User Password = 00, XXXX
PPP Port Option = 00, IPCP,IP Address,3,Auto,Negotiation Not Required,Negotiable
,IP,0.0.0.0
PPP Port Option = 00, IPCP,Primary DNS Server,129,Auto,Negotiation Not Required,
Negotiable,IP,0.0.0.0
PPP Port Option = 00, IPCP,Secondary DNS Server,131,Auto,Negotiation Not Require
d,Negotiable,IP,0.0.0.0
[[ ATM WAN Device Driver = Section Start ]]
ATM WAN Virtual Connection Parms = 00, 0, 32, 0
[[ DHCP = Section Start ]]
DHCP Server = enabled
[[ IP Routing = Section Start ]]
IP NAT = enabled
[[ WEB = Section Start ]]
WEB = enabled

cbos# wtf...?


text:
Q: modification of bfs for ford fulkerson algorithm,to find augmenting path i am using bfs to find augmenting path.but it is producing same path every time.but ford fulkerson algorithm requires that,we choose different path every time from source to sink,so can somebody suggest me how to modify bfs so that it produces different path every time between source and sink.graph is directed and weighted

A: You need to make sure that the BFS ignores edges where all of the capacity has been used. Usually, the BFS is being run on the so-called residual network, in which each edge capacity tells how much capacity remains on that edge (given the flow you've sent through that edge). You can either maintain a separate residual graph, or you can have an implicit one by making the BFS look at the difference between the original capacity and the current flow for each edge (and treating an edge as absent if its capacity is zero).


text:
Q: Получить верный `text` с MySQL Есть в базе данных message столбец text

я получаю text, пишу вот такой код
$sql = "SELECT * FROM `messages` WHERE `id` = $id";
$result = $connect->query($sql);
$getmess = $result->fetch_row();
$text= $getmess[3];
echo $text;

и выводится

Как сделать чтобы выводилось


text:
Q: pandas csv write by ascii ignore encoding Pandas csv parser (http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_csv.html) supports different encodings:
import pandas
data = pandas.read_csv(myfile, encoding='utf-8', quotechar='"', delimiter=',')

How do implement ascii ignore encoding case for my dataframe?
encode('ascii', 'ignore')

A: Pandas doesn't seem to let you do that.  I had to pre-process my CSV file before reading with pandas:
decoded = codecs.decode(myfile.read(), "utf-8", "ignore")
encoded = codecs.encode(decoded, "utf-8", "ignore") #probably superfluous
fakefile = StringIO.StringIO(encoded)
data = pandas.read_csv(fakefile, encoding="utf-8")

Possibly terrible if you have a very large CSV file, but you could read chunks of the csv file at a time.


text:
Q: Show Y-Axis ticks from -1 to 1 I am writing a Matlab script to plot a regular sine wave with a frequency of 5Hz sampled every .01 second. I am trying to achieve this..

But I am gettting this..

I just want my graph to show -1 to 1.
Here is the matlab code...
% Script that will show stem plots of a sine wave with a frequency of
% 5Hz sampled every .01 seconds.

time = [0:.01:0.5]; % Sampling time 0 - 10 seconds at a rate of .01 second
frequency = 5; % The frequency is 5 Hz
samplingFrequency = .01;
fc = frequency/samplingFrequency;

sineWave = sin(2*pi*frequency*time);

figure(1)
plot(time, sineWave);

figure(2)
stem(time, sineWave, ':r');

Please any clue on how to achieve this would be appreciated.
Thanks.

A: If you are asking how to remove the extra ticks on the Y axis, you can use this:
set(gca,'ytick',[-1 0 1]);

Otherwise, I think that we'll need more description.


text:
Q: Python default arguments and argument names I was wondering if the 'a=a', and 'b=b' can lead to problems/unexpected behaviour? code works fine in the example.
def add_func(a=2,b=3):
   return a+b

a=4
b=5
answer = add_func(a=a, b=b)

Thanks

A: Not that I know of, although I'd love to be proved wrong.
The formal language reference defines the lexical structure of a function call. The important bit is that it defines a "keyword_item" as identifier "=" expression. Also, here's what it says about how the arguments to the call are interpreted:

If keyword arguments are present, they are first converted to
  positional arguments, as follows. First, a list of unfilled slots is
  created for the formal parameters. If there are N positional
  arguments, they are placed in the first N slots. Next, for each
  keyword argument, the identifier is used to determine the
  corresponding slot (if the identifier is the same as the first formal
  parameter name, the first slot is used, and so on). If the slot is
  already filled, a TypeError exception is raised. Otherwise, the value
  of the argument is placed in the slot, filling it (even if the
  expression is None, it fills the slot). When all arguments have been
  processed, the slots that are still unfilled are filled with the
  corresponding default value from the function definition.

This lists a few possible scenarios.
In the simple case, like you mentioned, where there are two formal arguments (a and b), and if you specify the function call using keyword parameters like add_func(a=a, b=b), here's what happens:

*

*Two slots are created to hold the parameters.

*Since you didn't provide any positional arguments in the call (just keyword arguments), none of the slots are filled initially.

*Each of your keyword arguments are analyzed individually, and the identifier of your argument (the "a" in the a= part) is compared with all of the formal parameters names of the function (the names that were given the parameters when the function was defined, in our case, a and b).

*When a match occurs, the value of the keyword arguments (in this case, 4!) is used to fill the corresponding slot.

*This repeats until all keyword arguments are analyzed. If all slots aren't filled, then Python tries to assign a default value to the remaining slots if one exists. If not, an error is raised.

So, Python treats the "identifier" in a keyword argument completely differently. This is only true for keyword arguments, though; obviously, if you tried something like add_func(b, a), even though your parameters themselves are called b and a, this would not be mapped to the formal parameters in the function; your parameters would be backwards. However, add_func(b=b, a=a) works fine; the positions don't matter as long as they are keyword arguments.

A: It depends on whether or not the global objects pointed to are mutable or immutable. immutable objects such as your integers are copies when modified, so it's safe. Mutable objects such as lists are modified in-place, and are NOT safe to use this way. Any change to them persists between calls and may (and probably will) cause unexpected behaviors.
This:
a=[]
def f(a=a):
    pass

Is the same as:
def f(a=[]):
    pass

Which is a known bad practice in Python programs.


text:
Q: reverse geocode location in a tableviewcontroller How can I reverse geocode locations in each tableview row cell?
I have a table view controller where each uber request comes in as latitude and longitude.  How can I convert each coordinate to actual address in a tableviewcontroller?
The code below in cellForRowAt is:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if self.rideRequests.count != 0 {

        let request = self.rideRequests[indexPath.row]

        if let cell = tableView.dequeueReusableCell(withIdentifier: "RequestsCell") as? RequestsCell {

            cell.configureCell(requests: request)

            return cell
        }
    }

    return RequestsCell()
}

Reverse Geocode location in my rider app (uber-clone) is:
func geoCode(location : CLLocation!) {
    /*  Only one reverse geocoding can be in progress at a time so we need to cancel existing
     one if we are getting location updates */

    geoCoder.cancelGeocode()
    geoCoder.reverseGeocodeLocation(location, completionHandler: { (data, error) -> Void in
        guard let placeMarks = data as [CLPlacemark]! else {
            return
        }
        let loc: CLPlacemark = placeMarks[0]
        let addressDict : [NSString: NSObject] = loc.addressDictionary as! [NSString: NSObject]
        let addrList = addressDict["FormattedAddressLines"] as! [String]
        let address = addrList.joined(separator: ", ")
        print(addrList)
        self.address.text = address
        self.previousAddress = address
    })
}

Configure cell from another file:
class RequestsCell: UITableViewCell {

@IBOutlet weak var longitudeLabel: UILabel!
@IBOutlet weak var latitudeLabel: UILabel!
@IBOutlet weak var usernameLabel: UILabel!

func configureCell(requests: Requests) {

    self.longitudeLabel.text = "\(requests.longitude)"
    self.latitudeLabel.text = "\(requests.latitude)"
    self.usernameLabel.text = "\(requests.usersname)"
}

} // class RequestsCell

A: You should do this in:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{

}

method.


text:
Q: How would I test my login function has been called? Angular2+ I am struggling with how to test if a function has been called between a component and a service.
If there is something I'm missing, please educate me!

A: in your specs, you name the auth service authServ:
(authServ: AuthService) => {
but you're spying on auth:
spy = spyOn(auth, 'login').and.callThrough();
Can you try renaming the auth service authServ => auth?
If this doesn't help, please post the error message(s), otherwise it's hard to debug.


text:
Q: Coq - proving something which has already been defined? Taking the very straightforward proof of "the sum of two naturals is odd if one of them is even and the other odd":
Require Import Arith.
Require Import Coq.omega.Omega.

Definition even (n: nat) := exists k, n = 2 * k.
Definition odd  (n: nat) := exists k, n = 2 * k + 1.

Lemma sum_odd_even : forall n m, odd (n + m) -> odd n /\ even m \/ even n /\ odd m.
Proof.
  intros n. intros m. left.
  destruct H. firstorder.

The state at the end of this block of code is:
2 subgoals
n, m, x : nat
H : n + m = 2 * x + 1
______________________________________(1/2)
odd n
______________________________________(2/2)
even m

To my understanding, it is telling me that I need to prove to it that I have an odd number n and an even number m through the hypothesis? Even though I have already stated than n is odd and m is even? How do I proceed from here?
UPDATE:
After a bit of fidgeting around (in light of the comments), I guess I would have to do something like this?
Lemma even_or_odd: forall (n: nat), even n \/ odd n.
Proof.
  induction n as [|n IHn].
  (* Base Case *)
  left. unfold even. exists 0. firstorder.
  (* step case *)
  destruct IHn as [IHeven | IHodd].
  right. unfold even in IHeven. destruct IHeven as [k Heq].
  unfold odd. exists k. firstorder.
  left. unfold odd in IHodd. destruct IHodd as [k Heq].
  unfold even. exists (k + 1). firstorder.
Qed.

Which means that now:
Lemma sum_odd : forall n m, odd (n + m) -> odd n /\ even m \/ even n /\ odd m.
Proof.
  intros n. intros m. left. destruct H. firstorder.
  pose proof (even_or_odd n). pose proof (even_or_odd m).

Result:
    2 subgoals
n, m, x : nat
H : n + m = 2 * x + 1
H0 : even n \/ odd n
H1 : even m \/ odd m
______________________________________(1/2)
odd n
______________________________________(2/2)
even m

Intuitively, all that I have done is saying that every number is either even or odd. Now I have to tell coq that my odd and even numbers are indeed odd and even (I guess?).
UPDATE 2:
As an aside, the problem is solvable with just firstorder:
Lemma sum_odd : forall n m, odd (n + m) -> odd n /\ even m \/ even n /\ odd m.
Proof.
  intros n. intros m. firstorder.
  pose proof (even_or_odd n). pose proof (even_or_odd m).
  destruct H0 as [Even_n | Odd_n]. destruct H1 as [Even_m | Odd_m].
  exfalso. firstorder.
  right. auto.
  destruct H1. left. auto.
  exfalso. firstorder.
Qed.

A: Your use of left is still incorrect and keeps you from completing the proof. You apply it to the following goal:
odd (n + m) -> odd n /\ even m \/ even n /\ odd m

and it gives:
H : odd (n + m)
______________________________________(1/1)
odd n /\ even m

You are committing to proving that if n + m is odd, then n is odd and m is even. But this is not true: n might be odd and m might be even. Only apply left or right once you have enough information in the context to be sure which one you want to prove.
So let's restart without left:
Lemma sum_odd : forall n m, odd (n + m) -> odd n /\ even m \/ even n /\ odd m.
Proof.
  intros n. intros m. firstorder.
  pose proof (even_or_odd n). pose proof (even_or_odd m).

At this point we are at:
H : n + m = 2 * x + 1
H0 : even n \/ odd n
H1 : even m \/ odd m
______________________________________(1/1)
odd n /\ even m \/ even n /\ odd m

Now you want to prove something from disjunctions. In order to prove something of the form A \/ B -> C in Coq's constructive logic, you must prove both A -> C and B -> C. You do this by case analysis on the A \/ B (using destruct or other tactics). In this case we have two disjunctions to decompose:
  destruct H0 as [Even_n | Odd_n], H1 as [Even_m | Odd_m].

This gives four cases. I'll show you the first two, the last two are symmetric.
Fist case:
H : n + m = 2 * x + 1
Even_n : even n
Even_m : even m
______________________________________(1/1)
odd n /\ even m \/ even n /\ odd m

The assumptions are contradictory: If both n and m are even, then H cannot hold. We can prove this as follows:
  - exfalso. destruct Even_n, Even_m. omega.

(Step through this to understand what happens!) The exfalso is not really necessary, but it's good documentation that we are doing a proof by showing that the assumptions contradict.
Second case:
H : n + m = 2 * x + 1
Even_n : even n
Odd_m : odd m
______________________________________(1/1)
odd n /\ even m \/ even n /\ odd m

Now, knowing assumptions that apply in this case, we can commit to the right disjunct. This is why your left kept you from making progress!
  - right.

All that remains to be proved is:
Even_n : even n
Odd_m : odd m
______________________________________(1/1)
even n /\ odd m

And auto can handle this.


text:
Q: MediaRouter BT active audio source id or MAC address I need the active audio source id or MAC address to compare it with my own list of Bluetooth devices. MediaRouter.getSelectedRoute gives very basic information like the name, type of the device. I see there is a getAddress() API which is hidden in MediaRouter class. Is there any other unique id to identify and compare the BT devices with my own list. Name field is not reliable as there can be multiple devices with same name.
Also, Samsung devices can have multiple Bluetooth devices active at the same time. Didn't find any API which can give the correct information.
        val mediaRouter = applicationContext.getSystemService(Context.MEDIA_ROUTER_SERVICE) as MediaRouter
        val selectedRoute = mediaRouter.getSelectedRoute(MediaRouter.ROUTE_TYPE_LIVE_AUDIO)
        Log.e("MainActivity", "route:" + selectedRoute)

Also, tried the below for Samsung devices. This gives the connected device list but not the active device.
 List<BluetoothDevice> a2dpList = bluetoothProfileProxy.getConnectedDevices();


text:
Q: Server side computer speaks to all users? I want users to be able to play a trivia game online. I have experience with real-time communications, but I need to store and pass out the data.
What I have now is run the same code on a "master" computer. Players send their data to this computer, and when the round is up, the master computer shares this data.
However, when the user with the master computer leaves, this becomes problematic. I was wondering if I could have this "master" computer run server side, at all times, and work with all clients at once.


text:
Q: Directory Scanner in Java Scan a set of directories continuously for a set of file name filters.
For each file name filter arrived, process the file and repeat the steps for all
What can be the recommended design for this in jdk 1.5 , possibly using java.concurrent.Executor and Future

A: I guess this is what you are trying to do:

*

*You have a set of dirs:

dir1
  dir2
  dir3

*And you need to place a "watch" on these 3 directories for a specific file name pattern.
Example: If a new file is added with name: watchme_9192.log, then you java logic should kick in and process that file.
So, based on that assumption, you can try: jnotify

JNotify is a java library that allow java application to listen to
  file system events, such as:
      File created
      File modified
      File renamed
      File deleted

Also, related: best practice for directory polling

A: I have done a similar task with the web crawler.Just a few changes had to be made... It is a concurrent implementation with newly found directories getting scanned by the thread pool in the Executor Framework.It uses concurrent collections for Queue and List to hold the indexed files. The indexer picks up the files from the queue and does something with them.
here is the FileFilter implementation

    public class ImageFileFilter implements FileFilter
    {
      private final String[] okFileExtensions =
        new String[] {"jpg", "png", "gif"};

      public boolean accept(File file)
      {
        for (String extension : okFileExtensions)
        {
          if (file.getName().toLowerCase().endsWith(extension))
          {
            return true;
          }
        }
        return false;
      }
    }

here is the Class with the main method...

     public class FileFilterTest {
        public static void main(String[] args) {
            File dir = new File("D:\\dev\\css-templates\\cms-admin");
            BlockingQueue blockingQueue = new ArrayBlockingQueue(5);
            FileCrawler fileCrawler = new FileCrawler(blockingQueue,
                    new ImageFileFilter(), dir);
            new Thread(fileCrawler).start();

            FileIndexer indexer = new FileIndexer(blockingQueue);
            new Thread(indexer).start();
        }
    }

Here is the file crawler thread

     public class FileCrawler implements Runnable {
            private final BlockingQueue fileQueue;
            private ConcurrentSkipListSet indexedFiles = new ConcurrentSkipListSet();
            private final FileFilter fileFilter;
            private final File root;
            private final ExecutorService exec = Executors.newCachedThreadPool();

            public FileCrawler(BlockingQueue fileQueue,
                               final FileFilter fileFilter,
                               File root) {
                this.fileQueue = fileQueue;
                this.root = root;
                this.fileFilter = new FileFilter() {
                    public boolean accept(File f) {
                        return f.isDirectory() || fileFilter.accept(f);
                    }
                };
            }

            public void run() {

                    submitCrawlTask(root);

            }

            private void submitCrawlTask(File f) {
                CrawlTask crawlTask = new CrawlTask(f);
                exec.execute(crawlTask);
            }

            private class CrawlTask implements Runnable {
                private final File file;

                CrawlTask(File file ) {

                    this.file= file;
                }

             public void run() {
                 if(Thread.currentThread().isInterrupted())
                return;

                    File[] entries = file.listFiles(fileFilter);

                    if (entries != null) {
                        for (File entry : entries)
                            if (entry.isDirectory())
                                submitCrawlTask(entry);
                            else if (entry !=null && !indexedFiles.contains(entry)){
                                indexedFiles.add(entry);
                                try {
                                    fileQueue.put(entry);
                                } catch (InterruptedException e) {
                                        Thread.currentThread().interrupt();
                                }
                            }
                    }
                }
        }
       }

Here is the file indexer thread

        public class FileIndexer implements Runnable {
        private final BlockingQueue queue;

        public FileIndexer(BlockingQueue queue) {
            this.queue = queue;
        }

        public void run() {
            try {
                while (true) {
                    indexFile(queue.take());
                }
            } catch (InterruptedException e) {
                System.out.println("Indexer Interrupted");
                Thread.currentThread().interrupt();
            }
        }

        public void indexFile(File file) {
            // do something with the file...
            System.out.println("Indexing File : " + file.getAbsolutePath() + " " + file.getName());
        };
    }


text:
Q: Detect the Serializer being used in an Adapter I switched to Ember-Cli from a plain old Ember application.
The problem is that my models are not being properly serialized.
How can I debug all the serializers to see what is going on?
- The application serializer
- The adapter serializer
- The model serializer
Can I for example do this with a console.log in my custom adapter's createRecord() function?


text:
Q: If statement provides false for only one string value Hey guys i have been trying to leet code to improve my coding skills. I came across an "easy" question on it and was trying out my own solution. while doing this I found out something surprising.
my if statement provides a false value for the "c" string but works on all of the others, I have tried checking with other string values and they work. any reason why my code is providing a false result for this statement?
here is my code
    string allowed ="abc";
    vector<string> words =
    {
    "a",
    "b",
    "c",
    "ab",
    "ac",
    "bc",
    "abc"
    };

    int count = 0;
    bool contains;

    for(string w: words)
    {
        for(auto c: w)
        {
            if(allowed.find(c) <= w.size())
            {
              contains = true;
            }else
            {
                contains = false;
                break;
            }

        }

        if(contains)
        {
            count++;
        }
    }

    return count;

my question is are there any reason why my code is providing a false result for the "c" string?
or is there something wrong with my if else statement.
how can I fix this?
thank you so much in advance to everyone who helped me out!

A: if(allowed.find(c) <= w.size())

This searches in the string allowed looking for the character c and if it finds it, compares the returned index of that character with the length of the string w.  So when w is shorter than allowed and the found character is later in the string than the length of w, it will return false even if it found it.
You probably meant to write
if(allowed.find(c) < allowed.size())

or even better would be
if(allowed.find(c) != string::npos)

for making the intent clearer.


text:
Q: AttributeError 'UserViewset' object has no attribute 'action' I've been using the Django rest framework, and I'm trying to customize the get_parsers method in my UserViewset, I looked at the docs and found a similar use case with permission classes in docs, and I tried to customize the get_parsers like this
class UserViewset(viewsets.ModelViewSet):
serializer_class = UserSerializer

# Redefine get_parsers, so that only the update methods have form-data media type
def get_parsers(self):
    if self.action == 'update' or self.action == 'partial_update':
        parser_classes = [FormParser, MultiPartParser]
    else:
        parser_classes = [JSONParser]
    return [parser() for parser in parser_classes]

but I keep getting the error: AttributeError at /api/auth/users/: 'UserViewset' object has no attribute 'action'
I tried the use case found in the docs and it worked perfectly.
What am I doing wrong here ?

A: So, thanks to fb.com/laidani.basset @bdbd and @willem-van-onsem and u/vikingvynotking, I've been able to fix it with 2 different solutions:

*

*The first is to override initialize_request like this, the idea is to set the request parsers to the instance of which parser you want; the drop back is when you're using swagger or any API doc, it'll not differentiate between the method parsers and it'll be just one parser, in my case it's JSONParser:
 def initialize_request(self, request, *args, **kwargs):

     request = super().initialize_request(request, *args, **kwargs)
     print(request.method)
     if request.method in ['PUT', 'PATCH']:
         request.parsers = [FormParser(), MultiPartParser()]
     else:
         request.parsers = [JSONParser()]

     self.action = self.action_map.get(request.method.lower())
     return request

*The second solution is to override initialize_request so that the self.action is called before calling the request, and then use the get_parsers method as you like, in this case, the swagger will differentiate between the parsers of each method:
 def initialize_request(self, request, *args, **kwargs):
     self.action = self.action_map.get(request.method.lower())
     return super().initialize_request(request, *args, **kwargs)

A: You should cast your viewset to .as_view() for example;
path('users/', UserViewset.as_view(), name='users'),


text:
Q: Not be able to install tabletext Traceback (most recent call last):
  File "C:\Users\rajat\Anaconda3\Scripts\pip-script.py", line 11, in <module>
    load_entry_point('pip==1.5.2', 'console_scripts', 'pip')()
  File "C:\Users\rajat\Anaconda3\lib\site-packages\pkg_resources\__init__.py", line 489, in load_entry_point
    return get_distribution(dist).load_entry_point(group, name)
  File "C:\Users\rajat\Anaconda3\lib\site-packages\pkg_resources\__init__.py", line 2852, in load_entry_point
    return ep.load()
  File "C:\Users\rajat\Anaconda3\lib\site-packages\pkg_resources\__init__.py", line 2443, in load
    return self.resolve()
  File "C:\Users\rajat\Anaconda3\lib\site-packages\pkg_resources\__init__.py", line 2449, in resolve
    module = __import__(self.module_name, fromlist=['__name__'], level=0)
  File "C:\Users\rajat\AppData\Roaming\Python\Python37\site-packages\pip-1.5.2-py3.7.egg\pip\__init__.py", line 9, in <module>
    from pip.log import logger
  File "C:\Users\rajat\AppData\Roaming\Python\Python37\site-packages\pip-1.5.2-py3.7.egg\pip\log.py", line 9, in <module>
    from pip._vendor import colorama, pkg_resources
  File "C:\Users\rajat\AppData\Roaming\Python\Python37\site-packages\pip-1.5.2-py3.7.egg\pip\_vendor\pkg_resources.py", line 1423, in <module>
    register_loader_type(importlib_bootstrap.SourceFileLoader, DefaultProvider)

Always getting error for this.


text:
Q: Let Ubuntu server send an mail when system restart is required Is there a possibility that Ubuntu server 20.04 LTS can send a mail to specific email adresses when an update has been installed that require a server reboot
So for instance when the file /var/run/reboot-required.pkgs does exist that it sends a mail to the admins so they can reboot?
I have looked al over Google but cannot find an easy tutorial for this

A: Try /etc/apt/apt.conf.d/50unattended-upgrades
// Send email to this address for problems or packages upgrades
// If empty or unset then no email is sent, make sure that you
// have a working mail setup on your system. A package that provides
// 'mailx' must be installed. E.g. "user@example.com"
Unattended-Upgrade::Mail "user@example.com";

// Set this value to "true" to get emails only on errors. Default
// is to always send a mail if Unattended-Upgrade::Mail is set
Unattended-Upgrade::MailOnlyOnError "false";

That's actually the easy part. Next, we must set up a lightweight postal system to get the e-mail off the server and over to you.
Here's one way to do that:
sudo apt install msmtp msmtp-mta bsd-mailx

Config file: /root/.msmtprc
account        your_label_here
host           smtp.example.com
port           465
from           root@your_machine.your_domain
user           user@example.com (your email)
password       your_smtp_password
auth           on
tls            on
tls_starttls   off
tls_certcheck  off
logfile        /root/.msmtp.log
account default : your_label_here

Test command:
echo "This is the email body" > /tmp/body.txt && sudo mailx -s "This is the subject" user@example.com < /tmp/body.txt; rm /tmp/body.txt

A: Thanks I have followed the tutorial and edited a cronjob for this so infact as user root I have created the config file /root/.msmtprc
account        your_label_here
host           smtp.example.com
port           465
from           root@your_machine.your_domain
user           user@example.com (your email)
password       your_smtp_password
auth           on
tls            on
tls_starttls   off
tls_certcheck  off
logfile        /root/.msmtp.log
account default : your_label_here

Afterwards I created a file in /etc/cron.hourly/reboot-check
#!/usr/bin/env bash

if [ -f /var/run/reboot-required ]; then
        echo "A reboot is required following updates to server <TestServer> the machine will auto reboot in 1h" > /tmp/body.txt && sudo mailx -s "Reboot Required" receivers@adress.com < /tmp/body.txt; rm /tmp/body.txt
fi

And when the machine has an update that requires a reboot and creates the /var/run/reboot-required file it sends me an email to notify me of the reboot


text:
Q: Why docker not running flask app on 0.0.0.0? I am trying to dockerize my flask app. I see that docker will host on 0.0.0.0. But I am not getting it. My dockerfile:
#!/bin/bash
FROM python:3.8
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
EXPOSE 5000
#ENTRYPOINT [ "./main_class.py" ]
#CMD [ "flask", "run", "-h", "0.0.0.0", "-p", "5000" ]
CMD [ "python", "main_class.py", "flask", "run", "-h", "0.0.0.0", "-p", "5000" ]

When I build it , it build successfully. When I run it docker run -p 5000:5000 iris, it ran successfully. It says Running on http://172.17.0.2:5000/ (Press CTRL+C to quit).
Moreover when I see 172.17.0.2:5000 in browser, it does not work. But if I use 127.0.0.1:5000 it works. How can I bring 0.0.0.0:5000 ? In main_class.py I am using
if __name__ == '__main__':
    app.run(debug=True, threaded=True, host="0.0.0.0")

When I type docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS                                       NAMES
90a8a1ee3625   iris      "python main_class.p…"   23 minutes ago   Up 21 minutes   0.0.0.0:5000->5000/tcp, :::5000->5000/tcp   thirsty_lalande

Is there anything wrong I am doing in dockerfile ?
Moreover when I use ENTRYPOINT, it shows me an error standard_init_linux.go:228: exec user process caused: exec format error, thats why I am not using ENTRYPOINT.

A: The flask run -h 0.0.0.0 will tell your flask process to bind to any local IP address, as mentioned in the comments. This will also allow flask to respond to your Docker port-forwarding (5000->5000), i.e. to answer incoming traffic from the Docker bridge.
On the Docker level your effective port-forwarding is 0.0.0.0:5000->5000/tcp as shown by docker ps, so on your host system port 5000 on any local IP address will be forwarded to your container's flask process.
Please mind that 0.0.0.0 isn't a real IP address, but a placeholder to bind to any local IP address.
You can access your flask application on any IP that routes to your host system, port 5000.


text:
Q: django 3.2 how to loop a field with foreign-keys I'd like to loop a field based from the Question Model. Here are my models.## Heading ##
models.py
from django.db import models
from django.db.models.deletion import CASCADE
from django.conf import settings
class Question(models.Model):
    id = models.BigAutoField(primary_key=True)
    title = models.CharField(max_length=50, unique=True)
    question = models.CharField(max_length=255, unique=True)
class Declaration(models.Model):
    id = models.BigAutoField(primary_key=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='declarations', on_delete=models.CASCADE)
class Checklist(models.Model):
    id = models.BigAutoField(primary_key=True)
    declaration = models.ForeignKey(Declaration, related_name='checklist_declaration', on_delete=models.CASCADE)
    question = models.ForeignKey(Question, related_name='checklist_question', on_delete=models.CASCADE, limit_choices_to={'is_active': 'True'})
    is_yes = models.BooleanField()

and my forms.py
from django.utils.safestring import mark_safe
from django import forms
from declaration.models import Checklist, Question

class DeclarationForm(forms.ModelForm):
class Meta:
    model = Declaration
    fields = '__all__'
class ChecklistForm(forms.ModelForm):
    is_yes = forms.BooleanField(required=False)
    class Meta:
        model = Checklist
        fields = ['question', 'is_yes']

and here is my expected output
enter image description here
I dunno how to do it in the forms.py since django's only way to validate fields is through forms.
*Additional question
this is my views.
def submit(request):
if request.method == 'POST':
    checklist = ChecklistForm(request.POST)
    declaration = DeclarationForm(request.POST)
    if declaration.is_valid() and checklist.is_valid():
        user = request.user
        declaration = Declaration.objects.create(user=user)
        declaration.save()
        checklist.save(commit=False)
        checklist.declaration = declaration
        checklist.save()

        return redirect('student-dashboard')

do i need to loop to check every checklist to work? it only saves declaration object but no checklists objects and shows no error.
Updated***
Following the approach of TaipanRex it works but my problem is it looks like this enter image description here
Is there a way to instead of show dropdown menu of the question just the quest text instead?

A: You are going to need two Forms, a DeclarationForm and a ChecklistForm (though I would probably rename your Checklist model to DeclarationQuestionAnswer). Remove the __init__ code from your ChecklistForm and add all the fields to fields.
You are going to use formsets to list all the questions in your form. You will have to check out the docs on how these work, but to set the formset up you will do this:
questions = []
for q in Question.objects.all():
    questions.append({'question': str(q.id), 'is_yes': None})
formset = inlineformset_factory(Declaration, Checklist,
    form=ChecklistForm, fk_name="declaration", extra=len(questions),
                can_delete=False)
question_formset = formset(prefix='questions_fs', initial=questions)

UPDATED: Your view for saving the forms is not correct, should be something like this:
if request.method == 'POST':
    formset = inlineformset_factory(Declaration, Checklist,
    form=ChecklistForm, fk_name="declaration")
    declaration_form = DeclarationForm(request.POST)
    if declaration_form.is_valid():
        declaration_form.user = request.user
        declaration = declaration_form.save(commit=False)
        checklist = formset(request.POST, prefix='question_fs', instance=declaration)
    if checklist.is_valid():
            with transaction.atomic():
                declaration.save()
                checklist.save()

A: Hi tenzai and welcome to the great stackoverflow community!
1. django model.ManyToManyField
One way to deal with such many to many architecture (Checklist) is the use django admin widget with the models.ManyToManyField declaration. Widget in forms.py from django.contrib.admin.widgets import FilteredSelectMultiple. But for that, you'll have to simplify your model.

*

*Checklist.is_yes field is useless since data presence in the checklist table attest that a user checked a question.

*If you don't have any other field in Declaration class it is also useless.

From there, the only thing you need is the declaration of a many2many relation to Question class from User class. But in that case, you'll have to use a custom user model or a one to one relation to Auth.models.User class of django. Cfr. How to Extend Django User Model
# Add this question field to the custom User class
question = models.ManyToManyField(Question, verbose_name="Question")

The form become
from django.contrib.auth import get_user_model
from django.contrib.admin.widgets import FilteredSelectMultiple

class ChecklistForm(forms.ModelForm):

    class Meta:
        model = get_user_model()
        widgets = {"question" :
             FilteredSelectMultiple(Question._meta.verbose_name_plural, False)
        }

But this will result in a simple drag and drop of your questions from left to right.
2. Left join raw SQL
One other way to do it would be to build a function view with a left join raw SQL. Keep your model as it is
2.1. models.py
Remarks from point 1. remains and therefore Checklist class become
from django.contrib.auth import get_user_model

my_user_model = get_user_model()

class Checklist(models.Model):
    id = models.BigAutoField(primary_key=True)
    user = models.ForeignKey(my_user_model, related_name='checklist_declaration', on_delete=models.CASCADE)
    question = models.ForeignKey(Question, related_name='checklist_question', on_delete=models.CASCADE)

You must go for this architecture if you are planing to add specific fields into the Checklist (Question & User combinations)
2.2. views.py
Note for Checklist.is_deletable method called into the view:

If your selected fields of questions are referenced somewhere in your
DB you need to ensure that the unselection of the choice will not
delete all related field of the specified user quesion in your DB.
That's where the
is_deletable
method intervenes.

import logging

from django.shortcuts import render, redirect
from django.utils.translation import gettext_lazy as _
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .models import Checklist, Question

LOG = logging.getLogger(__name__)

@login_required
def my_question(request):
    """
    Function view based on raw select in order to manage outer join
    and display
    """
    myuser = request.user
    qchecks = Checklist.objects.raw('''
    select qq.id, qq.title, aa.qid from question_question as qq
    left join (select question_id as qid
                 from question_checklist
                where user_id = {0}) aa
    on aa.qid = qq.id
    order by qq.title ASC
    '''.format(myuser.id))

    if request.method == 'POST':
        # selected elements provided by the form
        selected = request.POST.getlist("qcheck")
        for ticked in selected:
            ticked_inst = Question.objects.get(id=ticked)
            Checklist.objects.for_user(myuser).get_or_create(profile=myuser,
                                                             question=ticked_inst)

        # Get unselected elements and remove them
        unselected_inst = Question.objects.exclude(id__in=selected)
        for unticked in unselected_inst:
            try:
                obj = Checklist.objects.filter(user=myuser).get(question=unticked)
                # check related before delete
                related_list = Checklist.is_deletable(obj)
                if related_list:
                    messages.error(request,
                        _(f"Checklist delete {obj}. Please first delete related records.")
                    )
                    for related in related_list:
                        related_model = related.model._meta.verbose_name
                        related_values = [i.__str__() for i in related.all()]
                        msg = f"{related_model}: {related_values}"
                        messages.warning(request, msg)
                    return redirect('my_question')
                else:
                    obj.delete()
            except Checklist.DoesNotExist:
                pass
        messages.success(request, _('Changes saved'),
                                fail_silently=True)

        return redirect('my_question')

    context = {'user': request.user,
               'qchecks': qchecks,
               'myuser': myuser,
               'upd_allowed': upd_allowed}

    return render(request, 'select_question_form.html', context)

2.3. html template (select_question_form.html)
{% extends 'base.html' %}
{% load i18n %}

{% block content %}

Do you have

{% if qchecks %}

        <form action="" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {% for qcheck in qchecks %}

                {{ qcheck.title }}

                    <input type="checkbox" name="qcheck" value="{{ qcheck.id }}" {% if qcheck.id == qcheck.qid %} checked {% endif %}
                    {% if not upd_allowed%} disabled{% endif %}/>

        {% endfor %}
        {% if upd_allowed %}

<input class="btn btn-danger2" type="submit" value="{% trans "Save" %}" />

        {% endif %}

        </form>

{% else %}

No question check.

{% endif %}

{% endblock content %}

2.4 urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('questions', views.my_question, name='my_question')
]


text:
Q: ImageView lose ripple effect if it overlays another ImageView having setBackground The ripple effect on on iv_button ImageView works fine untill I set background on wrapper ImageView. How to fix this?
Any help would be greatly appreciated.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/wrapper"
        android:background="@color/green"  //the ripple effect works without this line
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <ImageView
        android:id="@+id/iv_button"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_centerInParent="true"
        android:background="?selectableItemBackgroundBorderless"
        android:clickable="true"
        android:src="@android:drawable/ic_delete" />

</RelativeLayout>

A: If you set a background in that xml you will lose the ripple effect. If you want to keep it, you should set it in an style and then give that style to your button.


text:
Q: Numpy : convert 2D array to 3D array I have a 2 dimensional array : A = numpy.array([[1, 2, 3], [4, 5, 6]]) and would like to convert it to a 3 dimensional array : B = numpy.array([[[1, 2, 3], [4, 5, 6]]])
Is there a simple way to do that ?

A: Simply add a new axis at the start with np.newaxis -
import numpy as np

B = A[np.newaxis,:,:]

We could skip listing the trailing axes -
B = A[np.newaxis]

Also, bring in the alias None to replace np.newaxis for a more compact solution -
B = A[None]

A: It is also possible to create a new NumPy array by using the constructor so that it takes in a list.  This list contains a single element which is the array A and it will allow you to create same array with the singleton dimension being the first one.  The result would be the 3D array you desire:
B = numpy.array([A])

Example Output
In [13]: import numpy as np

In [14]: A = np.array([[1, 2, 3], [4, 5, 6]])

In [15]: B = np.array([A])

In [16]: B
Out[16]:
array([[[1, 2, 3],
        [4, 5, 6]]])


text:
Q: Target (variable "") is not a signal error in VHDL I have this piece of code
  function func (k1, k2 : in bit_vector) return bit_vector is

    variable result : bit_vector(1 to 32);

    begin
        for i in 0 to 31 loop
            result(i) <= k1(i);
        end loop;

        return result;
    end func;

I get this error :

target (variable "result") is not a signal

I know I need to change the type of result but I don't know what it should be.
Thanks.

A: When assigning to a variable use := as:
result(i) := k1(i);

Assign with <= is for assign to signal.
The range of result (1 to 32) does not match the range in the loop (0 to 31), so first assign in the loop (result(0) := k1(0)) will cause in a range error.  Fix this by changing either result or loop range.


text:
Q: Projective Special Linear Group is an Linear Algebraic Group So I was wondering why the group $PSL(2,K)$ is a linear algebraic group, in the case that the characteristic of $K$ is not equal to $2$.
Actually there is a description of $PSL(2,K)$, namely:
$PSL(2,K) = SL(2,L)/C,$
whereas $C$ is the center of $SL(2,K)$, namely the subrgoup $x  \cdot I$, with $I$ the identity and $x$ any solution of $x^2 = 1$.
We can embedd $SL(2,K)$ in the affine space $\mathbb{A}^4$ where the coordinate ring is just $K[x_1,x_2,x_3,x_4]/(x_1x_3 - x_2x_4 - 1)$. We can simply extend the action of $C$ on the affine space $\mathbb{A}^4$. But I dont know houw to embedd $\mathbb{A}^4/C$ in some bigger affine space, s. th. we get a description of $PSL(2,K)$ i.e. s. th. $PSL(2,K)$ is itself an linear algebraic group.
I would appreciate some hints.

A: The general result is that the quotient of a linear algebraic group by a closed normal subgroup is a linear algebraic group.  Surprisingly this doesn't appear to be in Humphries, but it's definitely in Springer.  The proof doesn't work by quotienting all of the ambient affine space, though; IIRC the idea of all these results is to let a group act on a ring of functions, extract a finite-dimensional faithful subrepresentation, and use that to embed the group as a subgroup of some $GL_n$.

A: I haven't checked everything, but I think the following works.
Let $\{x_1,x_2\}$ be a basis for the space that $SL_2(K)$ acts on naturally. That is
$$
x_1=\binom10,\qquad x_2=\binom01,
$$
and
$$
A=\left(\begin{array}{rr}a&b\\c&d\end{array}\right)
$$
acts as $A.x_1=ax_1+cx_2$, $A.x_2=bx_1+dx_2$.
The group $SL_2(K)$ then also acts on the 3-dimensional space of homogeneous quadratic polynomials, spanned by $\{x_1^2,x_1x_2,x_2^2\}$. The action goes by the above linear substitutions, so for example $A.x_1^2=(ax_1+cx_2)^2$ et cetera. This gives a homomorphism from $f:SL_2(K)\to GL_3(K)$ - a 3-dimensional representation of $SL_2(K)$ if you wish.
The point is that the matrix $-I_2$ is in the kernel of $f$. Because the center is the only non-trivial normal subgroup of $SL_2$ we have, in fact, $\ker f=\langle -I_2\rangle$.
So the remaining task is to show that $\operatorname{Im} f\cong PSL_2(K)$ is an algebraic subgroup of $GL_3(K)$.

A: Despite being 6 years too late to answer the question, I really enjoyed going through the details of Jyrki's suggestion, and I would like to share my results here.
Let $\mathbb{k}$ be any base field of characteristic $\neq 2$ (actually, any base ring containing $1/2$ would do). Jyrki's group action leads to a homomorphism $\varphi \colon \mathrm{SL}_2 \to \mathrm{SL}_3$
$$ \left( \begin{array}{cc} a & b\\ c & d \end{array} \right) \mapsto \left( \begin{array}{cc} a^2 & ab & b^2\\ 2ac & ad+bc & 2bd\\ c^2 & cd & d^2\end{array} \right) $$
of algebraic groups over $\mathbb{k}$. The kernel of $\varphi$ is canonically isomorphic to $\mu_2$ (the algebraic group given by the equation $x^2=1$). My aim is to find the image of $\varphi$ as an algebraic group in the naive sense, i.e. the smallest functor of subgroups of $\mathrm{SL}_3$ given by polynomial equations containing the set theoretic image of $\varphi$.

As a possible candidate for the image of $\varphi$, consider the functor $G \colon \mathbb{k}\text{-}\mathrm{Alg} \to \mathrm{Set}$ sending any $\mathbb{k}$-algebra $A$ to the subset of ($3\times3$)-matrices $(x_{ij}) \in A^{3 \times 3}$ satisfying the following equations.
$$
\begin{align}
x_{11} x_{13} &= x_{12}^2 \tag{1}\label{eq:1}\\
x_{31} x_{33} &= x_{32}^2 \tag{2}\label{eq:2}\\
x_{11} x_{33} - 2x_{12}x_{32} + x_{13}x_{31} &= 1 \tag{3}\label{eq:3}\\
2(x_{32} x_{11} - x_{31}x_{12}) &= x_{21} \tag{4}\label{eq:4}\\
2(x_{33} x_{12} - x_{32}x_{13}) &= x_{23} \tag{5}\label{eq:5}\\
2(x_{32} x_{12} - x_{31}x_{13}) &= x_{22}-1 \tag{6}\label{eq:6}\\
2(x_{33} x_{11} - x_{32}x_{12}) &= x_{22}+1 \tag{7}\label{eq:7}\\
\end{align}
$$
It is easy to check that the matrices produced by $\varphi$ all satisfy \eqref{eq:1} - \eqref{eq:7}, so $\varphi$ gives rise to a natural transformation $\varphi' \colon \mathrm{SL}_2 \to G$ of functors. The hard part is to show that these equations imply all polynomial equalities satisfied by those matrices. For example, it is easy to see that all matrices produced by $\varphi$ have determinant one, but how does this follow from \eqref{eq:1} - \eqref{eq:7}? It is also unclear at the moment whether $G$ is a group functor, i.e. whether matrices satisfying \eqref{eq:1} - \eqref{eq:7} are closed under multiplication and inversion.

All those questions can be answered at once by the following "surjectivity" condition.
Claim:  For any $\mathbb{k}$-algebra $A$ and for any matrix $X \in G(A)$ there is an algebra extension $B/A$ such that $X$ (regarded as an element of $G(B)$) can be pulled back to $\mathrm{SL}_2(B)$.
Proof: Let $A$ be any $\mathbb{k}$-algebra, and let $X = (x_{ij}) \in G(A)$ be some element. We construct the extension algebra $B$ in two steps: First, we define an $A$-module M, then we pick two elements $a,b \in \mathrm{End}_A(M)$ and define $B$ as the $A$-sub-abgebra generated by $a$ and $b$. Finally, we pick certain elements $c,d \in B$ such that $ad-bc=1$ and
$\varphi \left( \begin{array}{cc} a&b\\c&d \end{array}\right) = X.$
We define $M$ by 3 generators and 2 relations:
$$ M = \left\langle \hat{1}, \hat{a}, \hat{b} \mid x_{12}\hat{a}=x_{11}\hat{b}, x_{13}\hat{a}=x_{12}\hat{b} \right\rangle $$
The endomorphisms $a,b \in \mathrm{End}_A(M)$ are defined by their actions on the generators:
$$ a \colon \quad \hat{1} \mapsto \hat{a}, \quad \hat{a} \mapsto x_{11}\hat{1}, \quad \hat{b} \mapsto x_{12} \hat{1} $$
$$ b \colon \quad \hat{1} \mapsto \hat{b}, \quad \hat{a} \mapsto x_{12}\hat{1}, \quad \hat{b} \mapsto x_{13} \hat{1} $$
Checking $a$ and $b$ are well-defined is immediately done by looking at equation $\eqref{eq:1}$. It is easy to check (again, by looking at the generators of $M$) that
$$ a^2 = x_{11}, \quad b^2 = x_{13}, \quad ab = ba = x_{12} \tag{*} \label{eq:b_rels} $$
holds.
Let $B$ be the (commutative!) $A$-sub-algebra of $\mathrm{End}_A(M)$ generated by $a$ and $b$. We define the elements $c, d \in B$ by
$$ c = x_{32}a - x_{31}b, \quad d = x_{33}a - x_{32}b. $$
Now $c^2 = x_{31}$ follows by $\eqref{eq:2}$ and $\eqref{eq:3}$, $ac = x_{21}/2$ follows by $\eqref{eq:4}$, and $bc = (x_{22}-1)/2$ follows by $\eqref{eq:6}$.
Likewise, $d^2 = x_{33}$ follows by $\eqref{eq:2}$ and $\eqref{eq:3}$, $ad = (x_{22}+1)/2$ follows by $\eqref{eq:7}$, and $bd = x_{23}/2$ follows by $\eqref{eq:5}$.
Finally, $cd = x_{32}$ follows by $\eqref{eq:2}$ and $\eqref{eq:3}$, and $ad+bc = x_{22}$ as well as $ad-bc=1$ are immediate.
In summary, we have found a matrix $\left( \begin{array}{cc} a&b\\c&d \end{array}\right) \in \mathrm{SL}_2(B)$ sent to $X \in G(B)$ by $\varphi'$. $\square$

Let's see how this property answeres the previous questions. To begin with, let's see why all matrices in $G$ have determinant one.
Let $A$ be any $\mathbb{k}$-algebra, and let $X \in G(A)$. By "surjectivity" we can extend $A$ to an algebra $B$ such that $X$ regarded as an element of $G(B)$ can be written as $X = \varphi'(X')$ for some matrix $X' \in \mathrm{SL}_2(B)$. Since we already know that all matrices produced by $\varphi'$ have determinant one, the same must be true for $X$ (even as an element of $G(A)$).
Exactly the same argument shows that all polynomial equations satisfied by the set theoretic image of $\varphi$ are also satisfied by the elements of $G$. In this way, $G$ is "as small as possible".
Analogously, we can show that $G$ is an algebraic group. Let $A$ be any $\mathbb{k}$-algebra, and let $X, Y \in G(A)$ arbitrary matrices. Of course the product matrix $X \cdot Y$ has coefficients in $A$, so in order to prove $X \cdot Y \in G(A)$, we only have to show that this product satisfies the equations $\eqref{eq:1} - \eqref{eq:7}$. This is easily done by "surjectivity": We may extend $A$ (twice if necessary) to an algebra $B$ and pick matrices $X', Y' \in \mathrm{SL}_2(B)$ such that $\varphi'(X') = X$ and $\varphi(Y') = Y$. Therefore, $XY = \varphi'(X'Y')$ satisfies all defining equations for $G$, whence $XY \in G(A)$. In the same way we conclude $X^{-1} \in G(A)$.
In summary, we see that $\varphi$ factors into a composition
$$ \mathrm{SL}_2 \to G \to \mathrm{SL}_3, $$
and $G$ is the smallest closed subgroup of $\mathrm{SL}_3$ with that property.

Using the basics of the theory of algebraic quotient groups, one can easily show that $G$ (together with $\varphi')$ is the quotient of $\mu_2 \to \mathrm{SL}_2$. However, our construction shows that it would be a bad idea to call this quotient $\mathrm{PSL}_2$, since $\varphi'$ is not surjective for all fields $\mathbb{K}$. More concretely, $G(\mathbb{K})$ in general contains strictly more elements than $\mathrm{PSL}_2(\mathbb{K})$. For example, the matrix
$$ \left(\begin{array}{cc} -1 & 0 & 0\\ 0 & 1 & 0\\ 0 & 0 & -1 \end{array}\right) \in G(\mathbb{Q}) $$
is not in the image of $\varphi' \colon \mathrm{SL}_2(\mathbb{Q}) \to G(\mathbb{Q})$, and therefore does not correspond to an element of $\mathrm{PSL}_2(\mathbb{Q})$. (However, it corresponds to an element of $\mathrm{PSL}_2(\mathbb{Q(i)})$, as it can be written by $ \varphi' \left(\begin{array}{cc} i & 0\\ 0&-i \end{array}\right)$). Surprisingly, it turns out that $G$ is isomorphic to $\mathrm{PGL}_2$!


text:
Q: redirect to controller action from view component Trying to return a regular view or even redirect to a controller action method from a viewcomponent(.cs) for one edge case.  Is this possible?

A: @Html.Action("MethodName", "ControllerName", param)

In the controller return a partial view:
    public ActionResult MethodName(paramType param)
    {
        return PartialView("viewName", param);
    }


text:
Q: Why does Dynamics CRM 2013 plugin fire twice on owner change? I have a simple plugin for a custom entity that is set to trigger on Update of my custom entity. It is registered in the Post Operation stage. I have noticed some strange behaviour when I make changes to the Owner field of the record in addition to other standard fields (e.g. text boxes, dates etc).
The plugin fires the first time and the only attributes that come across in the image are all the regular fields. The owner field does not come across.
The plugin then fires again, but the Depth property of the context is still only one (i.e. the plugin is not getting triggered by changes made in the plugin code). In this run of the plugin, the attribute that come across is only the Owner field.
My theory is that because the owner fields are 'special', the CRM is doing two different requests - one to change the regular fields, and then another request for changing the owner via an AssignRequest. However, I cannot find any 'official' documentation for this behaviour.
Can someone explain why this is happening?
I am running Dynamcs CRM 2013 UR2

A: The Update event fires during the Assign event. So if an assignment takes place your plug-in will execute. The same is true for SetState - if you activate/deactivate a record an Update event takes place. These items are not documented in the SDK.
A good practice is to use Attribute Filtering on your Update plugin so it only fires for the fields it is concerned about - this will, assuming it is isn't looking at the owner related fields, avoid it firing twice. If you have logic specific to record ownership you would put it in a plugin that is registered on the Assign event.

A: I was not able to find official documentation about this, but I think Assign message is what you are looking for (if the entity is user-owned. See http://msdn.microsoft.com/en-us/library/gg328576.aspx. I would strongly recommend that you specify Filtering Attributes if you are registering a plugin on Update message. You could also debug your plugin and inspect MessageName property of plugin context and see what message gets triggered. I hope this helps.


text:
Q: What term describes the property that of terms can be multiplied or divide in any order? What term describes the property of terms that can be multiplied or divided in any order?
ie, xyz = yxz
or x+y+xy+c = c+x+y+yx

A: The property that describes the fact that the order in which a sum or product is done does not affect the outcome of the sum or product is called the commutative property, and the property may extend to all sorts of different operations, like group multiplication (in Abelian groups, of course).
EDIT:
  Notice that commutativity does not always hold; as an example, consider multiplication of matrices in the set of all $n\times n$ matrices with entries in (for definiteness) the reals, in which the only matrices that commute with all other scalar matrices are the matrices that are scalar multiples of the identity, i.e., matrices of the type $cI$ , where $c$ is a real scalar, and $I$ is the identity  See e.g this link. Still, there are subsets of the set of all matrices with real entries that commute with each other under multiplication, like rotation matrices (with all rotations done about the same axis of rotation). The fact that these matrices commute is a reflection of the fact that rotating (again, fixing the axis of rotation) first by an angle $\theta$ and then by $\alpha$ is equivalent to rotating first by $\alpha$ and then by $\theta$.


text:
Q: REST API: How to query oldest data - Limits/Offset I'm trying to retrieve the oldest collections on Opensea, I'm using this https://docs.opensea.io/reference/retrieving-collections. Using the maximum of limits and offests
( https://api.opensea.io/api/v1/collections?limit=300&offset=50000 ) the oldest collection I'm able to fetch it's only dated 2 days ago! Any tips?


text:
Q: How to write functional tests I have the requirement to test a Kafka consumer method which in turn creates a post call to another service. How can I write wiremock for the another service. The code is:

*

*Kafka Consumer

func (handler FxmWorklogEventHandler) ProcessMessage(message kafka.Message) (swgykafka.Status, error) {
    txn := util.TraceTransaction(handler.MessageType())
    if txn != nil {
        defer txn.End()
    }
    var fxmWorklogEvent event.FxmWorklogEvent
    err := json.Unmarshal(message.Data, &fxmWorklogEvent)
    if err != nil {
        log.Error().Err(err).Msg("FxmWorklogEventHandler - Failed to un marshall the message")
        return swgykafka.HardFailure, err
    }
    log.Info().Msgf("Processing fxm worklog event for order %s", fxmWorklogEvent.OrderId)
    fxmEventToPersist := BuildFxmEventToPersist(fxmWorklogEvent)
    _, err = handler.am.SaveFxmWorklog(fxmEventToPersist)
    if err != nil {
        log.Error().Err(err).Msgf("Failed to save fxm worklog event in am for order %s", fxmWorklogEvent.OrderId)
        return swgykafka.SoftFailure, nil
    }

    return swgykafka.Success, nil
}

*Post  Call

func (am *AssistanceManagerClient) SaveFxmWorklog(r request.FxmWorklogDetails) (*response.BaseResponse, error) {
    url := config.Client.GetString(amHost) + util.AssistanceManagerSaveFxmWorklog
    return am.hc.Post(url, r, http.Header{}, util.AssistanceManagerCommand)
}

*External Service Method

func SaveFxmWorklog(w http.ResponseWriter, r *http.Request) {
    var rb entity.FxmWorklogDetails
    err := json.NewDecoder(r.Body).Decode(&rb)
    if err != nil {
        log.Error().Err(err).Msgf("Failed to parse the fxm worklog request %s", util.ToJSON(rb))
        util.ErrorResponse(w, err.Error(), http.StatusBadRequest)
        return
    }
    log.Info().Msgf("Save fxm worklog request received for order %s", rb.OrderId)
    response, err := service.FxmService.SaveFxmWorklogEvent(rb)
    if err != nil {
        log.Error().Err(err).Msgf("Failed to save fxm worklog event %s", util.ToJSON(rb))
        util.ErrorResponse(w, err.Error(), http.StatusInternalServerError)
        return
    }
    w.WriteHeader(response.HTTPStatusCode)
    _ = json.NewEncoder(w).Encode(response)
}

How can I test this method by wiremocking the external service api call?


text:
Q: Insert order and pagination with Cassandra Let me start from saying that I'm not very experienced with Cassandra and there is a chance I'm trying to use it for an incorrect task.
I'm having a piece of code which stores URLs I want to visit
List<URL> urls = new ArrayList();

The problem is that I'm storing lots of URLs and my application runs of of memory. In fact in don't want to keep this list in memory because it will grow to gigabytes. Cassandra appears to be the best solution because it can store data sets which are greater than available memory.
I created a simple table
CREATE TABLE links (
    url text,
    PRIMARY KEY(url));

and I was trying to get the next URL like this
SELECT *
FROM url
WHERE token(url) < ?
LIMIT 1
Where ? is the recently visited URL.
The problem is that if I insert new URLs before running the above query those URLs might be inserted "below" the recently visited site. My application will miss them and will never go to those pages.
My question is how paginate though a growing table (while it's growing) and not miss anything?

A: url in your case is a partition key, and defines a node on which the row (partition) will be stored. It doesn't define an order of rows (partitions).
http://cassandra.apache.org/doc/cql3/CQL.html#createTablepartitionClustering

A: Cassandra doesn't exactly fit your use case. You may want to look at a journaling system. May be look at Java Chronicle to see if it is a better fit.


text:
Q: cuFFT output not correct I have a problem with this program:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <cufft.h>
#include <cuComplex.h>

#define SIGNAL_SIZE        1024

int main(int argc, char **argv) {
   cudaEvent_t start, stop;
   cudaEventCreate(&start);
   cudaEventCreate(&stop);

   // Allocate host memory for the signal
   cuDoubleComplex *h_signal = (cuDoubleComplex *) malloc(sizeof(cuDoubleComplex) * SIGNAL_SIZE);

   // Initalize the memory for the signal
   for (unsigned int i = 0; i < SIGNAL_SIZE; ++i) {
      if((double)i/SIGNAL_SIZE>=0 && (double)i/SIGNAL_SIZE<0.5)  h_signal[i].x = (double)i/SIGNAL_SIZE;
      else if((double)i/SIGNAL_SIZE>=0.5 && (double)i/SIGNAL_SIZE<1)  h_signal[i].x = (double)i/SIGNAL_SIZE-1;
      h_signal[i].y = 0;
   }

// Allocate device memory for signal
   cuDoubleComplex *d_signal;

   cudaMalloc((void **) &d_signal, SIGNAL_SIZE*sizeof(cuDoubleComplex));
   // Copy host memory to device
   cudaMemcpy(d_signal, h_signal, SIGNAL_SIZE*sizeof(cuDoubleComplex), cudaMemcpyHostToDevice);

cudaEventRecord(start, 0);
   cufftHandle plan;
   cufftPlan1d(&plan, SIGNAL_SIZE , CUFFT_C2C, 1);

   // FFT computation
   cufftExecC2C(plan, (cufftComplex *) d_signal, (cufftComplex *) d_signal,
         CUFFT_FORWARD);

    cufftExecC2C(plan, (cufftComplex *) d_signal, (cufftComplex *) d_signal, CUFFT_INVERSE);

   cuDoubleComplex *h_signal_inv =(cuDoubleComplex *) malloc(sizeof(cuDoubleComplex) * SIGNAL_SIZE);
   cudaMemcpy(h_signal_inv, d_signal, sizeof(cuDoubleComplex) * SIGNAL_SIZE, cudaMemcpyDeviceToHost);

   cudaEventRecord(stop, 0);
   cudaEventSynchronize(stop);

   float elapsedTime;
   cudaEventElapsedTime(&elapsedTime, start, stop);
   printf("Elapsed Time:  %3.1f ms\n", elapsedTime);

    for(int i=0;i<SIGNAL_SIZE;i++) printf("\n%f %f", h_signal[i].x, h_signal_inv[i].x);

    cufftDestroy(plan);

   free(h_signal);
   free(h_signal_inv);

   cudaFree(d_signal);

   cudaDeviceReset();
   return 0;
}

I'd like to transform a signal and then come back with the inverse, but the output is wrong in the first half.
Can you help me to find the errors?
Thank you very much!

A: You are getting your datatypes confused.
cufftDoubleComplex is not the same as cufftComplex.  When using cufftDoubleComplex, your transform type should be Z2Z, not C2C.
Also, in order to see data parity when doing a forward transform followed by an inverse transform using CUFFT, it's necessary to divide the result by the signal size:

cuFFT performs un-normalized FFTs; that is, performing a forward FFT on an input data set followed by an inverse FFT on the resulting set yields data that is equal to the input, scaled by the number of elements. Scaling either transform by the reciprocal of the size of the data set is left for the user to perform as seen fit.

The following code has the above issues addressed and should give you better results:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <cufft.h>
#include <cuComplex.h>

#define SIGNAL_SIZE        1024

int main(int argc, char **argv) {
   cudaEvent_t start, stop;
   cudaEventCreate(&start);
   cudaEventCreate(&stop);

   // Allocate host memory for the signal
   cuDoubleComplex *h_signal = (cuDoubleComplex *) malloc(sizeof(cuDoubleComplex) * SIGNAL_SIZE);

   // Initalize the memory for the signal
   for (unsigned int i = 0; i < SIGNAL_SIZE; ++i) {
      if((double)i/SIGNAL_SIZE>=0 && (double)i/SIGNAL_SIZE<0.5)  h_signal[i].x = (double)i/SIGNAL_SIZE;
      else if((double)i/SIGNAL_SIZE>=0.5 && (double)i/SIGNAL_SIZE<1)  h_signal[i].x = (double)i/SIGNAL_SIZE-1;
      h_signal[i].y = 0;
   }

// Allocate device memory for signal
   cuDoubleComplex *d_signal;

   cudaMalloc((void **) &d_signal, SIGNAL_SIZE*sizeof(cuDoubleComplex));
   // Copy host memory to device
   cudaMemcpy(d_signal, h_signal, SIGNAL_SIZE*sizeof(cuDoubleComplex), cudaMemcpyHostToDevice);

cudaEventRecord(start, 0);
   cufftHandle plan;
   cufftPlan1d(&plan, SIGNAL_SIZE , CUFFT_Z2Z, 1);

   // FFT computation
   cufftExecZ2Z(plan, d_signal, d_signal, CUFFT_FORWARD);

    cufftExecZ2Z(plan, d_signal, d_signal, CUFFT_INVERSE);

   cuDoubleComplex *h_signal_inv =(cuDoubleComplex *) malloc(sizeof(cuDoubleComplex) * SIGNAL_SIZE);
   cudaMemcpy(h_signal_inv, d_signal, sizeof(cuDoubleComplex) * SIGNAL_SIZE, cudaMemcpyDeviceToHost);

   cudaEventRecord(stop, 0);
   cudaEventSynchronize(stop);

   float elapsedTime;
   cudaEventElapsedTime(&elapsedTime, start, stop);
   printf("Elapsed Time:  %3.1f ms\n", elapsedTime);

    for(int i=0;i<SIGNAL_SIZE;i++) printf("\n%f %f", h_signal[i].x, h_signal_inv[i].x/SIGNAL_SIZE);

    cufftDestroy(plan);

   free(h_signal);
   free(h_signal_inv);

   cudaFree(d_signal);

   cudaDeviceReset();
   return 0;
}


text:
Q: Line break (continuation) for commands (options, arguments) How to do proper line breaking (continuation) for commands, i.e. their options and/or their arguments? For example, in order to transform this:
\usepackage[top=1.0cm, bottom=1.0cm, left=1.0cm, right=1.0cm, includehead, includefoot]{geometry}

Into this:
\usepackage[top=1.0cm,
            bottom=1.0cm,
            left=1.0cm,
            right=1.0cm,
            includehead,
            includefoot]{geometry}

A: I don't know if I understood your question. Do you want to break lines automatically? You can just type RETURN. Also, insert a comment command at the end of line.
\usepackage[top=1.0cm,%
            bottom=1.0cm,%
            left=1.0cm,%
            right=1.0cm,%
            includehead,%
            includefoot]{geometry}

A: keyval (and I think most key/value parsing packages following it) trims all white space around the , and the =. So
[a=b,c=d]

is the same as
[ a
=
b , , , ,
c
=
d
]


text:
Q: a prototype question in javascript <script type="text/javascript">

var Person =
{

    Create: function(name, age) {
        this.name = name;
        this.age = age;
    },
    showMe: function() {
        return " Person   Name: " + this.name + "  Age: " + this.age + " ";
    }
};

function New(aClass, aParams) {
    function new_() {
        aClass.Create.apply(this, aParams);
    };
    new_.prototype = aClass;
    var obj = new new_();
    return obj;
}
</script>

I don't quite understand the code above. Could someone tell me the meanings of Person, Create, showMe, New and new_? Thanks a lot.

A: Person is an object with two functions - Create and showMe. In JavaScript, there are no classes, only objects, and this is how you write up an object - using 'Object Literal Notation' (the curly braces and functions/properties separated by commas).
New is a clever re-implementation of the new keyword. Instead of classes, javascript has prototypes, and instead of creating an instance of a class you create a copy of the prototype. In this case, if you passed Person to New(), it would used as the prototype in new_.prototype = aClass, and the rest of this function will return an object with the Person prototype, which means any changes to Person later on will be inherited into obj as well (unless obj has overridden them).

A: `Person` -- a variable w/ 'parts' (used loosely) `Person.Create` and `Person.showMe'
     `Person.Create` -- function of `Person` that sets `Person.name` and `Person.age` to its arguments
     `Person.showMe` -- returns a string explaining values of `Person.name` and `Person.age`

`New` -- a function intended to instantiate new Person's thru prototypal (this is NOT class based) inheritenced
  `New._new` -- `New` uses this to get it done

Basically thru prototype inheritence, even though Person is only 'made' once, other 'versions' of it can be constructed in kind.  It can be used like this (try it here: http://jsfiddle.net/PBhCs/)
var Person =    {
    Create: function(name, age)
    {
        this.name = name;
        this.age = age
    },

    showMe: function()
    {
        return " Person   Name: " + this.name + "  Age: " + this.age + " ";
    }
};

function New(aClass, aParams)
{
    function new_()
    {
        aClass.Create.apply(this, aParams);
    };
    new_.prototype = aClass;
    var obj = new new_();
    return obj;
}

var a = New(Person, ['moo', 5]);
var b = New(Person, ['arf', 10]);
alert(a.showMe() + b.showMe());


text:
Q: Empty variable after function is complete I have a addMovie function in this template,
%ul#showresults
  %li.search_results{"ng-if" => "movie.release_date && movie.poster_path", "ng-repeat" => "movie in movieList | orderBy:'-release_date'"}
    .addmovie{"ng-click" => "addMovie(movie)"}
      %span
        Add Movie

When a user clicks the .addmovie div the addMovie(movie) function fires,
$scope.wishlistID = [];

$scope.addMovie = function(movie) {
  $scope.wishlistID.push({id: movie.id});
  var movieID = $scope.wishlistID[0].id;
  console.log (movieID)

  movieAdd.add(movieID)
   .then(function(response){
      $scope.movieListID = response;

This function pushes the ID of the movie record that's been added into a scope called wishlistID and passes it into a variable. Then it requests a function called add in the movieAdd service and passes the movieID variable with it,
var service = {};
var baseUrl = 'http://api.themoviedb.org/3/movie/';

function httpPromise (url) {
  var deferred = $q.defer();
  $http({
    method:'JSONP',
    url: url
  })
    .success(function(data){
      deferred.resolve(data);
    })
    .error(function(){
      deferred.reject();
    });
  return deferred.promise;
}

service.add = function(movieID){
  return httpPromise(
    baseUrl + movieID + '?api_key=a8f7039633f2065942cd8a28d7cadad4&query=' + '&append_to_response=releases&callback=JSON_CALLBACK')
}

The service does a JSONP request and returns the data which get put into the movieListID scope.
Now if I add a movie it stores the ID of that movie into the variable, something like 140048, but if I enter a new searchquery and add a different movie the variable movieID still has the 140048 value, which causes the app to add the same movie again (even though there's been a new search action, and a new movie!)

A: It appears you keep grabbing the same index of the wishListID array, which is the first index (the first movie you add).
var movieID = $scope.wishlistID[0].id;

Why not update this line to match:

movieAdd.add(movie.id)

Instead of:

movieAdd.add(movieID)

Edit:
Are you just trying to find the key value that the movie was added for? Instead of the 'movie id' that the object contains, that is passed through the function.


text:
Q: Git fetch remote branch A few hours ago I created a new branch on my home machine (eg. branch2), and pushed it to remote. On another machine at work, I created the same local branch, but fetching remote branch doesn't update my local repo with git fetch. My guess is that my local branch on other machine isn't tracked. Should I add track to my local branch, delete local branch, and checkout on remote branch?

A: You need to rebase your local branch with the remote branch.
For this just do the following::
git fetch
git rebase origin/your_branch

This should solve your problem.

A: Git fetch only used to fetch the delta from the remote. If you want to fetch the remote content and want them in your working directory.
git fetch

Only fetches the delta only.
If you want to fetch the  remote contents and want the changes within your remote repository.
git pull = git fetch + git merge

Try using pit pull and the results will be in your working directory.


text:
Q: How to manipulate structure members using bitwise operations? For example, for a structure:
struct name{
 int a;
 char b;
 float c;
}g;
g.b='X';

Now I would like to access structure member b using bitwise operators(<<,>> etc.) and change it to 'A'.
Is it possible to access structure members using such operators??

A: Bitwise operations on struct's doesn't make to much sense because of padding and  more importantly it's just killing the purpose of having a struct in the first place. Bitwise operation are as the name said to operate on bit's in variable. Struct variables usually (if they're not packed) will be padded so until you pack them you wouldn't have guarantee where they are to access them but if you want to ask if you can, yes you can, but you would have to cast struct g to let's say 32 bit value then if two variables would be in this space you could use bit operation on this casted value. If it's necessary you can create union from your struct and have raw variable as one union part, and structure as the other option, then you can manipulate bitwise on raw variable.

A: You can change the data by getting offset of b. I know, this code does not look good.But it serve your purpose.
#include <stdio.h>

struct name
{
        int a;
        char b;
        float c;
}g;

int main()
{
        g.b='X';
        int y=0;

        int offset = &((struct name *)NULL)->b; // Find Offset of b
        char *p = (char *)&g;
        int i=0;

        for(i=0;i<offset;i++)
        {
                ++p;
        }

        *p=*p|(1<<0);

       // *p = 'A';

        printf("........%c\n",g.b);

}

A: there's a way, you have to copy the structure content into a variable (size of your struct), then manipulate the variable and finally copy the variable content back into the struct using memset.


text:
Q: How to Stop long duration execution task ( e.g. Infinite Loop) execution inside a Executor Service Below is a sample program. If i uncomment the Thread.sleep it works fine.
But there may be some need, where we are not sure how much time the code written inside Call method takes, can be a infinite time. Or, can be a bad program where the DB connection logic inside Call method takes more time and we need to kill.
Could you please tell, why the below code does not work if i comment the thread.sleep and how to kill and stop that without writing Thread.interrupted condition. (Assume i do not have permission write any logic inside the Call method)
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class stopThreadTest {

    public static void main(String[] args) {

        java.util.concurrent.ExecutorService executor = null;
        Future a1 = null;

        try {
            executor = java.util.concurrent.Executors.newFixedThreadPool(4);
            a1 = executor.submit(new java.util.concurrent.Callable() {
                public String call() throws Exception {
                    int i = 0;
                    while (true) {
                        //Thread.sleep(100);
                        // System.out.println("hello");
                        if (i > 10)
                            break;
                    }
                    return null;
                }
            });

            // Wait until all threads are finish
            /*
             * while (!executor.isTerminated()) { }
             */
            System.out.println("Calling PartialOrFullSuccessCheck");

            try {
                boolean isThreadError = (a1 != null) ? ((a1.get(2,
                        TimeUnit.SECONDS) == null) ? false : true) : false;

            } catch (TimeoutException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

                // interrupts the worker thread if necessary
                System.out
                        .println("Cancelled" + a1.isDone() + a1.isCancelled());
                a1.cancel(true);

                System.out.println("encountered problem while doing some work");
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

                // interrupts the worker thread if necessary
                System.out
                        .println("Cancelled" + a1.isDone() + a1.isCancelled());
                a1.cancel(true);
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

                // interrupts the worker thread if necessary
                System.out
                        .println("Cancelled" + a1.isDone() + a1.isCancelled());
                a1.cancel(true);
            }

        } finally {
            System.out.println("ShutDown Executor");
            executor.shutdown();
        }
    }
}

A: There is no safe way to stop a thread without its cooperation. Threads allow other threads to stop them by being interrupted, by periodically checking the value of some shared variable or both. Other than that, the only safe thing to do is shut down the JVM (the whole process). This post is quite detailed:
How do you kill a thread in Java?


text:
Q: Sebastien's jquery.flowchart how to manually add operator connector, renaming operator connector, saving I am using this jquery plugin by Sebastien
https://github.com/sdrdis/jquery.flowchart
It is an open source ui plugin that I can use to diagram the flow of the system i am developing. the problem is there are some tweaks that I would like to do but my knowledge on jquery is not sufficient enough to develop it on my own.
here is what I have to do.

*

*how to edit the operation connector.

*manually renaming the connector.

*after all the method has been done. saving the flowchart.

here is what i have so far.
HTML

    <button class="btn btn-primary" id="create_operator">Create A Start Operation</button>
    <button class="btn btn-danger" id="delete_selected_button">Delete Selected Operation</button>

        Operator's title: <input type="text" id="operator_title">
        Input: <input type="text" id="operator_input" />

jquery
$(document).ready(function () {
var data = {
    operators: {
        operator1: {
            top: 20,
            left: 20,
            properties: {
                title: 'Operator 1',
                inputs: {},
                outputs: {
                    output_1: {
                        label: 'Output 1',
                    }
                }
            }
        },
        operator2: {
            top: 80,
            left: 300,
            properties: {
                title: 'Operator 2',
                inputs: {
                    input_1: {
                        label: 'Input 1',
                    },
                    input_2: {
                        label: 'Input 2',
                    },
                },
                outputs: {}
            }
        },
    },
    links: {
        link_1: {
            fromOperator: 'operator1',
            fromConnector: 'output_1',
            toOperator: 'operator2',
            toConnector: 'input_2',
        },
    }
};

var $operatorProperties = $('#operator_properties');
var $linkProperties = $('#link_properties');
var $operatorTitle = $('#operator_title');
var $linkColor = $('#link_color');

// Apply the plugin on a standard, empty div...
var $flowchart = $('#example_8');
$flowchart.flowchart({
    data: data,
    onOperatorSelect: function (operatorId) {
        $operatorTitle.val($flowchart.flowchart('getOperatorTitle', operatorId));
        return true;
    },
    onOperatorUnselect: function () {
        $operatorProperties.hide();
        return true;
    }
});

$operatorTitle.keyup(function () {
    var selectedOperatorId = $flowchart.flowchart('getSelectedOperatorId');
    if (selectedOperatorId != null) {
        $flowchart.flowchart('setOperatorTitle', selectedOperatorId, $operatorTitle.val());
    }
});

var operatorI = 0;
$flowchart.siblings('#create_operator').click(function () {
    var operatorId = 'created_operator_' + operatorI;
    var operatorData = {
        top: 60,
        left: 500,
        properties: {
            title: 'Operator ' + (operatorI + 3),
            inputs: {
                input_1: {
                    label: 'Input 1',
                }
            },
            outputs: {
                output_1: {
                    label: 'Output 1',
                }
            }
        }
    };

    $operatorProperties.show();

    operatorI++;

    $flowchart.flowchart('createOperator', operatorId, operatorData);
});

$flowchart.siblings('#delete_selected_button').click(function () {
    $flowchart.flowchart('deleteSelected');
});

});

A: my solution is :
function create(nname, inC, outC) {
                var inp = '';
                var outp = '';
                if (inC < 0) {
                    inp = '"ins":{"label":"Input (:i)","multiple":true}';
                } else if (inC > 0) {
                    for (i = 0; i < inC; i++) {
                        inp += '"input_' + i + '":{"label":"Input (:i)"}';
                        if ((inC - 1) > i)
                            inp += ',';
                    }
                }
                if (outC < 0) {
                    outp = '"outs":{"label":"Output (:i)","multiple":true}';
                } else if (outC > 0) {
                    for (i = 0; i < outC; i++) {
                        outp += '"output_' + i + '":{"label":"Output (:i)"}';
                        if ((outC - 1) > i)
                            outp += ',';
                    }
                }
                var operatorId = 'nname' + operatorI;
                var operatorData = '{"top":200,"left":200,"properties":{"title":"'+nname+'","inputs":{' + inp + '},"outputs":{' + outp + '}}}';

                operatorI++;

                $flowchart.flowchart('createOperator', operatorId, JSON.parse(operatorData));
            }