Esempio n. 1
0
    def test_say_hello(self, mock_print):
        # call the function
        say_hello()

        # Make sure it only called `print` once
        self.assertEqual(mock_print.call_count, 1)

        # getting the arguments and keyword arguments passed to the
        # mocked function
        args, kwargs = mock_print.call_args

        # Make sure it prints the correct string
        self.assertEqual(args, ('Hello, World!', ))
Esempio n. 2
0
 def test_example(self):
     ans = _(
         'When "Charles" is the user\'s name, ``hello`` contains "{}" instead of "Hello, Charles!"'
     )
     student_ans = hello.say_hello("Charles")
     self.assertEqual("Hello, Charles!", student_ans,
                      ans.format(student_ans))
Esempio n. 3
0
 def test_names(self):
     names = ["Kim", "Siegfried", "Johnny"]
     ans = _(
         'When "{0}" is the user\'s name, ``hello`` contains "{1}" instead of "Hello, {0}!"'
     )
     for i in range(len(names)):
         student_ans = hello.say_hello(names[i])
         self.assertEqual("Hello, {}!".format(names[i]), student_ans,
                          ans.format(names[i], student_ans))
Esempio n. 4
0
 def test_random(self):
     random_name = ''.join(
         random.choice(string.ascii_letters) for _ in range(5))
     ans = _(
         'When "{0}" is the user\'s name, ``hello`` contains "{1}" instead of "Hello, {0}!"'
     )
     student_ans = hello.say_hello(random_name)
     self.assertEqual("Hello, {}!".format(random_name), student_ans,
                      ans.format(random_name, student_ans))
Esempio n. 5
0
def message_callback():
    app.logger.info(request.json)
    entries = request.json['entry']
    for entry in entries:
        messagings = entry['messaging']
        if messagings is None:
            continue
        for m in messagings:
            if 'message' in m:
                to = m['sender']['id']
                message_bodies = [{
                    "text":
                    "I don't understand your message. (%s)" %
                    (m['message']['text'])
                }]
                post_message_url = 'https://graph.facebook.com/v2.6/me/messages?access_token={token}'.format(
                    token=FB_TOKEN)
                ai_request = ai.text_request()
                ai_request.lang = 'en'  # optional, default value equal 'en'
                ai_request.query = m['message']['text']
                ai_response = json.loads(ai_request.getresponse().read())
                action = None
                parameters = None
                if "result" in ai_response:
                    action = ai_response["result"].get("action", None)
                    parameters = ai_response["result"].get("parameters", None)
                if action is not None:
                    app.logger.info("Action=%s" % (action))
                    app.logger.info("Parameters=%s" % (parameters))
                    if action == "show_weather":
                        message_bodies = fetch_weather()
                    if action == "show_news":
                        message_bodies = fetch_news(parameters['Media'])
                    if action == "show_restro":
                        message_bodies = fetch_restro(parameters['Places'])
                    if action == "say_hello":
                        message_bodies = say_hello()
                    if action == "say_goodbye":
                        message_bodies = say_goodbye()
                for message_body in message_bodies:
                    response_message = json.dumps({
                        "recipient": {
                            "id": to
                        },
                        "message": message_body
                    })
                    app.logger.info(response_message)
                    req = requests.post(
                        post_message_url,
                        headers={"Content-Type": "application/json"},
                        data=response_message)
                    app.logger.info(req.text)

    return "Done"
