示例#1
0
def rand_words():
    perfect = []
    rw = RandomWords()
    f = input('Enter the first alphabet of word or press enter for all words >'
              ).strip()
    print()
    for n in range(10000):
        score = 0
        if f and f.isascii():
            word = rw.random_word(f).upper()
        else:
            word = rw.random_word().upper()
        for ch in word:
            if ch in alpha_value.keys():
                score += alpha_value[ch]
        if score == 100 and word not in perfect:
            perfect.append(word)
    print('Random words with 100% score value are as listed below:')
    for ch in up_alp:
        subword = []
        for word in perfect:
            if word.startswith(ch):
                subword.append(word)
        if subword:
            print(f'Word starting with "{ch}" are:')
            print(subword)
            print()
    print()
示例#2
0
def dbpost():

	#changes these to the master
	try:
		conn = psycopg2.connect(database=os.environ.get('PG_DATABASE'), user=os.environ.get('PG_USER'), host=os.environ.get('PG_MASTER_RC_SERVICE_HOST'), password=os.environ.get('PG_ROOT_PASSWORD'))
	except:
		print(os.environ.get('PG_USER')	+ "  " + os.environ.get('PG_SLAVE_RC_SERVICE_HOST'))

	#Need to generate some data - no need for ID
	#NEED a name and a lat and long
	lat = random.uniform(-90,90)
	lon = random.uniform(-180,180)
	rw = RandomWords()
	name = rw.random_word() + " " + rw.random_word()

	#here comes the insert srid = 4326
	cur = conn.cursor()
	cur.execute("""select parkid, name, ST_AsText(the_geom) from parkpoints limit 10""")

	rows = cur.fetchall()
	result_string = "<h2>Here are your results: </h2>"
	for row in rows:
		result_string += "<h3>" + str(row[0]) + ", " + str(row[1]) + ", " + str(row[2]) + "</h3>"

	return  result_string
示例#3
0
文件: models.py 项目: lmcindewar/pllc
 def random_words(self):
     #for url creation
     rw =  RandomWords()
     w1 = rw.random_word()
     w2 = rw.random_word()
     w3 = rw.random_word()
     return w1 + "-" + w2 + "-" + w3
示例#4
0
def dbpost():

    #changes these to the master
    try:
        conn = psycopg2.connect(
            database=os.environ.get('PG_DATABASE'),
            user=os.environ.get('PG_USER'),
            host=os.environ.get('PG_MASTER_RC_SERVICE_HOST'),
            password=os.environ.get('PG_ROOT_PASSWORD'))
    except:
        print(
            os.environ.get('PG_USER') + "  " +
            os.environ.get('PG_SLAVE_RC_SERVICE_HOST'))

    #Need to generate some data - no need for ID
    #NEED a name and a lat and long
    lat = random.uniform(-90, 90)
    lon = random.uniform(-180, 180)
    rw = RandomWords()
    name = rw.random_word() + " " + rw.random_word()

    #here comes the insert srid = 4326
    cur = conn.cursor()
    cur.execute(
        """select parkid, name, ST_AsText(the_geom) from parkpoints limit 10"""
    )

    rows = cur.fetchall()
    result_string = "<h2>Here are your results: </h2>"
    for row in rows:
        result_string += "<h3>" + str(row[0]) + ", " + str(
            row[1]) + ", " + str(row[2]) + "</h3>"

    return result_string
示例#5
0
def generate(request):
    print "You made it to generate!"
    if request.method == "POST":

        try:
            request.session['count'] = request.session['count'] + 1
        except:
            request.session['count'] = 1

        #Even though the image uses a random string of letters/nums
        #I wanted to try and do a length 14 word so I imported
        #the the module RandomWords and used a loop
        #to loop randomly through the dictionary until I found a 14
        #letter word. Not the most efficient in terms of speed
        #by any means, but still a functional product.

        rw = RandomWords()
        word = rw.random_word()

        while len(word) != 14:
          word = rw.random_word()
          print "searching for a word"

        request.session['random_word'] = word

        return redirect('/')

    else:

        return redirect('/')
示例#6
0
def dbpost():
    # changes these to the master
    try:
        conn = psycopg2.connect(database=os.environ.get('PG_DATABASE'), user=os.environ.get('PG_USER'),
                                host=os.environ.get('MASTER_SERVICE_HOST'), password=os.environ.get('PG_PASSWORD'))
    except:
        print(os.environ.get('MASTER_SERVICE_HOST'))

    # generate a random lat, lon, and place name
    lat = random.uniform(-90, 90)
    lon = random.uniform(-180, 180)
    rw = RandomWords()
    name = rw.random_word() + " " + rw.random_word()

    sql_string = """insert into parkpoints(name, the_geom) values ('""" + name + """', ST_GeomFromText('POINT("""
    sql_string = sql_string + str(lon) + " " + str(lat) + ")', 4326));"

    cur = conn.cursor()
    # I know not this is not good form but I couldn't get it to work with the SRID stuff - probably just being lazy
    cur.execute(sql_string)

    conn.commit()

    # now let's get back our data we just put in
    cur.execute("""select parkid, name, ST_AsText(the_geom) from parkpoints ORDER by parkid DESC LIMIT 10""")

    rows = cur.fetchall()
    result_string = "<h2>Here are your results: </h2>"
    for row in rows:
        result_string += "<h3>" + str(row[0]) + ", " + str(row[1]) + ", " + str(row[2]) + "</h3>"

    cur.close()
    conn.close()
    return result_string
示例#7
0
def getRandomSearchWord(listSize):
    global searchQs
    rw = RandomWords()
    word = rw.random_word()
    searchQs=[] # clear existing word list
    for w in range(0,listSize):
        searchQs.append(rw.random_word())
    return searchQs
示例#8
0
文件: models.py 项目: ldyson/pllc
 def random_words(self):
     '''
     Generates three random words for meeting id and url creation
     Outputs: meeting id (a string)
     '''
     rw = RandomWords()
     w1 = rw.random_word()
     w2 = rw.random_word()
     w3 = rw.random_word()
     return w1 + "-" + w2 + "-" + w3
示例#9
0
文件: models.py 项目: ladyson/pllc
 def random_words(self):
     '''
     Generates three random words for meeting id and url creation
     Outputs: meeting id (a string)
     '''
     rw =  RandomWords()
     w1 = rw.random_word()
     w2 = rw.random_word()
     w3 = rw.random_word()
     return w1 + "-" + w2 + "-" + w3
示例#10
0
    def gen_words(self):
        rw = RandomWords()
        for i in range(50):
            rand_words = rw.random_word()
            while len(rand_words) > 10:
                rand_words = rw.random_word()

            self.falling_words.append(
                Word(rand_words, self.screen, self.game_font, self.white,
                     self.bg_color))
            self.falling_words[i].draw()
示例#11
0
    def get_word(self):
        rw = RandomWords()
        word = rw.random_word()
        self.word = word.lower()

        # To show word on terminal for demo purposes only
        print(self.word)
示例#12
0
def generate_example_fixed_file(outfile,
                                column_names,
                                offsets,
                                include_header,
                                encoding='windows-1252'):
    """Writes an example fixed-width file with random text.

    Args:
        outfile (str): output file name
        column_names (str[]): list of column names
        offsets (int[]): list of widths for each column
        encoding (str): encoding of the output file
        include_header (bool): whether to include the header in the output
            file

    Returns:
        N/A
    """
    log = logging.getLogger(__name__)
    log.info('Writing example fixed-width file following the spec...')

    rw = RandomWords()
    with open(outfile, 'w', encoding=encoding) as out_fh:
        # write header
        if include_header:
            for i, column in enumerate(column_names):
                out_fh.write(pad_fixed_column(column, offsets[i]))
            out_fh.write('\n')
        # write contents
        for i in range(0, EXAMPLE_FIXED_FILE_ROWS):
            for offset in offsets:
                out_fh.write(pad_fixed_column(rw.random_word(), offset))
            out_fh.write('\n')
示例#13
0
def generate(request):
    print(request.method)
    print "made it to the route"
    request.session['attempt'] += 1
    rw = RandomWords()
    request.session['random_word'] = word = rw.random_word()
    return redirect('/')
示例#14
0
def goToPhoto():
    driver.implicitly_wait(5)

    photos = []

    elems = driver.find_elements_by_xpath("//a[@href]")
    for elem in elems:
        if (re.search("https://www.instagram.com/p/",
                      elem.get_attribute("href"))):
            photos.append(elem.get_attribute("href"))

    for photo in photos:
        driver.get(photo)
        time.sleep(5)

        if (len(
                driver.find_element_by_tag_name('svg').get_attribute(
                    "aria-label")) == len("J'aime")):
            print("j'aime")
            driver.find_element_by_class_name(
                "_8-yf5 ").click()  #click sur j'aime
        time.sleep(10)

    rw = RandomWords()
    goToTag(rw.random_word())
    goToPhoto()
示例#15
0
class Giphy():
    """Class to contain API information and run requests."""
    def __init__(self, api_key):
        """Create an API instance using the api_key."""
        self._api_key = api_key
        self._api_instance = giphy_client.DefaultApi()
        self._random_words = RandomWords()
        logger.info("Started Giphy instance")

    def get_random_term(self):
        """Return a random, two word phrase."""
        term = "{} {}".format(
            self._random_words.random_word(),
            self._random_words.random_word(),
        )
        return term

    def get_random_gif_for_term(self, term):
        """Return a random gif that matches the given term."""
        api_response = self._api_instance.gifs_search_get(self._api_key,
                                                          term,
                                                          limit=1)
        if len(api_response.data) <= 0:
            logger.debug("Giphy couldn't find anything for: {}\n{}".format(
                term, api_response))
            raise GiphyException()

        return api_response.data[0].images.preview_gif.url
示例#16
0
def gen(rank):
    # 先确认每个小时的查询数目,里面的数都是随机生成的,没有什么特殊含义
    query_nums = []
    for h in range(0, 6):
        query_nums.append(random.randint(1, 10) * rank) # 0点到6点的比较少
    for h in range(6, 12):
        query_nums.append(random.randint(h * 2, h * 3) * rank) # 6点到12点的逐渐增多
    for h in range(12, 24):
        query_nums.append(random.randint((24 - h) * 2, (24 - h) * 3) * rank) # 12点到24点逐渐减少
    print("每小时访问数"+str(query_nums))
    print("总访问数:"+str(sum(query_nums)))
    rw = RandomWords() # 用于随机生成一个单词
    terminals = ["pc", "android", "iphone"] # 终端,可以分析维度
    zero_ts = time.mktime(time.strptime("2021-01-04 00:00:00", "%Y-%m-%d %H:%M:%S")) # 时间戳的起点
    res = []
    for hour in range(24):
        for cnt in range(0, query_nums[hour]): # 生成每小时的具体访问记录
            user_id = random.randint(50, 100)
            word = rw.random_word()
            terminal = terminals[random.randint(0, 2)]
            ts = str(int(zero_ts) + hour * 3600 + random.randint(0, 3600))
            res.append((str(user_id), word, terminal,ts))
    res.sort(key=lambda x: x[3]) # 按时间戳排序
    # 写入文件
    with open("./user_word.log", mode="w", encoding="utf-8") as f:
        for r in res:
            f.write(",".join(r) + "\n")
