Q:

How can I draw text to a window using a class?

I'm new to python and PsychoPy. I want to draw a window and show my instructions for a task. If spacebar is pressed, the next instruction is supposed to show.
I tried it without using a class but I would like to stick to object-oriented programming.
from psychopy import visual, core, event
winsize=[1536, 864]
mywin = visual.Window(winsize, monitor='testMonitor', units='deg',allowGUI=False, winType='pyglet',fullscr=True, color = 'dimgrey',colorSpace ='rgb')

class textstim():
    def __init__(self, win, txt='Unicorn'):
        self.window = win
        self.text = visual.TextStim(win, text=txt, font=['Gill Sans MT', 'Arial','Helvetica','Verdana'], pos=[winsize[0]/4,winsize[1]/4], units='deg', alignHoriz='left', wrapWidth=winsize[0]/2, alignVert='top', height=1.0, color='gainsboro')

    def settext(self, txt):
        self.text.setText(text=txt)

    def show_until_spacebar(self):
        while True:
            self.text.draw()
            self.window.flip()
            if event.getKeys(['space']):
                break

welcome = textstim(mywin)
welcome.settext("Hello!\n\n"
                "Thank you for participating!")
welcome.show_until_spacebar()

With my code I'm opening a window and when I hit space it closes again, but there is no text to be seen.

A:

I suspect the non-appearance of your text may simply be due to a units inconsistency. You have defined the units for the text stimulus to be in degrees, yet you calculate its position based upon the variable winsize, which is in pixels. I suspect the stimulus is being drawn, but it is massively offscreen (i.e. something like 1536/4 deg off to the right of centre and 864/4 deg above centre).
But at a higher level, you might want to give more though to your OOP design here. e.g., the init and settext methods of your textstim class just duplicate existing behaviour of the underlying TextStim class. So you could just add your new show_until_spacebar functionality to TextStim and be done with it, without all of that overhead. The fact that the two classes effectively have the same name indicates that there is some duplication going on (and as a result you've been forced to abandon the convention of naming classes with an initial capital, to avoid a conflict).
But regardless, you then perhaps need to consider whether the show_until_spacebar() functionality belongs in an individual stimulus class, or other more properly it should be added as a function to the Window class.
i.e. what happens if you want this functionality to exist for another sort of stimulus? Do you repeat yourself and add the same function to that class, or do you create a base superclass that they both inherit from? But even that is limiting. e.g. what happens if you want this functionality to exist for a window with multiple stimuli? It seems messy to call the function on only one of them.
That indicates that the function should probably reside in the Window class. There, it only needs to be defined once, and it can simply cycle through drawing all of the stimuli attached to it, and wait for the space bar. That way, it works cleanly, regardless of whether there it contains just a single text stimulus, or many others, and you then have a much more flexible function that can be used in other situations.
Good luck with whatever route you take: it is nice seeing someone consciously adopt an object-oriented approach to PsychoPy code. Being designed for non-programmers, it can more easily be used in a simple procedural way, but an object-oriented approach leads to more cognitive discipline on your part and hopefully much cleaner and more readable code. But if does require quite a bit of thought and preparation beforehand: if one hasn't properly conceptualised how the various classes will interact over the course of an experiment, you can end up backed into a corner due to an inflexible class system.


Q:

Ubuntu MATE 16.04 restart/shut-down halts due to a not responding program. How to stop it?

On my Ubuntu MATE 16.04, whenever I press shutdown, restart button, I get a message that at-spi-registryd.desktop program is not responding and I either need to wait for the program to finish or I could reboot/shutdown anyway (warns me that I may lose work). Why does this happen? How can I make the shutdown/restart process smoother ie. not see that message and restart/shutdown the normal way?

A:

This seems to be a regression of this bug:
https://bugs.launchpad.net/ubuntu/+source/unity/+bug/729827
So, the workaround (provided you dont need assistive technologies) would be:
sudo mv /usr/lib/at-spi2-core/at-spi2-registryd /usr/lib/at-spi2-core/at-spi2-registryd.old

This renames the file for at-spi2-registry so that the system won't run it, but maybe you also want to reopen it on launchpad.


Q:

Is web.xml required to deploy a spring boot application

I was trying to package a spring boot application as a war. According to this, I modified my Application class:
@SpringBootApplication
@EntityScan({"org.mdacc.rists.cghub.model"})
@EnableJpaRepositories(basePackages = {"org.mdacc.rists.cghub.ws.repository"})
public class Application extends SpringBootServletInitializer
{

    public static void main( String[] args )
    {
        SpringApplication.run(Application.class, args);
    }

    @Override
     protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
         return application.sources(Application.class);
     }
}

Also added the following in my pom.xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>

When I package the project though, I got the following error:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.2:war (default-war) on project cg-web: Error assembling WAR: webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode) -> [Help 1]

As I was reading upon spring boot application, I never saw anything about creating a web.xml. Is web.xml required in deploying spring boot application as war?

A:

According to this answer make Maven ignore the web.xml absence by adding the following snippet to your pom.xml:
<plugin>
  <artifactId>maven-war-plugin</artifactId>
  <version>2.6</version>
  <configuration>
    <failOnMissingWebXml>false</failOnMissingWebXml>
  </configuration>
</plugin>

A:

Do you have the web dependencies.
  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

You can always have your web.xml if you need some configuration on it, just place the file in the correct folder within WEB-INF so spring can take it an read the configurations. Also change the packaging to
<packaging>war</packaging>

Consider as well use the parent pom for spring-boot as
   <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.2.RELEASE</version>
    </parent>

This configuration
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>

Only tell maven not to include tomcat dependencies in the war file, to avoid interference with the servlet provider.


Q:

didset not working anymore - trying to find workaround

i found this answer to get the didset back again:
extension Binding {
    /// Execute block when value is changed.
    ///
    /// Example:
    ///
    ///     Slider(value: $amount.didSet { print($0) }, in: 0...10)
    func didSet(execute: @escaping (Value) ->Void) -> Binding {
        return Binding(
            get: {
                return self.wrappedValue
            },
            set: {
                execute($0)
                self.wrappedValue = $0
            }
        )
    }
}

now i tried the same with Published, but got error and don't know how to fix.
Error is: Type of expression is ambiguous without more context
@available(iOS 13.0, *)
extension Published {
    /// Execute block when value is changed.
    ///
    /// Example:
    ///
    ///     Slider(value: $amount.didSet { print($0) }, in: 0...10)
    func didSet(execute: @escaping (Value) ->Void) -> Published<Any> {
        return Published ( // error here : Type of expression is ambiguous without more contex`enter code here`
            get: {
                return self.wrappedValue
        },
            set: {
                execute($0)
                self.wrappedValue = $0
        }
        )
    }
}

A:

It works, but really for "did set only"... ie.. after direct assignment.
Please consider the following example. Tested with Xcode 11.4 / iOS 13.4
struct FooView: View {
    @ObservedObject var test = Foo()
    var body: some View {
        VStack {
            Button("Test Assign") { self.test.foo = 10 }    // << didSet works !!
            Button("Test Modify") { self.test.foo += 1 }    // xx nope !!
            Divider()
            Text("Current: \(test.foo)")
        }
    }
}

class Foo: ObservableObject {

    @Published var foo: Int = 1 {
        didSet {
            print("foo ==> \(foo)")
        }
    }
}


Q:

laraval query join on not null

I have this query join in mysql
left join the_fields as tf on
  tf.tf_kode = x.tf_kode
  and tf.is_payed is not null

I tried to convert to laravel query builder like this:
->leftJoin('the_fields as tf', function ($j) {
    $j->on('tf.tf_kode', '=', 'x.tf_kode');
    $j->on('tf.is_payed','!=', null);
})

but it shows error unknown column '' on clouse.
please help. Thanks!

A:

->on method arguments are columns and operators, You cant pass where condition in it.
You can use this:
->leftJoin('the_fields as tf', function ($j) {
    $j->on('tf.tf_kode', '=', 'x.tf_kode')->whereNotNull('tf.is_payed');
});

Hope this helps you


Q:

Differences in assigning C# event handlers?

I've always assigned event handlers like this, guided by Intellisense auto-completion.
RangeSelector.RangeChanged += new EventHandler(RangeSelector_RangeChanged);

I've recently noticed one of my colleagues does it this way.
RangeSelector.RangeChanged += RangeSelector_RangeChanged;

Both methods are syntactically correct, compile and behave as expected.
What are the differences, benefits or disadvantages of these methods. Do they result in the same IL code or is there some subtle difference that I need to be aware of?

A:

What are the differences, benefits or disadvantages of these methods.

The second method is newer, i.e. it is only supported since C# 2.0 (I believe), which added an automatic conversion from a method group (i.e. a method name) to a delegate. The constructor call is thus added by the compiler and the second method is just syntactic sugar for the first one.
Because of that, there are no other differences between the two.
Since the second method does the same as the first, with less syntax, it should be preferred.

