WeixiangYan/CodeTransOcean huggingface dataset:
Task: Ascending primes


C++: 

#include <cmath>
#include <iostream>
#include <queue>
#include <vector>

using namespace std;


queue<unsigned> suspected;
vector<unsigned> primes;


bool isPrime(unsigned n)
{
    if (n == 2)
    {
        return true;
    }
    if (n == 1 || n % 2 == 0)
    {
        return false;
    }
    unsigned root = sqrt(n);
    for (unsigned k = 3; k <= root; k += 2)
    {
        if (n % k == 0)
        {
            return false;
        }
    }
    return true;
}


int main(int argc, char argv[])
{
    for (unsigned k = 1; k <= 9; k++)
    {
        suspected.push(k);
    }

    while (!suspected.empty())
    {
        int n = suspected.front();
        suspected.pop();

        if (isPrime(n))
        {
            primes.push_back(n);
        }

        
        
        for (unsigned k = n % 10 + 1; k <= 9; k++)
        {
            suspected.push(n * 10 + k);
        }
    }

    copy(primes.begin(), primes.end(), ostream_iterator<unsigned>(cout, " "));

    return EXIT_SUCCESS;
}







VB: Module AscendingPrimes

    Function isPrime(n As Integer)
        n = Math.Abs(n)
        If n = 2 Then
            Return True
        End If
        If n = 1 Or n Mod 2 = 0 Then
            Return False
        End If
        Dim root As Integer = Math.Sqrt(n)
        For k = 3 To root Step 2
            If n Mod k = 0 Then
                Return False
            End If
        Next
        Return True
    End Function


    Sub Main()

        Dim queue As Queue(Of Integer) = New Queue(Of Integer)
        Dim primes As List(Of Integer) = New List(Of Integer)

        For k = 1 To 9
            queue.Enqueue(k)
        Next

        While queue.Count > 0
            Dim n As Integer = queue.Dequeue()
            If (isPrime(n)) Then
                primes.Add(n)
            End If
            For k = n Mod 10 + 1 To 9
                queue.Enqueue(n * 10 + k)
            Next
        End While

        For Each p As Integer In primes
            Console.Write(p)
            Console.Write(" ")
        Next
        Console.WriteLine()

    End Sub

End Module
Task: Ascending primes

C: 

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>

#if UINT_MAX < 123456789
#error "we need at least 9 decimal digits (32-bit integers)"
#endif


#define MAXSIZE 1000

unsigned queue[MAXSIZE];
unsigned primes[MAXSIZE];

unsigned begin = 0;
unsigned end = 0;
unsigned n = 0;


bool isPrime(unsigned n)
{
    if (n == 2)
    {
        return true;
    }
    if (n == 1 || n % 2 == 0)
    {
        return false;
    }
    unsigned root = sqrt(n);
    for (unsigned k = 3; k <= root; k += 2)
    {
        if (n % k == 0)
        {
            return false;
        }
    }
    return true;
}


int main(int argc, char argv[])
{
    for (int k = 1; k <= 9; k++)
    {
        queue[end++] = k;
    }

    while (begin < end)
    {
        int value = queue[begin++];
        if (isPrime(value))
        {
            primes[n++] = value;
        }
        for (int k = value % 10 + 1; k <= 9; k++)
        {
            queue[end++] = value * 10 + k;
        }
    }

    for (int k = 0; k < n; k++)
    {
        printf("%u ", primes[k]);
    }
 
    return EXIT_SUCCESS;
}






PHP: <?php

function isPrime($n)
{
    if ($n == 2)
        return true;
    if ($n == 1 || $n % 2 == 0)
        return false;
    $root = intval(sqrt($n));
    for ($k = 3; $k <= $root; $k += 2)
        if ($n % $k == 0)
            return false;
    return true;    
}

$queue = [];
$primes = [];

$begin = 0;
$end = 0;

for ($k = 1; $k <= 9; $k++)
    $queue[$end++] = $k;

while ($begin < $end)
{
    $n = $queue[$begin++];

    if (isPrime($n))
        $primes[] = $n;
    for ($k = $n % 10 + 1; $k <= 9; $k++)
        $queue[$end++] = $n * 10 + $k;
}

foreach($primes as $p)
    echo "$p ";
