예제 #1
0
 def _test(c):
     loc = 0
     for _ in range(20):
         if loc == 0:
             self.TSF_find_board_index(c)
             loc == 1
         elif loc == 1:
             i = random.int(1, 10)
             if i < 3:
                 nav = c.find_element_by_id('nav-main')
                 nav.click()
                 loc == 0
             elif i < 7:
                 i = random.int(1, 10)
                 if i < 6:
                     self.TSF_navigate_board(c)
                 else:
                     self.TSF_navigate_banner(c)
             else:
                 self.TSF_navigate_thread(c)
                 loc == 2
         elif loc == 2:
             i = random.int(1, 10)
             if i < 6:
                 nav = c.find_element_by_id('nav-main')
                 nav.click()
                 loc == 0
             else:
                 i = random.int(1, 10)
                 if i < 6:
                     self.TSF_navigate_board(c)
                 else:
                     self.TSF_navigate_banner(c)
                 loc == 1
예제 #2
0
 def mutateNewComponent(self):
   splitEdgeIndex = random.int(0,self.nedged-1)
   while not edges[splitEdgeIndex].value.activated:
     splitEdgeIndex = random.int(0,self.nedged-1)
   edged[splitEdgeIndex].value.deactivate()
   isbefore = randomChance(0.5)
   newNodeIndex = self.addNode()
   if isBefore:
     addEdge(edges[splitEdgeIndex].start,newNodeIndex, edges[splitEdgeIndex].value)
     self.addEdge(edges[splitEdgeIndex].end, newNodeIndex, randomElectricGene())
   else:
     addEdge(edges[splitEdgeIndex].start,newNodeIndex, randomElectricGene())
     self.addEdge(edges[splitEdgeIndex].end, newNodeIndex, [splitEdgeIndex].value)
예제 #3
0
def generate_sentence(model, prob=False):
	sentence_length = random.int(1, 10) # longest text
	if prob == True:
        # Make it based on highest probability
		copy_model = deepcopy(model)
		starting_bigram = max(copy_model)[0]
		copy_model.pop(starting_bigram)
		sentence = starting_bigram[0]
		for i in range(sentence_length):
			possible_bigrams = find_similar_bigrams(copy_model, starting_bigram[0])
			next_bigram = max(possible_bigrams)
			starting_bigram = next_bigram
			copy_model.pop(next_bigram)
			sentence += " " + next_bigram[1]
		return sentence
	else:
        # This will be random, will make the function long
		starting_word = random.choice(list(model.keys()))[0]
		sentence = starting_word
		for i in range(sentence_length):
			possible_bigrams = find_similar_bigrams(model, starting_word)
			next_word = random.choice(possible_bigrams)[1]
			sentence += " " + next_word[1]
			starting_word = next_word
		return sentence
예제 #4
0
    def initShuffle(self):

        startState = State(self.tour, len(self.tour))
        optimalTour = None
        initBssfNode = TSPNode(startState)
        initBssfNode.addVertex(startState.getCities()[0])

        result = self.recursiveFindFirstOptimal(initBssfNode, startState)
        if result[0] == True:
            optimalTour = result[1]

        else:
            print("NO route exists. mesa sad man")

        self.tour = optimalTour.path
        return

        initCities = []
        random.shuffle(self.tour)
        citesLeft = copy.deepcopy(self.tour)
        initCities.append(citesLeft.pop())
        while len(citesLeft) > 0:
            random.shuffle(citesLeft)
            index = 0
            while True:
                if len(citesLeft) > 0 or initCities[-1].costTo(citesLeft[index]) != math.inf:
                    if initCities[-1].costTo(citesLeft[index]) != math.inf:
                        initCities.append(citesLeft.pop(index))
                        break
                    else:
                        index += 1
                else:
                    citesLeft.append(initCities.pop(random.int(0,len(initCities)-1)))
                    break