A:

No difference, it results in the same IL.
It's just a way to say the same thing with less code.

A:

The result is the same in both cases. But in the latter the C# compiler will infer the EventHandler type from the code, thus saving you a few key strokes.


Q:

isset($var) - BLADE versus raw php

I am using Laravel 4.2. I have a situation that I need to address in laravel blade..
WITHIN the template I have this ( and it works fine)
    <?php
        $faqGroup = json_decode(Lng::faq(), true);
        $lang = Lng::faq()['view_as'];
        $Q = 'question_' . $lang;
        $A = 'answer_' . $lang;

        foreach ($faqGroup as $key => $faq) {
            if (isset($faq[$Q]) && isset($faq[$A])) {
    ?>
                <?php echo $faq[$Q]; ?>

                <?php echo $faq[$A]; ?>

    <?php
            }
        }
    ?>

my output is
question1 eng
answer1 eng

question2 eng
answer2 eng

question3 eng
answer3 eng

When I try to do the same with blade
    <?php
        $faqGroup = json_decode(Lng::faq(), true);
        $lang = Lng::faq()['view_as'];
        $Q = 'question_' . $lang;
        $A = 'answer_' . $lang;
    ?>

    @foreach ($faqGroup as $key => $faq)

        {{ isset($faq[$Q]) }}

        {{ isset($faq[$A]) }}

    @endforeach

my output is
1
1
1

If I try this
    @foreach ($faqGroup as $key => $faq)
        {{ $faq->$Q }}

    @endforeach

I get Trying to get property of non-object
If I try this
    @foreach ($faqGroup as $key => $faq)

        {{ $faq[$Q] }}

    @endforeach

I get Illegal string offset 'question_eng'
Help?

A:

Based upon your original code and logic which is working - your @foreach loop should be like this
@forreach ($faqGroup as $key => $faq)
    @if (isset($faq[$Q]) && isset($faq[$A]))
        {{ $faq[$Q] }}

        {{ $faq[$A] }}

    @endif
@endforeach


Q:

Abstract and final are access modifiers or access specifiers

abstract final class Outer {

}

So i was compiling the above code and got obvious error ,but the error was Illegal combination of access modifiers ,but the java doc http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html says there are only 3  access modifiers (public ,private and protected ) So these abstract ,final,public ,private and protected  are access modifiers or access specifiers or something else?because in many books and website they mentioned these keywords as sometimes access modifiers and sometimes access specifiers. i am so confused here.

A:

In the context of class declaration, and according to the JLS #8.1.1, these are all class modifiers.
And if you read a bit further you will see that only public, private and protected are access modifiers (which makes sense: they determine whether the class is accessible or not from other parts of the code).
So yes, technically, abstract and final are not access modifiers and the error message could be more precise. Note that javac (Java 8) error message is:

illegal combination of modifiers: abstract and final


Q:

Accessing jBPM database