def tweetDictionary():

    dictionary = PyDictionary()
    rw = RandomWords()

    word = rw.random_word()
    definitions = dictionary.meaning(word)     # definitions is dictionary of two items (noun,verb)

    # print('\nWord : ',word, '\nDefinitions : ', definitions)
    # F-strings provide a way to embed expressions inside string literals, using a minimal syntax

    now = getDatetime()
    tweet = f'''Word of the Day
    Date: {now.strftime("%y-%m-%d")}
    Word: {word}
    Meaning: {definitions}
    Source: "PyDictionary"
    '''
    size = sys.getsizeof(tweet)
    print('Dictionary tweet size: ', size)

    if size < 362:
        api.update_status(tweet)
        print('Word tweeted successfully')
    else:
        print('error, loading again')
        tweetDictionary()
def wordgen():
    rw = RandomWords()
    word = str(rw.random_word())
    blank ='_'
    for i in range(0,len(word)):
        blank += '_'
    return word,blank
def gen_words():
    rw=RandomWords()
    words=[]
    while len(words)<10:
        word=rw.random_word()
        if 3<len(word)<9:
            words.append(word)
    return words
示例#20
0
def getQuestion():
    rw = RandomWords()
    ans = rw.random_word()
    hint = dictionary.meaning(ans)
    print(hint)
    print(ans)
    question = reorganize(ans)
    return question, ans, hint
def getQuestion():
    rw = RandomWords()
    word4game = rw.random_word()
    hint = dictionary.meaning(word4game)
    print(hint)
    print(word4game)
    question, ansLetter = word_to_underscore(word4game)
    return question, ansLetter, hint
示例#22
0
def teste_hashtable():
    rw = RandomWords()
    arquivo = open('tempo_memoria_hash10k2.txt', 'w')
    memoria_usada = psutil.virtual_memory().used
    tabela, documentos = hash_table.carregar_indice()
    arquivo.write('Memória utilizada: ' +
                  str(psutil.virtual_memory().used - memoria_usada) + '\n')
    comeco = time.time()
    for i in range(0, 10000):
        palavra = rw.random_word()
        palavra = palavra + ' ' + rw.random_word()
        if i % 1000 == 0:
            agora = time.time()
            arquivo.write(str(i) + ' - ' + str(agora - comeco) + '\n')
        busca_hashtable(tabela, documentos, palavra)
    final = time.time()
    arquivo.write('Tempo total: ' + str(final - comeco))
示例#23
0
def generate(request):
    if request.method == 'POST':
        rw = RandomWords()
        word = rw.random_word()
        request.session['count'] = request.session['count'] + 1
        request.session['word'] = word
        return redirect('/')
    else:
        return redirect('/')
def getQuestion():
    rw = RandomWords()
    ans = rw.random_word()
    fakeAns = 2
    definition = dictionary.meaning(ans)
    print(definition)
    print(ans)

    possibleAns = []
    possibleAns.append(ans)

    for i in range(fakeAns):
        fake = rw.random_word()
        possibleAns.append(fake)

    random.shuffle(possibleAns)

    question = reorganize(ans)
    return possibleAns, ans, definition
示例#25
0
def index():
    rw = RandomWords()
    print(session['count'])
    session['count'] += 1
    count = 7 - session['count']

    if session['count'] == 1:
        session['guesses'] = []
        session['wordform'] = 'Guess ! \n'
        session['word'] = rw.random_word().upper()
        session['wordlen'] = len(session['word'])
        name = request.form['word']
        session['wordform'] = "Welcome " + name + " ! "
        for i in range(session['wordlen']):
            session['guesses'].append("?")
            session['wordform'] += "_?_"
        return render_template('number2.html',
                               word=session['wordform'],
                               count=count)

    else:
        guess = str(request.form['gue']).upper()
        if len(guess) > 1 or session['word'].find(guess) == -1:

            if session['count'] == 7:
                lost = "YOU LOST ! The Word was "
                lost += session['word']
                return lost
            return render_template('number2.html',
                                   word=session['wordform'],
                                   count=count)

        else:
            indexing = 0
            session['count'] -= 1
            session['wordform'] = ""
            while indexing < session['wordlen']:
                indexing = str(session['word']).find(guess, indexing)
                if indexing == -1:
                    break
                session['guesses'][indexing] = guess
                indexing += 1
            for i in range((session['wordlen'])):
                session['wordform'] += "_ " + str(session['guesses'][i]) + " _"

            if not '?' in session['guesses']:
                text = "YOU WIN !! THE WORD IS "
                for i in range(session['wordlen']):
                    text += session['guesses'][i]
                return text

            return render_template('number2.html',
                                   word=session['wordform'],
                                   count=count)
def get_random_list(list_type, size, max_number):
    randomlist = []
    if list_type == "words":
        for i in range(0, size):
            rw = RandomWords()
            word = rw.random_word()
            randomlist.append(word)
    if list_type == "numbers":
        for i in range(0, size):
            n = random.randint(1, max_number)
            randomlist.append(str(n))
    return randomlist
示例#27
0
def dbpost():

    # changes these to the master
    try:
        conn = psycopg2.connect(
            database=os.environ.get("PG_DATABASE"),
            user=os.environ.get("PG_USER"),
            host=os.environ.get("PG_MASTER_RC_DC_SERVICE_HOST"),
            password=os.environ.get("PG_ROOT_PASSWORD"),
        )
    except:
        print(os.environ.get("PG_USER") + "  " + os.environ.get("PG_MASTER_RC_DC_SERVICE_HOST"))

        # Need to generate some data - no need for ID
        # NEED a name and a lat and long
    lat = random.uniform(-90, 90)
    lon = random.uniform(-180, 180)
    rw = RandomWords()
    name = rw.random_word() + " " + rw.random_word()

    sql_string = """insert into parkpoints(name, the_geom) values ('""" + name + """', ST_GeomFromText('POINT("""
    sql_string = sql_string + str(lon) + " " + str(lat) + ")', 4326));"

    cur = conn.cursor()
    # I know not this is not good form but I couldn't get it to work with the SRID stuff - probably just being lazy
    cur.execute(sql_string)

    conn.commit()

    # now let's get back our data we just put in
    cur.execute("""select parkid, name, ST_AsText(the_geom) from parkpoints ORDER by parkid DESC LIMIT 10""")

    rows = cur.fetchall()
    result_string = "<h2>Here are your results: </h2>"
    for row in rows:
        result_string += "<h3>" + str(row[0]) + ", " + str(row[1]) + ", " + str(row[2]) + "</h3>"

    cur.close()
    conn.close()
    return result_string
示例#28
0
def armador(n,m):
	palabras = []
	for _ in range(1,n+1):
		rw = RandomWords()
		word = rw.random_word()
		palabras.append(word)

	res = []
	for _ in range(1,m+1):
		secure_random = random.SystemRandom()
		res.append(secure_random.choice(palabras))

	return res
    def start_the_game(self):

        ### GENERATE A WORD ###
        rw = RandomWords()
        generate_word = rw.random_word()
        self.word = generate_word

        ### GENERATE SAME A SAME LONG STRING IN LIST ###
        for i in range(len(self.word)):
            self.Guess_WORD.append("-")
        print(self.word)
        self.word = list(self.word)
        print(self.Guess_WORD)
        self.find_out_the_word()
示例#30
0
def sologame():
    global guess
    guess = []
    #  from https://pypi.python.org/pypi/RandomWords/0.1.5
    rw = RandomWords()
    hint = rw.random_word()

    #  from https://www.datamuse.com/api/
    api = Datamuse()

    foo_complete = api.words(ml=hint, max=4)
    foo_df = scripts.dm_to_df(foo_complete)

    loo = api.words(rel_par=hint, max=1)
    loo_df = scripts.dm_to_df(loo)

    maybe = api.words(rel_trg=hint, max=1)
    maybe_df = scripts.dm_to_df(maybe)

    values = foo_df['word'].values
    val = loo_df['word'].values
    v = maybe_df['word'].values
    wordList = set()

    level = 0
    if score > 5:
        level = 2

    for i in values:
        if 3+level < len(i) < 7+level and i.isalpha():
            wordList.add(i)
    for i in val:
        if 3+level < len(i) < 7+level and i.isalpha():
            wordList.add(i)
    for i in v:
        if 3+level < len(i) < 7+level and i.isalpha():
            pass
            wordList.add(i)

    wordList = list(wordList)
    if len(wordList) < 2:
        sologame()
    while len(wordList) > 3:
        wordList.pop()

    soloB = screen.Solo.game(wordList)
    try:
        main(wordList, soloB, hint, "solo")
    except:
        sologame()
示例#31
0
def book_generator(filepath, chapters, chapter_len):
    rw = RandomWords()
    file = open(filepath, "w")
    file.write("#Chapter 0")
    file.write("\n")
    for chapt in range(2, chapters):
        for word in range(chapter_len):
            file.write(rw.random_word() + " ")
            if random.randrange(15) == 3:
                file.write("\n")
        file.write("\n")
        file.write("\n")
        file.write("#Chapter " + str(chapt))
        file.write("\n")
    file.close()
class Million_words_driver:
    def generate_million_words(self, manager_arr):
        self.rw = RandomWords()
        for i in range(1, 10):
            million_words_return = [
                self.rw.random_word() for _ in range(900000)
            ]

            ##This array will be used to introduce 10% noise in the row
            ten_percent_null_array = [None] * 100000
            million_words_with_null = million_words_return + ten_percent_null_array
            random.shuffle(million_words_with_null)
            manager_arr.append(million_words_with_null)

        return manager_arr
示例#33
0
def newWord():
    d = PyDictionary()
    rw = RandomWords()

    word = rw.random_word()
    definitions = d.meaning(word)

    try:
        part_of_speech = random.choice(list(definitions.keys()))
        definition = random.choice(definitions[part_of_speech])
    except:
        return "NULL_DEFINITION"
    return {
        "word": word,
        "definition": definition,
        "part_of_speech": part_of_speech
    }
    def _new_game(self, user, game_name):
        # retrieve key from user_name
        user_key = ndb.Key(User, user.user_name)

        # generate game_id
        game_id = Game.allocate_ids(size=1, parent=user_key)[0]

        # create key using generated game_id and user as its ancestor
        game_key = ndb.Key(Game, game_id, parent=user_key)

        # generate random word for this game
        rw = RandomWords()
        word = rw.random_word()

        guessed_chars_of_word = []

        # make this impl more 'pythonic' way
        for c in word:
            guessed_chars_of_word.append('*')

        game = Game(key=game_key,
                    game_id=game_id,
                    game_name=game_name,
                    word=word,
                    guessed_chars_of_word=guessed_chars_of_word)
        # save game
        game.put()

        # score id
        score_id = Score.allocate_ids(size=1, parent=user_key)[0]

        # score key using generated score_id and user as its ancestor
        score_key = ndb.Key(Score, score_id, parent=user_key)

        # score entity for this game
        score = Score(key=score_key,
                      score_id=score_id,
                      game_key=game_key)
        # save score
        score.put()

        # capture game snapshot
        self._capture_game_snapshot(game, '')

        return game
 def writeProductsData(self, categoriesList):
     rw = RandomWords()
     productsList = []
     for i in range(500):
         product_name = rw.random_word()
         if (product_name not in productsList):
             category = random.choice(categoriesList)
             product = {
                 "name": product_name,
                 "price": getRandomPrice(),
                 "category": category["name"],
                 "category_id": category["_id"]
             }
             productsList.append(product)
     db = self.client[args.database]
     coll = db["products"]
     for p in productsList:
         coll.insert_one(p)