예제 #5
0
def create_literal(label, dt, cardinality):
    """
    Function: create_literal
    ---------------------------------
    Input:

    Output:
    """

    # TODO: adequately adjust the ranges for int, float, dateTime

    # get only the actual type
    type = dt.split('#')[1]
    if "string" in type:
        val = label + "_" + str(cardinality)
    elif "integer" in type:
        val = random.int(-13, 13)
    elif "nonNegativeInteger" in type:
        val = random.randint(0)
        # alternative: randint(a, b)
    elif "positiveInteger" in type:
        val = random.randint(1)
        # alternative: randint(a, b)
    elif "float" in type:
        val = random.uniform(-13, 13)
    elif "dateTime" in type:
        val = create_random_datetime('1990/01/01 00:00', datetime.datetime.utcnow(), '%Y/%m/%d %H:%M', random.random())

    literal = rdflib.Literal(val, datatype=rdflib.URIRef(dt))

    return literal
예제 #6
0
def convert(snippet, phrase):
    class_names = [
        w.capitalize() for w in random.sample(WORDS, snippet.count("%%%"))
    ]
    other_names = random.sample(WORDS, snippet.count("***"))
    results = []
    param_names = []

    for i in range(0, snippet.count("@@@")):
        param_count = random.int(1, 3)
        param_names.append(', '.join(random.sample(WORDS, param_count)))

    for sentence in snippet, phrase:
        result = sentence[:]

        for word in class_names:
            result = result.replace("%%%", word, 1)

        for word in other_names:
            result = result.replace("***", word, 1)

        for word in param_names:
            result = result.replace("@@@", word, 1)

        results.append(result)

    return results
def apply_occlusion_set(net, X, y, conn_name="", columnwise=True):
    import random
    import time
    time.sleep(random.int(1, 10000) / 1000.0)  # For parallelization
    x_len = X.shape[2]
    y_len = X.shape[3]
    dir_path = os.path.join('occlusion_preds')
    if conn_name != "":
        dir_path = os.path.join(dir_path, conn_name)
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)
    or_preds_filename = os.path.join(dir_path, 'original_preds.txt')
    or_y_filename = os.path.join(dir_path, 'original_y.txt')
    if not os.path.isfile(or_y_filename) or \
        not os.path.isfile(or_preds_filename):
        base_pred, base_preds = binary_predict(net, X, y, ret_preds=True)
        base_preds = np.array(base_preds)
        np.savetxt(or_preds_filename, base_preds)
        np.savetxt(or_y_filename, np.array(y))
    base_preds = np.loadtxt(or_preds_filename)
    y = np.loadtxt(or_y_filename)
    if columnwise:
        for i in range(x_len):
            filename = os.path.join(dir_path, 'oc_pred_%d.txt' % i)
            filename_arr = os.path.join(dir_path, 'oc_arr_%d.txt' % i)
            if not os.path.isfile(filename) or not os.path.isfile(
                    filename_arr):
                open(filename, 'a').close()  # For parallelization
                X_o, ones = get_one_occlusion_set(X, i)
                pred, preds = binary_predict(net, X_o, y, ret_preds=True)
                try:
                    np.savetxt(filename, np.array(preds))
                    np.savetxt(filename_arr, ones)
                except:
                    if os.path.isfile(filename):
                        os.remove(filename)
                    if os.path.isfile(filename_arr):
                        os.remove(filename_arr)
                    continue
    else:  # Occludes one edge at a time
        for i in range(x_len):
            for j in range(i + 1, x_len):
                filename = os.path.join(dir_path, 'oc_pred_%d_%d.txt' % (i, j))
                filename_arr = os.path.join(dir_path,
                                            'oc_arr_%d_%d.txt' % (i, j))
                if not os.path.isfile(filename) or not \
                    os.path.isfile(filename_arr):
                    open(filename, 'a').close()  # For parallelization
                    X_o, ones = get_one_occlusion_set(X, i, j)
                    pred, preds = binary_predict(net, X_o, y, ret_preds=True)
                    try:
                        np.savetxt(filename, np.array(preds))
                        np.savetxt(filename_arr, ones)
                    except:
                        if os.path.isfile(filename):
                            os.remove(filename)
                        if os.path.isfile(filename_arr):
                            os.remove(filename_arr)
                        continue
    def _scroll(self, amount):
        # we should find max boundaries of the screen
        # and randomly select the starting, ending point

        init_x = int(self.driver.DISPLAYSIZE["width"] * random.gauss(0.5, 0.1))
        init_y = random.int(0, self.driver.DISPLAYSIZE["height"] - amount)

        self.driver.swipe(init_x, init_y, init_x, init_y + amount)