Esempio n. 6
0
def message_callback():
    app.logger.info(request.json)
    entries = request.json['entry']
    for entry in entries:
        messagings = entry['messaging']
        if messagings is None:
            continue
        for m in messagings:
            if 'message' in m:
                to = m['sender']['id']
                message_bodies = [{"text":"I don't understand your message. (%s)" % (m['message']['text'])}]
                post_message_url = 'https://graph.facebook.com/v2.6/me/messages?access_token={token}'.format(token=FB_TOKEN)
                ai_request = ai.text_request()
                ai_request.lang = 'en'  # optional, default value equal 'en'
                ai_request.query = m['message']['text']
                ai_response = json.loads(ai_request.getresponse().read())
                action = None
                parameters = None
                if "result" in ai_response:
                    action = ai_response["result"].get("action", None)
                    parameters = ai_response["result"].get("parameters", None)
                if action is not None:
                    app.logger.info("Action=%s" % (action))
                    app.logger.info("Parameters=%s" % (parameters))
                    if action == "show_weather":
                        message_bodies = fetch_weather()
                    if action == "show_news":
                        message_bodies = fetch_news(parameters['Media'])
                    if action == "show_restro":
                        message_bodies = fetch_restro(parameters['Places'])
                    if action == "say_hello":
                        message_bodies = say_hello()
                    if action == "say_goodbye":
                        message_bodies = say_goodbye()
                for message_body in message_bodies:
                    response_message = json.dumps({"recipient":{"id": to}, 
                                       "message":message_body})
                    app.logger.info(response_message)
                    req = requests.post(post_message_url, 
                                headers={"Content-Type": "application/json"}, 
                                data=response_message)
                    app.logger.info(req.text)
 
    return "Done"
Esempio n. 7
0
    def __init__(self):
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.connect("delete_event", self.delete_event)
        self.window.connect("destroy", self.destroy)

        self.window.set_size_request(1200, 600)

        #argumenty
        self.trescPlikuOrg = ''
        self.trescPlikuTlum = ''

        #menu
        self.menu_item1 = gtk.MenuItem("Otwórz oryginał")
        self.menu_item1.connect("activate", self.otworzPlik, 'org')
        self.menu_item1.show()

        self.menu_item2 = gtk.MenuItem("Otwórz tłumaczenie")
        self.menu_item2.connect("activate", self.otworzPlik, 'tlum')
        self.menu_item2.show()

        self.menu_item3 = gtk.MenuItem("Otwórz JSON")
        self.menu_item3.connect("activate", self.otworzJSON)
        self.menu_item3.show()

        self.menu_item4 = gtk.MenuItem("Zapisz JSON")
        self.menu_item4.connect("activate", self.zapiszJSON)
        self.menu_item4.show()

        self.menu_item5 = gtk.MenuItem("Wygeneruj Tex")
        self.menu_item5.connect("activate", self.zapiszTex)
        self.menu_item5.show()

        self.menu = gtk.Menu()
        self.menu.append(self.menu_item1)
        self.menu.append(self.menu_item2)
        self.menu.append(self.menu_item3)
        self.menu.append(self.menu_item4)
        self.menu.append(self.menu_item5)

        self.root_menu = gtk.MenuItem("Plik")
        self.root_menu.show()
        self.root_menu.set_submenu(self.menu)

        self.menu_bar = gtk.MenuBar()
        self.menu_bar.append(self.root_menu)
        self.menu_bar.show()

        self.menuWrapper = gtk.HBox(False, 0)
        self.menuWrapper.pack_start(self.menu_bar, True, True, 5)
        self.menuWrapper.show()

        hello.say_hello('aaa')

        #body
        self.mainvbox = gtk.VBox(False, 0)

        self.hboxOrg = gtk.VBox(False, 0)
        self.hboxTlum = gtk.VBox(False, 0)
        self.hboxOrg.show()
        self.hboxTlum.show()

        self.linie = []

        self.bodybox = gtk.VBox(True, 0)
        self.sterownia = gtk.HBox(True, 0)
        self.sterownia.show()

        #przyciski
        self.buttonTyl = gtk.Button("<<<")
        self.buttonTyl.connect("clicked", self.doTylu, "check button 1")
        self.sterownia.pack_start(self.buttonTyl, True, False, 0)
        self.buttonTyl.show()

        self.tfStrona = gtk.Entry()
        self.tfStrona.connect("key_release_event", self.zmienStrone)
        self.tfStrona.set_width_chars(4)
        self.sterownia.pack_start(self.tfStrona, False, False, 0)
        self.tfStrona.show()

        self.ngStrona = gtk.Entry()
        self.ngStrona.set_width_chars(20)
        self.sterownia.pack_start(self.ngStrona, False, False, 0)
        self.ngStrona.show()

        self.buttonPrzod = gtk.Button(">>>")
        self.buttonPrzod.connect("clicked", self.doPrzodu, "check button 2")
        self.sterownia.pack_start(self.buttonPrzod, True, False, 0)
        self.buttonPrzod.show()

        self.bodybox.pack_start(self.sterownia, False)
        self.bodybox.show()

        self.zdania = [[], []]

        self.sw = gtk.ScrolledWindow()
        self.sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        self.sw.add_with_viewport(self.bodybox)
        self.sw.show()

        self.strona = 0
        self.elementow_na_strone = 5

        self.mainvbox.pack_start(self.menuWrapper, False)
        self.mainvbox.pack_start(self.sw, True, True)

        self.mainvbox.show()

        self.window.add(self.mainvbox)
        self.window.show()