示例#36
0
文件: AlexBot.py 项目: Loikya/AlexBot
def generate_post(who, num, flag):
    if(len(num) > 1):
        if(int(num[1]) < 7):
            num = int(num[1])
        else: num = 1
    else: num = 1
    rw = RandomWords()
    if(flag == 0):
        bot.messages.send(peer_id=who, message="Подготавливаю пост, ждите(это может быть быстро, а может долго. Производительность рандомная, также как и генерируемый пост...)", random_id=random.randint(0, 200000))
    """p = requests.get("https://unsplash.it/900/600/?random")"""

    word = rw.random_word()
    url = flickr.get_random_img(word)
    p = requests.get(url)
    out = open("random.jpg", "wb")
    out.write(p.content)
    out.close()

    img = {'photo': ('img.jpg', open(r'random.jpg', 'rb'))}
    # Получаем ссылку для загрузки изображений
    if(flag == 0):
        response = bot.photos.getMessagesUploadServer()
    else: response = bot.photos.getWallUploadServer()
    upload_url = response['upload_url']

    # Загружаем изображение на url
    response = requests.post(upload_url, files=img)
    result=response.json()

    # Сохраняем фото на сервере и получаем id
    photo1=result['photo'] 
    hash1=result['hash'] 
    server1=result['server']
  
    text = requests.get("http://api.forismatic.com/api/1.0/?method=getQuote&key=457653&format=text&lang=ru")
    if(photo1 != '[]'):
        if(flag == 0): 
            response = bot.photos.saveMessagesPhoto(server=server1, photo=photo1,   hash=hash1) 
        else: response = bot.photos.saveWallPhoto(user_id="360474541", server=server1, photo=photo1,   hash=hash1)
        attach="photo"+str(response[0]['owner_id'])+"_"+str(response[0]['id'])+","+get_random_audio(num)
        if(flag == 0):
            bot.messages.send(peer_id=who, random_id=random.randint(0, 200000),message=text.text, attachment=attach)
        else: bot.wall.post(owner_id="360474541", guid=random.randint(0, 200000),message=text.text, attachment=attach)
示例#37
0
    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        if form.is_valid():
            phone = form.cleaned_data['username']
            # Genarates the random word for the sms code
            random_word = RandomWords()
            sms_code = random_word.random_word()

            # Creates the record with the random 
            # activation word and the phone number
            ActivationSMSCode.objects.create(
                sms_code=sms_code,
                phone=phone,
                sms_code_init_time=datetime.datetime.utcnow().replace(
                    tzinfo=utc)
            )

            try:
                # Sends sms message with the random word
                api.send_sms(
                    body=sms_code,
                    from_phone=settings.PHONE_NUMBER_FROM,
                    to=[phone],
                    flash=True
                )
            except Exception, e:
                messages.add_message(
                    request,
                    messages.ERROR,
                    SEND_MESSAGE_ERROR
                )
                return HttpResponseRedirect(reverse("signup"))

            return HttpResponseRedirect(
                reverse('signup_activation',
                    kwargs={
                        'phone': form.cleaned_data['username']
                    }
                )
            )
class Command(BaseCommand):
    def __init__(self):
        super(Command, self).__init__()
        self.rw = RandomWords()
        self.li = LoremIpsum()
        self.array_size = 2

    def handle(self, *args, **options):
        tags = []
        for i in xrange(20000):
            name = self.make_name()
            tag, created = Tag.objects.get_or_create(name=name)
            if created:
                tags.append(tag)
        print '{0} tags has been created.'.format(len(tags))

        posts = []
        tags_ids = Tag.objects.all().values_list('id', flat=True)
        if self.array_size < len(tags_ids):
            for i in xrange(100000):
                name = self.make_name()
                rand = random.sample(tags_ids, self.array_size)
                post, created = Post.objects.get_or_create(
                    name=name,
                    defaults={
                        'tags': rand,
                        'description': self.li.get_sentences(5),
                    }
                )
                if created:
                    posts.append(post)
            print '{0} posts has been created.'.format(len(posts))

        else:
            print 'Please generate more tags than {0}.'.format(self.array_size)

    def make_name(self):
        name = self.rw.random_word().capitalize()
        name = '{0}{1}'.format(name, random.randint(1, 10))
        return name
示例#39
0
# -*- coding: utf-8 -*-
"""
Created on Sat Oct  1 19:27:55 2016

@author: SRINIVAS
"""
from random_words import RandomWords
rw = RandomWords()
rw=rw.random_word()

from PyDictionary import PyDictionary
dictionary=PyDictionary()
import nltk
from nltk.corpus import words


def randWord2():
	rw = RandomWords()
	word1 = rw.random_word()
	word2 = rw.random_word()
	word = word1+" "+word2
	return word
示例#41
0
文件: server.py 项目: unscsprt/DryIce
def generate_ez_link():
    rw = RandomWords()
    return rw.random_word().capitalize() + rw.random_word().capitalize()
示例#42
0
from __future__ import division
from time import time

s = set()
s.add(1)
s.add(2)
s.add(2)
x = len(s)
print(2 in s)
print(3 in s)

from random_words import RandomWords
rw = RandomWords()
word = rw.random_word()
print(word)

word = rw.random_word('y')
print(word)

words = rw.random_words(count=10)
print(words)

words = rw.random_words(letter='r', count=5)
print(words)

words = rw.random_words(letter=None, count=2)
print(words)

hundreds_of_other_words = []