def lottery(n):
    import random
    k=0
    y=[]
    times=int(n)
    if k<times:
        number=random.int(1,49)
        y.append(number)
        k+=1
        return y
    else:
        print(y)
def fromVegetarian(inputRecipe):
	##Returns a new recipe that is a vegetarian version of the input recipe
	ingredient_map = dict()
	fish_map = dict()
	meatList = []
	method_map = dict()
	newRecipe = inputRecipe
	newIngredients = []
	switchFlag = 0
	f = open('Team5/VegetarianIngredientMap.txt', 'r')
	for line in f:
		line = line.split('\n')[0]
		map = line.split(':')
		ingredient_map[map[1]] = map[0]
		
	ingredient_map["fishless fillet"] = "salmon"
		
		
	f = open('Team5/MeatList.txt', 'r')
	for line in f:
		line = line.split('\n')[0]
		soyMeat = "soy " + line
		ingredient_map[soyMeat] = line
		
	#First see if we've hardcoded a replacement
	for ingredient in inputRecipe.ingredients:
		tmpName = " ".join(s.lower() for s in ingredient.name)
		newIngredient = ingredient
		for key in ingredient_map.keys():
			if key in tmpName: 
				switchFlag = 1
				newName = ingredient_map[key].split(" ")
				if ingredient.measurement == "unit":
					newIngredient = Ingredient(newName, ingredient.quantity*4, "ounce")
				else:	
					newIngredient = Ingredient(newName, ingredient.quantity, ingredient.measurement)
		newIngredients.append(newIngredient)
		
	#If we didn't change anything, just add bacon
	#TODO: Proportion this properly
	if (switchFlag == 0):
		amount = random.int(500, 1000)
		amount = amount/1000.
		newIngredient = Ingredient("bacon", amount, "pound")	
		
		newIngredients.append(newIngredient)
	newRecipe.ingredients = newIngredients
	
	
	return newRecipe
예제 #11
0
    def random_walk(self, num_words=11):
        
        # length = len(self.states)
        # rand = random.randint(0, length)

        counter = 0
        last_word = None

         
        if last_word not None:
            pickings = self.states[last_word] # dictionary of words to pick from based on last_word's hist
            total_wc = 0
            for value in pickings.values():
                total_wc += value
            rand = random.int(0, 100)
예제 #12
0
	def generate_riboswitch(effector):
		index_a = effector.find('a')
		temp = effector[::-1].find('a')

		if temp < index_a:
			index_a = temp
			effector = effector[::-1]

		effector_in_stem = effector[0:index_a]
		remaining_effector = effector[index_a:]

		stem_strand = generate_random_seq(random.randint(10,20), True) + effector_in_stem
		revcomp_stem_strand = reverse_complement(stem_strand)
		loop = generate_random_loop(random.int(4, 6))

		revcomp_remaining_effector = reverse_complement(remaining_effector)

		riboswitch_sequence = revcomp_remaining_effector + revcomp_stem_strand + loop + stem_strand

		return riboswitch_sequence
예제 #13
0
def randemoji(number):
    try:
        emojis = {
            "1": "XwX",
            "2": "OvO",
            "3": "OwO",
            "4": "UwU",
            "5": ">:3",
            "6": "-w-",
            "7": "ÙwÚ",
            "8": "CwC"
        }
        emoji = emojis[str(number)]
        if number == random:
            number = random.int(1, 8)
            emoji = emojis[str(number)]
        return emoji
    except KeyError:
        error = f"Number '{number}' is not a valid option, please pick from 1-8"
        raise NotAValidNumber(error)