Esempio n. 8
0
def main():
    print('Hello World')
    hello.say_hello("python")
Esempio n. 9
0
import hello

print dir(hello)
hello.say_hello("python friend")
Esempio n. 10
0
import hello

hello.say_hello("John")
hello.say_hello(12345)
Esempio n. 11
0
from hello import say_hello #importando funcion
#from hello import say_hello_list

#forma 1
saludo= say_hello("Ana",30)
print(saludo)

#say_hello("Pablo")
#say_hello("Inma")
#say_hello("elvira")

# forma 2
#lista_nombres = ["Ana", "Pablo", "Elvira", "Inma"]
#from nombre in lista_nombres:
   # say_hello(nombre)

#forma 3
#say_hello_list(lista_nombres)
Esempio n. 12
0
import hello
hello.say_hello('Nick')
Esempio n. 13
0
 def test_hello(self):
     """ Test the hello world extension. """
     self.assertEqual(hello.say_hello("World"), "Hello World!\n")
Esempio n. 14
0
end = time.time()
print('\n\nPure Hello: Time taken in seconds -', end - start)
"""
The following call throws an error if called with GODEBUG=cgocheck=1

panic: runtime error: cgo result has Go pointer

goroutine 17 [running, locked to thread]:
main._cgoexpwrap_80580a90e820_sayHello.func1(0xc000048e50)
	_cgo_gotypes.go:69 +0x51
main._cgoexpwrap_80580a90e820_sayHello(0x10d4b5de0, 0x7, 0xc00001a0f0, 0xd)
	_cgo_gotypes.go:71 +0xfd

To bypass this error I need to export GODEBUG=cgocheck=0 to disable dynamic cgo runtime check but this is not the safer thing to do as you can read here https://golang.org/cmd/cgo/#hdr-Passing_pointers
"""
for i in range(0, 900000):
    print('\r' + say_hello("PyPizza"), end='')
end = time.time()
print('\n\nSay Hello: Time taken in seconds -', end - start)

start = time.time()
for i in range(0, 900000):
    print('\r' + say_hello_slowly("PyPizza"), end='')
end = time.time()
print('\n\nSay Hello slowly: Time taken in seconds -', end - start)

start = time.time()
say_hello_faster("PyPizza", 900000)
end = time.time()
print('\n\nSay Hello faster: Time taken in seconds -', end - start)
Esempio n. 15
0
#-*- coding: utf-8 -*-

import hello

if __name__=='__main__':
    hello.say_hello('asdfasfd')
Esempio n. 16
0
# http://stackoverflow.com/questions/5049842/autocomplete-in-pycharm-for-python-compiled-extensions

import hello

hello.say_hello("you")
hello.Foo().doSomething()  # In PyCharm bad autocomplete


class Foo(object):
    def doSomething(self):
        hello.Foo().doSomething()