stopwords_list = ["a", "an", "at"] + hundreds_of_other_words + ["yet", "you"]
示例#43
0
class TestBankApi(TestCase):
    def __init__(self, *args, **kwargs):
        super(TestBankApi, self).__init__(start_server_func, get_vnc_api_client, *args, **kwargs)
        self.rw = RandomWords()

    def get_api_server(self):
        return get_api_server()

    def test_domain_crud(self):
        self.useFixture(DomainTestFixtureGen(self._vnc_lib, auto_prop_val=True))

    def test_global_system_config_crud(self):
        self.useFixture(GlobalSystemConfigTestFixtureGen(self._vnc_lib, auto_prop_val=True))

    def test_namespace_crud(self):
        parent_fix = self.useFixture(
            DomainTestFixtureGen(self._vnc_lib, domain_name=self.rw.random_word(), auto_prop_val=True)
        )
        self.useFixture(NamespaceTestFixtureGen(self._vnc_lib, auto_prop_val=True, parent_fixt=parent_fix))
        self._vnc_lib.namespaces_list()
        objects = self._vnc_lib.namespaces_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.namespaces_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.namespace_read, id="no_op")

    def test_namespace_create_fail(self):
        def _with_fixture():
            parent_fix = None
            parent_fix = self.useFixture(
                DomainTestFixtureGen(self._vnc_lib, domain_name=self.rw.random_word(), auto_prop_val=True)
            )
            self.useFixture(
                NamespaceTestFixtureGen(
                    self._vnc_lib, namespace_name=self.rw.random_word(), auto_prop_val=True, parent_fixt=parent_fix
                )
            )

        flexmock(self.get_api_server()).should_receive("_post_common").replace_with(
            lambda x, y, z: (False, (501, "namespace create Error"))
        )
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call("_post_common")
        resource_class = (
            flexmock(NamespaceServerGen)
            .should_receive("http_post_collection")
            .replace_with(lambda x, y, z: (False, (501, "Collection Error")))
        )
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called, 0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_namespace_read_fail(self):
        def _with_fixture():
            parent_fix = self.useFixture(
                DomainTestFixtureGen(self._vnc_lib, domain_name=self.rw.random_word(), auto_prop_val=True)
            )
            self.useFixture(
                NamespaceTestFixtureGen(
                    self._vnc_lib, namespace_name=self.rw.random_word(), auto_prop_val=True, parent_fixt=parent_fix
                )
            )

        flexmock(self.get_api_server()).should_receive("_get_common").replace_with(
            lambda x, y: (False, (501, "account read Error"))
        )
        self.assertRaises(HttpError, _with_fixture)

    def test_access_control_list_crud(self):
        self.useFixture(AccessControlListTestFixtureGen(self._vnc_lib, auto_prop_val=True))
        self._vnc_lib.access_control_lists_list()
        objects = self._vnc_lib.access_control_lists_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.access_control_lists_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.access_control_list_read, id="no_op")

    def test_access_control_list_create_fail(self):
        def _with_fixture():
            parent_fix = None
            self.useFixture(
                AccessControlListTestFixtureGen(
                    self._vnc_lib, access_control_list_name=self.rw.random_word(), auto_prop_val=True
                )
            )

        flexmock(self.get_api_server()).should_receive("_post_common").replace_with(
            lambda x, y, z: (False, (501, "access_control_list create Error"))
        )
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call("_post_common")
        resource_class = (
            flexmock(AccessControlListServerGen)
            .should_receive("http_post_collection")
            .replace_with(lambda x, y, z: (False, (501, "Collection Error")))
        )
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called, 0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_access_control_list_read_fail(self):
        def _with_fixture():
            self.useFixture(
                AccessControlListTestFixtureGen(
                    self._vnc_lib, access_control_list_name=self.rw.random_word(), auto_prop_val=True
                )
            )

        flexmock(self.get_api_server()).should_receive("_get_common").replace_with(
            lambda x, y: (False, (501, "account read Error"))
        )
        self.assertRaises(HttpError, _with_fixture)

    def test_account_info_crud(self):
        self.useFixture(AccountInfoTestFixtureGen(self._vnc_lib, auto_prop_val=True))
        self._vnc_lib.account_infos_list()
        objects = self._vnc_lib.account_infos_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.account_infos_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.account_info_read, id="no_op")

    def test_account_info_create_fail(self):
        def _with_fixture():
            parent_fix = None
            self.useFixture(
                AccountInfoTestFixtureGen(self._vnc_lib, account_info_name=self.rw.random_word(), auto_prop_val=True)
            )

        flexmock(self.get_api_server()).should_receive("_post_common").replace_with(
            lambda x, y, z: (False, (501, "account_info create Error"))
        )
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call("_post_common")
        resource_class = (
            flexmock(AccountInfoServerGen)
            .should_receive("http_post_collection")
            .replace_with(lambda x, y, z: (False, (501, "Collection Error")))
        )
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called, 0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_account_info_read_fail(self):
        def _with_fixture():
            self.useFixture(
                AccountInfoTestFixtureGen(self._vnc_lib, account_info_name=self.rw.random_word(), auto_prop_val=True)
            )

        flexmock(self.get_api_server()).should_receive("_get_common").replace_with(
            lambda x, y: (False, (501, "account read Error"))
        )
        self.assertRaises(HttpError, _with_fixture)

    def test_phone_crud(self):
        parent_fix = self.useFixture(
            AccountInfoTestFixtureGen(self._vnc_lib, account_info_name=self.rw.random_word(), auto_prop_val=True)
        )
        self.useFixture(PhoneTestFixtureGen(self._vnc_lib, auto_prop_val=True, parent_fixt=parent_fix))
        self._vnc_lib.phones_list()
        objects = self._vnc_lib.phones_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.phones_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.phone_read, id="no_op")

    def test_phone_create_fail(self):
        def _with_fixture():
            parent_fix = None
            parent_fix = self.useFixture(
                AccountInfoTestFixtureGen(self._vnc_lib, account_info_name=self.rw.random_word(), auto_prop_val=True)
            )
            self.useFixture(
                PhoneTestFixtureGen(
                    self._vnc_lib, phone_name=self.rw.random_word(), auto_prop_val=True, parent_fixt=parent_fix
                )
            )

        flexmock(self.get_api_server()).should_receive("_post_common").replace_with(
            lambda x, y, z: (False, (501, "phone create Error"))
        )
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call("_post_common")
        resource_class = (
            flexmock(PhoneServerGen)
            .should_receive("http_post_collection")
            .replace_with(lambda x, y, z: (False, (501, "Collection Error")))
        )
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called, 0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_phone_read_fail(self):
        def _with_fixture():
            parent_fix = self.useFixture(
                AccountInfoTestFixtureGen(self._vnc_lib, account_info_name=self.rw.random_word(), auto_prop_val=True)
            )
            self.useFixture(
                PhoneTestFixtureGen(
                    self._vnc_lib, phone_name=self.rw.random_word(), auto_prop_val=True, parent_fixt=parent_fix
                )
            )

        flexmock(self.get_api_server()).should_receive("_get_common").replace_with(
            lambda x, y: (False, (501, "account read Error"))
        )
        self.assertRaises(HttpError, _with_fixture)

    def test_user_crud(self):
        self.useFixture(UserTestFixtureGen(self._vnc_lib, auto_prop_val=True))
        self._vnc_lib.users_list()
        objects = self._vnc_lib.users_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.users_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.user_read, id="no_op")

    def test_user_create_fail(self):
        def _with_fixture():
            parent_fix = None
            self.useFixture(UserTestFixtureGen(self._vnc_lib, user_name=self.rw.random_word(), auto_prop_val=True))

        flexmock(self.get_api_server()).should_receive("_post_common").replace_with(
            lambda x, y, z: (False, (501, "user create Error"))
        )
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call("_post_common")
        resource_class = (
            flexmock(UserServerGen)
            .should_receive("http_post_collection")
            .replace_with(lambda x, y, z: (False, (501, "Collection Error")))
        )
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called, 0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_user_read_fail(self):
        def _with_fixture():
            self.useFixture(UserTestFixtureGen(self._vnc_lib, user_name=self.rw.random_word(), auto_prop_val=True))

        flexmock(self.get_api_server()).should_receive("_get_common").replace_with(
            lambda x, y: (False, (501, "account read Error"))
        )
        self.assertRaises(HttpError, _with_fixture)

    def test_api_access_list_crud(self):
        parent_fix = self.useFixture(
            DomainTestFixtureGen(self._vnc_lib, domain_name=self.rw.random_word(), auto_prop_val=True)
        )
        self.useFixture(ApiAccessListTestFixtureGen(self._vnc_lib, auto_prop_val=True, parent_fixt=parent_fix))
        self._vnc_lib.api_access_lists_list()
        objects = self._vnc_lib.api_access_lists_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.api_access_lists_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.api_access_list_read, id="no_op")

    def test_api_access_list_create_fail(self):
        def _with_fixture():
            parent_fix = None
            parent_fix = self.useFixture(
                DomainTestFixtureGen(self._vnc_lib, domain_name=self.rw.random_word(), auto_prop_val=True)
            )
            self.useFixture(
                ApiAccessListTestFixtureGen(
                    self._vnc_lib,
                    api_access_list_name=self.rw.random_word(),
                    auto_prop_val=True,
                    parent_fixt=parent_fix,
                )
            )

        flexmock(self.get_api_server()).should_receive("_post_common").replace_with(
            lambda x, y, z: (False, (501, "api_access_list create Error"))
        )
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call("_post_common")
        resource_class = (
            flexmock(ApiAccessListServerGen)
            .should_receive("http_post_collection")
            .replace_with(lambda x, y, z: (False, (501, "Collection Error")))
        )
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called, 0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_api_access_list_read_fail(self):
        def _with_fixture():
            parent_fix = self.useFixture(
                DomainTestFixtureGen(self._vnc_lib, domain_name=self.rw.random_word(), auto_prop_val=True)
            )
            self.useFixture(
                ApiAccessListTestFixtureGen(
                    self._vnc_lib,
                    api_access_list_name=self.rw.random_word(),
                    auto_prop_val=True,
                    parent_fixt=parent_fix,
                )
            )

        flexmock(self.get_api_server()).should_receive("_get_common").replace_with(
            lambda x, y: (False, (501, "account read Error"))
        )
        self.assertRaises(HttpError, _with_fixture)

    def test_project_crud(self):
        parent_fix = self.useFixture(
            DomainTestFixtureGen(self._vnc_lib, domain_name=self.rw.random_word(), auto_prop_val=True)
        )
        self.useFixture(ProjectTestFixtureGen(self._vnc_lib, auto_prop_val=True, parent_fixt=parent_fix))
        self._vnc_lib.projects_list()
        objects = self._vnc_lib.projects_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.projects_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.project_read, id="no_op")

    def test_project_create_fail(self):
        def _with_fixture():
            parent_fix = None
            parent_fix = self.useFixture(
                DomainTestFixtureGen(self._vnc_lib, domain_name=self.rw.random_word(), auto_prop_val=True)
            )
            self.useFixture(
                ProjectTestFixtureGen(
                    self._vnc_lib, project_name=self.rw.random_word(), auto_prop_val=True, parent_fixt=parent_fix
                )
            )

        flexmock(self.get_api_server()).should_receive("_post_common").replace_with(
            lambda x, y, z: (False, (501, "project create Error"))
        )
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call("_post_common")
        resource_class = (
            flexmock(ProjectServerGen)
            .should_receive("http_post_collection")
            .replace_with(lambda x, y, z: (False, (501, "Collection Error")))
        )
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called, 0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_project_read_fail(self):
        def _with_fixture():
            parent_fix = self.useFixture(
                DomainTestFixtureGen(self._vnc_lib, domain_name=self.rw.random_word(), auto_prop_val=True)
            )
            self.useFixture(
                ProjectTestFixtureGen(
                    self._vnc_lib, project_name=self.rw.random_word(), auto_prop_val=True, parent_fixt=parent_fix
                )
            )

        flexmock(self.get_api_server()).should_receive("_get_common").replace_with(
            lambda x, y: (False, (501, "account read Error"))
        )
        self.assertRaises(HttpError, _with_fixture)
示例#44
0
#perform "timing attacks" where they try to timestamp the data to
#help deanonymize, traffic obfusication and simular systems, originally written
#for the layerprox project but feel free to hack it in anyway you want

import urllib2, httplib
import datetime, time
from random import randint #not great but this is only a beta version, i could mix it with the day gen in otw
from random_words import RandomWords #https://pypi.python.org/pypi/RandomWords/0.1.5
from otw import genday
rw = RandomWords()
#put it in a loop n run with sysd or something simular



def genip():
	f = randint(1,254)
	i = randint(1,254)
	r = randint(1,254)
	s = randint(1,254)
	t = str(f + '.' + i + '.' + r + '.'  + s)
	ip = int(t)
	return ip

while 1:
	host = genip()
	conn = httplib.HTTPConnection(host)
	where = str(rw.random_word() + '.html')#make it look legit with a "random" word
	conn.request("HEAD","/index.html")
	time.sleep(100)# make this a randomly-generated int

示例#45
0
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 30 12:13:17 2016