예제 #14
0
def flip_coin(call, bet):
    #Has to bet money
    if bet <= 0:
        print("They say you need money to make money! Make sure your bet is over 0.")
        return 0
    
    #Intro to game -> Prints player's call
    print("Let's flip a coin! You called " + call)
    result = random.int(1,2)

    #Prints flip result -> Heads=1 Tails=2
    if result == 1:
        print("Heads!")
    else: print("Tails!")

    #Prints bet result
    if (call == "Heads" and result == 1) or (call == "Tails" and result == 2):
        print("You've won " + str(bet) + " dollars!")
        return bet
    else:
        print("You've lost " + str(bet)+" dollars!")
        return -bet
    def random_walk(self, num_words=11):
        
        # length = len(self.states)
        # rand = random.randint(0, length)

        counter = 0
        last_word = None
        word = None
         
        if last_word not None:
            pickings = self.states[last_word] # dictionary of words to pick from based on last_word's hist
            total_wc = 0 # number of words in dictionary for a word
            dart = random.int(0, 100)
            counter = 0

            for value in pickings.values(): # calculates total word count
                total_wc += value
            
            for key,value in pickings.items():
                while counter < dart
                    counter += value / total_wc
                    last_word = key
예제 #16
0
    def storage():

            return random.int(1000,10000)
예제 #17
0
파일: movable.py 프로젝트: kandluis/sap2000
 def climb_off(self, loc):
   '''
   Decides whether or not the robot should climb off the structure
   '''
   return helpers.compare(loc[2],0) and random.int(0,1) == 1
예제 #18
0
def battle_damage():
    damage = random.int(1, 12)
    return damage
예제 #19
0
# Adivina el numero: Ingrese una cantidad de intentos el computador debe seleccionar un numero enre 1 y 100 aleatorio la ir ingresando numeros el computador debe indicarle si el numero que penso es menor o mayor.
import random

int = raw_imput("intentos > ")
n = random.int(0, 100)
예제 #20
0
def generate_l_prime(start=random_start, end=random_end):
    number = random.int(random_start, random_end)

    while not is_the_num_prime(number):
        number = random.randint(random_start, random_end)
    return number
예제 #21
0
 def spawn(self, number):
     for i in range(number):
         newBall = Ball(self.screen, random.randint(0, self.screen.get_width()), random.randint(0, self.screen.get_height()), 5, (random.int(0, 255), (random.int(0, 255), (random.int(0, 255)), 15)))
예제 #22
0
 def climb_off(self, loc):
     '''
 Decides whether or not the robot should climb off the structure
 '''
     return helpers.compare(loc[2], 0) and random.int(0, 1) == 1
예제 #23
0
def fake_port():
    return random.int(0, 65535)
예제 #24
0
def get_random_words(num):
    '''
    This function selects a
    random word from the txt file
    '''
    random_word = random.int(0, len(num))
예제 #25
0
# 判断文件夹是否存在
res = os.path.isdir(TEST_PATH})
# 创建文件夹
os.mkdir(DIR_PATH)
# 删除文件夹
os.rmdir(DIR_PATH)
# 删除文件
os.remove(file_name)
# 获取指定文件夹下面的所有文件夹名和文件名
os.listdir(DIR_PATH)


"""random模块"""
import random
# 随机从1-9中返回一个整数
res = random.int(1,9)
# 返回0-1之间的浮点数
res = random.random()
# shuffle(洗牌)有索引的可变可迭代对象
my_list = [1, 2, 3, 3, 7]
random.shuffle(my_list)
print(my_list)
# choice(随机选择)有索引的可迭代对象
my_str =  'yyh NO.1'
random.choice(my_str)
# 例题:生成随机验证码
def random_code(n):
    char_range = [chr(i) for i in range(65, 91)] + \
                 [chr(i) for i in range(97, 123)] + \
                 [str(i) for i in range(10)]
    result = ''
예제 #26
0
파일: servebase.py 프로젝트: AJOmer/Python
def numset():
    session['answer'] = random.int(1, 100)
