function stringlengths 11 56k | repo_name stringlengths 5 60 | features list |
|---|---|---|
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
... | 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, 'curren... | 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
... | 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.play... | 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': playl... | 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... | 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 = r... | 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] == "&#":
... | 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')
... | 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("á","á")
string = string.replace("é","é")
string = string.replace("í","í")
string = string.replace("ó","ó")
... | 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")
t... | 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(sh... | 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().starts... | 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]
... | 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'
... | 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._fi... | 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,
... | 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")
se... | 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_tim... | 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 = ... | 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 = b... | 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.Win... | 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)
# l... | 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... | 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 s... | 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]
... | 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 ... | 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.WindowCloseBut... | 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... | 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.WindowClose... | 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:
... | 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... | 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.... | 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.a... | 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])
... | 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 clu... | 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())
... | 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... | 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= mi... | 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
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.