@author: SRINIVAS
"""

from nltk.corpus import words
from random_words import RandomWords
rw = RandomWords()
a=0
while a<20:
    
    word = rw.random_word()
    i=list(word)
    i.reverse()
    i=''.join(i)
    if i in words.words():
        print(word)
        a=a+1
def randWord():
	rw = RandomWords()
	word = rw.random_word()
	return word
示例#47
0
class Restaurant:
  '''
    equipment is a list of Appliances
    tables is a list of Tables

  '''
  waiting_list_max = 20
  drink_menu = [
    {
      "name": "Beer",
      "price": 6.0,
      "requirements": ["alcohol"],
      "type": "alcohol",
      "cook_time": 2,
      "difficulty": 0,
      "cost": 1.0
    },
    {
      "name": "Vodka",
      "price": 8.0,
      "requirements": ["alcohol"],
      "type": "alcohol",      
      "cook_time": 2,
      "difficulty": 0,
      "cost": 2.5
    }
  ]
  food_menu = [
    {
        "name": "Pizza Slice",
        "price": 2.0,
        "requirements": ["pizza","oven","microwave"],
        "type": "pizza",
        "cook_time": 5, #in minutes
        "difficulty": 0.1,
        "cost": 1.0
    },
    {
        "name": "Personal Pan Pizza",
        "price": 10.0,
        "requirements": ["pizza","oven","microwave"],
        "type": "pizza",
        "difficulty": 0.5,
        "cook_time": 10,
        "cost": 7.0
    },
    {
        "name": "Wood-Fired Pizza",
        "price": 60.0,
        "requirements": ["brick_oven","pizza","oven"],
        "type": "pizza",
        "cook_time":15,
        "difficulty": 0.9,
        "cost": 30
    },
    {
        "name": "Sushi",
        "price": 15.0,
        "requirements": ["sushi"],
        "type": "sushi",
        "cook_time":15,
        "difficulty": 0.9,
        "cost": 8
    }
  ]
  def __init__(self, name, equipment, tables, staff, start_time='2019-01-01T00:00:00', day_log = None, food_menu = None, drink_menu = None, verbose=False):
    self.env = simpy.Environment()
    self.setup_constants()
    if food_menu:
      self.food_menu = food_menu
    if drink_menu:
      self.drink_menu = drink_menu
    self.menu = []
    for f in self.food_menu:
      self.menu.append(f)
    for d in self.drink_menu:
      self.menu.append(d)
    self.ledger = Ledger(self.env, self.food_menu,self.drink_menu,verbose=verbose,save_messages=True, rdq = day_log)
    self.env.ledger = self.ledger
    self.env.day = 0 # just a counter for the number of days
    self.name = name
    

    # queue for reporting the days internally or externally (if day_log is an rdq, see flask_app for more details)
    # if day_log:
    #   self.day_log = day_log
    # else:
    #   self.day_log = queue.Queue()

    # sim mechanics note that due to dependencies, the order matters here (e.g. seating needs staff to be setup to calculate table service ratings)
    self.setup_neighborhood()
    self.setup_staffing(staff)
    equipment = self.add_aux_equipment(equipment,tables)
    self.setup_kitchen(equipment)
    self.setup_menu() #notice that here we are refactoring the menu to weed out lesser options in requirements (if we have a brick oven, wood-fired pizza should wait for it)
    self.setup_seating(tables)
    

    # tools
    self.name_generator = RandomWords()
    self.start_time = arrow.get(start_time) # this doesn't really matter unless we start considering seasons etc.
    self.monkey_patch_env()

    # stats
    self.satisfaction_scores = []
    self.restaurant_rating = 1 #score between 0 and 1
    self.checks = []
    self.generated_parties = []
    self.entered_parties = []
    self.seated_parties = []
    self.order_log = []
    self.daily_costs = []
    self.closing_order = 0
    self.env.process(self.simulation_loop())

  def setup_constants(self):
    self.env.max_budget = 100
    self.env.max_wait_time = 60
    self.env.max_noise_db = 50
    self.env.rent = 200
    self.env.worker_wage = 150
    self.env.sim_loop_delay = 10*60 # in minutes

  def setup_staffing(self,staff):
    self.env.ledger.staff = [Staff(s['x'],s['y']) for s in staff]

  def add_aux_equipment(self,equipment,tables):
    for t in tables:
      if "appliances" in t["attributes"]:
        appliances = t["attributes"]["appliances"]
        for a in appliances:
          a["attributes"]["x"] = t["attributes"]["x"]
          a["attributes"]["y"] = t["attributes"]["y"]
          equipment.append(a)
    return equipment

  def setup_kitchen(self, equipment):
    self.kitchen = simpy.FilterStore(self.env, capacity=len(equipment))
    self.kitchen.items = [Appliance(self.env,e["name"],e["attributes"]) for e in equipment]
    self.food_menu = [m for m in self.food_menu if any(any(req in appliance.capabilities for req in m["requirements"]) for appliance in self.kitchen.items)]
    self.drink_menu = [d for d in self.drink_menu if any(any(req in appliance.capabilities for req in d["requirements"]) for appliance in self.kitchen.items)]
    self.env.ledger.print("Menu: {}".format(self.food_menu))
    self.env.ledger.set_appliances( [a for a in self.kitchen.items] )

  def setup_seating(self, tables):
    self.seating = simpy.FilterStore(self.env, capacity=len(tables))
    self.seating.items = [Table(self.env,t["name"],t["attributes"]) for t in tables]
    self.max_table_size = max([t.seats for t in self.seating.items])
    self.env.ledger.capacity = np.sum([t.seats for t in self.seating.items])
    self.env.ledger.set_tables( [t for t in self.seating.items] )
    for t in self.env.ledger.tables:
      t.start_simulation()
    self.env.ledger.service_rating = np.mean([t.service_rating for t in self.env.ledger.tables])

  def setup_menu(self):
    all_capabilities = []
    for appliance in self.env.ledger.appliances:
      for c in appliance.capabilities:
        all_capabilities.append(c)
    all_capabilities = list(set(all_capabilities))
    for meal in self.food_menu:
      new_reqs = []
      for r in meal["requirements"]:
        new_reqs.append(r)
        if r in all_capabilities:
          meal["requirements"] = new_reqs
          break
    for drink in self.drink_menu:
      new_reqs = []
      for r in drink["requirements"]:
        new_reqs.append(r)
        if r in all_capabilities:
          drink["requirements"] = new_reqs
          break
    for item in self.menu:
      new_reqs = []
      for r in item["requirements"]:
        new_reqs.append(r)
        if r in all_capabilities:
          item["requirements"] = new_reqs
          break
    self.env.ledger.menu = self.menu
    self.env.ledger.food_menu = self.food_menu
    self.env.ledger.drink_menu = self.drink_menu
    #print("\n\nFFFFFFOOOOOODDD",self.food_menu)




  def setup_neighborhood(self):
    self.max_party_size = 10
    self.neighborhood_size = 10000
    self.max_eating_pop = 0.1*self.neighborhood_size
    self.demographics = ["size","affluence","taste","noisiness","leisureliness","patience","noise_tolerance","space_tolerance", "mood","sensitivity", "appetite", "drink_frequency"] #sensitivity has to do with how much you care about service
    self.demographic_means = np.array([0.25,0.3,0.5,0.6,0.6,0.5,0.3,0.5, 0.5, 0.6,0.5, 0.5])
                                        # size aff taste  noi   leis  pat noi_t space_t
    # self.demographic_cov = np.matrix([[ 0.02, 0.00, 0.00, 0.09, 0.02,-0.02, 0.06,-0.02], #size
    #                                   [ 0.00, 0.02, 0.10,-0.02, 0.06,-0.07,-0.07,-0.07], #affluence
    #                                   [ 0.00, 0.10, 0.02,-0.02, 0.07,-0.01,-0.01, 0.0], #taste
    #                                   [ 0.09,-0.02,-0.02, 0.02, 0.01, 0.00, 0.08, 0.03], #noisiness
    #                             self.start_time.replace(seconds=self.env.now)      [ 0.02, 0.06, 0.07, 0.01, 0.02, 0.07,-0.06,-0.06], #leisureliness
    #                             self.start_time.replace(seconds=self.env.now)      [-0.02,-0.07,-0.01, 0.00, 0.07, 0.02, 0.07, 0.06], #patience
    #                             self.start_time.replace(seconds=self.env.now)      [ 0.06,-0.07,-0.01, 0.08,-0.06, 0.07, 0.02, 0.09], #noise tolerance
    #                             self.start_time.replace(seconds=self.env.now)      [-0.02,-0.07, 0.00, 0.03,-0.06, 0.06, 0.09, 0.02] #space toleranceseating.put(self.table)
    #                                  ])  
    self.demographic_cov = np.matrix([[ 0.05,  0.0,   0.0,   0.018, 0.004,-0.004, 0.012,-0.004, 0.00, -0.001, 0.000, 0.000],
                                      [ 0.0,   0.05,  0.03, -0.004, 0.012,-0.014,-0.014,-0.014, 0.00, 0.02, 0.000, 0.000],
                                      [ 0.0,   0.03,  0.05, -0.004, 0.014,-0.002,-0.002, 0.0, 0.00,  0.01, 0.000, 0.000],
                                      [ 0.018,-0.004,-0.004, 0.05,  0.002, 0.0,   0.016, 0.006, 0.00, 0.00, 0.000, 0.01],
                                      [ 0.004, 0.012, 0.014, 0.002, 0.05,  0.014,-0.012,-0.012, 0.00, 0.01, 0.000, 0.000],
                                      [-0.004,-0.014,-0.002, 0.0,   0.014, 0.05,  0.014, 0.012, 0.00, -0.02, 0.000, 0.000],
                                      [ 0.012,-0.014,-0.002, 0.016,-0.012, 0.014, 0.05,  0.018, 0.00, -0.015, 0.000, 0.000],
                                      [-0.004,-0.014, 0.0,   0.006,-0.012, 0.012, 0.018, 0.05, 0.00, -0.010, 0.000, 0.000],
                                      [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.05, -0.01, 0.000, 0.000],
                                      [-0.001, 0.02, 0.01, 0.000, 0.01, -0.02, -0.015, -0.01, -0.01, 0.05, 0.000, 0.000],
                                      [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.05, 0.000],
                                      [0.000, 0.000, 0.000, 0.01, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.05]
                                      ])
    # TODO: write an assertion that this is positive semi-definite

  def current_time(self):
    # let's assume the time step is seconds
    return self.start_time.replace(seconds=self.env.now)
  
  def monkey_patch_env(self):
    self.env.m_start_time = self.start_time
    self.env.m_current_time = self.current_time
    self.env.m_rw = self.rw
  
  def rw(self):
    return self.name_generator.random_word()
  
  def handle_party(self, party):
    if len(self.drink_menu) > 0:
      self.env.process(party.start_ordering_drinks(self.kitchen,self.drink_menu))
    seated = yield self.env.process(party.wait_for_table(self.seating))
    if seated == False:
      check,satisfaction = yield self.env.process(party.leave(self.seating))
    else:
      self.seated_parties.append(party)
      noise_process = self.env.process(party.update_satisfaction(self.env.ledger.tables))  
      # order = Order(self.env,self.rw(),party,party.table)
      # yield self.env.process(order.place_order(self.kitchen,self.food_menu))
      if len(self.food_menu) > 0:
        # if there is a kitchen, then order food
        yield self.env.process(party.place_order(self.kitchen,self.food_menu))
        # self.order_log.append(order)  
        yield self.env.process(party.eat())
      # if there is no kitcehn, but there is a bar, sit for awhile (while ordering drinks)
      # or if there is no anything, just sit here awkwardly for a bit I suppose
      else:
        yield self.env.process(party.chill())
      check,satisfaction = yield self.env.process(party.leave(self.seating))
    self.checks.append(check)
    self.satisfaction_scores.append(satisfaction)
  
  
  def get_customer_rate(self):
    hourly_rates = [
        [0,0,0,0,0,0,0.1,0.2,0.5,0.9,0.7,0.5,1,1,0.6,0.2,0.2,0.6,0.8,0.8,0.7,0.3,0.1,0.1,0], #m
        [0,0,0,0,0,0,0.1,0.2,0.5,0.9,0.7,0.5,1,1,0.6,0.2,0.2,0.6,0.9,0.9,0.8,0.3,0.1,0.1,0], #t
        [0,0,0,0,0,0,0.1,0.2,0.5,0.9,0.7,0.5,1,1,0.6,0.2,0.2,0.6,0.9,0.9,0.8,0.3,0.1,0.1,0], #wseating.put(self.table)
        [0,0,0,0,0,0,0.1,0.2,0.5,0.9,0.7,0.5,1,1,0.6,0.2,0.2,0.6,0.9,0.9,0.8,0.3,0.1,0.1,0], #r
        [0,0,0,0,0,0,0.1,0.2,0.5,1,0.7,0.5,1,1,0.6,0.2,0.2,0.6,1,1,0.8,0.8,0.8,0.1,0], #f
        [0,0,0,0,0,0,0.1,0.2,0.5,1,0.7,0.5,1,1,0.6,0.2,0.2,0.6,1,1,0.8,0.8,0.8,0.1,0], #sa
        [0,0,0,0,0,0,0.1,0.5,0.8,1,1,1,1,1,0.6,0.2,0.2,0.6,0.8,0.8,0.6,0.3,0.1,0.1,0]  #su    
    ]
    cur_time = self.env.m_current_time().timetuple()
    raw_rate = hourly_rates[cur_time.tm_wday][cur_time.tm_hour]
    rate = self.max_eating_pop*raw_rate
    return rate# number of groups /hr
  
  def sample_num_parties(self):
    '''
      Sample the number of parties that are looking to eat in the town at that hour
    '''
    num_parties = np.random.poisson(self.get_customer_rate())
    return num_parties
        
  def generate_parties(self,n=1):
    '''
      Randomly generate a party
    '''
    self.env.ledger.print("Time is: {} from {}".format(self.current_time().format("HH:mm:ss"),self.env.now))
    entered_parties = []
    num_entered = 0
    parties = np.clip(np.random.multivariate_normal(self.demographic_means,self.demographic_cov,n),0.01,1)
    num_generated = len(parties)
    for party in parties:
      self.generated_parties.append(party)
      party_attributes = {k:v for (k,v) in zip(self.demographics,party)}
      party_attributes["size"] = int(np.ceil(party_attributes["size"]*self.max_party_size))
      if(self.decide_entry(party_attributes)):
        num_entered += 1
        p = Party(self.env,self.rw().capitalize(),party_attributes)
        self.env.ledger.parties.append(p)
        entered_parties.append(p)
      else:
        continue
    self.env.ledger.print("Total groups generated: {}, total entered: {}".format(num_generated, num_entered))   
    return entered_parties
  
  def decide_entry(self,party_attributes):
    if(party_attributes["size"] > self.max_table_size):
      return False
    # if the people are unhappy and the restaurant is bad, don't enter
    if party_attributes["mood"] < 1-self.env.ledger.satisfaction:
      if np.random.uniform(0,1) > self.env.ledger.satisfaction/5: #basically if the satisfaction is high, with some small prob they enter anyway 
        return False
    # if the service is bad and the people care about service, don't enter
    if party_attributes["sensitivity"] > self.env.ledger.service_rating:
      if np.random.uniform(0,1) > self.env.ledger.service_rating: #if the service is good, still enter with some probability
        return False
    if party_attributes["affluence"] < 0.3:
      if party_attributes["taste"] > self.env.ledger.yelp_rating:
        return False
    if party_attributes["affluence"] >= 0.3 and party_attributes["affluence"] <= 0.7:
      if party_attributes["taste"] > self.env.ledger.zagat_rating:
        return False
    if party_attributes["affluence"] > 0.7:
      if party_attributes["taste"] > self.env.ledger.michelin_rating:
        return False
    if np.random.uniform(0,1) > 0.05:
      # TODO: replace this with tuning the poisson entry rate
      return False
    else:
       return True
    
  def simulation_loop(self):
    day_of_week = ""
    daily_customers = 0
    party_index = 0
    while True:
      yield self.env.timeout(60*60) #every hour
      today = self.env.m_current_time().format("dddd")
      if today != day_of_week:
        day_of_week = today
        self.env.day += 1
        self.ledger.record_current_day()
        self.calc_stats()
        #costs = self.run_expenses()time_waited = 0
        #self.env.process(self.calc_stats())
        #self.summarize(costs,daily_customers,self.entered_parties[party_index:party_index+daily_customers])
        daily_customers = 0
        party_index += daily_customers
        #self.restaurant_rating = min(0,2)
        #self.restaurant_rating = np.mean(self.satisfaction_scores)
        #day = self.env.m_current_time().format("ddd MMM D")
        #print("Summary for {}: satisfaction: {}".format(day,self.restaurant_rating))
      # generate 0+ parties based on the time of day & popularity of the restaurant
      entering_parties =  self.generate_parties(self.sample_num_parties())
      daily_customers += len(entering_parties) 
      for p in entering_parties:    
        self.env.process(self.handle_party(p))
        
  def simulate(self,seconds=None,days=None):
    if seconds:
      max_seconds = seconds
    elif days:
      max_seconds = days*24*60*60
    else:
      max_seconds = 100
    self.env.run(until=max_seconds)
    
  def run_expenses(self):
    daily_cost = 0
    for a in self.env.ledger.appliances:
      daily_cost += a.daily_upkeep
    for t in self.env.ledger.tables:
      daily_cost += t.daily_upkeep
    for o in self.order_log[self.closing_order:]:
      daily_cost += o.total_cost
      self.closing_order = len(self.order_log)
    self.daily_costs.append(daily_cost)
    return daily_cost
    
  def calc_stats(self):
    if len(self.satisfaction_scores) > 0:
      self.restaurant_rating = np.mean(self.satisfaction_scores)

 
  def summarize(self,costs,volume,parties):
    day = self.env.m_current_time().format("ddd MMM D")
    customers = np.sum([p.size for p in parties])
    if customers > 0:
      noise = np.sum([p.size*p.noisiness for p in parties])/customers
      total_bills = np.sum([p.paid_check for p in parties])
      satisfaction = np.mean([p.satisfaction for p in parties if not np.isnan(p.satisfaction)])
      self.env.ledger.print("Summary for {}: satisfaction: {}".format(day,self.restaurant_rating))
    else:
      noise = 0
      total_bills = 0
      satisfaction = 0
    self.day_log.put({"day": self.env.day,"expenses":costs,"rating":self.restaurant_rating,"num_entered":volume, "noise": noise, "revenue":total_bills, "satisfaction": satisfaction})


  def final_report(self):
    stringbuilder = ""
    stringbuilder += "*"*80+"\n"
    stringbuilder += "Simulation run for {} days.\n".format(self.ledger.num_days)
    stringbuilder += "*"*80+"\n"
    stringbuilder += "Parties entered: {}\nParties seated: {}\nParties paid: {}\n".format(len(self.entered_parties),len(self.seated_parties),len([c for c in self.checks if c > 0]))
    revenue = np.sum(self.checks)
    stringbuilder += "Total Revenue: ${:.2f}\n".format(revenue)
    upfront_costs = np.sum([a.cost for a in self.env.ledger.appliances]) + np.sum([t.cost for t in self.env.ledger.tables])
    stringbuilder += "Total Upfront Costs: ${:.2f}\n".format(upfront_costs)
    costs = np.sum(self.daily_costs)
    stringbuilder += "Total Daily Costs: ${:.2f}\n".format(costs)
    stringbuilder += "Total Profit: ${:.2f}\n".format(revenue-costs-upfront_costs)
    # leftovers = len(self.entered_parties)-len(self.checks) #if we cut off the last day while people were dining
    # if leftovers > 0:
    #   truncated_entered_parties = self.entered_parties[:-leftovers]
    # else:
    #   truncated_entered_parties = self.entered_parties
    num_served = np.sum([p.size for i,p in enumerate(truncated_entered_parties) if p.paid_check>0])
    stringbuilder += "Total individual customers served: {}\nAverage price per entree: ${:.2f}\n".format(num_served,revenue/num_served)
    stringbuilder += "Avg Satisfaction Score: {:.2f}\nStd Satisfaction Score: {:.2f}\n".format(np.mean(self.satisfaction_scores), np.std(self.satisfaction_scores))
    stringbuilder += "Final Restaurant Rating: {:.2f}\n".format(self.restaurant_rating)
    #print(stringbuilder)
    return stringbuilder
示例#48
0
 def random_words(self):
     rw =  RandomWords()
     w1 = rw.random_word()
     w2 = rw.random_word()
     w3 = rw.random_word()
     return w1 + "-" + w2 + "-" + w3
示例#49
0
def generate_word():
    # TODO: generate random word
    rw = RandomWords()
    word = rw.random_word()
    return word
示例#50
0
def new_word():
	rw = RandomWords()
	word = rw.random_word()
	return word, hashlib.sha224(word).hexdigest()
示例#51
0
class shortener:
    def __init__(self):
        '''the cur and con objects for accsessing the db'''
        global cur,con
        
        self.cur = cur
        self.con = con
        #self.capt_code = capt_code
        self.rw = RandomWords()
        self.pass_enc = self.rw.random_word()

        ses_log('[init]', 'done')
        #self.link_pass=link_password
    
    @cherrypy.expose
    def index(self,d = None):
        '''redirect user to homepage or link'''

        #capt_code = get_sentences(1)
        redir = geturl(self,d)#get the url to redirect to
        
        #return 'hai'
        ses_log('\n[***SESSION STARTED!!***]', '')
        ses_log('[index]', 'redirecting user to %s' % redir)
        
        raise cherrypy.HTTPRedirect(redir)
        #raise cherrypy.HTTPError(418)

    ############FRONTEND: the pages that the user sees most of the time

    #@cherrypy.expose
    #def getuuid(self,text):
    #    return uuid(text)

    @cherrypy.expose
    def getcaptcha(self):
        cherrypy.response.headers['Content-Type'] = "image/png"
        #self.capt_code = self.rw.random_word()
        return newcaptcha(self.rw.random_word())

    @cherrypy.expose
    def getqr(self,url):
        '''generate qr from url'''

        ses_log('[qr gen]','sending qr image')
        cherrypy.response.headers['Content-Type'] = "image/jpg"
        return new_qr(base64.b64decode(url))

    @cherrypy.expose
    def add_url(self, short, long, password = None, owner = '', owner_pass = ''):
        '''the form from homepage redirects here'''
        #this gets called by the form, so the dangerous chars in the url are escaped
        
        if not special_match(short):   #test for invalid chars
            raise cherrypy.HTTPRedirect('static/info/invalid_chars.html')
        
        #long = base64.b64decode(long)
        ses_log('[add url]', 'calling func')
        result = new_url(self, short, long, password = password,
                     owner = owner, owner_pass = owner_pass)
        
        raise cherrypy.HTTPRedirect('/%s\
?surl=%s;lurl=%s' % (result[0],result[1],base64.b64encode(long)))
    #using result[1] instead of short, because if short is empty,
    #the function will set it to the hash of long, but
    #the short in this func won't be changed

    @cherrypy.expose
    def show_message(self, msg, redirect = False):
        '''for functions to display a message to the user.'''

        ses_log('[show message]', 'displaying message %s, redirect: %s' %
                (msg, str(redirect)))
        if redirect:
            raise cherrypy.HTTPRedirect(msg)
        return msg

    #########other
    @cherrypy.expose
    def login(self,name,password):#Store password and login for user
        password = sha1(password).hexdigest()
        self.cur0.execute("select password from owners where name = '%s'" % name)
        actual_pass = self.cur.fetchone()

        if name:
            if actual_pass:
                if password == actual_pass[0]:
                   self.cur.execute("select perm from owners where name = '%s'" % name)
                   cherrypy.session['owner_pass'] = password
                   cherrypy.session['owner_name'] = name
                   cherrypy.session['owner_permission'] = str(self.cur.fetchone()[0])
                else:
                    return 'incorrect pass'
            else:
                return 'unkown owner'
        else:
            return 'permission denied'
        
        raise cherrypy.HTTPRedirect('/get_all_owner_urls')

    @cherrypy.expose
    def exec_mysql(self,comman=''):
        perm_lvl = cherrypy.session.get('owner_permission')
        #self.cur.execute(command)
        return str(perm_lvl)

        #return str(self.cur.fetchall())
        
    @cherrypy.expose
    def get_all_owner_urls(self):#get all urls of owner (login+pass stored in session)
        '''all urls of a certain owner'''
        password = cherrypy.session.get('owner_pass')
        owner = cherrypy.session.get('owner_name')
                
        self.cur.execute("select longurl,pass,shorturl from urls where \
owner = '%s'" % owner[0])   #Select the links that belong to the owner

        ses_log('[all_owner_urls]', 'sending urls of owner %s, pass: %s' %
                (owner,password))

        ses_log('[...END SESSION!!...]', '')
        return str(cur.fetchall())
    
###########Backend: pages the user doesn't see a lot

    @cherrypy.expose
    def add_owner(self,name,password,email,captcha):
        #if invalid chars used
        if not special_match(name) or not special_match(password):
            raise cherrypy.HTTPRedirect('static/info/invalid_chars.html')
        #if cpatcha incorrect
        if captcha != cherrypy.session.get('capt_code'):
            return 'captcha incorrect'
    
        res = new_owner(self,name,password,email)
        return res
        #raise cherrypy.HTTPRedirect('/static/info/register/%s.html' % res)

    @cherrypy.expose
    def ads(self,destination):
        '''insert ads in here to show before redirecting to final page'''

        ses_log('[ads]', 'redirecting user')
        ses_log('[...END SESSION!!...]', '')
        
        destination = base64.b64decode(destination)#destination is encoded!
        log_visit(cherrypy.request.remote.ip, self, destination)

        if destination[:4] != 'http':   #if url does not include protocol, add it.
            destination = 'http://' + destination
        
        sleep(0.1)   #technical
        raise cherrypy.HTTPRedirect(destination.decode('ascii'))

    @cherrypy.expose
    def auth_link(self,dest,password):
        '''verify password for passworded links'''
        
        password = sha1(password).hexdigest()
        link_password = cherrypy.session.get('link_pass')
        ses_log('[validating password]', 'password: %s entered: %s' %
          (link_password, password))
        if password == link_password:
            ses_log('[validating password]', 'sucsess')
        else: return 'Pass incorrect'
        
        #Get longurl from shorturl
        self.cur.execute("select longurl from urls where shorturl = '%s'" % dest)
        dest2 = cur.fetchone()  #longurl
        ses_log('[auth_link]', 'got url, redirecting')
        
        raise cherrypy.HTTPRedirect("/ads?destination=%s" % base64.b64encode(dest2[0]))
示例#52
0
class TestDesignToolsApi(TestCase):
    def __init__(self, *args, **kwargs):
        super(TestDesignToolsApi, self).__init__(start_server_func, get_vnc_api_client, *args, **kwargs)
        self.rw = RandomWords()

    def get_api_server(self):
        return get_api_server()
    def test_domain_crud(self):
        self.useFixture(DomainTestFixtureGen(self._vnc_lib, auto_prop_val=True))
    def test_show_command_crud(self):
        self.useFixture(ShowCommandTestFixtureGen(self._vnc_lib, auto_prop_val=True))
        self._vnc_lib.show_commands_list()
        objects = self._vnc_lib.show_commands_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.show_commands_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.show_command_read,id='no_op')
        
    def test_show_command_create_fail(self):
        def _with_fixture():
            parent_fix=None
            self.useFixture(ShowCommandTestFixtureGen(self._vnc_lib, show_command_name=self.rw.random_word(),auto_prop_val=True))
        flexmock(self.get_api_server()).should_receive('_post_common').replace_with(lambda x,y,z: (False, (501, 'show_command create Error')))
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call('_post_common')
        resource_class = flexmock(ShowCommandServerGen).should_receive('http_post_collection').replace_with(lambda x,y,z: (False, (501, 'Collection Error')))
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called,0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_show_command_read_fail(self):
       def _with_fixture():
           self.useFixture(ShowCommandTestFixtureGen(self._vnc_lib, show_command_name=self.rw.random_word(),auto_prop_val=True))
       flexmock(self.get_api_server()).should_receive('_get_common').replace_with(lambda x,y: (False, (501, 'account read Error')))
       self.assertRaises(HttpError, _with_fixture)

    def test_fsd_ui_layout_crud(self):
        self.useFixture(FsdUiLayoutTestFixtureGen(self._vnc_lib, auto_prop_val=True))
        self._vnc_lib.fsd_ui_layouts_list()
        objects = self._vnc_lib.fsd_ui_layouts_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.fsd_ui_layouts_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.fsd_ui_layout_read,id='no_op')
        
    def test_fsd_ui_layout_create_fail(self):
        def _with_fixture():
            parent_fix=None
            self.useFixture(FsdUiLayoutTestFixtureGen(self._vnc_lib, fsd_ui_layout_name=self.rw.random_word(),auto_prop_val=True))
        flexmock(self.get_api_server()).should_receive('_post_common').replace_with(lambda x,y,z: (False, (501, 'fsd_ui_layout create Error')))
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call('_post_common')
        resource_class = flexmock(FsdUiLayoutServerGen).should_receive('http_post_collection').replace_with(lambda x,y,z: (False, (501, 'Collection Error')))
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called,0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_fsd_ui_layout_read_fail(self):
       def _with_fixture():
           self.useFixture(FsdUiLayoutTestFixtureGen(self._vnc_lib, fsd_ui_layout_name=self.rw.random_word(),auto_prop_val=True))
       flexmock(self.get_api_server()).should_receive('_get_common').replace_with(lambda x,y: (False, (501, 'account read Error')))
       self.assertRaises(HttpError, _with_fixture)

    def test_vnf_package_crud(self):
        self.useFixture(VnfPackageTestFixtureGen(self._vnc_lib, auto_prop_val=True))
        self._vnc_lib.vnf_packages_list()
        objects = self._vnc_lib.vnf_packages_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.vnf_packages_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.vnf_package_read,id='no_op')
        
    def test_vnf_package_create_fail(self):
        def _with_fixture():
            parent_fix=None
            self.useFixture(VnfPackageTestFixtureGen(self._vnc_lib, vnf_package_name=self.rw.random_word(),auto_prop_val=True))
        flexmock(self.get_api_server()).should_receive('_post_common').replace_with(lambda x,y,z: (False, (501, 'vnf_package create Error')))
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call('_post_common')
        resource_class = flexmock(VnfPackageServerGen).should_receive('http_post_collection').replace_with(lambda x,y,z: (False, (501, 'Collection Error')))
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called,0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_vnf_package_read_fail(self):
       def _with_fixture():
           self.useFixture(VnfPackageTestFixtureGen(self._vnc_lib, vnf_package_name=self.rw.random_word(),auto_prop_val=True))
       flexmock(self.get_api_server()).should_receive('_get_common').replace_with(lambda x,y: (False, (501, 'account read Error')))
       self.assertRaises(HttpError, _with_fixture)

    def test_global_system_config_crud(self):
        self.useFixture(GlobalSystemConfigTestFixtureGen(self._vnc_lib, auto_prop_val=True))
    def test_operation_command_crud(self):
        self.useFixture(OperationCommandTestFixtureGen(self._vnc_lib, auto_prop_val=True))
        self._vnc_lib.operation_commands_list()
        objects = self._vnc_lib.operation_commands_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.operation_commands_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.operation_command_read,id='no_op')
        
    def test_operation_command_create_fail(self):
        def _with_fixture():
            parent_fix=None
            self.useFixture(OperationCommandTestFixtureGen(self._vnc_lib, operation_command_name=self.rw.random_word(),auto_prop_val=True))
        flexmock(self.get_api_server()).should_receive('_post_common').replace_with(lambda x,y,z: (False, (501, 'operation_command create Error')))
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call('_post_common')
        resource_class = flexmock(OperationCommandServerGen).should_receive('http_post_collection').replace_with(lambda x,y,z: (False, (501, 'Collection Error')))
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called,0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_operation_command_read_fail(self):
       def _with_fixture():
           self.useFixture(OperationCommandTestFixtureGen(self._vnc_lib, operation_command_name=self.rw.random_word(),auto_prop_val=True))
       flexmock(self.get_api_server()).should_receive('_get_common').replace_with(lambda x,y: (False, (501, 'account read Error')))
       self.assertRaises(HttpError, _with_fixture)

    def test_nsd_package_crud(self):
        self.useFixture(NsdPackageTestFixtureGen(self._vnc_lib, auto_prop_val=True))
        self._vnc_lib.nsd_packages_list()
        objects = self._vnc_lib.nsd_packages_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.nsd_packages_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.nsd_package_read,id='no_op')
        
    def test_nsd_package_create_fail(self):
        def _with_fixture():
            parent_fix=None
            self.useFixture(NsdPackageTestFixtureGen(self._vnc_lib, nsd_package_name=self.rw.random_word(),auto_prop_val=True))
        flexmock(self.get_api_server()).should_receive('_post_common').replace_with(lambda x,y,z: (False, (501, 'nsd_package create Error')))
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call('_post_common')
        resource_class = flexmock(NsdPackageServerGen).should_receive('http_post_collection').replace_with(lambda x,y,z: (False, (501, 'Collection Error')))
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called,0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_nsd_package_read_fail(self):
       def _with_fixture():
           self.useFixture(NsdPackageTestFixtureGen(self._vnc_lib, nsd_package_name=self.rw.random_word(),auto_prop_val=True))
       flexmock(self.get_api_server()).should_receive('_get_common').replace_with(lambda x,y: (False, (501, 'account read Error')))
       self.assertRaises(HttpError, _with_fixture)

    def test_namespace_crud(self):
        parent_fix=self.useFixture(DomainTestFixtureGen(self._vnc_lib, domain_name=self.rw.random_word(), auto_prop_val=True))
        self.useFixture(NamespaceTestFixtureGen(self._vnc_lib, auto_prop_val=True, parent_fixt=parent_fix))
        self._vnc_lib.namespaces_list()
        objects = self._vnc_lib.namespaces_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.namespaces_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.namespace_read,id='no_op')
        
    def test_namespace_create_fail(self):
        def _with_fixture():
            parent_fix=None
            parent_fix=self.useFixture(DomainTestFixtureGen(self._vnc_lib, domain_name=self.rw.random_word(), auto_prop_val=True))
            self.useFixture(NamespaceTestFixtureGen(self._vnc_lib, namespace_name=self.rw.random_word(),auto_prop_val=True, parent_fixt=parent_fix))
        flexmock(self.get_api_server()).should_receive('_post_common').replace_with(lambda x,y,z: (False, (501, 'namespace create Error')))
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call('_post_common')
        resource_class = flexmock(NamespaceServerGen).should_receive('http_post_collection').replace_with(lambda x,y,z: (False, (501, 'Collection Error')))
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called,0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_namespace_read_fail(self):
       def _with_fixture():
           parent_fix=self.useFixture(DomainTestFixtureGen(self._vnc_lib, domain_name=self.rw.random_word(), auto_prop_val=True))
           self.useFixture(NamespaceTestFixtureGen(self._vnc_lib, namespace_name=self.rw.random_word(),auto_prop_val=True, parent_fixt=parent_fix))
       flexmock(self.get_api_server()).should_receive('_get_common').replace_with(lambda x,y: (False, (501, 'account read Error')))
       self.assertRaises(HttpError, _with_fixture)

    def test_functional_service_request_crud(self):
        self.useFixture(FunctionalServiceRequestTestFixtureGen(self._vnc_lib, auto_prop_val=True))
        self._vnc_lib.functional_service_requests_list()
        objects = self._vnc_lib.functional_service_requests_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.functional_service_requests_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.functional_service_request_read,id='no_op')
        
    def test_functional_service_request_create_fail(self):
        def _with_fixture():
            parent_fix=None
            self.useFixture(FunctionalServiceRequestTestFixtureGen(self._vnc_lib, functional_service_request_name=self.rw.random_word(),auto_prop_val=True))
        flexmock(self.get_api_server()).should_receive('_post_common').replace_with(lambda x,y,z: (False, (501, 'functional_service_request create Error')))
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call('_post_common')
        resource_class = flexmock(FunctionalServiceRequestServerGen).should_receive('http_post_collection').replace_with(lambda x,y,z: (False, (501, 'Collection Error')))
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called,0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_functional_service_request_read_fail(self):
       def _with_fixture():
           self.useFixture(FunctionalServiceRequestTestFixtureGen(self._vnc_lib, functional_service_request_name=self.rw.random_word(),auto_prop_val=True))
       flexmock(self.get_api_server()).should_receive('_get_common').replace_with(lambda x,y: (False, (501, 'account read Error')))
       self.assertRaises(HttpError, _with_fixture)

    def test_network_function_crud(self):
        self.useFixture(NetworkFunctionTestFixtureGen(self._vnc_lib, auto_prop_val=True))
        self._vnc_lib.network_functions_list()
        objects = self._vnc_lib.network_functions_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.network_functions_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.network_function_read,id='no_op')
        
    def test_network_function_create_fail(self):
        def _with_fixture():
            parent_fix=None
            self.useFixture(NetworkFunctionTestFixtureGen(self._vnc_lib, network_function_name=self.rw.random_word(),auto_prop_val=True))
        flexmock(self.get_api_server()).should_receive('_post_common').replace_with(lambda x,y,z: (False, (501, 'network_function create Error')))
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call('_post_common')
        resource_class = flexmock(NetworkFunctionServerGen).should_receive('http_post_collection').replace_with(lambda x,y,z: (False, (501, 'Collection Error')))
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called,0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_network_function_read_fail(self):
       def _with_fixture():
           self.useFixture(NetworkFunctionTestFixtureGen(self._vnc_lib, network_function_name=self.rw.random_word(),auto_prop_val=True))
       flexmock(self.get_api_server()).should_receive('_get_common').replace_with(lambda x,y: (False, (501, 'account read Error')))
       self.assertRaises(HttpError, _with_fixture)

    def test_access_control_list_crud(self):
        self.useFixture(AccessControlListTestFixtureGen(self._vnc_lib, auto_prop_val=True))
        self._vnc_lib.access_control_lists_list()
        objects = self._vnc_lib.access_control_lists_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.access_control_lists_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.access_control_list_read,id='no_op')
        
    def test_access_control_list_create_fail(self):
        def _with_fixture():
            parent_fix=None
            self.useFixture(AccessControlListTestFixtureGen(self._vnc_lib, access_control_list_name=self.rw.random_word(),auto_prop_val=True))
        flexmock(self.get_api_server()).should_receive('_post_common').replace_with(lambda x,y,z: (False, (501, 'access_control_list create Error')))
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call('_post_common')
        resource_class = flexmock(AccessControlListServerGen).should_receive('http_post_collection').replace_with(lambda x,y,z: (False, (501, 'Collection Error')))
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called,0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_access_control_list_read_fail(self):
       def _with_fixture():
           self.useFixture(AccessControlListTestFixtureGen(self._vnc_lib, access_control_list_name=self.rw.random_word(),auto_prop_val=True))
       flexmock(self.get_api_server()).should_receive('_get_common').replace_with(lambda x,y: (False, (501, 'account read Error')))
       self.assertRaises(HttpError, _with_fixture)

    def test_resource_service_request_crud(self):
        self.useFixture(ResourceServiceRequestTestFixtureGen(self._vnc_lib, auto_prop_val=True))
        self._vnc_lib.resource_service_requests_list()
        objects = self._vnc_lib.resource_service_requests_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.resource_service_requests_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.resource_service_request_read,id='no_op')
        
    def test_resource_service_request_create_fail(self):
        def _with_fixture():
            parent_fix=None
            self.useFixture(ResourceServiceRequestTestFixtureGen(self._vnc_lib, resource_service_request_name=self.rw.random_word(),auto_prop_val=True))
        flexmock(self.get_api_server()).should_receive('_post_common').replace_with(lambda x,y,z: (False, (501, 'resource_service_request create Error')))
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call('_post_common')
        resource_class = flexmock(ResourceServiceRequestServerGen).should_receive('http_post_collection').replace_with(lambda x,y,z: (False, (501, 'Collection Error')))
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called,0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_resource_service_request_read_fail(self):
       def _with_fixture():
           self.useFixture(ResourceServiceRequestTestFixtureGen(self._vnc_lib, resource_service_request_name=self.rw.random_word(),auto_prop_val=True))
       flexmock(self.get_api_server()).should_receive('_get_common').replace_with(lambda x,y: (False, (501, 'account read Error')))
       self.assertRaises(HttpError, _with_fixture)

    def test_vld_crud(self):
        self.useFixture(VldTestFixtureGen(self._vnc_lib, auto_prop_val=True))
        self._vnc_lib.vlds_list()
        objects = self._vnc_lib.vlds_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.vlds_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.vld_read,id='no_op')
        
    def test_vld_create_fail(self):
        def _with_fixture():
            parent_fix=None
            self.useFixture(VldTestFixtureGen(self._vnc_lib, vld_name=self.rw.random_word(),auto_prop_val=True))
        flexmock(self.get_api_server()).should_receive('_post_common').replace_with(lambda x,y,z: (False, (501, 'vld create Error')))
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call('_post_common')
        resource_class = flexmock(VldServerGen).should_receive('http_post_collection').replace_with(lambda x,y,z: (False, (501, 'Collection Error')))
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called,0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_vld_read_fail(self):
       def _with_fixture():
           self.useFixture(VldTestFixtureGen(self._vnc_lib, vld_name=self.rw.random_word(),auto_prop_val=True))
       flexmock(self.get_api_server()).should_receive('_get_common').replace_with(lambda x,y: (False, (501, 'account read Error')))
       self.assertRaises(HttpError, _with_fixture)

    def test_nsd_ui_layout_crud(self):
        self.useFixture(NsdUiLayoutTestFixtureGen(self._vnc_lib, auto_prop_val=True))
        self._vnc_lib.nsd_ui_layouts_list()
        objects = self._vnc_lib.nsd_ui_layouts_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.nsd_ui_layouts_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.nsd_ui_layout_read,id='no_op')
        
    def test_nsd_ui_layout_create_fail(self):
        def _with_fixture():
            parent_fix=None
            self.useFixture(NsdUiLayoutTestFixtureGen(self._vnc_lib, nsd_ui_layout_name=self.rw.random_word(),auto_prop_val=True))
        flexmock(self.get_api_server()).should_receive('_post_common').replace_with(lambda x,y,z: (False, (501, 'nsd_ui_layout create Error')))
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call('_post_common')
        resource_class = flexmock(NsdUiLayoutServerGen).should_receive('http_post_collection').replace_with(lambda x,y,z: (False, (501, 'Collection Error')))
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called,0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_nsd_ui_layout_read_fail(self):
       def _with_fixture():
           self.useFixture(NsdUiLayoutTestFixtureGen(self._vnc_lib, nsd_ui_layout_name=self.rw.random_word(),auto_prop_val=True))
       flexmock(self.get_api_server()).should_receive('_get_common').replace_with(lambda x,y: (False, (501, 'account read Error')))
       self.assertRaises(HttpError, _with_fixture)

    def test_functional_service_design_crud(self):
        self.useFixture(FunctionalServiceDesignTestFixtureGen(self._vnc_lib, auto_prop_val=True))
        self._vnc_lib.functional_service_designs_list()
        objects = self._vnc_lib.functional_service_designs_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.functional_service_designs_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.functional_service_design_read,id='no_op')
        
    def test_functional_service_design_create_fail(self):
        def _with_fixture():
            parent_fix=None
            self.useFixture(FunctionalServiceDesignTestFixtureGen(self._vnc_lib, functional_service_design_name=self.rw.random_word(),auto_prop_val=True))
        flexmock(self.get_api_server()).should_receive('_post_common').replace_with(lambda x,y,z: (False, (501, 'functional_service_design create Error')))
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call('_post_common')
        resource_class = flexmock(FunctionalServiceDesignServerGen).should_receive('http_post_collection').replace_with(lambda x,y,z: (False, (501, 'Collection Error')))
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called,0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_functional_service_design_read_fail(self):
       def _with_fixture():
           self.useFixture(FunctionalServiceDesignTestFixtureGen(self._vnc_lib, functional_service_design_name=self.rw.random_word(),auto_prop_val=True))
       flexmock(self.get_api_server()).should_receive('_get_common').replace_with(lambda x,y: (False, (501, 'account read Error')))
       self.assertRaises(HttpError, _with_fixture)

    def test_config_template_crud(self):
        self.useFixture(ConfigTemplateTestFixtureGen(self._vnc_lib, auto_prop_val=True))
        self._vnc_lib.config_templates_list()
        objects = self._vnc_lib.config_templates_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.config_templates_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.config_template_read,id='no_op')
        
    def test_config_template_create_fail(self):
        def _with_fixture():
            parent_fix=None
            self.useFixture(ConfigTemplateTestFixtureGen(self._vnc_lib, config_template_name=self.rw.random_word(),auto_prop_val=True))
        flexmock(self.get_api_server()).should_receive('_post_common').replace_with(lambda x,y,z: (False, (501, 'config_template create Error')))
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call('_post_common')
        resource_class = flexmock(ConfigTemplateServerGen).should_receive('http_post_collection').replace_with(lambda x,y,z: (False, (501, 'Collection Error')))
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called,0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_config_template_read_fail(self):
       def _with_fixture():
           self.useFixture(ConfigTemplateTestFixtureGen(self._vnc_lib, config_template_name=self.rw.random_word(),auto_prop_val=True))
       flexmock(self.get_api_server()).should_receive('_get_common').replace_with(lambda x,y: (False, (501, 'account read Error')))
       self.assertRaises(HttpError, _with_fixture)

    def test_api_access_list_crud(self):
        parent_fix=self.useFixture(DomainTestFixtureGen(self._vnc_lib, domain_name=self.rw.random_word(), auto_prop_val=True))
        self.useFixture(ApiAccessListTestFixtureGen(self._vnc_lib, auto_prop_val=True, parent_fixt=parent_fix))
        self._vnc_lib.api_access_lists_list()
        objects = self._vnc_lib.api_access_lists_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.api_access_lists_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.api_access_list_read,id='no_op')
        
    def test_api_access_list_create_fail(self):
        def _with_fixture():
            parent_fix=None
            parent_fix=self.useFixture(DomainTestFixtureGen(self._vnc_lib, domain_name=self.rw.random_word(), auto_prop_val=True))
            self.useFixture(ApiAccessListTestFixtureGen(self._vnc_lib, api_access_list_name=self.rw.random_word(),auto_prop_val=True, parent_fixt=parent_fix))
        flexmock(self.get_api_server()).should_receive('_post_common').replace_with(lambda x,y,z: (False, (501, 'api_access_list create Error')))
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call('_post_common')
        resource_class = flexmock(ApiAccessListServerGen).should_receive('http_post_collection').replace_with(lambda x,y,z: (False, (501, 'Collection Error')))
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called,0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_api_access_list_read_fail(self):
       def _with_fixture():
           parent_fix=self.useFixture(DomainTestFixtureGen(self._vnc_lib, domain_name=self.rw.random_word(), auto_prop_val=True))
           self.useFixture(ApiAccessListTestFixtureGen(self._vnc_lib, api_access_list_name=self.rw.random_word(),auto_prop_val=True, parent_fixt=parent_fix))
       flexmock(self.get_api_server()).should_receive('_get_common').replace_with(lambda x,y: (False, (501, 'account read Error')))
       self.assertRaises(HttpError, _with_fixture)

    def test_project_crud(self):
        parent_fix=self.useFixture(DomainTestFixtureGen(self._vnc_lib, domain_name=self.rw.random_word(), auto_prop_val=True))
        self.useFixture(ProjectTestFixtureGen(self._vnc_lib, auto_prop_val=True, parent_fixt=parent_fix))
        self._vnc_lib.projects_list()
        objects = self._vnc_lib.projects_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.projects_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.project_read,id='no_op')
        
    def test_project_create_fail(self):
        def _with_fixture():
            parent_fix=None
            parent_fix=self.useFixture(DomainTestFixtureGen(self._vnc_lib, domain_name=self.rw.random_word(), auto_prop_val=True))
            self.useFixture(ProjectTestFixtureGen(self._vnc_lib, project_name=self.rw.random_word(),auto_prop_val=True, parent_fixt=parent_fix))
        flexmock(self.get_api_server()).should_receive('_post_common').replace_with(lambda x,y,z: (False, (501, 'project create Error')))
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call('_post_common')
        resource_class = flexmock(ProjectServerGen).should_receive('http_post_collection').replace_with(lambda x,y,z: (False, (501, 'Collection Error')))
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called,0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_project_read_fail(self):
       def _with_fixture():
           parent_fix=self.useFixture(DomainTestFixtureGen(self._vnc_lib, domain_name=self.rw.random_word(), auto_prop_val=True))
           self.useFixture(ProjectTestFixtureGen(self._vnc_lib, project_name=self.rw.random_word(),auto_prop_val=True, parent_fixt=parent_fix))
       flexmock(self.get_api_server()).should_receive('_get_common').replace_with(lambda x,y: (False, (501, 'account read Error')))
       self.assertRaises(HttpError, _with_fixture)