예제 #27
0
def marc(isbnS, baseUrl='http://opac.nlc.cn/F', **kw):
    # source = open(data,'r')
    # okw = dict(func='full-set-set_body',find_code='ISB',request='',set_entry='000001',format='001',local_base='NLC01')
    okw = collections.OrderedDict()
    okw['find_code'] = 'ISB'
    okw['request'] = ''
    okw['local_base'] = 'NLC01'
    okw['func'] = 'find_b'
    arg = ''
    for k in kw:
        try:
            tti = okw[k]
        except KeyError:
            logger.warn(
                'File:isbnTt\nLine 29: tti = okw[k]\nFunc: isbn(isbnS,**kw)\n\
            KeyError:{} is not a property request arguments'.format(k))
            choice = input(
                'Please input "Y" to Accept or any other key to Jump :')
            if choice == 'Y':
                okw[k] = kw[k]
    index = urlopen(baseUrl)
    indexObj = BeautifulSoup(index, 'html.parser')
    iterObj = indexObj.find('form')
    iterUrlTt = iterObj.get('action')
    iterUrl = iterUrlTt[:-5] + '{:0>5}'.format(int(iterUrlTt[-5:]) + 1)
    isbnFailure = []
    global cursorE, mkconnE
    for isbn in isbnS:
        try:
            okw['request'] = isbn
            arg = '?'
            for k, v in okw.items():
                arg = arg + k + '=' + v + '&'
            arg = arg[:-1]
            logger.info(iterUrl + arg)
            iterHtml = urlopen(iterUrl + arg)
            iterObjI = BeautifulSoup(iterHtml, 'html.parser')
            # 获取下一次链接以及xhr参数URL
            iterObjII = iterObjI.find('form')
            iterUrl = iterObjII.get('action')
            # $('#hitnum')多结果分支
            objHit = iterObjI.find('div', id='hitnum')
            if objHit:
                xhrUrls = []
                objS = iterObjI.findAll('div', {'class': 'itemtitle'})
                numStr = objHit.get_text()
                num = int(numStr.split('"')[1].split(' ')[-1])
                preUrl = objS[0].a.get('href')[:-3] + '001'
                logger.info(preUrl)
                u0 = preUrl[:75]
                u1 = int(preUrl[75:80])
                u2 = preUrl[80:98] + '_body'
                u3 = preUrl[98:127]
                u4 = '&format=001'
                for i in range(num):
                    pUrl = (u0 + '{:0>5}' + u2 + u3 + '{:0>6}' + u4).format(
                        u1 + i * 9, i + 1)
                    logger.info(pUrl)
                    xhrUrls.append(pUrl)
                logger.info('==| Len of xhrUrls: {} |== '.format(len(xhrUrls)))
                for ix in xhrUrls:
                    try:
                        iterXhr = urlopen(ix)
                        marcObj = BeautifulSoup(iterXhr, 'html.parser')
                        marcEngine(marcObj)
                    except:
                        logger.exception('Failed: {} \n'.format(ix))
            else:
                # 查询结果唯一 的分支
                # 根据分析网页得到的action和xhr请求url的推算关系
                # 构造XHR参数
                iterUrlII = iterUrl[:-5] + '{:0>5}'.format(
                    int(iterUrl[-5:]) + 12)
                numberObj = iterObjI.find('input', id='set_number')
                if not numberObj:
                    continue
                set_number = numberObj.get('value')
                argFont = "?func=full-set-set_body&set_number="
                argEdn = "&set_entry=000001&format=001"
                iterUrlIII = iterUrlII + argFont + set_number + argEdn
                iterXhr = urlopen(iterUrlIII)
                marcObj = BeautifulSoup(iterXhr, 'html.parser')
                marcEngine(marcObj)
        except:
            logger.exception("Failed ISBN: {} ".format(isbn))
            isbnFailure.append(isbn)
            continue
        finally:
            time.sleep(random.int(10))
    cursorE.commit()
예제 #28
0
import random

a = random.int(1, 10)
print(a)
예제 #29
0
def roll_dice():
    if request.method == "GET":
        dice_1 = random.int(1, 6)
        dice_2 = random.int(1, 6)
        result = {'dice_1': dice_1, 'dice_2': dice_2}
        return jsonify(result)
예제 #30
0
def get_randomInt():
  # CHANGE ONLY THIS LINE BELOW
	random_number = random.int(1, 10)
	return random_number