Foo().doSomething()
Esempio n. 17
0
def Handler(pkt) :
  global beaconNumber
  global firstBeaconObserved
  global firstBeaconInternalTimer
  global x
  global y
  
  CONV = 1000000
  if pkt.haslayer(Dot11):
		if pkt.type == 0 and pkt.subtype == 8  and pkt.info == targetSSID:
			beaconNumber += 1
	  		if beaconNumber == 1:
			        #time stamp from radioTap header	  			
	  			firstBeaconObserved = hello.say_hello() 
	  			#timestamp from beacon frame 			
	  			firstBeaconInternalTimer = pkt.timestamp			
			print "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"			
			print "BeaconNUmber" , beaconNumber
			print "AP MAC: %s with SSID: %s  %s" %(pkt.addr2, pkt.info, pkt.timestamp)
			print "AP Beacon frame timestamp", pkt.timestamp
			print "Arrival timestamp frame", pkt.time
 			print "first beacon observed locally", firstBeaconObserved
			print "first AP beacon internally frame ", firstBeaconInternalTimer
			# get the elapsed time since the first beacon was observed
			# attempt to normalize 
			elapasedTime = hello.say_hello() - firstBeaconObserved
			print "elapased time mod", elapasedTime

			elapasedTime2 = pkt.timestamp - firstBeaconInternalTimer

			print "elapased time from c++ gettimeofday()", elapasedTime 
			print "elapasedTime from internal timestamp", elapasedTime2


			clockOffset = (elapasedTime2 - (elapasedTime))
			print "clockOffset", clockOffset 


			x.append(elapasedTime / CONV)
			y.append(clockOffset)

			if beaconNumber == 150:	
			#if unmod >= 15:	
				import numpy as np
				import matplotlib.pyplot as plt
				import matplotlib.pyplot as mpl
				mpl.plot(x, y, label="Curve", color="blue", linestyle='-',linewidth=1)
				mpl.grid(True)
				mpl.xticks(np.arange(min(x), max(x)+1, 1.0))
				mpl.xlabel('TIME')
				mpl.ylabel('clock')
				mpl.title("test")
				mpl.legend()
				mpl.show()

				# http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.lstsq.html
				print "least square"
				A = np.vstack([x, np.ones(len(x))]).T
				# print A
				m, c = np.linalg.lstsq(A, y)[0]
				print "slope + c"
				print m, c
				#print "m*x+c", (m*x + c)

				print "attempt at root mean square"
				import statsmodels.api as sm				
				stacked = np.column_stack((np.ones(len(y)), np.array(y)))
				ols = sm.OLS(np.array(x), stacked).fit()
				predictions = ols.predict()
				# print preds2	
				def rmse(predictions, targets):
					return np.sqrt(((predictions - targets) ** 2).mean())				      
				print rmse(predictions,np.array(y))
				sys.exit(0)
Esempio n. 18
0
import hello
import primes

hello.say_hello()
print primes.primes(100)
Esempio n. 19
0
def test_hello(capsys):
    say_hello('tox')
    out, _ = capsys.readouterr()
    assert out == 'Hello, tox!\n'
Esempio n. 20
0
#  Copyright Joel de Guzman 2002-2007. Distributed under the Boost
#  Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt
#  or copy at http://www.boost.org/LICENSE_1_0.txt)
#  Hello World Example from the tutorial

import hello



if __name__ == '__main__':
	print "HOLA"
	hello.say_hello('mundo')