i'm trying to use REST api with jbpm console.
i'm succeeding with that.i'm able to create task for a user via console.
But when i try to access the task details in DB (jdbc:h2:tcp://localhost/runtime/task)
All the tables including task table are empty.
Am i pointing to the right database.
Wht mistake i'm doing while accessing the jbpm console database.
TIA

A:

Stop jBOSS
ant start.human.task (Creates the table for task)
Start Jboss and verify with jbpm-console


Q:

Программируемые игры

Хотелось бы попробовать поиграть в программируемые игры. Что-то типа "CeeBot", но немного посложнее.
Желательно язык С++/Java/C# или свой, но похожий на них. Так же желательно наличие графической составляющей, а не консольной.
Если Вы знакомы с такими играми, буду очень рад получить их названия или даже полезные ссылочки.

A:

Linux-овский Robocode - весьма интересный проект, предлагающий программировать танк на уничтожение себе подобных. Программирование на Java.


Q:

Jquery select - how to be more efficient?

I have some markup like so:

1

2

I want to bind click event to the  tag, like this:
$("#mydiv A").click(this.function(){});

Can it be better? Thanks!

A:

Sure assign an id to the

$("#mylink").click(this.function(){});


Q:

Вывод данных из Sqlite3 python

Как сделать чтобы выводились полные данные а не последние которые записаны в БД
например сейчас в бд записи
ID  File
1   23
2   333
3   55
ну и как итог он у меня выводит только последнее значение 55
def existing():
conn = sqlite3.connect('bd/to.db')
cursor = conn.execute("SELECT File from OT")
for j in cursor:
    value = StringVar()
    valueChosen = ttk.Combobox(root, width=12, textvariable=value, state='readonly')
    print(len(j))

    valueChosen['values'] = (j)

    valueChosen.place(x=300,y=500)
    valueChosen.current(0)

A:

Нужно сделать чтобы значение выводились строчно вместо обозначения массива нужно написать results = cursor.fetchall()
    conn = sqlite3.connect('bd/to.db')
    cursor = conn.execute("SELECT File from OT")
    results = cursor.fetchall()
    value = StringVar()
    valueChosen = ttk.Combobox(root, width=12, textvariable=value, state='readonly')
    valueChosen['values'] = (results)
    valueChosen.place(x=300,y=500)
    valueChosen.current(0)


Q:

Methods that Clear the Thread.interrupt() flag

I have recently inherited a large Java Application that has almost no Thread safety in it. What I'm currently working on is getting all of the Threads to correctly handle being interrupted instead of using the very bad Thread.stop().
Part of the problem has been that I do not know every method call out there that clears the interrupt flag.
Currently I know that the following will clear the interrupt flag:
Thread.interrupted()
Thread.sleep(long)
Thread.join()
Thread.join(long)
Object.wait()
Object.wait(long)

What else am I missing? Thank you

A:

Part of the problem has been that I do not know every method call out there that clears the interrupt flag.

It is important to clarify that the following methods clear the interrupt flag by just calling them:
Thread.interrupted()
Thread.isInterrupted(true) -- added to your list

For this reason Thread.currentThread().isInterrupted() should always be used instead.
The following methods will clear the interrupted flag by immediately throwing InterruptedException either if they were called and then the thread was interrupted or if the thread was already interrupted and then they were called (see junit code below).  So it is not the method that clears the flag, throwing the exception does.
Your initial list:
Thread.interrupted()
Thread.sleep(long)
Thread.join()
Thread.join(long)
Object.wait()
Object.wait(long)

Added to your list:
Thread.sleep(long, int)
Thread.join(int, long)
Thread.isInterrupted(true)
Object.wait(int, long)
BlockingQueue.put(...)
BlockingQueue.offer(...)
BlockingQueue.take(...)
BlockingQueue.poll(...)
Future.get(...)
Process.waitFor()
ExecutorService.invokeAll(...)
ExecutorService.invokeAny(...)
ExecutorService.awaitTermination(...)
CompletionService.poll(...)
CompletionService.take(...)
CountDownLatch.await(...)
CyclicBarrier.await(...)
Semaphore.acquire(...)
Semaphore.tryAcquire(...)
Lock.lockInteruptibly()
Lock.tryLock(...)

Please note that the proper pattern with any code that catches InterruptedException is to immediately re-interrupt the thread.  We do this in case others are relying on the thread.isInterrupted() method:
try {
    ...
} catch (InterruptedException e) {
    // immediately re-interrupt the thread
    Thread.currentThread().interrupt();
    // log the exception or [likely] quit the thread
}

JUnit code that demonstrates some of this:
assertFalse(Thread.currentThread().isInterrupted());
// you can do this from another thread by saying: someThread.interrupt();
Thread.currentThread().interrupt();
// this method does _not_ clear the interrupt flag
assertTrue(Thread.currentThread().isInterrupted());
// but this one _does_ and should probably not be used
assertTrue(Thread.interrupted());
assertFalse(Thread.currentThread().isInterrupted());
Thread.currentThread().interrupt();
assertTrue(Thread.currentThread().isInterrupted());
try {
    // this throws immediately because the thread is _already_ interrupted
    Thread.sleep(1);
    fail("will never get here");
} catch (InterruptedException e) {
    // and when the InterruptedException is throw, it clears the interrupt
    assertFalse(Thread.currentThread().isInterrupted());
    // we should re-interrupt the thread so other code can use interrupt status
    Thread.currentThread().interrupt();
}
assertTrue(Thread.currentThread().isInterrupted());

A:

Common convention is the following: any method that throws InterruptedException (+ Thread.interrupted()) clears the interrupt flag.
So, in order to make your threads interruptable you need to find all places where InterruptedException gets caught without retrowing it or restoring the interrupt flag. Since InterruptedException is a checked exception it's not hard to do.


Q:

Linking issue whe compiling cpp code with gmplib on Windows

I'm having some issues compiling my code below and I think the problem is related to linking gmplib to the compiler.
I couldn't understand how to set the lib up on Windows or how to compile it. Here is my code. Variable names and comments are written in French. Sorry for that.
// projet(essai final).cpp : Defines the entry point for the console application.
//

//****** la classe rsa_gmp.h *******
#include "stdafx.h"
#include<iostream>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <gmp.h>
#include <time.h>
using namespace std;

class Class_one {
private:
    string fichierSource;
    string fichierDest;
    int tailleBloc ;
public:
    Class_one();
    void PGCD (mpz_t ,mpz_t,mpz_t);
    void puissance(mpz_t,mpz_t,mpz_t,mpz_t);
    void test_primalite(mpz_t,mpz_t);
    void InitialiseRandom(gmp_randstate_t );
    void nextprime (mpz_ptr , mpz_srcptr ) ;
    void Genere_publicKey( mpz_t  ,mpz_t  , mpz_t ,gmp_randstate_t  );
    void Genere_privateKey (mpz_t  , mpz_t  , mpz_t ) ;
    void Genere_nbPremier( mpz_t , mpz_t , int , gmp_randstate_t  ) ;
    void chiffre_Msg( mpz_t , mpz_t , mpz_t , mpz_t );
    void dechiffre_Msg( mpz_t , mpz_t  , mpz_t , mpz_t );
    short int SetFichiers(string nomFichierDest, string nomFichierSource);
    string DeTranscoder(mpz_t  );
    mpz_t Transcoder(string ) ;
    ~Class_one();
}

Class_one::Class_one(){

    this->fichierDest="";
    this->fichierSource="";
    this->tailleBloc=256;
};
Class_one::~Class_one(){};

void  Class_one::PGCD ( mpz_t resultat, mpz_t a , mpz_t b )
{
    mpz_t r , r1 ,r2;

    //intialiser les variables
    mpz_init( r );
    mpz_init( r1 );
    mpz_init( r2 );

    // affectation
    mpz_set (r , a ) ;
    mpz_set (r1 , b) ;

    while ( mpz_cmp_ui ( r1, 0) != 0)
    {
        mpz_mod ( r2, r, r1);
        mpz_set (r , r1 ) ;
        mpz_set (r1 , r2) ;
    }

    mpz_set (resultat , r) ;
    // liberer l'espace de variable
    mpz_clear( r );
    mpz_clear( r1 );
    mpz_clear( r2 );

}

void Class_one::puissance (mpz_t resultat ,mpz_t a, mpz_t e, mpz_t n)
{
    mpz_t temp,t,a_bis,e_bis ;
    // initialise la variable local
    mpz_init( temp );
    mpz_init( t );

    mpz_init( a_bis );
    mpz_set( a_bis , a );

    mpz_init( e_bis );
    mpz_set( e_bis , e );

    mpz_set_ui (temp , 1);

    while ( mpz_cmp_ui ( e_bis,0 )> 0)
    {
        mpz_mod_ui( t , e_bis , 2);
        if( mpz_cmp_ui( t , 0 ) != 0)
        {
            mpz_mul( temp , temp , a_bis);
            mpz_mod( temp , temp ,n );
        }
        mpz_mul(a_bis , a_bis, a_bis);
        mpz_mod ( a_bis, a_bis, n);

        mpz_tdiv_q_ui(e_bis,e_bis,2);
    }

    mpz_set( resultat , temp );
    // liberer l'espace utilisé
    mpz_clear( temp );mpz_clear(t);
    mpz_clear(a_bis );mpz_clear(e_bis );

}

/*
La test_primalite verifie si un nombre est premier,c'est une application
de Miller_Rabin
@ param long a, n( mod n)
@return 1 ou 0
*/
void Class_one::test_primalite ( mpz_t resultat , mpz_t n)
{
    mpz_t var ,p, e, m , i , k ,temp ;
    // initialiser les variables locals
    mpz_init(var) ;mpz_init(p) ;mpz_init(e) ;mpz_init( temp ) ;
    mpz_init( m) ;mpz_init( i) ;mpz_init( k) ;

    mpz_sub_ui ( m , n , 1);
    mpz_sub_ui ( e , n , 1);
    mpz_set_ui( var , 10 );

    mpz_set_ui ( k , 0 );
    mpz_mod_ui ( temp , e , 2);

    while ( mpz_cmp_ui ( temp , 0 )== 0)
    {
        mpz_tdiv_q_ui( e , e , 2);
        mpz_add_ui ( k , k , 1);
        mpz_mod_ui ( temp , e , 2);
    }

    Class_one::puissance( mpz_t p ,mpz_t var ,mpz_t  e , mpz_t n );

    if( mpz_cmp_ui ( p , 1) == 0)
    {
        mpz_set_ui( resultat , 1);
        return;
    }

    mpz_set_ui( i , 0);

    while( mpz_cmp ( i , k ) < 0)
    {
        if( mpz_cmp( p , m )== 0)
        {
            mpz_set_ui( resultat , 1);
            break ;
        }

        if( mpz_cmp_ui( p , 1 )== 0)
        {
            mpz_set_ui( resultat , 0);
            break ;
        }

        mpz_mul( p, p , p );
        mpz_mod( p , p , n) ;

        mpz_add_ui (i, i , 1);
    }

    // liberer l'espace utilisé par les variables locals
    mpz_init(var) ;mpz_init(p) ; mpz_init(e) ;mpz_init(temp) ;
    mpz_init( m) ;mpz_init( i) ;mpz_init( k) ;
}

// la fonction initializeRandom permet d,initialiser le generateur de nombre aleatoire
void Class_one::InitialiseRandom(gmp_randstate_t r_state )
{
    /* Initialisation de nombre aleatoire*/
    unsigned long int seed;
    seed = time(0);

    gmp_randinit_default (r_state);
    gmp_randseed_ui(r_state, seed);
}

// le nextprime permet de calculer le nombre premier suivant
void Class_one::nextprime (mpz_ptr p, mpz_srcptr t)
{
    mpz_t test ;
    mpz_init( test );
    mpz_add_ui (p, t, 13);

    void Class_one::test_primalite ( mpz_t test ,mpz_t  p);
    while (mpz_cmp_ui( test , 0)!= 1 )
    {
        mpz_add_ui (p, p, 13);
        void Class_one::test_primalite ( mpz_t test , mpz_t p);
    }

}

// la fonction genere_PK() permet de créer la clé public e

void Class_one:: Genere_publicKey( mpz_t e ,mpz_t p , mpz_t q ,gmp_randstate_t state )
{
    mpz_t a , b , c, r , y ,rand_Num;

    // initialiser les avriable locale
    mpz_init( a );
    mpz_init( b );
    mpz_init( c );
    mpz_init( y );
    mpz_init( r );
    mpz_init( rand_Num );

    mpz_sub_ui( a, p, 1 );
    mpz_sub_ui( b, q, 1 );

    mpz_mul( y, a, b );

    //Définition d'une valeur max de E.
    mpz_t max;
    mpz_init( max );
    mpz_set_str ( max , "97" ,0);

    mpz_urandomm( rand_Num, state, max );
    mpz_add_ui ( rand_Num , rand_Num , 3);
    mpz_mod(c,rand_Num,y);
    void Class_one::PGCD( mpz_t r , mpz_t c, mpz_t y);

    while (( mpz_cmp_ui( r,1 )!= 0) ||mpz_cmp( c ,max )>0 ||mpz_cmp_ui( c ,0) ==0 )
    {
        mpz_urandomm( rand_Num, state, max );
        mpz_add_ui ( rand_Num , rand_Num , 3);
        mpz_mod(c,rand_Num,y);
        void Class_one::PGCD( mpz_t r , mpz_t c, mpz_t y);
    }
    mpz_set( e ,c ) ;
    // effacer les espaces utilisées par les variables
    mpz_clear( a );mpz_clear( b );mpz_clear( y );mpz_clear( r );
    mpz_clear( rand_Num );mpz_clear( max );mpz_clear( c );

}

// La fonction genere_privateKey permet de determiner la clé public
// algorithme euclide etendu
void Class_one::Genere_privateKey (mpz_t d , mpz_t e , mpz_t phi)
{
    mpz_t e0,t0 , t , q, r, n0, temp ,temp2;

    // initialiser les variables
    mpz_init ( e0);mpz_init ( t0 );mpz_init ( t );mpz_init ( q );
    mpz_init ( r );mpz_init ( n0 );mpz_init ( temp );mpz_init ( temp2 );

    mpz_set_ui( t , 1) ;
    mpz_set ( n0 , phi );
    mpz_set ( e0 , e );
    mpz_tdiv_q( q , n0 , e0);
    mpz_mod ( r ,n0 , e0) ;

    while( mpz_cmp_ui ( r, 0) > 0)
    {
        mpz_mul( temp , q, t);
        mpz_sub( temp , t0, temp );

        if( mpz_cmp_ui ( temp , 0) >= 0)
        {
            mpz_mod ( temp , temp ,phi);
        }
        else
        {
            mpz_mod( temp , temp , phi);
        }

        mpz_set( t0 , t);
        mpz_set( t , temp);
        mpz_set( n0, e0);
        mpz_set( e0, r);
        mpz_tdiv_q( q , n0 , e0);
        mpz_mod ( r ,n0 , e0) ;

    }
    mpz_set ( d , t);
    // liberer l'espaces des variables
    mpz_clear( e0 );mpz_clear( t0 );mpz_clear( t );mpz_clear( q );
    mpz_clear( r );mpz_clear( n0 );mpz_clear( temp );mpz_clear( temp2 );
}

/*
La fonction Genere_nbPremier retourne les deux entiers P et Q
aleatoires et premiers
*/

void Class_one::Genere_nbPremier( mpz_t p, mpz_t q, int n, gmp_randstate_t state )
{
    //création de varaiable locale
    mpz_t rand, nb_aleatoire, max , min , varp , varq;

    // initialiser les variables
    mpz_init( rand ); mpz_init( nb_aleatoire ); mpz_init( max );
    mpz_init( min );mpz_init( varp );mpz_init( varq );

    // calcule du Borne Superieur
    mpz_ui_pow_ui( max, 2, n+1 );
    // calcule du borne inferieur
    mpz_ui_pow_ui( min, 2, n );

    // Génère un nombre compris entre 0 et max et le stocke dans rand. state initialise le générateur aléatoire.
    do
    {
        mpz_urandomm( rand, state, max );

    }while( mpz_cmp( rand, min) > 0 );
    // Vérifie que rand est supérieur à la borne inférieure
    void Class_one::nextprime ( mpz_ptr p ,mpz_srcptr  rand );

    // Génère un nombre Q compris entre 0 et max et le stocke dans rand. state initialise le générateur aléatoire.
    do
    {
        mpz_urandomm( nb_aleatoire, state, max );

    }while(( mpz_cmp( nb_aleatoire, min) > 0 )|| ( mpz_cmp ( p , q ) == 0));
    // Vérifie que rand est supérieur à la borne inférieure
    void Class_one::nextprime(mpz_ptr q ,mpz_srcptr  nb_aleatoire );

    // clear l'espace utilisé
    mpz_clear( nb_aleatoire );mpz_clear( rand );mpz_clear( max );
    mpz_clear( min );mpz_clear( varq );mpz_clear( varp );

}

// fonction de chiffrement de message
void Class_one::chiffre_Msg( mpz_t chiffre, mpz_t message , mpz_t e, mpz_t n)
{
    mpz_t cipher;
    mpz_t i;
    mpz_t temp;

    mpz_init(cipher);
    mpz_init(i);
    mpz_init(temp);
    mpz_set_si(cipher,1);

    void Class_one::puissance (mpz_t cipher ,mpz_t message,mpz_t  e,mpz_t  n);
    mpz_set(chiffre,cipher);

    mpz_clear(cipher);
    mpz_clear(temp);
}

// fonction dechiffrement de message
void Class_one:: dechiffre_Msg( mpz_t message2, mpz_t chiffre , mpz_t d, mpz_t n)
{
    mpz_t message;
    mpz_t i;
    mpz_t temp;

    mpz_init(message);
    mpz_init(i);
    mpz_init(temp);
    mpz_set(temp,chiffre);

    void Class_one::puissance ( mpz_t message,mpz_t temp ,mpz_t  d,mpz_t  n);
    mpz_set(message2,message);

    mpz_clear(message);
    mpz_clear(temp);
}

short int Class_one::SetFichiers(string nomFichierDest, string nomFichierSource)
{
    FILE *f1;
    FILE *f2;
    f1=fopen(nomFichierSource.c_str(), "rb");
    f2=fopen(nomFichierDest.c_str(), "wb");

    if(f1==NULL || f2==NULL)
    {
        if (f1!=NULL)   fclose(f1);
        if (f2!=NULL)   fclose(f2);
        return -1;
    }

    fclose(f1);
    fclose(f2);
    this->fichierDest=""+nomFichierDest;
    this->fichierSource=""+nomFichierSource;
    return 0;
}
mpz_t Class_one::Transcoder(string str)/*
La méthode Transcoder : Cette méthode prend une chaine de caractères, puis la transforme en un nombre équivalent. Le nombre est égale à la somme du
code ascii dernier caractère, l’avant dernier multiplié par 256, l’avant avant dernier multiplié par 2562…etc
*/
{
    mpz_t Somme;
    mpz_t var;
    mpz_t M;
    mpz_t Mul;
    mpz_t resultat ;
    signed long long int i;
    //initialisation des variables
    mpz_init(Somme);mpz_init(var);
    mpz_init(Mul);
    mpz_init(resultat);

    //affectation
    mpz_set_ui(M,1);

    for(i=(signed long long int)(str.length()-1); i>=0; i--)
    {

        aux =(unsigned char)str[(unsigned int)i];//La classe string est composé de signed char
        void Class_one::puissance(mpz_t resultat ,mpz_t  256 , mpz_t i, mpzt n);
        mpz_mul(Mul,resultat,aux);
        mpz_add(Somme,Somme, Mul);
    }
    return Somme ;
    mpz_clear(Somme);mpz_clear(var);mpz_clear(Mul);mpz_clear(resultat);
}

string Class_one::DeTranscoder(mpz_t  msg)
/*La méthode DeTranscoder : En prenant un nombre en paramètre,
elle génère une chaine de caractères équivalente, le nombre va être divisé par 256 en concaténant la chaine
déjà trouvée et le caractère dont le code ascii est le reste de la division par 256.*/

{
    mpz_t div;
    mpz_t aux;
    mpz_t reste;
    string str;
    //initialiser les variables
    mpz_init(div);mpz_init(aux);mpz_init(reste);
    // affectation
    mpz_set(aux,msg);
    mpz_set_ui(div,256);
    while(aux.size()>1 || aux!=0)
    {
        aux=mpz_div(aux, div, reste);
        str=(char)reste + str;
    }
    return str;
    //liberer  les variables
    mpz_clear(div); mpz_clear(aux); mpz_clear(reste);
}

class Cryptage{
    void crypter_RSA();
}

// la fonction principal du rsa en mode Standard

void Cryptage::crypter_RSA()
{
    // Variable locales
    mpz_t p , q , e,d , n , phi , message,msg_chiffre,cipher ;
    int choix ;

    //initialiser les variables locales
    mpz_init(msg_chiffre);  mpz_init(cipher);
    mpz_init(e); mpz_init(n); mpz_init(p);
    mpz_init(q); mpz_init(d); mpz_init(phi);
    ;mpz_init( message);

    // initialisationn du generateur
    gmp_randstate_t state;
    Class_one::InitialiseRandom(gmp_randstate_t state);
    Class_one::Genere_nbPremier(mpz_t  p,mpz_tq ,mpz_t 512, gmp_randstate_t state);

    // la valeur de N
    mpz_mul ( n , p , q);

    // les variablesP et Q
    gmp_printf ("\n\n \t P \t: \t%Zd \n", p );
    gmp_printf ("\n\n \t Q \t: \t%Zd \n", q );

    // Generer la clé public
    Class_one::Genere_publicKey( mpz_t e, mpz_t p ,mpz_t q , gmp_randstate_t state);
    gmp_printf("\n\n \t clef pubic : \t%Zd \n",e);

    // Calculer la valeur de phi
    mpz_sub_ui( p , p , 1);
    mpz_sub_ui( q , q , 1);
    mpz_mul( phi , p , q) ;

    // genere la cle privee
    Class_one::Genere_privateKey (mpz_t d ,mpz_t e , mpz_t phi );
    gmp_printf("\n\n \t clef prive : \t%Zd \n",d);

    // set fichier
    short int index= Class_one::SetFichiers(string nomFichierDest, string nomFichierSource);
    while (index!=0) {
    index= Class_one::SetFichiers(string nomFichierDest, string nomFichierSource);
    }

    // le message a chiffre // le message a chiffre
    printf("\n\n\n\t Entrez le message a crypter: ");
    gmp_scanf("%Zd",&message);

    cout<<"entrer \n 1)crypter\ n2)decrypter "<<endl;
    cin>>choix;
    switch(choix)
    {
    case 1 :
    //dechiffrement du message
          unsigned long long int j,nbZero,m;
        FILE *f1;
        FILE *f2;
        string str;
        string str2="e";
        string str3;
        mpz_t  msg;
        if(fichierSource.length()<1) break ;
        f1=fopen(this->fichierSource.c_str(), "rb");
        f2=fopen(this->fichierDest.c_str(), "wb");
        fseek(f1,0,SEEK_SET);
        for(j=0,m=1, nbZero=0;j<8;j++,m*=256) nbZero+=fgetc(f1)*m;
        str2[0]=fgetc(f1);
        while(str2[0]!=EOF)
        {
            str=""+str2;
            for(j=1;j<this->tailleBloc_; j++)
            {
                str2[0]=fgetc(f1);
                str=str+ str2 ;
            }
            str2[0]=fgetc(f1);

            msg=Class_one::Transcoder(str);
            Class_one::CrypterDecrypter(mpz_t msg,mpz_t ,mpz_t ,mpz_t);

            if (str2[0]==EOF)
            {
                for(j=0;j<(this->tailleBloc - nbZero); j++)
                    fputc((int)str[j], f2);
            }
            else
                for(j=0;j<this->tailleBloc ; j++)   fputc((int)str[j], f2);
        }
        fclose(f1);
        fclose(f2);

    Class_one::dechiffre_Msg (mpz_t cipher, mpz_t msg_chiffre ,mpz_t d ,mpz_t n);
    gmp_printf("\n\n\t Le message dechiffre :\t%Zd\n\n",cipher);
    break ;

    case 2 :
    //chiffrement du message
    mpz_init_set_str(cipher, "1",0);
     unsigned long long int j,aux;
            FILE *f1, *f2;
            unsigned char c;
            unsigned long long int nbZero ;
            string str ;
            string str2="e";
            mpz_t  msg;

            if(fichierSource.length()<1) return -1;
            f1=fopen(this->fichierSource.c_str(), "rb");
            f2=fopen(this->fichierDest.c_str(), "wb");
            str2[0]=fgetc(f1);
            if (str2[0]==EOF) break ;
            fseek(f1, 0, SEEK_END);
            //fpos_t <==> long long int pour notre compilateur
            fgetpos(f1,(fpos_t *)&nbZero);
            nbZero=nbZero%this->tailleBloc;
            if(nbZero!=0) nbZero=this->tailleBloc - nbZero;

            aux=nbZero;
            for(j=0;j<8;j++)
            {
                c=aux%256;
                aux=aux/256;
                fputc(c,f2);
            }

            fseek(f1,0, SEEK_SET);
            str2[0]=fgetc(f1);
            while(str2[0]!=EOF)
            {
                str=""+str2;
                for(j=1;j<(this->tailleBloc); j++)
                {
                    str2[0]=fgetc(f1);
                    str=str+str2 ;
                }
                str2[0]=fgetc(f1);
                if(str2[0]==EOF)
                {
                    for(j=this->tailleBloc-nbZero; j< this->tailleBloc; j++)
                        str[j]=0;
                }
                /*for(j=str.length();j<this->tailleBloc_; j++)
                    str=str2+str;*/
                msg=Class_one::Transcoder(str);
                Class_one::chiffre_Msg(mpz_t msg , mpz_t msg  ,  mpz_t e  , mpz_t n );
                str=Class_one::DeTranscoder(msg);
                for(j=str.length();j<this->tailleBloc_; j++)
                        fputc((int)0, f2);
                for(j=0;j<str.length(); j++)
                        fputc((int)str[j], f2);
            }
            fclose(f1);
            fclose(f2);

    break ;
    }
    // liberer les variables locales
    mpz_clear(p); mpz_clear(q);
    mpz_clear(e);mpz_clear(phi);mpz_clear(n);
    mpz_clear(message);mpz_clear( msg_chiffre);

}
int main (){
    void Cryptage::crypter_RSA();

}

A:

Some advice, even if it's not really an answer... You can't work like that, even for such a small project: you have to tackle one problem at a time.
Basically, you tried to write your whole program, and then only to compile it: you need to write your different functions and test them separately, especially since you are a beginner.
For instance, if you want to compile with gmplib, write something like this:
#include <gmp.h>

int main ()
{
    mpz_t x;
    return 0;
}

try to compile it and see what happens. If you have a compilation error, you will have a small piece of code that you can post here: add the exact message of your compiler, and the people here will help you instead of closing your question (again...).
This would be the first problem: compiling with another library. Once this works, you can add a small piece of your own code, recompile it and test what you have so far.
For instance, add your class declaration with a minimal definition for the functions: don't write the implementation, just a nearly empty body, e.g:
class OneClass {
   void pgcd (mpz_t, mpz_t, mpz_t) { /* empty function */ }
   // etc
};

you will be able (hopfully, it will be easy) to spot that you miss a semicolon at the end of your class declaration, and that your Transcoder function return a mpz_t, wich is illegal because mpz_t is a typedef for an array.
Then, when this works, add the implementations of your function one by one, in an order that allow you to test them as you write them.
You will be much more efficient, as it will be easier for you to know where you problem comes from.
In short, finding an error in the two lines you just added (if you know the rest is correct) is easy, but finding all the errors in such a big file is long and painfull...
Write one piece of code, compile it, test it and then only write the next one: it will pay !
Edit: actually, you will need to use one function in the library to test if you can link with it properly, but it's the same idea.

A:

I tried to install/build GMP as well as MPIR on Windows. Very difficult. Need to compile and build libraries first etc.
After a while i found C++ Big Integer Library from Matt McCutchen
https://mattmccutchen.net/bigint/
C++ source code only. Very simple to use. Integrated within 10 Minutes.


Q:

Unable to execute Java program with Json-simple jar file

I am trying to write a simple Java program which writes JSON data to a file. I am compiling it with the JSON simple jar file but I am getting an error. Below is what I have done:
//JsonSimpleWriteExample.java

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import java.io.FileWriter;
import java.io.IOException;

public class JsonSimpleWriteExample {

public static void main(String[] args) {

    JSONObject obj = new JSONObject();
    obj.put("name", "mkyong.com");
    obj.put("age", new Integer(100));

    JSONArray list = new JSONArray();
    list.add("msg 1");
    list.add("msg 2");
    list.add("msg 3");

    obj.put("messages", list);

    try (FileWriter file = new FileWriter("f:\\test.json")) {

        file.write(obj.toJSONString());
        file.flush();

    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.print(obj);

  }

 }

To compile the above program in a terminal, I am doing:
javac -cp json-simple-1.1.1.jar JsonSimpleWriteExample.java

I downloaded the json-simple-1.1.1.jar file from http://www.java2s.com/Code/Jar/j/json-simple.htm
I am getting the below error:
Note: JsonSimpleWriteExample.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

I am using MacOS. Can anybody help me figure out the issue.
When I try running my class file I get the below error:
$ java JsonSimpleWriteExample

Error that I got:
  Exception in thread "main" java.lang.NoClassDefFoundError: org/json/simple/JSONObject
at JsonSimpleWriteExample.main(JsonSimpleWriteExample.java:11)
  Caused by: java.lang.ClassNotFoundException: org.json.simple.JSONObject
  at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
  at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
  ... 1 more

A:

As you have it, you compile using the external jar file, so that the compiler finds the symbols you use during compilation time.
javac -cp json-simple-1.1.1.jar JsonSimpleWriteExample.java

The same has to be done at runtime:
java JsonSimpleWriteExample -cp ./json-simple-1.1.1.jar

In your example, this is the output:
{"name":"mkyong.com","messages":["msg 1","msg 2","msg 3"],"age":100}

As @Pshemo said, those "errors" you get are actually warnings. You can see more about unchecked or unsafe ops here and here.


Q:

Is eating olives daily OK?

Is there an issue [transgressing the Mishna Avos (Avos 3:8) of causing oneself to forget his learning] to eat olives seeing that Horayos (13b) writes olives eaten frequently will cause one to forget his learning? If there is an issue, is there a way to remove the forgetfulness?

A:

In a personal letter Rav Chaim Kanievsky wrote to me that one should wait thirty days between one "eating" of olives and the next "eating" so that one shouldn't be "ragil ba'zeisim." He said however that dipping the olives in olive oil is sufficient to remove the problem of eating olives altogether.


Q:

Windows 10 node-gyp cannot build: MSBUILD failed with exit code 1

Windows 10,
Microsoft Visual Studio 2013,
Node v0.12.7,
node-gyp v2.0.2
I always get the error build error with node-gyp:
Error: `C:\Program Files (x86)\MSBuild\12.0\bin\msbuild.exe` failed with exit code: 1

Also in red color description:
Could not write lines to file "Release\obj\validation\validation.tlog\validation.lastbuildstate". The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.

Bigger excerpt of error:
https://gist.github.com/nerijusgood/63e54d9c376999a044bb
As I understand everything is running fine, however msbuild cannot write long path names. Is there a patch for this or windows workaround?

A:

Long file paths is a big issue with Visual Studio that Microsoft has stated that they have no plans to fix in the near future!
Try moving your solution folder to the root of the drive (c:\project)
Also NPM version 3+ changes the module folder structure so they are not nested so deep. (it says it's in beta but seems to have solved some problems for me)
Regarding your post on Github, (I've been running into an endless string of problems with NPM and node-gyp as well, apparently everything is made to work well on linux!)

You probably need to install VS2013 (you can use the express version, make sure it includes c++)
From the npm errors on github:
v120 is VS2013
v140 is VS2015
To make node-gyp use the correct version for the package you are installing you may need to set an environment variable in Windows.
set GYP_MSVS_VERSION=2013
(if you set it in your windows system properties make sure to restart your command prompt)

A:

Edit: The question in title is a bit different from OP's actual issue (which this answer addresses).
For node-gyp, or MSBUILD errors in general please see other questions.
To solve the "The specified path, file name, or both are too long." issue, update npm to version 3+. This has been bothering all windows users for a while now, and the answer is to flatten your dependencies. npm@3.x automatically flattens all dependencies to the root even during install.


Q:

Why can't java find StringEntity class even after importing org.apache.http packages?

I am using a  sample code from Microsoft Cognitive Services. It makes use of StringEntity class to make request to the REST API. The java compiler seems to be unable to find 'symbol' StringEntity? What could be the reason for this and how to resolve this?
Here goes the code -
import java.net.URI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.http.*;

public class NEWS_FETCHER
{
    public static void main(String[] args)
    {
        HttpClient httpclient = HttpClients.createDefault();

        try
        {
            URIBuilder builder = new URIBuilder("https://api.cognitive.microsoft.com/bing/v5.0/news/search");

            builder.setParameter("q", "microsoft");
            builder.setParameter("count", "10");
            builder.setParameter("offset", "0");
            builder.setParameter("mkt", "en-us");
            builder.setParameter("safeSearch", "Moderate");

            URI uri = builder.build();
            HttpGet request = new HttpGet(uri);
            request.setHeader("Ocp-Apim-Subscription-Key", "<Key goes here>");

            // Request body
            StringEntity reqEntity = new StringEntity("");
            request.setEntity(reqEntity);

            HttpResponse response = httpclient.execute(request);
            HttpEntity entity = response.getEntity();

            if (entity != null)
            {
                System.out.println(EntityUtils.toString(entity));
            }
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}

Most of it is taken from Microsoft API Test Sample.
https://dev.cognitive.microsoft.com/docs/services/56b43f72cf5ff8098cef380a/operations/56b449fbcf5ff81038d15cdf

A:

The class StringEntity is in the package org.apache.http.entity, so you have to add the correct import for that:
import org.apache.http.entity.StringEntity


Q:

Folder/File browser with MVC 2?

How can you create a route that accept an undefined number of strings?
The folder browser should be able to browse the specified folder and all the sub folders.  Using JQuery to get the folders back from the server. The problem is how to build the JQuery?
$.ajax({
           type: "POST",
           url: "http://localhost:30218/Data/Folder1/Folder2/etc",
           dataType: "json",
           success: function (data) { }
       });

I mean, how can you create a MVC 2 url that could be like 10 subfolders deep? I don't want to define a static number of maximum folders that it can contain. How can you create the url and what routing should you use? Querystrings for subfolders?

A:

You can use the catchall on the last route segment, which is the asterisk character, like so:
"Files/{action}/{*path}"

That would cause everything at the end to be lumped together in the path parameter.


Q:

Finding speed of light by $c=f\lambda$?

When considering EM radiation as waves it is said that it is electric and magnetic fields that oscillate with time. Therefore $f$ is not frequency of distance but of electromagnetic fields.
I have also been taught to derive  wavelength from the equation $c=f\lambda$. However this raises a question: if $f$ is not frequency of oscillation of distance and $\lambda$ is measure of distance isn't the equation $c=f\lambda$ bogus in the first place?

A:

In general, for a wave with speed $v$ and frequency $f$, the wavelength is given by,
$$\lambda = \frac{v}{f}$$
In our case, for light or electromagnetic radiation, $v=c$. Hence, if we measure some incoming radiation which has frequency $f$, and wavelength $\lambda$, it must hold,
$$c=\lambda f$$
or roughly, as our measurements have uncertainties. Dimensionally, the equation is perfectly fine; notice that $[f]=\mathrm{s}^{-1}$ and $[\lambda]=\mathrm{m}$, hence $[\lambda f]=\mathrm{ms}^{-1}$ which is precisely velocity as required.

Alternatively, recall the energy of a photon with frequency $f$ is given by, $E=hf$ where $h$ is Planck's constant. Hence we could express the speed of light, $c$, as
$$c=\frac{E\lambda}{h}$$
with $E$ being the energy we measure, and $\lambda$ once again the wavelength. For example, for ultraviolet light, we know $E$ is large (in comparison to the other end of the spectrum), which implies a low $\lambda$.


Q:

number in the top right corner of the camera app?

Possible Duplicate:
What does the blue 0 mean in the top right hand corner of my camera?

What is the number shown in the top right corner of the camera app that comes installed with Android 2.3.5? It shows 905 right now but I don't know what it means. Does it have anything to do with the zoom or the light level or the space in the SD card for more pictures to be taken?

A:

This number represents the approximate amount of pictures left you'll be able to take, according to the free space on the media portion of the phone (e.g. SD Card) and the currently chosen settings, such as resolution.


Q:

Calculator application running on a console

I have a calculator created using C# that is running on a console.
The calculator accepts a string input (e.g. 5+5) then produces the result (5+5=10).  It will then prompt the user to enter another operator which will continue the evaluation (e.g. 10+5=15).  To terminate the program, one can type the string "done".
I would like to ask what other improvements I can make to increase the efficiency of my code.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text.RegularExpressions;
    using System.Xml.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Diagnostics;

    namespace Calculator
    {
        class Calculate
        {
            ulong firstNumber { get; set; }
            ulong secondNumber { get; set; }
            public static ulong result = 0;
            string equationOperator { get; set; }

            public Calculate(ulong firstNumber, ulong secondNumber, string equationOperator)
            {

                this.firstNumber = firstNumber;
                this.secondNumber = secondNumber;
                this.equationOperator = equationOperator;

                switch (this.equationOperator)
                {
                    case "+":
                        result = this.firstNumber + this.secondNumber;
                        break;
                    case "-":
                        if (result < this.secondNumber)
                        {
                           result = this.secondNumber - this.firstNumber;
                           break;
                        }
                        result = this.firstNumber - this.secondNumber;
                        break;
                    case "/":
                        if (this.secondNumber == 0)
                        {
                            Console.WriteLine("\nCannot Divide by Zero!");
                            break;
                        }
                        result = this.firstNumber / this.secondNumber;
                        break;
                    case "*":
                        result = this.firstNumber * this.secondNumber;
                        break;
                    case "%":
                        result = this.firstNumber % this.secondNumber;
                        break;
                }

                Console.WriteLine("\n{0}\t{1}\t{2}\t= {3}", this.firstNumber, this.equationOperator, this.secondNumber, result);
            }

        }

        class ContinueEval
        {
            public static void continueEvaluate()
            {
                string nextInput = "", equationOperator = "", secondNumber = "";
                ulong prevResult;
                while (nextInput != "done")
                {
                    Console.Write("\n{0}",Calculate.result);
                    prevResult = Calculate.result;
                    nextInput = Console.ReadLine();
                    if (nextInput == "done")
                        break;
                    ushort n = 1;
                    for (n = 0; n < nextInput.Length; n++)
                    {
                        if (!(Regex.IsMatch(nextInput.Substring(0, n), @"^\d+$")))
                        {
                            equationOperator = nextInput[n].ToString();
                            break;
                        }
                    }
                    secondNumber = nextInput.Substring((n + 1), (nextInput.Length - 1));

                    switch (equationOperator)
                    {
                        case "+":
                            Calculate.result += ulong.Parse(secondNumber);
                            break;
                        case "-":
                            if (Calculate.result < ulong.Parse(secondNumber))
                            {
                                Calculate.result = ulong.Parse(secondNumber) - Calculate.result;
                                break;
                            }
                            Calculate.result -= ulong.Parse(secondNumber);
                            break;
                        case "/":
                            if (ulong.Parse(secondNumber) == 0)
                            {
                                Console.WriteLine("\nCannot Divide by Zero!");
                                break;
                            }
                            Calculate.result /= ulong.Parse(secondNumber);
                            break;
                        case "*":
                            Calculate.result *= ulong.Parse(secondNumber);
                            break;
                        case "%":
                            Calculate.result %= ulong.Parse(secondNumber);
                            break;
                    }
                    Console.WriteLine("\n{0}\t{1}\t{2}\t= {3}", prevResult, equationOperator, secondNumber, Calculate.result);

                };
            }
        }

        class ESlicer
        {
            public static void sliceEquation(string inputValue)
            {
                if (inputValue == "done")
                    Environment.Exit(0);
                string firstNumber = "", secondNumber = "", equationOperator = "";
                ushort n = 1, end = 0;

                while (Regex.IsMatch(inputValue.Substring(0, n), @"^\d+$"))
                {
                    firstNumber = inputValue.Substring(0, n);
                    if (!(Regex.IsMatch(inputValue[n].ToString(), @"^\d+$")))
                    {
                        equationOperator = inputValue[n].ToString();
                        break;
                    }
                    if (n > inputValue.Length)
                        break;
                    n++;
                }
                end = (ushort)(inputValue.Length - (firstNumber.Length + 1));
                secondNumber = inputValue.Substring((n + 1), end);
                Calculate p = new Calculate(ulong.Parse(firstNumber), ulong.Parse(secondNumber), equationOperator);
            }
        }

        class Program
        {
            static void Main()
            {
                string inputValue;
                Console.Write("Enter string of Equation: ");
                inputValue = Console.ReadLine();

          ESlicer.sliceEquation(inputValue);
            ContinueEval.continueEvaluate();
            Console.Write("Thank you for using!");
            Console.Read();
        }

    }
}

A:

From your last comment, what you're actually looking for is not more efficiency (which is difficult to measure anyway), but more quality, and I think we can do that.
The biggest problem is that the program is very hard to read and follow, and thus hard to maintain. This is for several reasons:

Mixed responsibilities. You have split the work that your program needs to do into several classes, but not all of them do just one thing.
Unclear program flow. This is in part a result the first issue. At any level of the program it is very hard to tell what the current state is, where it comes from and exactly how the current code influences what happens later, or which other code the current part directly depends on. This is also due to your intermixing of class instance code, static code and semi-static constructors. This is a rather small program that can be written in different styles, but not all at the same time.

The most striking specific issue just from scrolling through the code is that the evaluation of the operator and the calculation of the result are present twice, and from looking more closely, it becomes clear that pretty much the whole program is present twice - the ContinueEval class has almost everything that is needed; that is because after the very first equation, the program only keeps looping within the continueEvaluate() method for all subsequent operations.
That means that the ContinueEval class has a number of responsibilities:

Taking the new input from the console
Parsing the input
Evaluating the operator
Doing the actual calculation
Displaying the result
Looping back to take the next input

That is a bit much to ask of one class. In addition, it duplicates the core functionality of the ESlicer (more or less) and Calculate classes in the process. One big problem this causes is that whenever you decide to change the way the input is parsed or add support for a new mathematical operation, you will have to make changes in two places, which is cumbersome and error prone.
Let's break down the program flow that is currently a bit hidden, not least because of the use of global state in the Calculate class (try to avoid using global/static state as much as you can, and instead look for sensible ways to pass everything you need to the classes that require it; this will help a lot in making program flow and dependencies more explicit and easier to follow).

Take the first input
Parse it for the arguments and operator
Calculate the first result
(Start of the loop) Take the next input
Parse it for the operator and argument
Calculate the new result
Loop back to take the next input

Looking at this shows that there are three tasks that are being repeated - taking an input, parsing it and calculating the result. At least the latter two are non-trivial, and we should do what is necessary to only have the code for them once; this will help a lot in understanding and maintaining the program.
I have tidied up the responsibilities and ended up with two classes for the main tasks, along with one to transfer the result of the parsed equation and a main loop which I left in Program.Main() for the time being[1]:
using System;
using System.Text.RegularExpressions;

namespace CalculatorX
{
    public class Program
    {
        private static void Main()
        {
            Calculator calculator = new Calculator();
            EquationParser parser = new EquationParser();

            Console.Write("Enter string of Equation: ");

            bool doLoop = true;
            bool isFirstLoop = true;

            do
            {
                if (!isFirstLoop)
                {
                    Console.Write(calculator.Result);
                }

                string inputValue = Console.ReadLine();
                if ("done" == inputValue)
                {
                    doLoop = false;
                }
                else
                {
                    ParseResult parsedInput = parser.Parse(inputValue);

                    long firstArgumentForOutput = (isFirstLoop ? parsedInput.FirstArgument : calculator.Result);

                    calculator.Process(parsedInput);

                    Console.WriteLine("\n{0}\t{1}\t{2}\t= {3}", firstArgumentForOutput, parsedInput.Operator, parsedInput.SecondArgument, calculator.Result);
                }

                isFirstLoop = false;
            }
            while (doLoop);

            Console.Write("\r\n\r\nThank you for using!");
            Console.Read();
        }
    }

    public class Calculator
    {
        private bool _isInitialized;

        public long Result { get; private set; }

        public void Process(ParseResult parsedInput)
        {
            if (!this._isInitialized)
            {
                this.Result = parsedInput.FirstArgument;

                this._isInitialized = true;
            }

            switch (parsedInput.Operator)
            {
                case "+":
                    this.Result += parsedInput.SecondArgument;
                    break;

                case "-":
                    this.Result -= parsedInput.SecondArgument;
                    break;

                case "*":
                    this.Result *= parsedInput.SecondArgument;
                    break;

                case "/":
                    this.Result /= parsedInput.SecondArgument;
                    break;

                case "%":
                    this.Result %= parsedInput.SecondArgument;
                    break;

                default:
                    break;
            }
        }
    }

    public class ParseResult
    {
        public long FirstArgument { get; set; }

        public string Operator { get; set; }

        public long SecondArgument { get; set; }
    }

    public class EquationParser
    {
        public ParseResult Parse(string input)
        {
            long firstArgument = 0;
            Match firstMatch = Regex.Match(input, "^\\d+");
            if (firstMatch.Success)
            {
                firstArgument = Convert.ToInt64(firstMatch.Value);
            }

            string operatorString = Regex.Match(input, "\\D+").Value;

            Match secondMatch = Regex.Match(input, "\\d+$");
            long secondArgument = Convert.ToInt64(secondMatch.Value);

            return new ParseResult()
                   {
                       FirstArgument = firstArgument,
                       Operator = operatorString,
                       SecondArgument = secondArgument
                   };
        }
    }
}

The significant differences to your solution are as follows:

No hidden global state. Everything that is important can be followed on its way through the code, and each Calculator object completely controls everything its calculation depends on. You can now have hundreds of them at the same time, and they would work correctly, while with your Calculate class, they all would have shared and modified the same result.
No hidden dependencies on other classes or static members. Your ESlicer class needs the Calculate class, but that is not apparent unless you actually happen to look into the code of that class and read that to the very last line.
Testability. You would have no way to test the parsing of the input and the actual calculations separately in your program - you can only run the program, enter equations and look at the output to verify everything works correctly. I can use a unit test framework to write code that tests each of my classes independently - I can check if equations are parsed correctly, and I can check if all the calculations work without having to parse an equation first. Actually, both of these classes were written using the so-called Test-Driven Development (TDD) method, which is a great way to build code with a better structure and quality from the outset.
Maintainability. When you find that something is not working correctly or need to extend the application (like adding 'power' as a new operation), it is very easy to make changes, because it's always very clear which parts of the code will be affected, and you can make changes with much less risk of breaking something, and thus with much greater confidence. This is also because you have no code duplications, so every change needs to be made in a single place only.
(For example, my EquationParser class cuts quite a few corners with respect to input validation - I could now easily go ahead and do this, because I can be sure that I only need to make changes in that one class, and as long as it produces a correct ParseResult, the whole program will still work.)

If you want to learn how to write well-structured, maintainable and evolvable high-quality code, making yourself familiar with the SOLID principles and the aforementioned Test-Driven Development is the way to go (I learned most of what I know from a guy named Mark Seemann - look him up; also look on YouTube for talks from Miško Hevery). Those are certainly no easy topics and may seem daunting, but they are worth every minute spent on them, because it is incredibly rewarding to see those things play out when you get the hang of them.
Also, try to keep your code as DRY as possible - DRY stands for "Don't Repeat Yourself" and means you should have as little duplicate code as possible, because duplicate code means more places to make changes, more places that can have bugs and more places to make mistakes.
Most importantly - practice. The more, the better. Read up on the topics I mentioned, and try following those principles. It will often seem impossible at first, but you'll get ahead eventually. And don't forget to come back here with your results and ask for advice, because trying to get your head around everything on your own is often very difficult.

[1] This would probably look slightly different if I was to write it as production code, but I wanted to keep it comprehensible in the first place.


Q:

ArrayAdapter text and image

In my activity I implement a list which contains the names of some files.
Every list's item refers to a layout in which I'd like to show the name of the images and a thumbnail of the image referenced. Ican show the the name using an ArrayAdapter but i don't know hot to insert the image thumbnail.
All the image referenced stay in sd_card and i have the path of they.
Here is the single row layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:orientation="horizontal" >

<ImageView
    android:id="@+id/imageView"
    android:layout_width="36dp"
    android:layout_height="wrap_content"
    android:src="@drawable/btn_nav_background_default" />

<TextView
    android:id="@+id/titoloTv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>

and the layout of the activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

<Button
    android:id="@+id/creaButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:text="Crea una nuova realtà aumentata" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:text="Ar già create"
    android:textAppearance="?android:attr/textAppearanceLarge" />

<ListView
    android:id="@+id/listView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

</ListView>

</LinearLayout>

and the activity code inherent adapter.
    ArrayAdapter<?> arrayAdapter = new ArrayAdapter<String>(this,R.layout.row,R.id.titoloTv,targetName);
    listView.setAdapter(arrayAdapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
           @Override
           public void onItemClick(AdapterView<?> adapter, final View componente, int pos, long id){

...................
           }

    });

I'm trying using this but doesn't work properly.
    String tempTarget;
    List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();

   for(int i = 0; i<ARelements.size();i++){
        Element ar = arIterator.next();

        Map<String,Object> map = new HashMap<String,Object>(2);
        tempTarget = ar.getAttributeValue("TARGET");
        thumbnailBitmap = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(tempTarget), THUMBSIZE, THUMBSIZE);
        map.put("thumbnail", thumbnailBitmap);
        map.put("titolo", tempTarget);
        data.add(map);
    }
   arIterator= null;

   SimpleAdapter simpleAdapter = new SimpleAdapter(this,data,R.layout.row,new String[] {"thumbnail","titolo"},new int[] {R.id.imageView, R.id.titoloTv});

    listView.setAdapter(simpleAdapter);

A:

You need to implement a custom array adapter and specify that imageview and textview layout/id(s) in the adapter.
Something like:
  public class CustomListViewAdapter extends ArrayAdapter<RowItem> {

    Context context;

    public CustomListViewAdapter(Context context, int resourceId, //resourceId=your layout
            List<RowItem> items) {
        super(context, resourceId, items);
        this.context = context;
    }

    /*private view holder class*/
    private class ViewHolder {
        ImageView imageView;
        TextView txtTitle;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        RowItem rowItem = getItem(position);

        LayoutInflater mInflater = (LayoutInflater) context
                .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.list_item, null);
            holder = new ViewHolder();
            holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
            holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
            convertView.setTag(holder);
        } else
            holder = (ViewHolder) convertView.getTag();

        holder.txtTitle.setText(rowItem.getTitle());
        holder.imageView.setImageResource(rowItem.getImageId());

        return convertView;
    }
}

And then:
listView = (ListView) findViewById(R.id.list);
        CustomListViewAdapter adapter = new CustomListViewAdapter(this,
                R.layout.list_item, rowItems);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);
    }

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {
    Toast toast = Toast.makeText(getApplicationContext(),
        "Item " + (position + 1) + ": " + rowItems.get(position),
        Toast.LENGTH_SHORT);
    toast.show();
}