Task: Ascending primes



C#: using System;
using System.Collections.Generic;

namespace ascendingprimes
{
    class Program
    {
        static bool isPrime(uint n)
        {
            if (n == 2)
                return true;
            if (n == 1 || n % 2 = 0)
                return false;
            uint root = (uint)Math.Sqrt(n);
            for (uint k = 3; k <= root; k += 2)
                if (n % k == 0)
                    return false;
            return true;
        }
        static void Main(string[] args)
        {
            var queue = new Queue<uint>();
            var primes = new List<uint>();

            for (uint k = 1; k <= 9; k++)
                queue.Enqueue(k);
            while(queue.Count > 0)
            {
                uint n = queue.Dequeue();
                if (isPrime(n))
                    primes.Add(n);
                for (uint k = n % 10 + 1; k <= 9; k++)
                    queue.Enqueue(n * 10 + k);
            }

            foreach (uint p in primes)
            {
                Console.Write(p);
                Console.Write(" ");
            }
            Console.WriteLine();
        }
    }
}




PHP: <?php

function isPrime($n)
{
    if ($n == 2)
        return true;
    if ($n == 1 || $n % 2 == 0)
        return false;
    $root = intval(sqrt($n));
    for ($k = 3; $k <= $root; $k += 2)
        if ($n % $k == 0)
            return false;
    return true;    
}

$queue = [];
$primes = [];

$begin = 0;
$end = 0;

for ($k = 1; $k <= 9; $k++)
    $queue[$end++] = $k;

while ($begin < $end)
{
    $n = $queue[$begin++];

    if (isPrime($n))
        $primes[] = $n;
    for ($k = $n % 10 + 1; $k <= 9; $k++)
        $queue[$end++] = $n * 10 + $k;
}

foreach($primes as $p)
    echo "$p ";
Task: Ascending primes


C++: 

#include <cmath>
#include <iostream>
#include <queue>
#include <vector>

using namespace std;


queue<unsigned> suspected;
vector<unsigned> primes;


bool isPrime(unsigned n)
{
    if (n == 2)
    {
        return true;
    }
    if (n == 1 || n % 2 == 0)
    {
        return false;
    }
    unsigned root = sqrt(n);
    for (unsigned k = 3; k <= root; k += 2)
    {
        if (n % k == 0)
        {
            return false;
        }
    }
    return true;
}


int main(int argc, char argv[])
{
    for (unsigned k = 1; k <= 9; k++)
    {
        suspected.push(k);
    }

    while (!suspected.empty())
    {
        int n = suspected.front();
        suspected.pop();

        if (isPrime(n))
        {
            primes.push_back(n);
        }

        
        
        for (unsigned k = n % 10 + 1; k <= 9; k++)
        {
            suspected.push(n * 10 + k);
        }
    }

    copy(primes.begin(), primes.end(), ostream_iterator<unsigned>(cout, " "));

    return EXIT_SUCCESS;
}





PHP: <?php

function isPrime($n)
{
    if ($n == 2)
        return true;
    if ($n == 1 || $n % 2 == 0)
        return false;
    $root = intval(sqrt($n));
    for ($k = 3; $k <= $root; $k += 2)
        if ($n % $k == 0)
            return false;
    return true;    
}

$queue = [];
$primes = [];

$begin = 0;
$end = 0;

for ($k = 1; $k <= 9; $k++)
    $queue[$end++] = $k;

while ($begin < $end)
{
    $n = $queue[$begin++];

    if (isPrime($n))
        $primes[] = $n;
    for ($k = $n % 10 + 1; $k <= 9; $k++)
        $queue[$end++] = $n * 10 + $k;
}

foreach($primes as $p)
    echo "$p ";
Task: Ascending primes




Go: package main

import (
    "fmt"
    "rcu"
    "sort"
)

var ascPrimesSet = make(map[int]bool) 

func generate(first, cand, digits int) {
    if digits == 0 {
        if rcu.IsPrime(cand) {
            ascPrimesSet[cand] = true
        }
        return
    }
    for i := first; i < 10; i++ {
        next := cand*10 + i
        generate(i+1, next, digits-1)
    }
}