Esempio n. 21
0
def Handler(pkt):
    global beaconNumber
    global firstBeaconObserved
    global firstBeaconInternalTimer
    global x
    global y

    CONV = 1000000
    if pkt.haslayer(Dot11):
        if pkt.type == 0 and pkt.subtype == 8 and pkt.info == targetSSID:
            beaconNumber += 1
            if beaconNumber == 1:
                #time stamp from radioTap header
                firstBeaconObserved = hello.say_hello()
                #timestamp from beacon frame
                firstBeaconInternalTimer = pkt.timestamp
            print "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
            print "BeaconNUmber", beaconNumber
            print "AP MAC: %s with SSID: %s  %s" % (pkt.addr2, pkt.info,
                                                    pkt.timestamp)
            print "AP Beacon frame timestamp", pkt.timestamp
            print "Arrival timestamp frame", pkt.time
            print "first beacon observed locally", firstBeaconObserved
            print "first AP beacon internally frame ", firstBeaconInternalTimer
            # get the elapsed time since the first beacon was observed
            # attempt to normalize
            elapasedTime = hello.say_hello() - firstBeaconObserved
            print "elapased time mod", elapasedTime

            elapasedTime2 = pkt.timestamp - firstBeaconInternalTimer

            print "elapased time from c++ gettimeofday()", elapasedTime
            print "elapasedTime from internal timestamp", elapasedTime2

            clockOffset = (elapasedTime2 - (elapasedTime))
            print "clockOffset", clockOffset

            x.append(elapasedTime / CONV)
            y.append(clockOffset)

            if beaconNumber == 150:
                #if unmod >= 15:
                import numpy as np
                import matplotlib.pyplot as plt
                import matplotlib.pyplot as mpl
                mpl.plot(x,
                         y,
                         label="Curve",
                         color="blue",
                         linestyle='-',
                         linewidth=1)
                mpl.grid(True)
                mpl.xticks(np.arange(min(x), max(x) + 1, 1.0))
                mpl.xlabel('TIME')
                mpl.ylabel('clock')
                mpl.title("test")
                mpl.legend()
                mpl.show()

                # http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.lstsq.html
                print "least square"
                A = np.vstack([x, np.ones(len(x))]).T
                # print A
                m, c = np.linalg.lstsq(A, y)[0]
                print "slope + c"
                print m, c
                #print "m*x+c", (m*x + c)

                print "attempt at root mean square"
                import statsmodels.api as sm
                stacked = np.column_stack((np.ones(len(y)), np.array(y)))
                ols = sm.OLS(np.array(x), stacked).fit()
                predictions = ols.predict()

                # print preds2
                def rmse(predictions, targets):
                    return np.sqrt(((predictions - targets)**2).mean())

                print rmse(predictions, np.array(y))
                sys.exit(0)
Esempio n. 22
0
#!/usr/bin/env python3

from hello import say_hello

from function import *

say_hello("world")
say_hello("Bernard")

# Seed the random number dice
set_up_dice()

# Let's try out some dice rolls
dice_roll_value = roll_a_dice()

print("Dice roll value is: " + str(dice_roll_value))

first_roll_value = roll_a_dice()
print("First roll value is: " + str(first_roll_value))
second_roll_value = roll_a_dice()
print("Second roll value is: " + str(second_roll_value))