Refer Extending other Adapters too, for ListView(s) and their custom implementation:
Eg.
http://theopentutorials.com/tutorials/android/listview/android-custom-listview-with-image-and-text-using-arrayadapter/

A:

You don't necessarily need a custom ArrayAdapter, a SimpleAdapter will do the trick for a thumbnail/text combo. You can store the path to the thumbnail and the text you want in a HashMap array, and then apply it using a SimpleAdapter. For example, if you had 5 thumbnails + text and arrays of each:
List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
for (int i = 0; i < 5; i++) {
            Map<String, Object> datum = new HashMap<String, Object>(2);
            datum.put("thumbnail", thumbnail[i]);
            datum.put("name", text[i]);
            data.add(datum);
        }
YourListViewId.setAdapter(new SimpleAdapter(this, data, R.layout.yoursinglerowlayout, new String[] {"thumbnail","name"}, new int[] {R.id.imageView, R.id.titoloTv}));


Q:

Как связать данные в БД и ExpandableListView

У меня есть БД SQLite и есть метод, который считывает данные из таблицы, и отдает массив. У меня сейчас в таблице 1800 записей и этот метод работает очень медленно. Можно ли его как-то оптимизировать?
public static ArrayList <String>  checkStoreWorks(Context context){
        ArrayList <String> docTypes = new ArrayList<>();
        SQLiteDatabase db = DBH.getInstance(context).getWritableDatabase();
        Cursor c = db.query(DBH.Storeworks.TABLE_NAME, null, null, null, null, null, null);
        if (c.moveToFirst()) {
            int nameColIndexO = c.getColumnIndex(DBH.Storeworks.DC.NAME);
            do {
                docTypes.add(c.getString(nameColIndexO));
                Log.d("StoreWorks!!!",
                                ", NAME = " + c.getString(nameColIndexO)
                );

            } while (c.moveToNext());
        } else
            Log.d("Nothing in DB", "0 rows");
        c.close();
        return docTypes;
    }

