function
stringlengths
11
56k
repo_name
stringlengths
5
60
features
sequence
def redo(self): if not self.hasRedo: return self._undos.append((dict(self._reg), dict(self._order))) self._reg, self._order = self._redos.popleft() if self._currentUid not in self._reg: self._currentUid = None self.onChanged()
petrushev/txplaya
[ 1, 1, 1, 3, 1449794901 ]
def hasUndo(self): return len(self._undos) > 0
petrushev/txplaya
[ 1, 1, 1, 3, 1449794901 ]
def hasRedo(self): return len(self._redos) > 0
petrushev/txplaya
[ 1, 1, 1, 3, 1449794901 ]
def move(self, origin, target, emit=True): if origin == target or origin + 1 == target: return keys = sorted(self._order.keys()) dpositionOrigin = keys[origin] trackUid = self._order[dpositionOrigin] if target == 0: dpositionTarget = keys[0] / 2 elif target >= len(self._order): dpositionTarget = max(self._order.keys()) + 1 else: dpositionTarget = (keys[target] + keys[target - 1]) / 2 self.mark() del self._order[dpositionOrigin] self._order[dpositionTarget] = trackUid if emit: self.onChanged()
petrushev/txplaya
[ 1, 1, 1, 3, 1449794901 ]
def currentPosition(self): if self._currentUid is None: return None keys = sorted(self._order.items(), key=itemgetter0) for position, (_, trackUid) in enumerate(keys): if trackUid == self._currentUid: return position raise PlaylistError, 'current uid not in _reg'
petrushev/txplaya
[ 1, 1, 1, 3, 1449794901 ]
def currentTrack(self): if self._currentUid is None: return None return self._reg[self._currentUid]
petrushev/txplaya
[ 1, 1, 1, 3, 1449794901 ]
def stop(self): self._currentUid = None
petrushev/txplaya
[ 1, 1, 1, 3, 1449794901 ]
def onChanged(self): log.err('Playlist not attached')
petrushev/txplaya
[ 1, 1, 1, 3, 1449794901 ]
def load(self, name): from txplaya.playlistregistry import playlistRegistry return playlistRegistry.loadPlaylist(name)
petrushev/txplaya
[ 1, 1, 1, 3, 1449794901 ]
def __init__(self): self.player = Player() self.playlist = Playlist() self.listenerRegistry = ListenerRegistry() self.infoListenerRegistry = ListenerRegistry() self.library = Library() self.scrobbler = getScrobbler() self.player.onPush = self.onBufferReceived self.player.onStart = self.onPlaybackStarted self.player.onTrackFinished = self.onTrackFinished self.player.onStop = self.onPlayerStopped self.player.onTimerUpdate = self.onTimerUpdate self.player.onPaused = self.onPlayerPaused self.playlist.onChanged = self.onPlaylistChange
petrushev/txplaya
[ 1, 1, 1, 3, 1449794901 ]
def onStop(self): from txplaya.playlistregistry import playlistRegistry paths = [track._path for track in self.playlist.iterTrack()] playlistRegistry.savePlaylist('__current__', paths)
petrushev/txplaya
[ 1, 1, 1, 3, 1449794901 ]
def onTrackFinished(self): if self.scrobbler is not None: deferLater(reactor, 0, self.scrobbler.scrobble, self.playlist.currentTrack) if self.playlist.stepNext() is None: self.onPlaylistFinished() return while True: try: self.player.feed(self.playlist.currentTrack, clear=False) except IOError: # next track not found on disk currentPosition = self.playlist.currentPosition self.playlist.remove(currentPosition, emit=False) if currentPosition >= len(self.playlist._reg): # no more tracks self.onPlaylistFinished() break else: # try next self.playlist.start(currentPosition) else: # track loaded successfuly self.player.start() self.onPlaybackStarted() break
petrushev/txplaya
[ 1, 1, 1, 3, 1449794901 ]
def onPlayerStopped(self): event = {'event': 'PlaybackFinished', 'data': {}} self.announce(event)
petrushev/txplaya
[ 1, 1, 1, 3, 1449794901 ]
def onPlaylistFinished(self): log.msg('Playlist finished') event = {'event': 'PlaybackFinished', 'data': {}} self.announce(event) self.player.history = deque() self.listenerRegistry.onPlaylistFinished()
petrushev/txplaya
[ 1, 1, 1, 3, 1449794901 ]
def onPlaylistChange(self): playlist = self.playlist event = {'event': 'PlaylistChanged', 'data': {'playlist': playlist.playlistData, 'hasUndo': playlist.hasUndo, 'hasRedo': playlist.hasRedo, 'position': playlist.currentPosition}} self.announce(event)
petrushev/txplaya
[ 1, 1, 1, 3, 1449794901 ]
def new_tmux_cmd(session, name, cmd): if isinstance(cmd, (list, tuple)): cmd = " ".join(str(v) for v in cmd) return name, "tmux send-keys -t {}:{} '{} && {}' Enter".format(session, name, 'source activate dhp_env', cmd)
YuhangSong2017/test_4
[ 75, 18, 75, 3, 1495617906 ]
def create_tmux_commands_auto(session, logdir, worker_running, game_i_at, subject_i_at): '''''' cmds_map = [] if (game_i_at>=len(config.game_dic)): print('all done') print(s) base_cmd = [ 'CUDA_VISIBLE_DEVICES=', sys.executable, 'worker.py', '--log-dir', logdir, '--env-id', config.game_dic[game_i_at], '--num-workers', str(1)] cmds_map += [new_tmux_cmd(session, 'g-'+str(game_i_at)+'-s-'+str(subject_i_at)+'-ps', base_cmd + ["--job-name", "ps", "--subject", str(subject_i_at)])] base_cmd = [ 'CUDA_VISIBLE_DEVICES=', sys.executable, 'worker.py', '--log-dir', logdir, '--env-id', config.game_dic[game_i_at], '--num-workers', str(1)] cmds_map += [new_tmux_cmd(session, 'g-'+str(game_i_at)+'-s-'+str(subject_i_at)+'-w-0', base_cmd + ["--job-name", "worker", "--task", str(0), "--subject", str(subject_i_at)])] '''created new worker, add worker_running''' print('a pair of ps_worker for game '+config.game_dic[game_i_at]+' subject '+str(subject_i_at)+' is created.') worker_running += 1 subject_i_at += 1 if subject_i_at >= config.num_subjects: game_i_at += 1 subject_i_at = 0 worker_running +=1 '''see if cmd added''' if len(cmds_map) > 0: '''''' windows = [v[0] for v in cmds_map] cmds = [] for w in windows: cmds += ["tmux new-window -t {} -n {}".format(session, w)] cmds += ["sleep 1"] for window, cmd in cmds_map: cmds += [cmd] '''excute cmds''' os.system("\n".join(cmds)) return worker_running, game_i_at, subject_i_at
YuhangSong2017/test_4
[ 75, 18, 75, 3, 1495617906 ]
def run(): args = parser.parse_args() session = "a3c" cmds = create_tmux_commands(session, config.log_dir) print("\n".join(cmds)) os.system("\n".join(cmds)) if config.mode is 'on_line': try: run_to = np.load(config.log_dir+'run_to.npz')['run_to'] game_i_at = run_to[0] subject_i_at = run_to[1] worker_running = run_to[2] print('>>>>>Previous run_to found, init run_to:') print('\t\tgame_i_at: '+str(game_i_at)) print('\t\tsubject_i_at: '+str(subject_i_at)) print('\t\tworker_running: '+str(worker_running)) except Exception, e: worker_running = config.num_workers_one_run # this is fake to start the run game_i_at=0 subject_i_at=0 print('>>>>>No previous run_to found, init run_to:') print('\t\tgame_i_at: '+str(game_i_at)) print('\t\tsubject_i_at: '+str(subject_i_at)) print('\t\tworker_running: '+str(worker_running)) '''record run_to''' while True: try: np.savez(config.log_dir+'run_to.npz', run_to=[game_i_at,subject_i_at,worker_running]) break except Exception, e: print(str(Exception)+": "+str(e)) time.sleep(1)
YuhangSong2017/test_4
[ 75, 18, 75, 3, 1495617906 ]
def __init__(self, state): self.state = state msg = "The state {} cannot be reached in the given TPM." super().__init__(msg.format(state))
wmayner/pyphi
[ 320, 79, 320, 8, 1396935070 ]
def __init__(self): self.active = True
janeczku/calibre-web
[ 8673, 1037, 8673, 363, 1438542102 ]
def search( self, query: str, generic_cover: str = "", locale: str = "en"
janeczku/calibre-web
[ 8673, 1037, 8673, 363, 1438542102 ]
def get_title_tokens( title: str, strip_joiners: bool = True
janeczku/calibre-web
[ 8673, 1037, 8673, 363, 1438542102 ]
def cache_page(url,post=None,headers=None,modo_cache=None, timeout=None): return cachePage(url,post,headers,modo_cache,timeout=timeout)
orione7/plugin.video.streamondemand-pureita
[ 8, 8, 8, 3, 1544054268 ]
def downloadpage(url,post=None,headers=None, follow_redirects=True, timeout=None, header_to_get=None): response = httptools.downloadpage(url, post=post, headers=headers, follow_redirects = follow_redirects, timeout=timeout)
orione7/plugin.video.streamondemand-pureita
[ 8, 8, 8, 3, 1544054268 ]
def downloadpageWithResult(url,post=None,headers=None,follow_redirects=True, timeout=None, header_to_get=None): response = httptools.downloadpage(url, post=post, headers=headers, follow_redirects = follow_redirects, timeout=timeout)
orione7/plugin.video.streamondemand-pureita
[ 8, 8, 8, 3, 1544054268 ]
def downloadpageWithoutCookies(url): response = httptools.downloadpage(url, cookies=False) return response.data
orione7/plugin.video.streamondemand-pureita
[ 8, 8, 8, 3, 1544054268 ]
def getLocationHeaderFromResponse(url): response = httptools.downloadpage(url, only_headers=True, follow_redirects=False) return response.headers.get("location")
orione7/plugin.video.streamondemand-pureita
[ 8, 8, 8, 3, 1544054268 ]
def get_headers_from_response(url, post=None, headers=None, follow_redirects=False): response = httptools.downloadpage(url, post=post, headers=headers, only_headers=True, follow_redirects=follow_redirects) return response.headers.items()
orione7/plugin.video.streamondemand-pureita
[ 8, 8, 8, 3, 1544054268 ]
def read_body_and_headers(url, post=None, headers=None, follow_redirects=False, timeout=None): response = httptools.downloadpage(url, post=post, headers=headers, follow_redirects=follow_redirects, timeout=timeout) return response.data, response.headers
orione7/plugin.video.streamondemand-pureita
[ 8, 8, 8, 3, 1544054268 ]
def printMatches(matches): i = 0 for match in matches: logger.info("streamondemand-pureita-master.core.scrapertools %d %s" % (i , match)) i = i + 1
orione7/plugin.video.streamondemand-pureita
[ 8, 8, 8, 3, 1544054268 ]
def find_single_match(data,patron,index=0): try: matches = re.findall( patron , data , flags=re.DOTALL ) return matches[index] except: return ""
orione7/plugin.video.streamondemand-pureita
[ 8, 8, 8, 3, 1544054268 ]
def find_multiple_matches(text,pattern): return re.findall(pattern,text,re.DOTALL)
orione7/plugin.video.streamondemand-pureita
[ 8, 8, 8, 3, 1544054268 ]
def unescape(text): """Removes HTML or XML character references and entities from a text string. keep &, >, < in the source code. from Fredrik Lundh http://effbot.org/zone/re-sub.htm#unescape-html """ def fixup(m): text = m.group(0) if text[:2] == "&#": # character reference try: if text[:3] == "&#x": return unichr(int(text[3:-1], 16)).encode("utf-8") else: return unichr(int(text[2:-1])).encode("utf-8") except ValueError: logger.info("error de valor") pass else: # named entity try: ''' if text[1:-1] == "amp": text = "&" elif text[1:-1] == "gt": text = ">" elif text[1:-1] == "lt": text = "<" else: print text[1:-1] text = unichr(htmlentitydefs.name2codepoint[text[1:-1]]).encode("utf-8") ''' import htmlentitydefs text = unichr(htmlentitydefs.name2codepoint[text[1:-1]]).encode("utf-8") except KeyError: logger.info("keyerror") pass except: pass return text # leave as is return re.sub("&#?\w+;", fixup, text) # Convierte los codigos html "ñ" y lo reemplaza por "ñ" caracter unicode utf-8
orione7/plugin.video.streamondemand-pureita
[ 8, 8, 8, 3, 1544054268 ]
def substitute_entity(match): from htmlentitydefs import name2codepoint as n2cp ent = match.group(2) if match.group(1) == "#": return unichr(int(ent)).encode('utf-8') else: cp = n2cp.get(ent) if cp: return unichr(cp).encode('utf-8') else: return match.group()
orione7/plugin.video.streamondemand-pureita
[ 8, 8, 8, 3, 1544054268 ]
def entitiesfix(string): # Las entidades comienzan siempre con el símbolo & , y terminan con un punto y coma ( ; ). string = string.replace("&aacute","á") string = string.replace("&eacute","é") string = string.replace("&iacute","í") string = string.replace("&oacute","ó") string = string.replace("&uacute","ú") string = string.replace("&Aacute","Á") string = string.replace("&Eacute","É") string = string.replace("&Iacute","Í") string = string.replace("&Oacute","Ó") string = string.replace("&Uacute","Ú") string = string.replace("&uuml" ,"ü") string = string.replace("&Uuml" ,"Ü") string = string.replace("&ntilde","ñ") string = string.replace("&#191" ,"¿") string = string.replace("&#161" ,"¡") string = string.replace(";;" ,";") return string
orione7/plugin.video.streamondemand-pureita
[ 8, 8, 8, 3, 1544054268 ]
def slugify(title): #print title # Sustituye acentos y eñes title = title.replace("Á","a") title = title.replace("É","e") title = title.replace("Í","i") title = title.replace("Ó","o") title = title.replace("Ú","u") title = title.replace("á","a") title = title.replace("é","e") title = title.replace("í","i") title = title.replace("ó","o") title = title.replace("ú","u") title = title.replace("À","a") title = title.replace("È","e") title = title.replace("Ì","i") title = title.replace("Ò","o") title = title.replace("Ù","u") title = title.replace("à","a") title = title.replace("è","e") title = title.replace("ì","i") title = title.replace("ò","o") title = title.replace("ù","u") title = title.replace("ç","c") title = title.replace("Ç","C") title = title.replace("Ñ","n") title = title.replace("ñ","n") title = title.replace("/","-") title = title.replace("&","&") # Pasa a minúsculas title = title.lower().strip() # Elimina caracteres no válidos validchars = "abcdefghijklmnopqrstuvwxyz1234567890- " title = ''.join(c for c in title if c in validchars) # Sustituye espacios en blanco duplicados y saltos de línea title = re.compile("\s+",re.DOTALL).sub(" ",title) # Sustituye espacios en blanco por guiones title = re.compile("\s",re.DOTALL).sub("-",title.strip()) # Sustituye espacios en blanco duplicados y saltos de línea title = re.compile("\-+",re.DOTALL).sub("-",title) # Arregla casos especiales if title.startswith("-"): title = title [1:] if title=="": title = "-"+str(time.time()) return title
orione7/plugin.video.streamondemand-pureita
[ 8, 8, 8, 3, 1544054268 ]
def remove_show_from_title(title,show): #print slugify(title)+" == "+slugify(show) # Quita el nombre del programa del título if slugify(title).startswith(slugify(show)): # Convierte a unicode primero, o el encoding se pierde title = unicode(title,"utf-8","replace") show = unicode(show,"utf-8","replace") title = title[ len(show) : ].strip() if title.startswith("-"): title = title[ 1: ].strip() if title=="": title = str( time.time() ) # Vuelve a utf-8 title = title.encode("utf-8","ignore") show = show.encode("utf-8","ignore") return title
orione7/plugin.video.streamondemand-pureita
[ 8, 8, 8, 3, 1544054268 ]
def unseo(cadena): if cadena.upper().startswith("VER GRATIS LA PELICULA "): cadena = cadena[23:] elif cadena.upper().startswith("VER GRATIS PELICULA "): cadena = cadena[20:] elif cadena.upper().startswith("VER ONLINE LA PELICULA "): cadena = cadena[23:] elif cadena.upper().startswith("VER GRATIS "): cadena = cadena[11:] elif cadena.upper().startswith("VER ONLINE "): cadena = cadena[11:] elif cadena.upper().startswith("DESCARGA DIRECTA "): cadena = cadena[17:] return cadena
orione7/plugin.video.streamondemand-pureita
[ 8, 8, 8, 3, 1544054268 ]
def get_filename_from_url(url): import urlparse parsed_url = urlparse.urlparse(url) try: filename = parsed_url.path except: # Si falla es porque la implementación de parsed_url no reconoce los atributos como "path" if len(parsed_url)>=4: filename = parsed_url[2] else: filename = "" if "/" in filename: filename = filename.split("/")[-1] return filename
orione7/plugin.video.streamondemand-pureita
[ 8, 8, 8, 3, 1544054268 ]
def get_season_and_episode(title): """ Retorna el numero de temporada y de episodio en formato "1x01" obtenido del titulo de un episodio Ejemplos de diferentes valores para title y su valor devuelto: "serie 101x1.strm", "s101e1.avi", "t101e1.avi" -> '101x01' "Name TvShow 1x6.avi" -> '1x06' "Temp 3 episodio 2.avi" -> '3x02' "Alcantara season 13 episodie 12.avi" -> '13x12' "Temp1 capitulo 14" -> '1x14' "Temporada 1: El origen Episodio 9" -> '' (entre el numero de temporada y los episodios no puede haber otro texto) "Episodio 25: titulo episodio" -> '' (no existe el numero de temporada) "Serie X Temporada 1" -> '' (no existe el numero del episodio) @type title: str @param title: titulo del episodio de una serie @rtype: str @return: Numero de temporada y episodio en formato "1x01" o cadena vacia si no se han encontrado """ filename = "" patrons = ["(\d+)x(\d+)", "(?:s|t)(\d+)e(\d+)", "(?:season|stag\w*)\s*(\d+)\s*(?:capitolo|epi\w*)\s*(\d+)"] for patron in patrons: try: matches = re.compile(patron, re.I).search(title) if matches: filename = matches.group(1) + "x" + matches.group(2).zfill(2) break except: pass logger.info("'" + title + "' -> '" + filename + "'") return filename
orione7/plugin.video.streamondemand-pureita
[ 8, 8, 8, 3, 1544054268 ]
def get_md5(cadena): try: import hashlib devuelve = hashlib.md5(cadena).hexdigest() except: import md5 import binascii devuelve = binascii.hexlify(md5.new(cadena).digest()) return devuelve
orione7/plugin.video.streamondemand-pureita
[ 8, 8, 8, 3, 1544054268 ]
def __init__(self, **kwargs): self.id = kwargs.get("id") self.server = kwargs.get("server") self.verify = kwargs.get("verify", True) self.api_key = kwargs.get("key", "") self.meta_data = kwargs.get("meta_data") self._user_agent = kwargs.get("user_agent") self._fields = kwargs.get("fields") self.get_params = {} if self.meta_data is None and self.id is None: raise CousteauGenericError( "Id or meta_data should be passed in order to create object." ) if self._fields: self.update_get_params() if self.meta_data is None: if not self._fetch_meta_data(): raise APIResponseError(self.meta_data) self._populate_data()
RIPE-NCC/ripe-atlas-cousteau
[ 57, 26, 57, 5, 1400156266 ]
def _fetch_meta_data(self): """Makes an API call to fetch meta data for the given probe and stores the raw data.""" is_success, meta_data = AtlasRequest( url_path=self.API_META_URL.format(self.id), key=self.api_key, server=self.server, verify=self.verify, user_agent=self._user_agent ).get(**self.get_params) self.meta_data = meta_data if not is_success: return False return True
RIPE-NCC/ripe-atlas-cousteau
[ 57, 26, 57, 5, 1400156266 ]
def _populate_data(self): """Assing some probe's raw meta data from API response to instance properties""" if self.id is None: self.id = self.meta_data.get("id") self.is_anchor = self.meta_data.get("is_anchor") self.country_code = self.meta_data.get("country_code") self.description = self.meta_data.get("description") self.is_public = self.meta_data.get("is_public") self.asn_v4 = self.meta_data.get("asn_v4") self.asn_v6 = self.meta_data.get("asn_v6") self.address_v4 = self.meta_data.get("address_v4") self.address_v6 = self.meta_data.get("address_v6") self.prefix_v4 = self.meta_data.get("prefix_v4") self.prefix_v6 = self.meta_data.get("prefix_v6") self.geometry = self.meta_data.get("geometry") self.tags = self.meta_data.get("tags") self.status = self.meta_data.get("status", {}).get("name")
RIPE-NCC/ripe-atlas-cousteau
[ 57, 26, 57, 5, 1400156266 ]
def __repr__(self): return str(self)
RIPE-NCC/ripe-atlas-cousteau
[ 57, 26, 57, 5, 1400156266 ]
def _populate_data(self): """Assinging some measurement's raw meta data from API response to instance properties""" if self.id is None: self.id = self.meta_data.get("id") self.stop_time = None self.creation_time = None self.start_time = None self.populate_times() self.protocol = self.meta_data.get("af") self.target_ip = self.meta_data.get("target_ip") self.target_asn = self.meta_data.get("target_asn") self.target = self.meta_data.get("target") self.description = self.meta_data.get("description") self.is_oneoff = self.meta_data.get("is_oneoff") self.is_public = self.meta_data.get("is_public") self.interval = self.meta_data.get("interval") self.resolve_on_probe = self.meta_data.get("resolve_on_probe") self.status_id = self.meta_data.get("status", {}).get("id") self.status = self.meta_data.get("status", {}).get("name") self.type = self.get_type() self.result_url = self.meta_data.get("result")
RIPE-NCC/ripe-atlas-cousteau
[ 57, 26, 57, 5, 1400156266 ]
def populate_times(self): """ Populates all different meta data times that comes with measurement if they are present. """ stop_time = self.meta_data.get("stop_time") if stop_time: stop_naive = datetime.utcfromtimestamp(stop_time) self.stop_time = stop_naive.replace(tzinfo=tzutc()) creation_time = self.meta_data.get("creation_time") if creation_time: creation_naive = datetime.utcfromtimestamp(creation_time) self.creation_time = creation_naive.replace(tzinfo=tzutc()) start_time = self.meta_data.get("start_time") if start_time: start_naive = datetime.utcfromtimestamp(start_time) self.start_time = start_naive.replace(tzinfo=tzutc())
RIPE-NCC/ripe-atlas-cousteau
[ 57, 26, 57, 5, 1400156266 ]
def test_mcast_sender(self): """Unit test for mcast_sender. """ mcgroup = (str(random.randint(224, 239)) + "." + str(random.randint(0, 255)) + "." + str(random.randint(0, 255)) + "." + str(random.randint(0, 255))) socket, group = bbmcast.mcast_sender(mcgroup) if mcgroup in ("0.0.0.0", "255.255.255.255"): self.assertEqual(group, "<broadcast>") self.assertEqual(socket.getsockopt(SOL_SOCKET, SO_BROADCAST), 1) else: self.assertEqual(group, mcgroup) self.assertEqual(socket.getsockopt(SOL_SOCKET, SO_BROADCAST), 0) socket.close() mcgroup = "0.0.0.0" socket, group = bbmcast.mcast_sender(mcgroup) self.assertEqual(group, "<broadcast>") self.assertEqual(socket.getsockopt(SOL_SOCKET, SO_BROADCAST), 1) socket.close() mcgroup = "255.255.255.255" socket, group = bbmcast.mcast_sender(mcgroup) self.assertEqual(group, "<broadcast>") self.assertEqual(socket.getsockopt(SOL_SOCKET, SO_BROADCAST), 1) socket.close() mcgroup = (str(random.randint(0, 223)) + "." + str(random.randint(0, 255)) + "." + str(random.randint(0, 255)) + "." + str(random.randint(0, 255))) self.assertRaises(IOError, bbmcast.mcast_sender, mcgroup) mcgroup = (str(random.randint(240, 255)) + "." + str(random.randint(0, 255)) + "." + str(random.randint(0, 255)) + "." + str(random.randint(0, 255))) self.assertRaises(IOError, bbmcast.mcast_sender, mcgroup)
pytroll/posttroll
[ 4, 11, 4, 11, 1346947230 ]
def __init__(self): super(CompareCalls, self).__init__() print("Starting...") self.setWindowTitle("AviaNZ call comparator") self.setWindowIcon(QIcon('img/Avianz.ico')) self.setWindowFlags((self.windowFlags() ^ Qt.WindowContextHelpButtonHint) | Qt.WindowMaximizeButtonHint | Qt.WindowCloseButtonHint) # menu bar fileMenu = self.menuBar()#.addMenu("&File") fileMenu.addAction("About", lambda: SupportClasses_GUI.MessagePopup("a", "About", ".").exec_()) fileMenu.addAction("Quit", QApplication.quit) # do we need this? # if platform.system() == 'Darwin': # helpMenu.addAction("About",self.showAbout,"Ctrl+A") # main dock setup area = QWidget() mainbox = QVBoxLayout() area.setLayout(mainbox) self.setCentralWidget(area) ## Data dir selection self.dirName = "" label = QLabel("Select input folder containing files named in one of the following formats:") formatlabel = QLabel("recordername_YYMMDD_hhmmss.wav\n or \nrecordername_YYYYMMDD_hhmmss.wav") formatlabel.setAlignment(Qt.AlignCenter) label.setStyleSheet("QLabel {color: #303030}") formatlabel.setStyleSheet("QLabel {color: #303030}") self.w_browse = QPushButton(" Browse Folder") self.w_browse.setIcon(self.style().standardIcon(QStyle.SP_DialogOpenButton)) self.w_browse.setStyleSheet('QPushButton {background-color: #c4ccd3; font-weight: bold; font-size:14px; padding: 3px 3px 3px 3px}') self.w_browse.setMinimumSize(170, 40) self.w_browse.setSizePolicy(QSizePolicy(1,1)) self.w_browse.clicked.connect(self.browse) # area showing the selected folder self.w_dir = QPlainTextEdit() self.w_dir.setReadOnly(True) self.w_dir.setFixedHeight(40) self.w_dir.setPlainText('') self.w_dir.setSizePolicy(QSizePolicy(3,1)) # feedback label self.labelDatasIcon = QLabel() self.labelDatas = QLabel() ## Clock shift adjustment labelClockSp = QLabel("Select species to analyse:") self.clockSpBox = QComboBox() labelHop = QLabel("Clock shift resolution (s)") self.hopSpin = QDoubleSpinBox() self.hopSpin.setSingleStep(0.1) self.hopSpin.setDecimals(3) self.hopSpin.setValue(1.0) self.suggestAdjBtn = QPushButton("Auto-suggest adjustment") self.suggestAdjBtn.setStyleSheet('QPushButton {background-color: #c4ccd3; font-weight: bold; font-size:14px; padding: 3px 3px 3px 3px}') self.suggestAdjBtn.clicked.connect(self.suggestAdjustment) self.suggestAdjBtn.setEnabled(False) self.labelAdjustIcon = QLabel() self.labelAdjust = QLabel() self.reviewAdjBtn = QPushButton("Review suggested adjustments") self.reviewAdjBtn.setStyleSheet('QPushButton {background-color: #c4ccd3; font-weight: bold; font-size:14px; padding: 3px 3px 3px 3px}') self.reviewAdjBtn.clicked.connect(self.showAdjustmentsDialog) self.reviewAdjBtn.setEnabled(False) # call review self.compareBtn = QPushButton("Compare calls") self.compareBtn.setStyleSheet('QPushButton {background-color: #c4ccd3; font-weight: bold; font-size:14px; padding: 3px 3px 3px 3px}') self.compareBtn.clicked.connect(self.showComparisonDialog) self.compareBtn.setEnabled(False) self.compareRecSelector = QComboBox() self.compareRecSelector.currentTextChanged.connect(self.updateShiftSpinbox) self.compareShiftSpinbox = QDoubleSpinBox() self.compareShiftSpinbox.setSingleStep(1.0) self.compareShiftSpinbox.setRange(-300, 300) self.adjustmentsOut = QPlainTextEdit() self.adjustmentsOut.setReadOnly(True) self.componentsOut = QPlainTextEdit() self.componentsOut.setReadOnly(True) ### Layouts for each box # input dir inputGroup = QGroupBox("Input") inputGrid = QGridLayout() inputGroup.setLayout(inputGrid) inputGroup.setStyleSheet("QGroupBox:title{color: #505050; font-weight: 50}") inputGrid.addWidget(label, 0, 0, 1, 4) inputGrid.addWidget(formatlabel, 1, 0, 1, 4) inputGrid.addWidget(self.w_dir, 2, 0, 1, 3) inputGrid.addWidget(self.w_browse, 2, 3, 1, 1) hboxLabel = QHBoxLayout() hboxLabel.addWidget(self.labelDatasIcon) hboxLabel.addWidget(self.labelDatas) hboxLabel.addStretch(10) inputGrid.addLayout(hboxLabel, 3, 0, 1, 4) # clock adjustment clockadjGroup = QGroupBox("Clock adjustment") clockadjGrid = QGridLayout() clockadjGroup.setLayout(clockadjGrid) clockadjGroup.setStyleSheet("QGroupBox:title{color: #505050; font-weight: 50}") clockadjGrid.addWidget(labelClockSp, 0, 0, 1, 1) clockadjGrid.addWidget(self.clockSpBox, 0, 1, 1, 3) clockadjGrid.addWidget(labelHop, 1, 0, 1, 1) clockadjGrid.addWidget(self.hopSpin, 1, 1, 1, 3) clockadjGrid.addWidget(self.suggestAdjBtn, 2, 0, 1, 4) hboxLabel2 = QHBoxLayout() hboxLabel2.addWidget(self.labelAdjustIcon) hboxLabel2.addWidget(self.labelAdjust) hboxLabel2.addStretch(10) clockadjGrid.addLayout(hboxLabel2, 3, 0, 1, 4) clockadjGrid.addWidget(self.reviewAdjBtn, 4, 0, 1, 4) # call comparator comparisonGroup = QGroupBox("Call comparison") comparisonGrid = QGridLayout() comparisonGroup.setLayout(comparisonGrid) comparisonGroup.setStyleSheet("QGroupBox:title{color: #505050; font-weight: 50}") comparisonGrid.addWidget(QLabel("Compare recorders:"), 0, 0) comparisonGrid.addWidget(self.compareRecSelector, 0, 2) comparisonGrid.addWidget(QLabel("with shift:"), 0, 3) comparisonGrid.addWidget(self.compareShiftSpinbox, 0, 4) comparisonGrid.addWidget(self.compareBtn, 1,0,1,4) # output save btn and settings outputGroup = QGroupBox("Output") outputGrid = QGridLayout() outputGroup.setLayout(outputGrid) outputGroup.setStyleSheet("QGroupBox:title{color: #505050; font-weight: 50}") outputGrid.addWidget(self.adjustmentsOut, 0, 0, 1, 4) outputGrid.addWidget(self.componentsOut, 1, 0, 1, 4) ### Main Layout mainbox.addWidget(inputGroup) mainbox.addWidget(clockadjGroup) mainbox.addWidget(comparisonGroup) mainbox.addWidget(outputGroup)
smarsland/AviaNZ
[ 21, 10, 21, 24, 1462012622 ]
def checkInputDir(self): """ Checks the input file dir filenames etc. for validity Returns an error code if the specified directory is bad. """ if not os.path.isdir(self.dirName): print("ERROR: directory %s doesn't exist" % self.dirName) return(1) # list all datas that will be processed alldatas = [] try: for root, dirs, files in os.walk(str(self.dirName)): for filename in files: if filename.lower().endswith('.wav.data'): alldatas.append(os.path.join(root, filename)) except Exception as e: print("ERROR: could not load dir %s" % self.dirName) print(e) return(1) # TODO Note: this is a bit fidgety as needs to be adapted to each survey recsInDirNames = False defaultToDMY = True # read in all datas to self.annots for f in alldatas: # must have correct naming format: infilestem = os.path.basename(f)[:-9] try: if recsInDirNames: recname = os.path.basename(os.path.normpath(os.path.dirname(f))) filedate, filetime = infilestem.split("_") # get [date, time] else: recname, filedate, filetime = infilestem.split("_") # get [rec, date, time] datestamp = filedate + '_' + filetime # make "date_time" # check both 4-digit and 2-digit codes (century that produces closest year to now is inferred) if len(filedate)==8: d = dt.datetime.strptime(datestamp, "%Y%m%d_%H%M%S") else: if defaultToDMY: try: d = dt.datetime.strptime(datestamp, "%d%m%y_%H%M%S") except ValueError: d = dt.datetime.strptime(datestamp, "%y%m%d_%H%M%S") else: try: d = dt.datetime.strptime(datestamp, "%y%m%d_%H%M%S") except ValueError: d = dt.datetime.strptime(datestamp, "%d%m%y_%H%M%S") print("Recorder ", recname, " timestamp ", d) # timestamp identified, so read this file: segs = Segment.SegmentList() try: segs.parseJSON(f, silent=True) except Exception as e: print("Warning: could not read file %s" % f) print(e) continue # store the wav filename segs.wavname = f[:-5] segs.recname = recname segs.datetime = d self.annots.append(segs) # also keep track of the different recorders self.allrecs.add(recname) except ValueError: print("Could not identify timestamp in", f) continue print("Detected recorders:", self.allrecs) return(0)
smarsland/AviaNZ
[ 21, 10, 21, 24, 1462012622 ]
def calculateOverlap(self, dtl1, dtl2, shift=0): """ Calculates total overlap between two lists of pairs of datetime obj: [(s1, e1), (s2, e2)] + [(s3, e3), (s4, e4)] -> total overl. in s Shift: shifts dt1 by this many seconds (+ for lead, - for lag) Assumes that each tuple is in correct order (start, end). """ overl = dt.timedelta() for dt1 in dtl1: st1 = dt1[0]+shift end1 = dt1[1]+shift for dt2 in dtl2: laststart = max(st1, dt2[0]) firstend = min(end1, dt2[1]) if firstend>laststart: overl = firstend - laststart + overl # convert from datetime timedelta to seconds overl = overl.total_seconds() return(overl)
smarsland/AviaNZ
[ 21, 10, 21, 24, 1462012622 ]
def showAdjustmentsDialog(self): self.adjrevdialog = ReviewAdjustments(self.overlaps_forplot, self.hopSpin.value(), self) self.adjrevdialog.exec_() self.cclist = self.connectedComponents() # update GUI after the dialog closes self.refreshMainOut()
smarsland/AviaNZ
[ 21, 10, 21, 24, 1462012622 ]
def findMatchIn(self, seglist, seg, tshift): """ Returns one segment from seglist that has the most overlap with seg. tshift will be added to the segment timestamp temporarily: this is used to adjusted for things like file timestamp differences, without affecting the stored segment. """ #print("--- trying to match segment", seg, "(delayed by ", tshift, "s) in list", [(s[0], s[1]) for s in seglist]) overlaps = [min(seg[1]+tshift, seg2[1]) - max(seg[0]+tshift, seg2[0]) for seg2 in seglist] mpos = np.argmax(overlaps) if overlaps[mpos]<=0: print("No match found for segment", seg) return([]) m = seglist[mpos] m.overlap = overlaps[mpos] return(m)
smarsland/AviaNZ
[ 21, 10, 21, 24, 1462012622 ]
def DFS(self, temp, templen, v, visited): # Mark the current vertex as visited visited[v] = True # Add this vertex and its shift to the current component if len(temp)>0: prevv = temp[templen-1][0] shift = temp[templen-1][1] + self.pairwiseShifts[v, prevv] print("total shift %.2f at %d / %s" %(shift, v, self.allrecs[v])) else: shift = 0 temp.append((v, shift)) templen = len(temp) # Run DFS for all vertices adjacent to this listOfNeighbours = np.nonzero(self.recConnections[v,])[0] print("Neighbours are", [self.allrecs[nb] for nb in listOfNeighbours]) for i in listOfNeighbours: if not visited[i]: temp = self.DFS(temp, templen, i, visited) return temp
smarsland/AviaNZ
[ 21, 10, 21, 24, 1462012622 ]
def connectedComponents(self): visited = [False] * len(self.allrecs) # symmetrize the adjacency matrix (which was upper triang so far) uptri = np.triu_indices_from(self.recConnections, k=1) self.recConnections[(uptri[1], uptri[0])] = self.recConnections[uptri] print("Using this adjacency matrix:", self.recConnections) componentList = [] for v in range(len(visited)): if not visited[v]: component = [] componentList.append(self.DFS(component, 0, v, visited)) # Additionally, total sum of absolute adjustments could be minimized if we de-median the shifts # just need some testing before doing this # component[,1] = component[,1] - np.median(component[,1]) print("Found the following components and shifts:") print(componentList) return componentList
smarsland/AviaNZ
[ 21, 10, 21, 24, 1462012622 ]
def __init__(self, adj, hop, parent=None): QDialog.__init__(self, parent) self.setWindowTitle('Check Clock Adjustments') self.setWindowIcon(QIcon('img/Avianz.ico')) self.setWindowFlags((self.windowFlags() ^ Qt.WindowContextHelpButtonHint) | Qt.WindowMaximizeButtonHint | Qt.WindowCloseButtonHint) self.parent = parent # list of dicts for each pair: {overlaps for each t, best overlap, best shift, (rec pair names)} self.shifts = adj self.xs = np.arange(-300*hop, 301*hop, hop) # top section self.labelCurrPage = QLabel("Page %s of %s" %(1, len(self.shifts))) self.labelRecs = QLabel() # middle section # The buttons to move through the overview self.leftBtn = QToolButton() self.leftBtn.setArrowType(Qt.LeftArrow) self.leftBtn.clicked.connect(self.moveLeft) self.leftBtn.setToolTip("View previous pair") self.rightBtn = QToolButton() self.rightBtn.setArrowType(Qt.RightArrow) self.rightBtn.clicked.connect(self.moveRight) self.rightBtn.setToolTip("View next pair") self.leftBtn.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.MinimumExpanding) self.rightBtn.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.MinimumExpanding) self.connectCheckbox = QCheckBox("Recorders are connected") self.connectCheckbox.setChecked(bool(self.parent.recConnections[0,1]==1)) self.connectCheckbox.toggled.connect(self.connectToggled) # main graphic mainpl = pg.PlotWidget() self.p1 = mainpl.plot() self.p1.setPen(pg.mkPen('k', width=1)) col = pg.mkColor(20, 255, 20, 150) self.bestLineO = pg.InfiniteLine(angle=0, movable=False, pen={'color': col, 'width': 2}) self.bestLineSh = pg.InfiniteLine(angle=90, movable=False, pen={'color': col, 'width': 2}) mainpl.addItem(self.bestLineO) mainpl.addItem(self.bestLineSh) # init plot with page 1 data self.currpage = 1 self.leftBtn.setEnabled(False) if len(self.shifts)==1: self.rightBtn.setEnabled(False) self.setData() # accept / close closeBtn = QPushButton("Close") closeBtn.clicked.connect(self.accept) # cancelBtn = QPushButton("Cancel") # cancelBtn.clicked.connect(self.reject) # Layouts box = QVBoxLayout() topHBox = QHBoxLayout() topHBox.addWidget(self.labelCurrPage, stretch=1) topHBox.addWidget(self.labelRecs, stretch=3) box.addLayout(topHBox) midHBox = QHBoxLayout() midHBox.addWidget(self.leftBtn) midHBox.addWidget(mainpl, stretch=10) midHBox.addWidget(self.rightBtn) box.addLayout(midHBox) box.addWidget(self.connectCheckbox) bottomHBox = QHBoxLayout() bottomHBox.addWidget(closeBtn) # bottomHBox.addWidget(cancelBtn) box.addLayout(bottomHBox) self.setLayout(box)
smarsland/AviaNZ
[ 21, 10, 21, 24, 1462012622 ]
def moveLeft(self): self.currpage = self.currpage - 1 self.rightBtn.setEnabled(True) if self.currpage==1: self.leftBtn.setEnabled(False) self.setData()
smarsland/AviaNZ
[ 21, 10, 21, 24, 1462012622 ]
def setData(self): # update plot etc currdata = self.shifts[self.currpage-1] self.p1.setData(y=currdata['series'], x=self.xs) self.bestLineO.setValue(currdata['bestOverlap']) self.bestLineSh.setValue(currdata['bestShift']) self.labelCurrPage.setText("Page %s of %s" %(self.currpage, len(self.shifts))) self.rec1 = currdata['recorders'][0] self.rec2 = currdata['recorders'][1] self.labelRecs.setText("Suggested shift for recorder %s w.r.t. %s" % (self.rec1, self.rec2)) i = self.parent.allrecs.index(self.rec1) j = self.parent.allrecs.index(self.rec2) result = self.parent.recConnections[i, j]==1 self.connectCheckbox.setChecked(bool(result))
smarsland/AviaNZ
[ 21, 10, 21, 24, 1462012622 ]
def __init__(self, annots1, annots2, parent=None): QDialog.__init__(self, parent) self.setWindowTitle('Compare Call Pairs') self.setWindowIcon(QIcon('img/Avianz.ico')) self.setWindowFlags((self.windowFlags() ^ Qt.WindowContextHelpButtonHint) | Qt.WindowMaximizeButtonHint | Qt.WindowCloseButtonHint) self.parent = parent self.rec1 = annots1[0].recname self.rec2 = annots2[0].recname self.annots1 = annots1 self.annots2 = annots2 # Set colour map # cmap = self.config['cmap'] # TODO Read these from config self.lut = colourMaps.getLookupTable("Grey") self.cmapInverted = False self.topLabel = QLabel("Comparing recorders %s (top) and %s (bottom)" %(self.rec1, self.rec2)) self.labelPair = QLabel() # Volume, brightness and contrast sliders. (NOTE hardcoded init) self.specControls = SupportClasses_GUI.BrightContrVol(80, 20, False) self.specControls.colChanged.connect(self.setColourLevels) # self.specControls.volChanged.connect(self.volSliderMoved) # TODO add volume and playback at some point # spectrograms self.wPlot = pg.GraphicsLayoutWidget() self.pPlot1 = self.wPlot.addViewBox(enableMouse=False, row=0, col=1) self.pPlot2 = self.wPlot.addViewBox(enableMouse=False, row=1, col=1) self.plot1 = pg.ImageItem() self.plot2 = pg.ImageItem() self.pPlot1.addItem(self.plot1) self.pPlot2.addItem(self.plot2) # Y (freq) axis self.sg_axis1 = pg.AxisItem(orientation='left') self.sg_axis1.linkToView(self.pPlot1) self.sg_axis2 = pg.AxisItem(orientation='left') self.sg_axis2.linkToView(self.pPlot2) self.wPlot.addItem(self.sg_axis1, row=0, col=0) self.wPlot.addItem(self.sg_axis2, row=1, col=0) # The buttons to move through the overview self.leftBtn = QToolButton() self.leftBtn.setArrowType(Qt.LeftArrow) self.leftBtn.clicked.connect(self.moveLeft) self.leftBtn.setToolTip("View previous pair") self.rightBtn = QToolButton() self.rightBtn.setArrowType(Qt.RightArrow) self.rightBtn.clicked.connect(self.moveRight) self.rightBtn.setToolTip("View next pair") self.leftBtn.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.MinimumExpanding) self.rightBtn.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.MinimumExpanding) # accept / close closeBtn = QPushButton("Close") closeBtn.clicked.connect(self.accept) # init GUI with page 1 data self.currpage = 1 self.leftBtn.setEnabled(False) if len(self.annots1)==1: self.rightBtn.setEnabled(False) self.setData() # layout box = QVBoxLayout() box.addWidget(self.topLabel) box.addWidget(self.labelPair) box.addWidget(self.specControls) midHBox = QHBoxLayout() midHBox.addWidget(self.leftBtn) midHBox.addWidget(self.wPlot, stretch=10) midHBox.addWidget(self.rightBtn) box.addLayout(midHBox) box.addWidget(closeBtn) self.setLayout(box)
smarsland/AviaNZ
[ 21, 10, 21, 24, 1462012622 ]
def moveRight(self): self.currpage = self.currpage + 1 self.leftBtn.setEnabled(True) if self.currpage==len(self.annots1): self.rightBtn.setEnabled(False) self.setData()
smarsland/AviaNZ
[ 21, 10, 21, 24, 1462012622 ]
def setColourLevels(self, brightness, contrast): """ Listener for the brightness and contrast sliders being changed. Also called when spectrograms are loaded, etc. Translates the brightness and contrast values into appropriate image levels. Calculation is simple. """ try: self.stopPlayback() except Exception: pass if not self.cmapInverted: brightness = 100-brightness colRange = colourMaps.getColourRange(self.sgMinimum, self.sgMaximum, brightness, contrast, self.cmapInverted) self.plot1.setLevels(colRange) self.plot2.setLevels(colRange)
smarsland/AviaNZ
[ 21, 10, 21, 24, 1462012622 ]
def traverse_ds_store_file(d): """ Traverse a DSStore object from the node and yeld each entry. :param d: DSStore object :return: None """ node = d._rootnode with d._get_block(node) as block: next_node, count = block.read(b'>II') if next_node: for n in range(count): ptr = block.read(b'>I')[0] for e in d._traverse(ptr): yield e e = DSStoreEntry.read(block) yield e for e in d._traverse(next_node): yield e else: for n in range(count): e = DSStoreEntry.read(block) yield e
j4v/DS_Store-Scanner
[ 3, 2, 3, 1, 1502267843 ]
def registerExtenderCallbacks(self, callbacks): """ Implement IBurpExtender :param callbacks: :return: """ # Callbacks object self._callbacks = callbacks # Set extension name callbacks.setExtensionName(".DS_Store Scanner") self._callbacks.registerScannerCheck(self) self._callbacks.registerExtensionStateListener(self) # Helpers object self._helpers = callbacks.getHelpers() return
j4v/DS_Store-Scanner
[ 3, 2, 3, 1, 1502267843 ]
def doActiveScan(self): """ Just so the scanner doesn't return a "method not implemented error" :return: None """ return None
j4v/DS_Store-Scanner
[ 3, 2, 3, 1, 1502267843 ]
def consolidateDuplicateIssues(self, existingIssue, newIssue): if existingIssue.getUrl() == newIssue.getUrl() and \ existingIssue.getIssueDetail() == newIssue.getIssueDetail(): return -1 else: return 0
j4v/DS_Store-Scanner
[ 3, 2, 3, 1, 1502267843 ]
def __init__(self, httpservice, url, name, severity, detailmsg, remediationmsg): self._url = url self._httpservice = httpservice self._name = name self._severity = severity self._detailmsg = detailmsg self._remediationmsg = remediationmsg
j4v/DS_Store-Scanner
[ 3, 2, 3, 1, 1502267843 ]
def getHttpMessages(self): return None
j4v/DS_Store-Scanner
[ 3, 2, 3, 1, 1502267843 ]
def getRemediationDetail(self): return None
j4v/DS_Store-Scanner
[ 3, 2, 3, 1, 1502267843 ]
def getIssueBackground(self): return None
j4v/DS_Store-Scanner
[ 3, 2, 3, 1, 1502267843 ]
def getIssueType(self): return 0
j4v/DS_Store-Scanner
[ 3, 2, 3, 1, 1502267843 ]
def getSeverity(self): return self._severity
j4v/DS_Store-Scanner
[ 3, 2, 3, 1, 1502267843 ]
def __init__( self, id_, login, ratings={}, avatar=None, country=None, clan=None, league=None, **kwargs
FAForever/client
[ 72, 87, 72, 101, 1411532757 ]
def id_key(self): return self.id
FAForever/client
[ 72, 87, 72, 101, 1411532757 ]
def update(self, **kwargs): _transaction = kwargs.pop("_transaction") old_data = self.copy() ModelItem.update(self, **kwargs) self.emit_update(old_data, _transaction)
FAForever/client
[ 72, 87, 72, 101, 1411532757 ]
def global_estimate(self): return self.rating_estimate()
FAForever/client
[ 72, 87, 72, 101, 1411532757 ]
def ladder_estimate(self): return self.rating_estimate(RatingType.LADDER.value)
FAForever/client
[ 72, 87, 72, 101, 1411532757 ]
def global_rating_mean(self): return self.rating_mean()
FAForever/client
[ 72, 87, 72, 101, 1411532757 ]
def global_rating_deviation(self): return self.rating_deviation()
FAForever/client
[ 72, 87, 72, 101, 1411532757 ]
def ladder_rating_mean(self): return self.rating_mean(RatingType.LADDER.value)
FAForever/client
[ 72, 87, 72, 101, 1411532757 ]
def ladder_rating_deviation(self): return self.rating_deviation(RatingType.LADDER.value)
FAForever/client
[ 72, 87, 72, 101, 1411532757 ]
def number_of_games(self): count = 0 for rating_type in self.ratings: count += self.ratings[rating_type].get("number_of_games", 0) return count
FAForever/client
[ 72, 87, 72, 101, 1411532757 ]
def rating_mean(self, rating_type=RatingType.GLOBAL.value): try: return round(self.ratings[rating_type]["rating"][0]) except (KeyError, IndexError): return 1500
FAForever/client
[ 72, 87, 72, 101, 1411532757 ]
def game_count(self, rating_type=RatingType.GLOBAL.value): try: return int(self.ratings[rating_type]["number_of_games"]) except KeyError: return 0
FAForever/client
[ 72, 87, 72, 101, 1411532757 ]
def __str__(self): return ( "Player(id={}, login={}, global_rating={}, ladder_rating={})" ).format( self.id, self.login, (self.global_rating_mean, self.global_rating_deviation), (self.ladder_rating_mean, self.ladder_rating_deviation), )
FAForever/client
[ 72, 87, 72, 101, 1411532757 ]
def currentGame(self): return self._currentGame
FAForever/client
[ 72, 87, 72, 101, 1411532757 ]
def set_currentGame(self, game, _transaction=None): if self.currentGame == game: return old = self._currentGame self._currentGame = game _transaction.emit(self.newCurrentGame, self, game, old)
FAForever/client
[ 72, 87, 72, 101, 1411532757 ]
def lognormalize(x): return np.exp(x - np.logaddexp.reduce(x))
dtrckd/pymake
[ 11, 4, 11, 3, 1482371496 ]
def categorical(params): return np.where(np.random.multinomial(1, params) == 1)[0]
dtrckd/pymake
[ 11, 4, 11, 3, 1482371496 ]
def random_powerlaw(alpha, x_min, size=1): ### Discrete alpha = float(alpha) u = np.random.random(size) x = (x_min-0.5)*(1-u)**(-1/(alpha-1))+0.5 return np.floor(x)
dtrckd/pymake
[ 11, 4, 11, 3, 1482371496 ]
def gem(gmma, K): sb = np.empty(K) cut = np.random.beta(1, gmma, size=K) for k in range(K): sb[k] = cut[k] * cut[0:k].prod() return sb
dtrckd/pymake
[ 11, 4, 11, 3, 1482371496 ]
def wmean(a, w, mean='geometric'): if mean == 'geometric': kernel = lambda x : np.log(x) out = lambda x : np.exp(x) elif mean == 'arithmetic': kernel = lambda x : x out = lambda x : x elif mean == 'harmonic': num = np.sum(w) denom = np.sum(np.asarray(w) / np.asarray(a)) return num / denom else: raise NotImplementedError('Mean Unknwow: %s' % mean) num = np.sum(np.asarray(w) * kernel(np.asarray(a))) denom = np.sum(np.asarray(w)) return out(num / denom)
dtrckd/pymake
[ 11, 4, 11, 3, 1482371496 ]
def draw_square(mat, value, topleft, l, L, w=0): tl = topleft # Vertical draw mat[tl[0]:tl[0]+l, tl[1]:tl[1]+w] = value mat[tl[0]:tl[0]+l, tl[1]+L-w:tl[1]+L] = value # Horizontal draw mat[tl[0]:tl[0]+w, tl[1]:tl[1]+L] = value mat[tl[0]+l-w:tl[0]+l, tl[1]:tl[1]+L] = value return mat
dtrckd/pymake
[ 11, 4, 11, 3, 1482371496 ]
def sorted_perm(a, label=None, reverse=False): """ return sorted $a and the induced permutation. Inplace operation """ # np.asarray applied this tuple lead to error, if label is string # because a should be used as elementwise comparison if label is None: label = np.arange(a.shape[0]) hist, label = zip(*sorted(zip(a, label), reverse=reverse)) hist = np.asarray(hist) label = np.asarray(label) return hist, label
dtrckd/pymake
[ 11, 4, 11, 3, 1482371496 ]
def clusters_hist(clusters, labels=None, remove_empty=True): """ return non empty clusters histogramm sorted. parameters --------- clusters: np.array array of clusters membership of data. returns ------- hist: np.array count of element by clusters (decrasing hist) label: np.array label of the cluster aligned with hist """ block_hist = np.bincount(clusters) if labels is None: labels = range(len(block_hist)) hist, labels = sorted_perm(block_hist, labels, reverse=True) if remove_empty is True: null_classes = (hist == 0).sum() if null_classes > 0: hist = hist[:-null_classes]; labels = labels[:-null_classes] return hist, labels
dtrckd/pymake
[ 11, 4, 11, 3, 1482371496 ]
def degree_hist(_degree, filter_zeros=False): if isinstance(_degree, np.ndarray) and _degree.ndim == 2 : degree = list(dict(adj_to_degree(_degree)).values()) elif isinstance(_degree, (list, np.ndarray)): degree = _degree else: # networkx degree = list(dict(_degree).values()) max_c = np.max(degree) d = np.arange(max_c+1) dc = np.bincount(degree, minlength=max_c+1) if len(d) == 0: return [], [] if dc[0] > 0: lgg.debug('%d unconnected vertex' % dc[0]) d = d[1:] dc = dc[1:] if filter_zeros is True: #d, dc = zip(*filter(lambda x:x[1] != 0, zip(d, dc))) nzv = (dc != 0) d = d[nzv] dc = dc[nzv] return d, dc
dtrckd/pymake
[ 11, 4, 11, 3, 1482371496 ]
def reorder_mat(y, clusters, labels=False, reverse=True): """Reorder the matrix according the clusters membership @Debug: square matrix """ assert(y.shape[0] == y.shape[1] == len(clusters)) if reverse is True: hist, label = clusters_hist(clusters) sorted_clusters = np.empty_like(clusters) for i, k in enumerate(label): if i != k: sorted_clusters[clusters == k] = i else: sorted_clusters = clusters N = y.shape[0] nodelist = [k[0] for k in sorted(zip(range(N), sorted_clusters), key=lambda k: k[1])] y_r = y[nodelist, :][:, nodelist] if labels is True: return y_r, nodelist else: return y_r
dtrckd/pymake
[ 11, 4, 11, 3, 1482371496 ]
def floatRgb(mag, cmin, cmax): """ Return a tuple of floats between 0 and 1 for the red, green and blue amplitudes. """ try: # normalize to [0,1] x = float(mag-cmin)/float(cmax-cmin) except: # cmax = cmin x = 0.5 blue = min((max((4*(0.75-x), 0.)), 1.)) red = min((max((4*(x-0.25), 0.)), 1.)) green= min((max((4*math.fabs(x-0.5)-1., 0.)), 1.)) return (red, green, blue)
dtrckd/pymake
[ 11, 4, 11, 3, 1482371496 ]
def rgb(mag, cmin, cmax): """ Return a tuple of integers to be used in AWT/Java plots. """ red, green, blue = floatRgb(mag, cmin, cmax) return (int(red*255), int(green*255), int(blue*255))
dtrckd/pymake
[ 11, 4, 11, 3, 1482371496 ]
def __init__(self, data, cache): self.data = data self.cache = cache
jonian/kickoff-player
[ 40, 10, 40, 3, 1473685315 ]
def get_channels_pages(self): data = self.get('channels') items = ['channels'] if data is not None: for page in data.xpath('//div[@id="system"]//div[@class="pagination"]//a[@class=""]'): items.append(page.get('href')) return items
jonian/kickoff-player
[ 40, 10, 40, 3, 1473685315 ]