func main() {
    for digits := 1; digits < 10; digits++ {
        generate(1, 0, digits)
    }
    le := len(ascPrimesSet)
    ascPrimes := make([]int, le)
    i := 0
    for k := range ascPrimesSet {
        ascPrimes[i] = k
        i++
    }
    sort.Ints(ascPrimes)
    fmt.Println("There are", le, "ascending primes, namely:")
    for i := 0; i < le; i++ {
        fmt.Printf("%8d ", ascPrimes[i])
        if (i+1)%10 == 0 {
            fmt.Println()
        }
    }
}



PHP: <?php

function isPrime($n)
{
    if ($n == 2)
        return true;
    if ($n == 1 || $n % 2 == 0)
        return false;
    $root = intval(sqrt($n));
    for ($k = 3; $k <= $root; $k += 2)
        if ($n % $k == 0)
            return false;
    return true;    
}

$queue = [];
$primes = [];

$begin = 0;
$end = 0;

for ($k = 1; $k <= 9; $k++)
    $queue[$end++] = $k;

while ($begin < $end)
{
    $n = $queue[$begin++];

    if (isPrime($n))
        $primes[] = $n;
    for ($k = $n % 10 + 1; $k <= 9; $k++)
        $queue[$end++] = $n * 10 + $k;
}

foreach($primes as $p)
    echo "$p ";
Task: Ascending primes





Java: 

package example.rossetacode.ascendingprimes;

import java.util.Arrays;

public class Program implements Runnable {

    public static void main(String[] args) {
        long t1 = System.nanoTime();
        new Program().run();
        long t2 = System.nanoTime();
        System.out.println(
                "total time consumed = " + (t2 - t1) * 1E-6 + " milliseconds");
    }

    public void run() {

        final int MAX_SIZE = 1000;
        final int[] queue = new int[MAX_SIZE];
        int begin = 0;
        int end = 0;

        for (int k = 1; k <= 9; k++) {
            queue[end++] = k;
        }

        while (begin < end) {
            int n = queue[begin++];
            for (int k = n % 10 + 1; k <= 9; k++) {
                queue[end++] = n * 10 + k;
            }
        }

        
        
        
        System.out.println(Arrays.stream(queue).filter(this::isPrime).boxed().toList());
    }

    private boolean isPrime(int n) {
        if (n == 2) {
            return true;
        }
        if (n == 1 || n % 2 == 0) {
            return false;
        }
        int root = (int) Math.sqrt(n);
        for (int k = 3; k <= root; k += 2) {
            if (n % k == 0) {
                return false;
            }
        }
        return true;
    }
}


PHP: <?php

function isPrime($n)
{
    if ($n == 2)
        return true;
    if ($n == 1 || $n % 2 == 0)
        return false;
    $root = intval(sqrt($n));
    for ($k = 3; $k <= $root; $k += 2)
        if ($n % $k == 0)
            return false;
    return true;    
}

$queue = [];
$primes = [];

$begin = 0;
$end = 0;

for ($k = 1; $k <= 9; $k++)
    $queue[$end++] = $k;

while ($begin < $end)
{
    $n = $queue[$begin++];

    if (isPrime($n))
        $primes[] = $n;
    for ($k = $n % 10 + 1; $k <= 9; $k++)
        $queue[$end++] = $n * 10 + $k;
}

foreach($primes as $p)
    echo "$p ";
Task: Ascending primes






PHP: <?php

function isPrime($n)
{
    if ($n == 2)
        return true;
    if ($n == 1 || $n % 2 == 0)
        return false;
    $root = intval(sqrt($n));
    for ($k = 3; $k <= $root; $k += 2)
        if ($n % $k == 0)
            return false;
    return true;    
}

$queue = [];
$primes = [];

$begin = 0;
$end = 0;

for ($k = 1; $k <= 9; $k++)
    $queue[$end++] = $k;

while ($begin < $end)
{
    $n = $queue[$begin++];

    if (isPrime($n))
        $primes[] = $n;
    for ($k = $n % 10 + 1; $k <= 9; $k++)
        $queue[$end++] = $n * 10 + $k;
}

foreach($primes as $p)
    echo "$p ";


Python: from sympy import isprime

def ascending(x=0):
    for y in range(x*10 + (x%10) + 1, x*10 + 10):
        yield from ascending(y)
        yield(y)