A:

При работе с данными, хранящимися в БД, не рекомендуется делать дополнительные копирования в какие то коллекции, массивы и тп., так как это может занимать достаточно много времени при определенном количестве данных. Рекомендуется работать напрямую с Cursor и соответствующими адаптерами.
Для связи данных в БД с ExpanadableListView имеется класс-адаптер SimpleCursorTreeAdapter, одной из особенностей которого является выборка данных по мере надобности (раскрытия пунктов списка), что положительно сказывается на производительности.
Для работы с этим адаптером понадобится организация определенной структуры БД, состоящая из двух таблиц: таблицы с заголовками пунктов (группы) и таблицы с содержимым для раскрывающегося списка, связанные с заголовками их ID (подпункты одной группы промаркированы ID этой группы).
Адаптер выводит список, состоящий из пунктов первой таблицы, как обычный SimpleCursorAdapter, так же при реализации адаптера необходимо реализовать метод getChildrenCursor(), который будет осуществлять запрос для выборки данных раскрывающейся части списка (из второй таблицы по ID группы). Смотрите пример реализации.
Так же вы можете использовать класс CursorLoader для большей оптимизации за счет асинхронных запросов в БД. Данный класс так же берет на себя обязанности по управлению курсором (не требуется самостоятельно его закрывать при ненадобности или восстанавливать при сменах состояния и др). Пример реализации с CursorLoader.
PS: хочу отметить, что работа с SQLite в Android реализована достаточно громоздко и "многострочно", а составление и обработка запросов вызывает много трудностей, я бы рекомендовал использовать вместо SQL, базы данных на основе ORM, лучшей из которых считаю Realm. Это позволяет работать с более понятными сущностями, как POJO-объекты, количество кода существенно сократится, а CRUD-операции будут более Java-подобные.