# Let's call rolling two six-sided dice, a throw.
# So, Player 1 will have a throw, then player 2 will have a throw.
''' Our first try...
first_roll_value_player1 = roll_a_dice()
print("First roll value for player 1 is: " + str(first_roll_value_player1))
second_roll_value_player1 = roll_a_dice()
print("Second roll value for player 1 is: " + str(second_roll_value_player1))

throw_player1 = (first_roll_value_player1, second_roll_value_player1)
print(name)
x = input("Write a number:")
float(x) / 2
# Built in Modules and Functions
import math
math.sqrt(16)
print(math.sqrt(16))


# Creating a Module
def say_hello():
    print("Hello!")


import hello
hello.say_hello()
from hello import say_hello
say_hello()
# Modules can be aliased
import hello as ai
ai.say_hello()
# A module can be stand alone runnable srcipt
if __name__ == '__main__':
    from hello import say_hello
    say_hello()
# The String Function - str() and repr()
s = """w'o"w"""
repr(s)
str(s)
eval(repr(s)) == s
import datetime
Esempio n. 24
0
import hello
import fib

import faulthandler

if __name__ == '__main__':
    #  cookbook:  https://python3-cookbook.readthedocs.io/zh_CN/latest/c15/p01_access_ccode_using_ctypes.html
    #  https://en.wikibooks.org/wiki/Python_Programming/Extending_with_C
    #  使用swig更简单[pure c代码]
    #  使用CFFI
    hello.say_hello('lwz')
    fib.fib(10)


Esempio n. 25
0
# cython_mpi.py
"""
Demonstrates how to use mpi4py in cython.

Run this with 4 processes like:
$ mpiexec -n 4 python cython_mpi.py
"""

from mpi4py import MPI
import hello

comm = MPI.COMM_WORLD

hello.say_hello(comm)
hello.c_say_hello(comm)

new_comm = hello.return_comm(comm)

if not new_comm is None:
    print 'new_comm.size = %d' % new_comm.size
Esempio n. 26
0
def test():
	return say_hello('gautam')
Esempio n. 27
0
'''
\brief Example program which uses the hello module.
'''

import hello


# a Python function
def sum(a, b):
    return a + b


print("Result from myFunction:", hello.my_set_callback(sum))
hello.say_hello("to all")
Esempio n. 28
0
#!/usr/bin/env python3
def greet():
    print("Greetings!")

print('__name__ as seen by greeter.py: {}'.format(__name__))

if __name__ == '__main__':
    import hello

    name = 'john'

    hello.say_hello("John")
    name = 'jack'
    hello.say_hello("James")
    hello.say_hello("Steve")

Esempio n. 29
0
# use import to import modules
import hello

hello.say_hello("Sponge Bob")

#to import specific functions only
from hello import say_hello

#giving a function an alias
from hello import say_hello as sh

#giving an alias to a module
import hello as h

#import all functions in a module
from pizza import *
Esempio n. 30
0
# hello_test.py

import hello
hello.say_hello("World")
import numpy
from hello import say_hello

say_hello()
Esempio n. 32
0
 def test_hello(self):
     self.assertEqual(say_hello('world'), 'Hello world')
Esempio n. 33
0
def test_output():
    assert hello.say_hello() == "Hello"
Esempio n. 34
0
 def test_hello(self):
     output = io.StringIO()
     hello.say_hello('cihann', file=output)
     self.assertEqual(output.getvalue(), 'Hello, cihann!\n')
Esempio n. 35
0
 def test_can_say_hello_to_mohamed(self):
     self.assertEqual(hello.say_hello('Mohamed', 'Amaka'))
Esempio n. 36
0
import hello

hello.say_hello('test a bug')
def test_hello():
    assert hello.say_hello() == "Hello"
Esempio n. 38
0
def say_hello_world():
    return say_hello() + " world"
Esempio n. 39
0
import hello
i = hello.say_hello("asdfdf")
print i
Esempio n. 40
0
# 부르기 첫번째 방법
# as 로 줄여서 할 수 도 있음
# 줄이기 않고 import hello만 한다면 hello.say_hello
# 모듈을 만들면 외부에 있는 파일을 사용할 수 있다.

import hello as hel
import hello

# 이렇게 부를 수 도 있다.
from hello import say_hello

# hello파일에 있는 모든 함수를 다 가져와라
from hello import *

if __name__ == '__main__':
    hello.say_hello("haeun")
    hel.say_hello2("mose")

    say_hello("Lee")
    say_hello2("chi")
Esempio n. 41
0
import hello
hello.say_hello("World")

Esempio n. 42
0
#  Copyright Joel de Guzman 2002-2007. Distributed under the Boost
#  Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt
#  or copy at http://www.boost.org/LICENSE_1_0.txt)
#  Hello World Example from the tutorial

import hello

if __name__ == '__main__':
    print "HOLA"
    hello.say_hello('mundo')
Esempio n. 43
0
# 모듈 : 변수, 함수, 클래스를 모아둔 파일
# 패키지 : 여러 모듈을 하나의 디렉토리로 모아둔 것

# built-in 된 모듈 - print 함수 같은 거 ( Import 하지 않아도 되는 것 )

import sys

import hello
import hello as h
# from hello import say_hello
from hello import *  # from ( 패키지, 모듈 ) import(모듈, 변수나 함수나 클래스)

print(sys.modules)  # 기본적으로 설치되어있는 모듈
print("=" * 50)
print(sys.path)  # 새로 설치한 모듈

hello.say_hello()
h.say_hello()

say_hello()
Esempio n. 44
0
 def test_can_say_hello_to_you_guy(self):
     self.assertEqual(hello.say_hello("Chiamaka"), "Hello, Chiamaka")