print(sorted(x for x in ascending() if isprime(x)))
Task: Ascending primes






PHP: <?php

function isPrime($n)
{
    if ($n == 2)
        return true;
    if ($n == 1 || $n % 2 == 0)
        return false;
    $root = intval(sqrt($n));
    for ($k = 3; $k <= $root; $k += 2)
        if ($n % $k == 0)
            return false;
    return true;    
}

$queue = [];
$primes = [];

$begin = 0;
$end = 0;

for ($k = 1; $k <= 9; $k++)
    $queue[$end++] = $k;

while ($begin < $end)
{
    $n = $queue[$begin++];

    if (isPrime($n))
        $primes[] = $n;
    for ($k = $n % 10 + 1; $k <= 9; $k++)
        $queue[$end++] = $n * 10 + $k;
}

foreach($primes as $p)
    echo "$p ";



VB: Module AscendingPrimes

    Function isPrime(n As Integer)
        n = Math.Abs(n)
        If n = 2 Then
            Return True
        End If
        If n = 1 Or n Mod 2 = 0 Then
            Return False
        End If
        Dim root As Integer = Math.Sqrt(n)
        For k = 3 To root Step 2
            If n Mod k = 0 Then
                Return False
            End If
        Next
        Return True
    End Function


    Sub Main()

        Dim queue As Queue(Of Integer) = New Queue(Of Integer)
        Dim primes As List(Of Integer) = New List(Of Integer)

        For k = 1 To 9
            queue.Enqueue(k)
        Next

        While queue.Count > 0
            Dim n As Integer = queue.Dequeue()
            If (isPrime(n)) Then
                primes.Add(n)
            End If
            For k = n Mod 10 + 1 To 9
                queue.Enqueue(n * 10 + k)
            Next
        End While

        For Each p As Integer In primes
            Console.Write(p)
            Console.Write(" ")
        Next
        Console.WriteLine()

    End Sub

End Module
Task: Keyboard input_Keypress check

C: #include <stdio.h>
#include <termios.h>  
#include <unistd.h>   
#include <fcntl.h>

void set_mode(int want_key)
{
	static struct termios old, new;
	if (!want_key) {
		tcsetattr(STDIN_FILENO, TCSANOW, &old);
		return;
	}

	tcgetattr(STDIN_FILENO, &old);
	new = old;
	new.c_lflag &= ~(ICANON | ECHO);
	tcsetattr(STDIN_FILENO, TCSANOW, &new);
}

int get_key()
{
	int c = 0;
	struct timeval tv;
	fd_set fs;
	tv.tv_usec = tv.tv_sec = 0;

	FD_ZERO(&fs);
	FD_SET(STDIN_FILENO, &fs);
	select(STDIN_FILENO + 1, &fs, 0, 0, &tv);

	if (FD_ISSET(STDIN_FILENO, &fs)) {
		c = getchar();
		set_mode(0);
	}
	return c;
}

int main()
{
	int c;
	while(1) {
		set_mode(1);
                
                fflush(stdout);
		while (!(c = get_key())) usleep(10000);
		printf("key %d\n", c);
	}
}



C#: string chr = string.Empty;
if(Console.KeyAvailable)
  chr = Console.ReadKey().Key.ToString();
Task: Keyboard input_Keypress check

C: #include <stdio.h>
#include <termios.h>  
#include <unistd.h>   
#include <fcntl.h>

void set_mode(int want_key)
{
	static struct termios old, new;
	if (!want_key) {
		tcsetattr(STDIN_FILENO, TCSANOW, &old);
		return;
	}

	tcgetattr(STDIN_FILENO, &old);
	new = old;
	new.c_lflag &= ~(ICANON | ECHO);
	tcsetattr(STDIN_FILENO, TCSANOW, &new);
}

int get_key()
{
	int c = 0;
	struct timeval tv;
	fd_set fs;
	tv.tv_usec = tv.tv_sec = 0;

	FD_ZERO(&fs);
	FD_SET(STDIN_FILENO, &fs);
	select(STDIN_FILENO + 1, &fs, 0, 0, &tv);

	if (FD_ISSET(STDIN_FILENO, &fs)) {
		c = getchar();
		set_mode(0);
	}
	return c;
}