Q:

What kind of CSS is this?

I was looking at an old installation of mediawiki which is not rendering css properly the code in the Chrome Dev Tools is showing CSS like this
{{{border-width|1}}}px solid {{{titleborder|{{{border|#ababab}}}}}}
Not able to understand what is the pre-processor used and why its not working. Can someone hint to some direction.
Here in the image the span text is not rendered as a blue bar since The CSS breaks because of the template code. Not sure where to look for this CSS Template issue. Isnt much aware about the Media Wiki Architecture.

A:

Most likely, this CSS is used inline in a template on your page.
{{{border-width|1}}} means “use the value of the parameter border-width, or 1 if none is given”. In this case, the parameters to the template are not expanded. There are a number of possible reasons, though until you show us the template code, or give us a link to the page, we can only guess:

Syntax errors in the template (like a missing bracket somewhere, or a stray <nowiki> tag)
A complex template chain passed the expansion depth limit.
Too many templates on one page (surpassing the post-expand include size)

You can check the category Category:Pages containing omitted template arguments to see if it is any of the latter, though I strongly suspect the first.
Edit: Also, before doing anything else, you can try to simply purge the page, to re-render it.
Edit2: Now that we have a screenshot, it looks like some wikicode that an extension could have thrown in there. Start by disabling all extensions, and, if that helps, enable them again one by one.


Q:

how to secure connectionString

I have an application, where I should connect to a SQL Server. It is protected by password. So when I'm starting program for the first time, I'm creating dynamically connectionString and save it in app.config. For the next times I can use created connectionString. I've googled and decided to do following: encrypt connectionString in app.config and save password in my code. When I would like to connect to database next time, I will decrypt connectionString, add userId and password and connect with new connectionString to server. Before closing program, I will delete userId and password from connectionString and encrypt it again.  But I have some questions:
1) Is it a good solution?
2) When I am starting program for the first time, I need to create connection string, so somewhere in code should be userId and password. How to deal with this problem?

A:

Before closing program, I will delete userId and password from connectionString and encrypt it again

That's not a good solution. Your data should always be encrypted or at least be lost on program termination. If your user kills your program using the task manager (or it simply crashes), and you rely on the fact that your program will encrypt data on exit, your data is left unencrypted.
You could encrypt the whole connection string at the point you get the username and password. Then, any time you want to connect, decrypt it, pass it to the required functions and get rid of it. Never persist it in an unencrypted way.