def httpsGet(self, url): Log.d("GET " + url) url = self.completeUrl(url) headers = self.createHeaders() conn = HTTPSConnection(self.server) conn.request("GET", url, None, headers) self.lastResponse = self.parseResponse(conn.getresponse()) return self.lastResponse
def httpsGet(self, url): Log.d('GET ' + url) url = self.completeUrl(url) headers = self.createHeaders() conn = HTTPSConnection(self.server) conn.request('GET', url, None, headers) self.lastResponse = self.parseResponse(conn.getresponse()) return self.lastResponse
def post(self, url, param): Log.d("POST " + url) Log.d(" " + param) url = self.completeUrl(url) headers = self.createHeaders(param) conn = self.createConnection() conn.request("POST", url, param, headers) self.lastResponse = self.parseResponse(conn.getresponse()) return self.lastResponse
def post(self, url, param): Log.d('POST ' + url) Log.d(' ' + param) url = self.completeUrl(url) headers = self.createHeaders(param) conn = self.createConnection() conn.request('POST', url, param, headers) self.lastResponse = self.parseResponse(conn.getresponse()) return self.lastResponse
def handle_client_disconnection(): Log.d('Received disconnection from client (' + request.sid + ')') # Delete the player from the players list assert request.sid is not None game.remove_player(request.sid) # Tell the other clients that the player left change_game_state(broadcast=True) update_title_screen(broadcast=True) update_game_screen(broadcast=True)
def update_time(self, unix_time): if self.can_update(unix_time): self.totalTime += unix_time - self.lapTime self.initTime = self.lapTime self.lapTime = unix_time self.lapCount += 1 Log.d( self.TAG, str(self.id) + ' ==> Vuelta #' + str(self.lapCount) + '. Tiempo: ' + str(self.lapTime - self.initTime) + '. Tiempo total: ' + str(self.totalTime)) self.update_database(self)
def guess(self, letter): Log.d("Guessing the letter " + letter + " in " + self.phrase) self.userGuess = letter.upper() self.usedLetters.append(self.userGuess) if self.inPhrase(self.userGuess) == False: self.numLives = self.numLives - 1 for x in range(0, self.numChars): if self.phrase[x].upper() == self.userGuess.upper(): self.underlinePhrase = self.underlinePhrase[:( 2 * x)] + self.phrase[x] + self.underlinePhrase[(2 * x) + 1:]
def handle_client_connection(json): Log.d('Received connection from client (' + request.sid + ') with data: ' + json['data']) # Add the player to the players list assert request.sid is not None game.add_player(request.sid) # Set the player as spectator by default game.set_spectator(request.sid) # Send the state information required for a connecting client to first render the page change_game_state() update_title_screen() update_game_screen() discovered_phrase()
def load_file(name, type=''): try: i = im.open(name) if type != "": i = i.convert(type) except IOError as msg: log.e("Picture couln't be loaded '{}': {}".format(name, msg)) return None # Resize if too big if max(i.size) > MAX_DIMENSION: max_dim = 0 if i.size[0] > i.size[1] else 1 old_max = i.size[max_dim] new_max = MAX_DIMENSION factor = new_max / float(old_max) log.d("Image is big: {}. Resizing by a factor of {}".format( i.size, factor)) i = i.resize((int(i.size[0] * factor), int(i.size[1] * factor))) return i
def save_to_file(img_object, output_dir=None): """ Attempts to save the file Parameters ---------- img_object: PIL.Image.Image The image object to save output_dir : The directory where to save the file Returns ------- tuple(bool, str) State: True if ok Additional data: Path to stored image if success, else reason of failure """ file_ext = DEFAULT_OUTPUT_EXTENSION # Trying to save with image name format if output_dir is None: savefolder = SAVEFOLDER else: savefolder = output_dir # Try to create folder, if it doesn't exist already if not os.path.exists(savefolder): try: os.mkdir(savefolder) except IOError as e: log.e("Cannot create file: {}".format(e)) return False, "Could not create output directory '{}': {}".format( savefolder, e) outfile_name = u"{date}{ext}".format(date=time.strftime( "%Y%m%d-%H%M%S", time.localtime()), ext=file_ext) out_path = os.path.join(savefolder, outfile_name) try: r = img_object.save(out_path) log.d("Saved file in {}".format(out_path)) return True, out_path except IOError as e: log.e("Error trying to save image: {}".format(e)) return False, "Could not create file '{}': {}".format(out_path, e)
def main(): log.i("--- Started generation ---") parsed_args = obtain_args() log.d("Arguments: ") for key in vars(parsed_args): log.d("\t {}: {}".format(key, getattr(parsed_args, key))) t0 = time.time() i = make_stereogram(parsed_args) if not parsed_args.output: log.i( "Process finished successfully after {0:.2f}s".format(time.time() - t0)) log.i("No output file specified. Showing in temporary preview") show_img(i) return # print "Saving..." success, additional_info = save_to_file(i, parsed_args.output) log.d("Finished. Success: {}, Additional info: {}".format( success, additional_info)) if not success: log.e("Process finished with errors: '{}'".format(additional_info)) return_http_response(_HTTPCode.INTERNAL_SERVER_ERROR, additional_info) else: log.i( "Process finished successfully after {0:.2f}s".format(time.time() - t0)) return_http_response(_HTTPCode.OK, os.path.basename(additional_info))
def call_api(inp, tag=""): Log.i("Wolfram API call: %s" % inp) inp = '+'.join(inp.split()) url = WOLFRAM_API % inp content = None try: # Makes the API call and gets the data, read by 'content' content = urllib2.urlopen(url).read() except urllib2.URLError: return if content: root = ET.fromstring(content) # Makes an Element Tree values = [[res.find('plaintext').text for res in root[1].findall('subpod')]] if tag: for child in root.findall('pod'): if child.attrib['title'] == tag: values.append([res.find('plaintext').text for res in child.findall('subpod')]) break # ans = re.compile(r'^[^0-9]*([-]?\d+[.]?\d*)[^0-9]*$') print values # result = [ans.match(res).group(1) for res in values] result = [[res[((res.find("~~") + 1) or (res.find("=") + 1)) + 1:] for res in val] for val in values] # TODO: For parsing exact forms - Replace keywords # space = re.compile(r'[^,] ') # result = [[space.sub(lambda x: '*', res) for res in val] for val in result] # sqrt = re.compile(r'sqrt([(].*?[)])') # result = [[sqrt.sub(lambda x: r'%s ** 1/2' % x.group(1), res) for res in val] for val in result] Log.d("Api Call result: %s" % result) return result
def make_background(size, filename="", dots_prob=None, bg_color="000", dot_colors_string=None): """ Constructs background pattern Parameters ---------- size : tuple(int, int) Size of the depthmap filename : str Name of the pattern image, if any. Empty if dot pattern dots_prob : float Probability of dots appearing. Only makes sense if filename is not set (or equals to 'dots') bg_color : str hex code for color Returns ------- """ log.d("colors string: {}".format(dot_colors_string)) pattern_width = (int)(size[0] / PATTERN_FRACTION) # Pattern is a little bit longer than original picture, so everything fits on 3D (eye crossing shrinks the picture horizontally!) i = im.new("RGB", (size[0] + pattern_width, size[1]), color=_hex_color_to_tuple(bg_color)) i_pix = i.load() if filename == "R" and random() < DOT_OVER_PATTERN_PROBABILITY: filename = "dots" # Load from picture is_image = False if filename != "" and filename != "dots": pattern = load_file( (get_random("pattern") if filename == "R" else filename)) if pattern is None: log.w("Error loading patter '{}'. Will generate using random dots". format(filename)) filename = "" else: is_image = True pattern = pattern.resize((pattern_width, (int)( (pattern_width * 1.0 / pattern.size[0]) * pattern.size[1])), im.LANCZOS) # Repeat vertically region = pattern.crop((0, 0, pattern.size[0], pattern.size[1])) y = 0 while y < i.size[1]: i.paste(region, (0, y, pattern.size[0], y + pattern.size[1])) y += pattern.size[1] # Random fill if filename == "" or filename == "dots": for f in range(i.size[1]): for c in range(pattern_width): if random() < dots_prob: if dot_colors_string is None: i_pix[c, f] = choice([(255, 0, 0), (255, 255, 0), (200, 0, 255)]) else: colors = [ _hex_color_to_tuple(s) for s in dot_colors_string.split(",") ] i_pix[c, f] = choice(colors) return i, is_image
def make_stereogram(parsed_args): # Load or create stereogram depthmap if parsed_args.text: dm_img = make_depth_text(parsed_args.text, parsed_args.font) else: dm_img = load_file(parsed_args.depthmap, "L") # Apply gaussian blur if needed if parsed_args.blur and parsed_args.blur != 0: dm_img = dm_img.filter(imflt.GaussianBlur(parsed_args.blur)) # Redistribute grayscale range (force depth) if parsed_args.text: dm_img = redistribute_grays( dm_img, parsed_args.forcedepth if parsed_args.forcedepth is not None else 0.5) elif parsed_args.forcedepth: dm_img = redistribute_grays(dm_img, parsed_args.forcedepth) # Create blank canvas pattern_width = (int)(dm_img.size[0] / PATTERN_FRACTION) canvas_img = im.new(mode="RGB", size=(dm_img.size[0] + pattern_width, dm_img.size[1]), color=(0, 0, 0) if parsed_args.dot_bg_color is None else _hex_color_to_tuple(parsed_args.dot_bg_color)) # Create pattern pattern_strip_img = im.new( mode="RGB", size=(pattern_width, dm_img.size[1]), color=(0, 0, 0) if parsed_args.dot_bg_color is None else _hex_color_to_tuple(parsed_args.dot_bg_color)) if parsed_args.pattern: # Create from file pattern_raw_img = load_file(parsed_args.pattern) p_w = pattern_raw_img.size[0] p_h = pattern_raw_img.size[1] # Resize to strip width pattern_raw_img = pattern_raw_img.resize((pattern_width, (int)( (pattern_width * 1.0 / p_w) * p_h)), im.LANCZOS) # Repeat vertically region = pattern_raw_img.crop( (0, 0, pattern_raw_img.size[0], pattern_raw_img.size[1])) y = 0 while y < pattern_strip_img.size[1]: pattern_strip_img.paste( region, (0, y, pattern_raw_img.size[0], y + pattern_raw_img.size[1])) y += pattern_raw_img.size[1] # Oversample. Smoother results. dm_img = dm_img.resize(((int)(dm_img.size[0] * OVERSAMPLE), (int)(dm_img.size[1] * OVERSAMPLE))) canvas_img = canvas_img.resize( ((int)(canvas_img.size[0] * OVERSAMPLE), (int)(canvas_img.size[1] * OVERSAMPLE))) pattern_strip_img = pattern_strip_img.resize( ((int)(pattern_strip_img.size[0] * OVERSAMPLE), (int)(pattern_strip_img.size[1] * OVERSAMPLE))) pattern_width = pattern_strip_img.size[0] else: # create random dot pattern pixels = pattern_strip_img.load() dot_prob = parsed_args.dot_prob if parsed_args.dot_prob else 0.4 if parsed_args.dot_colors: hex_tuples = list() for hex_str in parsed_args.dot_colors.split(','): if re.match(r'.+x\d+', hex_str): # multiplier factor = int(re.sub(r'.*x', '', hex_str)) hex_tuples.extend([re.sub(r'x\d+', '', hex_str)] * factor) else: hex_tuples.append(hex_str) color_tuples = [_hex_color_to_tuple(hex) for hex in hex_tuples] else: color_tuples = [(255, 0, 0), (255, 255, 0), (200, 0, 255)] log.d("Colors to use for dots: {}".format(color_tuples)) for y in range(pattern_strip_img.size[1]): for x in range(pattern_width): if random() < dot_prob: pixels[x, y] = choice(color_tuples) # Important objects here: dm_img, pattern_strip_img, canvas_img # Start stereogram generation def shift_pixels(dm_start_x, depthmap_image_object, canvas_image_object, direction): """ shifts pixel of image. direction==1 right, -1 left """ depth_factor = pattern_width * SHIFT_RATIO cv_pixels = canvas_image_object.load() while 0 <= dm_start_x < dm_img.size[0]: for dm_y in range(depthmap_image_object.size[1]): constrained_end = max( 0, min(dm_img.size[0] - 1, dm_start_x + direction * pattern_width)) for dm_x in range(int(dm_start_x), int(constrained_end), direction): dm_pix = dm_img.getpixel((dm_x, dm_y)) px_shift = int(dm_pix / 255.0 * depth_factor * (1 if parsed_args.wall else -1)) * direction if direction == 1: cv_pixels[dm_x + pattern_width, dm_y] = canvas_img.getpixel( (px_shift + dm_x, dm_y)) if direction == -1: cv_pixels[dm_x, dm_y] = canvas_img.getpixel( (dm_x + pattern_width + px_shift, dm_y)) dm_start_x += direction * pattern_strip_img.size[0] # paste first pattern dm_center_x = dm_img.size[0] / 2 canvas_img.paste(pattern_strip_img, (int(dm_center_x), 0, int(dm_center_x + pattern_width), canvas_img.size[1])) if not parsed_args.wall: canvas_img.paste(pattern_strip_img, (int(dm_center_x - pattern_width), 0, int(dm_center_x), canvas_img.size[1])) shift_pixels(dm_center_x, dm_img, canvas_img, 1) shift_pixels(dm_center_x + pattern_width, dm_img, canvas_img, -1) # Bring back from oversample if parsed_args.pattern: canvas_img = canvas_img.resize( ((int)(canvas_img.size[0] / OVERSAMPLE), (int)(canvas_img.size[1] / OVERSAMPLE)), im.LANCZOS) # NEAREST, BILINEAR, BICUBIC, LANCZOS return canvas_img
# Return letters used def getUsedLetters(self): return self.usedLetters def getNumLives(self): return self.numLives # Used to test the class if __name__ == '__main__': hm = Hangman(raw_input("Enter phrase to guess: ")) while (True): lettersUsed = hm.getUsedLetters() numLives = hm.getNumLives() if numLives == 0: Log.d("Game Over") break elif hm.isCompleted() == True: Log.d("You win!") break repeatLetter = False print "Used letters: ", for x in range(0, len(lettersUsed)): print lettersUsed[x], print Log.d("Lives remaining: " + str(numLives)) guessedLetter = raw_input("Enter letter: ") for x in range(0, len(lettersUsed)): if guessedLetter.upper() == lettersUsed[x].upper():