int main()
{
	int c;
	while(1) {
		set_mode(1);
                
                fflush(stdout);
		while (!(c = get_key())) usleep(10000);
		printf("key %d\n", c);
	}
}





Java: import java.awt.event.*;
import javax.swing.*;

public class Test extends JFrame {

    Test() {
        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                int keyCode = e.getKeyCode();
                System.out.println(keyCode);
            }
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            Test f = new Test();
            f.setFocusable(true);
            f.setVisible(true);
        });
    }
}
Task: Keyboard input_Keypress check



C#: string chr = string.Empty;
if(Console.KeyAvailable)
  chr = Console.ReadKey().Key.ToString();


Go: package main

import (
    "log"
    "time"

    gc "code.google.com/p/goncurses"
)

func main() {
    s, err := gc.Init()
    if err != nil {
        log.Fatal("init:", err)
    }
    defer gc.End()
    gc.Cursor(0)
    s.Move(20, 0)
    s.Print("Key check in ")
    for i := 3; i >= 1; i-- {
        s.MovePrint(20, 13, i)
        s.Refresh()
        time.Sleep(500 * time.Millisecond)
    }
Task: Keyboard input_Keypress check



C#: string chr = string.Empty;
if(Console.KeyAvailable)
  chr = Console.ReadKey().Key.ToString();



Java: import java.awt.event.*;
import javax.swing.*;

public class Test extends JFrame {

    Test() {
        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                int keyCode = e.getKeyCode();
                System.out.println(keyCode);
            }
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            Test f = new Test();
            f.setFocusable(true);
            f.setVisible(true);
        });
    }
}
Task: Keyboard input_Keypress check



C#: string chr = string.Empty;
if(Console.KeyAvailable)
  chr = Console.ReadKey().Key.ToString();





Python: 

from __future__ import absolute_import, division, unicode_literals, print_function

import tty, termios
import sys
if sys.version_info.major < 3:
    import thread as _thread
else:
    import _thread
import time


try:
    from msvcrt import getch  
except ImportError:
    def getch():   
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

def keypress():
    global char
    char = getch()

def main():
    global char
    char = None
    _thread.start_new_thread(keypress, ())

    while True:
        if char is not None:
            try:
                print("Key pressed is " + char.decode('utf-8'))
            except UnicodeDecodeError:
                print("character can not be decoded, sorry!")
                char = None
            _thread.start_new_thread(keypress, ())
            if char == 'q' or char == '\x1b':  
                exit()
            char = None
        print("Program is running")
        time.sleep(1)

if __name__ == "__main__":
    main()
Task: Keyboard input_Keypress check




Go: package main

import (
    "log"
    "time"

    gc "code.google.com/p/goncurses"
)

func main() {
    s, err := gc.Init()
    if err != nil {
        log.Fatal("init:", err)
    }
    defer gc.End()
    gc.Cursor(0)
    s.Move(20, 0)
    s.Print("Key check in ")
    for i := 3; i >= 1; i-- {
        s.MovePrint(20, 13, i)
        s.Refresh()
        time.Sleep(500 * time.Millisecond)
    }


Java: import java.awt.event.*;
import javax.swing.*;

public class Test extends JFrame {

    Test() {
        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                int keyCode = e.getKeyCode();
                System.out.println(keyCode);
            }
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            Test f = new Test();
            f.setFocusable(true);
            f.setVisible(true);
        });
    }
}
Task: Keyboard input_Keypress check




Go: package main

import (
    "log"
    "time"

    gc "code.google.com/p/goncurses"
)

func main() {
    s, err := gc.Init()
    if err != nil {
        log.Fatal("init:", err)
    }
    defer gc.End()
    gc.Cursor(0)
    s.Move(20, 0)
    s.Print("Key check in ")
    for i := 3; i >= 1; i-- {
        s.MovePrint(20, 13, i)
        s.Refresh()
        time.Sleep(500 * time.Millisecond)
    }




Python: 

from __future__ import absolute_import, division, unicode_literals, print_function

import tty, termios
import sys
if sys.version_info.major < 3:
    import thread as _thread
else:
    import _thread
import time


try:
    from msvcrt import getch  
except ImportError:
    def getch():   
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

def keypress():
    global char
    char = getch()

def main():
    global char
    char = None
    _thread.start_new_thread(keypress, ())

    while True:
        if char is not None:
            try:
                print("Key pressed is " + char.decode('utf-8'))
            except UnicodeDecodeError:
                print("character can not be decoded, sorry!")
                char = None
            _thread.start_new_thread(keypress, ())
            if char == 'q' or char == '\x1b':  
                exit()
            char = None
        print("Program is running")
        time.sleep(1)

if __name__ == "__main__":
    main()
Task: Keyboard input_Keypress check

C: #include <stdio.h>
#include <termios.h>  
#include <unistd.h>   
#include <fcntl.h>

void set_mode(int want_key)
{
	static struct termios old, new;
	if (!want_key) {
		tcsetattr(STDIN_FILENO, TCSANOW, &old);
		return;
	}

	tcgetattr(STDIN_FILENO, &old);
	new = old;
	new.c_lflag &= ~(ICANON | ECHO);
	tcsetattr(STDIN_FILENO, TCSANOW, &new);
}

int get_key()
{
	int c = 0;
	struct timeval tv;
	fd_set fs;
	tv.tv_usec = tv.tv_sec = 0;

	FD_ZERO(&fs);
	FD_SET(STDIN_FILENO, &fs);
	select(STDIN_FILENO + 1, &fs, 0, 0, &tv);

	if (FD_ISSET(STDIN_FILENO, &fs)) {
		c = getchar();
		set_mode(0);
	}
	return c;
}

int main()
{
	int c;
	while(1) {
		set_mode(1);
                
                fflush(stdout);
		while (!(c = get_key())) usleep(10000);
		printf("key %d\n", c);
	}
}




Go: package main

import (
    "log"
    "time"

    gc "code.google.com/p/goncurses"
)

func main() {
    s, err := gc.Init()
    if err != nil {
        log.Fatal("init:", err)
    }
    defer gc.End()
    gc.Cursor(0)
    s.Move(20, 0)
    s.Print("Key check in ")
    for i := 3; i >= 1; i-- {
        s.MovePrint(20, 13, i)
        s.Refresh()
        time.Sleep(500 * time.Millisecond)
    }
Task: Keyboard input_Keypress check

C: #include <stdio.h>
#include <termios.h>  
#include <unistd.h>   
#include <fcntl.h>

void set_mode(int want_key)
{
	static struct termios old, new;
	if (!want_key) {
		tcsetattr(STDIN_FILENO, TCSANOW, &old);
		return;
	}

	tcgetattr(STDIN_FILENO, &old);
	new = old;
	new.c_lflag &= ~(ICANON | ECHO);
	tcsetattr(STDIN_FILENO, TCSANOW, &new);
}

int get_key()
{
	int c = 0;
	struct timeval tv;
	fd_set fs;
	tv.tv_usec = tv.tv_sec = 0;

	FD_ZERO(&fs);
	FD_SET(STDIN_FILENO, &fs);
	select(STDIN_FILENO + 1, &fs, 0, 0, &tv);

	if (FD_ISSET(STDIN_FILENO, &fs)) {
		c = getchar();
		set_mode(0);
	}
	return c;
}

int main()
{
	int c;
	while(1) {
		set_mode(1);
                
                fflush(stdout);
		while (!(c = get_key())) usleep(10000);
		printf("key %d\n", c);
	}
}







Python: 

from __future__ import absolute_import, division, unicode_literals, print_function

import tty, termios
import sys
if sys.version_info.major < 3:
    import thread as _thread
else:
    import _thread
import time


try:
    from msvcrt import getch  
except ImportError:
    def getch():   
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

def keypress():
    global char
    char = getch()

def main():
    global char
    char = None
    _thread.start_new_thread(keypress, ())

    while True:
        if char is not None:
            try:
                print("Key pressed is " + char.decode('utf-8'))
            except UnicodeDecodeError:
                print("character can not be decoded, sorry!")
                char = None
            _thread.start_new_thread(keypress, ())
            if char == 'q' or char == '\x1b':  
                exit()
            char = None
        print("Program is running")
        time.sleep(1)

if __name__ == "__main__":
    main()