code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
N = len(power) coh = np.zeros(np.shape(cross)) for i in range(N): for j in range(N): coh[i, j] = cross[i, j] / np.sqrt(power[i] * power[j]) assert(len(freq) == len(coh[0, 0])) return freq, coh
def coherence(freq, power, cross)
Calculate frequency resolved coherence for given power- and crossspectra. Parameters ---------- freq : numpy.ndarray Frequencies, 1 dim array. power : numpy.ndarray Power spectra, 1st axis units, 2nd axis frequencies. cross : numpy.ndarray, Cross spectra, 1st axis units, 2...
2.449261
2.522563
0.970941
mu = mean(data, time=True) var = variance(data, time=True) cv = np.sqrt(var) / mu if units is True: return np.mean(cv) else: return cv
def cv(data, units=False)
Calculate coefficient of variation (cv) of data. Mean and standard deviation are computed across time. Parameters ---------- data : numpy.ndarray 1st axis unit, 2nd axis time. units : bool Average `cv`. Returns ------- numpy.ndarray If units=False, series of u...
4.118793
4.636012
0.888435
mu = mean(data, time=True) var = variance(data, time=True) ff = var / mu if units is True: return np.mean(ff) else: return ff
def fano(data, units=False)
Calculate fano factor (FF) of data. Mean and variance are computed across time. Parameters ---------- data : numpy.ndarray 1st axis unit, 2nd axis time. units : bool Average `FF`. Returns ------- numpy.ndarray If units=False, series of unit FFs. float ...
4.483614
5.320552
0.842697
# Resync COMM.Barrier() # Raise Exception if there are no gdf files to be read if len(glob.glob(os.path.join(self.spike_output_path, self.label + '*.'+ self.ext))) == 0: raise Exception('path to files contain no gdf-files!') ...
def collect_gdf(self)
Collect the gdf-files from network sim in folder `spike_output_path` into sqlite database, using the GDF-class. Parameters ---------- None Returns ------- None
7.379362
6.04379
1.220982
x = {} y = {} for X, nodes in self.nodes.items(): x[X] = np.array([]) y[X] = np.array([]) if fraction != 1: nodes = np.random.permutation(nodes)[:int(nodes.size*fraction)] nodes.sort() spiketimes = self.d...
def get_xy(self, xlim, fraction=1.)
Get pairs of node units and spike trains on specific time interval. Parameters ---------- xlim : list of floats Spike time interval, e.g., [0., 1000.]. fraction : float in [0, 1.] If less than one, sample a fraction of nodes in random order. ...
3.506001
3.19847
1.09615
yoffset = [sum(self.N_X) if X=='TC' else 0 for X in self.X] for i, X in enumerate(self.X): if y[X].size > 0: ax.plot(x[X], y[X]+yoffset[i], marker, markersize=markersize, mfc=self.colors[i], mec='none' if ma...
def plot_raster(self, ax, xlim, x, y, pop_names=False, markersize=20., alpha=1., legend=True, marker='o', rasterized=True)
Plot network raster plot in subplot object. Parameters ---------- ax : `matplotlib.axes.AxesSubplot` object plot axes xlim : list List of floats. Spike time interval, e.g., [0., 1000.]. x : dict Key-value entries are populatio...
3.009789
3.018646
0.997066
bins = np.arange(xlim[0], xlim[1]+binsize, binsize) (hist, bins) = np.histogram(x[X], bins=bins) if plottype == 'fill_between': ax.fill_between(bins[:-1], hist * 1000. / self.N_X[i], color=self.colors[i], lw=0.5, label=X, rasterized=rast...
def plot_f_rate(self, ax, X, i, xlim, x, y, binsize=1, yscale='linear', plottype='fill_between', show_label=False, rasterized=False)
Plot network firing rate plot in subplot object. Parameters ---------- ax : `matplotlib.axes.AxesSubplot` object. X : str Population name. i : int Population index in class attribute `X`. xlim : list of floats Spike ti...
2.36185
2.363317
0.99938
x, y = self.get_xy(xlim) fig = plt.figure() fig.subplots_adjust(left=0.12, hspace=0.15) ax0 = fig.add_subplot(211) self.plot_raster(ax0, xlim, x, y, markersize=markersize, alpha=alpha, marker=marker) remove_axis_junk(ax0) ax0.s...
def raster_plots(self, xlim=[0, 1000], markersize=1, alpha=1., marker='o')
Pretty plot of the spiking output of each population as raster and rate. Parameters ---------- xlim : list List of floats. Spike time interval, e.g., `[0., 1000.]`. markersize : float marker size for plot, see `matplotlib.pyplot.plot` alp...
3.345126
3.490085
0.958466
''' suitable for plotting fraction of neurons ''' plt.sca(ax) N = len(sst) current_ymax = 0 counter = 0 while True: if len(ax.get_lines()) !=0: data = ax.get_lines()[-1-counter].get_data()[1] if np.sum(data) != 0: # if not empty array curr...
def add_sst_to_dot_display(ax, sst, color= '0.',alpha= 1.)
suitable for plotting fraction of neurons
4.385602
3.823355
1.147056
''' Delete all axis ticks and labels ''' plt.sca(ax) plt.setp(plt.gca(),xticks=[],xticklabels=[]) return ax
def empty_bar_plot(ax)
Delete all axis ticks and labels
7.824412
6.412655
1.220152
''' This function takes an axes and adds one bar to it ''' plt.sca(ax) plt.setp(ax,xticks=np.append(ax.get_xticks(),np.array([x]))\ ,xticklabels=[item.get_text() for item in ax.get_xticklabels()] +[name]) plt.bar([x],number , color = color, width = 1.) return ax
def add_to_bar_plot(ax, x, number, name = '', color = '0.')
This function takes an axes and adds one bar to it
4.921262
4.169933
1.180178
''' This function takes an axes and adds one line to it ''' plt.sca(ax) plt.plot(x,y, color = color, label = label) return ax
def add_to_line_plot(ax, x, y, color = '0.' , label = '')
This function takes an axes and adds one line to it
4.772582
3.224761
1.47998
''' draw colorbar without resizing the axes object to make room kwargs: :: fig : matplotlib.figure.Figure ax : matplotlib.axes.AxesSubplot im : matplotlib.image.AxesImage width : float, colorbar width in fraction of ax width height : float, colorbar height in fra...
def colorbar(fig, ax, im, width=0.05, height=1.0, hoffset=0.01, voffset=0.0, orientation='vertical')
draw colorbar without resizing the axes object to make room kwargs: :: fig : matplotlib.figure.Figure ax : matplotlib.axes.AxesSubplot im : matplotlib.image.AxesImage width : float, colorbar width in fraction of ax width height : float, colorbar height in fraction of ax ...
2.624429
1.550094
1.693077
''' Figure styles for frontiers ''' inchpercm = 2.54 frontierswidth=8.5 textsize = 5 titlesize = 7 plt.rcdefaults() plt.rcParams.update({ 'figure.figsize' : [frontierswidth/inchpercm, frontierswidth/inchpercm], 'figure.dpi' : 160, 'xtick.labelsize' : tex...
def frontiers_style()
Figure styles for frontiers
2.706309
2.587788
1.0458
'''add a subplot annotation number''' ax.text(-ncols*linear_offset, 1+nrows*linear_offset, letter, horizontalalignment='center', verticalalignment='center', fontsize=fontsize, fontweight='demibold', transform=ax.transAxes)
def annotate_subplot(ax, ncols=1, nrows=1, letter='a', linear_offset=0.075, fontsize=8)
add a subplot annotation number
4.220951
3.26543
1.292617
'''return a list of color tuples to use in plots''' colors = [] for i in xrange(num): if analysis_params.bw: colors.append('k' if i % 2 == 0 else 'gray') else: i *= 256. if num > 1: i /= num - 1. else: i /= num ...
def get_colors(num=16, cmap=plt.cm.Set1)
return a list of color tuples to use in plots
4.897958
4.440086
1.103122
if windowLength == None: windowLength = self.defaultWindowLength compressed = "" pos = 0 lastPos = len(data) - self.minStringLength while pos < lastPos: searchStart = max(pos - windowLength, 0); matchLength = self.minStringLength foundMatch = False bestMatchDistance = self.maxStringDista...
def compress(self, data, windowLength = None)
Compresses text data using the LZ77 algorithm.
2.697989
2.644747
1.020131
decompressed = "" pos = 0 while pos < len(data): currentChar = data[pos] if currentChar != self.referencePrefix: decompressed += currentChar pos += 1 else: nextChar = data[pos + 1] if nextChar != self.referencePrefix: distance = self.__decodeReferenceInt(data[pos + 1 : pos + 3], ...
def decompress(self, data)
Decompresses LZ77 compressed text data
2.643148
2.668026
0.990676
# Parse arguments parser = argparse.ArgumentParser(description="Convert rational numbers between bases.") parser.add_argument("-n", "--number", default=None, help="The number to convert as a string, else stdin used.") parser.add_argument("-i", "--input-base", default=10, ...
def main()
Main entry point for running baseconvert as a command. Examples: $ python -m baseconvert -n 0.5 -i 10 -o 20 -s True 0.A $ echo 3.1415926 | python -m baseconvert -i 10 -o 16 -d 3 -s True 3.243
2.151796
2.07669
1.036166
jid = '%s@%s' % (username, domain) if self.api_version <= (14, 7): # TODO: it's unclear when send_message was introduced command = 'send_message_chat' args = domain, '%s@%s' % (username, domain), message else: command = 'send_message' ...
def message_user(self, username, domain, subject, message)
Currently use send_message_chat and discard subject, because headline messages are not stored by mod_offline.
4.908258
4.635955
1.058737
value = int(value) with self.lock: self.value += value
def notify(self, value)
Increment or decrement the value, according to the given value's sign The value should be an integer, an attempt to cast it to integer will be made
6.946874
6.328378
1.097734
if not self._config: namespace = {} if os.path.exists(self.config_path): execfile(self.config_path, namespace) self._config = namespace.get('config') or Configuration() return self._config
def get_config(self)
Load user configuration or return default when not found. :rtype: :class:`Configuration`
3.650171
3.117698
1.17079
# Prepare the watch to receive something. cookie = self._prepare() # Send it. self._send_object(cookie) # Commit it. self._commit(cookie) # Install it. self._install(cookie)
def send(self)
Sends the object to the watch. Block until completion, or raises :exc:`.PutBytesError` on failure. During transmission, a "progress" event will be periodically emitted with the following signature: :: (sent_this_interval, sent_so_far, total_object_size)
9.957998
9.196873
1.082759
shell = dict() shell['rsp:InputStreams'] = " ".join(input_streams) shell['rsp:OutputStreams'] = " ".join(output_streams) shell['rsp:IdleTimeout'] = str(self.idle_timeout) if self.working_directory is not None: shell['rsp:WorkingDirectory'] = str(self.working...
def open(self, input_streams=['stdin'], output_streams=['stderr', 'stdout'])
Opens the remote shell
2.941532
2.871502
1.024388
logging.info('running command: ' + command) resource = ResourceLocator(CommandShell.ShellResource) resource.add_selector('ShellId', self.__shell_id) resource.add_option('WINRS_SKIP_CMD_SHELL', ['FALSE', 'TRUE'][bool(skip_cmd_shell)], True) resource.add_option('WINRS_CONS...
def run(self, command, arguments=(), console_mode_stdin=True, skip_cmd_shell=False)
This function does something. :param command: The command to be executed :type name: str. :param arguments: A list of arguments to be passed to the command :type state: str. :returns: int -- the return code. :raises: AttributeError, KeyError iclegg: blocking i/o...
4.322331
4.743145
0.91128
logging.info('receive command: ' + command_id) response_streams = dict.fromkeys(streams, '') (complete, exit_code) = self._receive_poll(command_id, response_streams) while not complete: (complete, exit_code) = self._receive_poll(command_id, response_streams) ...
def receive(self, command_id, streams=('stdout', 'stderr'), command_timeout=60)
Recieves data :param command_id: :param streams: :param command_timeout: :return:
3.523349
3.65011
0.965272
logging.info('receive command: ' + command_id) resource = ResourceLocator(CommandShell.ShellResource) resource.add_selector('ShellId', self.__shell_id) stream_attributes = {'#text': " ".join(response_streams.keys()), '@CommandId': command_id} receive = {'rsp:Receive': {...
def _receive_poll(self, command_id, response_streams)
Recieves data :param command_id: :param streams: :return:
4.877045
4.89837
0.995647
resource = ResourceLocator(CommandShell.ShellResource) resource.add_selector('ShellId', self.__shell_id) self.session.delete(resource)
def close(self)
Closes pipe :return:
19.938454
22.907526
0.870389
keys = data_dict.keys() dummy_dict = copy.deepcopy(data_dict) changed_dict = {} for key in keys: changed_dict[prefix + str(key)] = dummy_dict.pop(key) return changed_dict
def change_dict_keys(self, data_dict, prefix)
Prefixes 'L_'/'R_' to the collection keys :param data_dict: dictionary which is to be altered :type data_dict: dict :param prefix: prefix to be attached before every key :type prefix: string :return dict_: dict
2.770111
3.064026
0.904075
joined_docs = [] if (len(left_collection_list) != 0) and (len(right_collection_list) != 0): for left_doc in left_collection_list: for right_doc in right_collection_list: l_dict = self.change_dict_keys(left_doc, 'L_') r_dict = ...
def generate_join_docs_list(self, left_collection_list, right_collection_list)
Helper function for merge_join_docs :param left_collection_list: Left Collection to be joined :type left_collection_list: MongoCollection :param right_collection_list: Right Collection to be joined :type right_collection_list: MongoCollection :return joine...
1.660418
1.715396
0.967951
join = defaultdict(list) for key in keys: join[key] = self.generate_join_docs_list( self.collections_data['left'].get(key, []), self.collections_data['right'].get(key, [])) return join
def merge_join_docs(self, keys)
Merges the final list of docs :param left_collection_list: :type left_collection_list: MongoCollection :return join: dict
4.948032
4.687708
1.055533
self.get_collections_data() inner_join = self.merge_join_docs(set(self.collections_data['left'].keys()) & set( self.collections_data['right'].keys())) return inner_join
def inner(self)
Performs Inner Join :return inner_join: dict
8.747496
5.99065
1.460191
self.get_collections_data() left_outer_join = self.merge_join_docs( set(self.collections_data['left'].keys())) return left_outer_join
def left_outer(self)
Performs Left Outer Join :return left_outer: dict
10.067746
8.272602
1.216999
self.get_collections_data() right_outer_join = self.merge_join_docs( set(self.collections_data['right'].keys())) return right_outer_join
def right_outer(self)
Performs Right Outer Join :return right_outer: dict
10.025427
8.210354
1.221071
self.get_collections_data() full_outer_join = self.merge_join_docs( set(self.collections_data['left'].keys()) | set(self.collections_data['right'].keys())) return full_outer_join
def full_outer(self)
Performs Full Outer Join :return full_outer: dict
5.922093
5.010704
1.181888
@functools.wraps(meth) def wrapped(*args, **kwargs): if not args[0].authorized: raise exceptions.NotAuthorizedError('Please login first!') return meth(*args, **kwargs) return wrapped
def needs_auth(meth)
Wraps a method of :class:`TwitchSession` and raises an :class:`exceptions.NotAuthorizedError` if before calling the method, the session isn't authorized. :param meth: :type meth: :returns: the wrapped method :rtype: Method :raises: None
2.62959
2.591901
1.014541
if oauthlib.oauth2.is_secure_transport(url): m = super(OAuthSession, self).request else: m = super(requests_oauthlib.OAuth2Session, self).request log.debug("%s \"%s\" with %s", method, url, kwargs) response = m(method, url, **kwargs) response.rais...
def request(self, method, url, **kwargs)
Constructs a :class:`requests.Request`, prepares it and sends it. Raises HTTPErrors by default. :param method: method for the new :class:`Request` object. :type method: :class:`str` :param url: URL for the new :class:`Request` object. :type url: :class:`str` :param kwarg...
3.750721
4.384225
0.855504
self.login_server = oauth.LoginServer(session=self) target = self.login_server.serve_forever self.login_thread = threading.Thread(target=target) self.login_thread.setDaemon(True) log.debug('Starting login server thread.') self.login_thread.start()
def start_login_server(self, )
Start a server that will get a request from a user logging in. This uses the Implicit Grant Flow of OAuth2. The user is asked to login to twitch and grant PyTwitcher authorization. Once the user agrees, he is redirected to an url. This server will respond to that url and get the oauth t...
3.417308
3.628357
0.941833
log.debug('Shutting down the login server thread.') self.login_server.shutdown() self.login_server.server_close() self.login_thread.join()
def shutdown_login_server(self, )
Shutdown the login server and thread :returns: None :rtype: None :raises: None
3.531793
3.846605
0.918159
self._token = token if token: self.current_user = self.query_login_user()
def token(self, token)
Set the oauth token and the current_user :param token: the oauth token :type token: :class:`dict` :returns: None :rtype: None :raises: None
8.025577
7.162239
1.12054
url = TWITCH_KRAKENURL + endpoint headers = kwargs.setdefault('headers', {}) headers['Accept'] = TWITCH_HEADER_ACCEPT headers['Client-ID'] = CLIENT_ID # https://github.com/justintv/Twitch-API#rate-limits return self.request(method, url, **kwargs)
def kraken_request(self, method, endpoint, **kwargs)
Make a request to one of the kraken api endpoints. Headers are automatically set to accept :data:`TWITCH_HEADER_ACCEPT`. Also the client id from :data:`CLIENT_ID` will be set. The url will be constructed of :data:`TWITCH_KRAKENURL` and the given endpoint. :param method: the req...
3.638948
2.744539
1.325887
url = TWITCH_USHERURL + endpoint return self.request(method, url, **kwargs)
def usher_request(self, method, endpoint, **kwargs)
Make a request to one of the usher api endpoints. The url will be constructed of :data:`TWITCH_USHERURL` and the given endpoint. :param method: the request method :type method: :class:`str` :param endpoint: the endpoint of the usher api. The base url is...
7.764938
4.715384
1.646725
headers = kwargs.setdefault('headers', {}) headers['Client-ID'] = CLIENT_ID # https://github.com/justintv/Twitch-API#rate-limits url = TWITCH_APIURL + endpoint return self.request(method, url, **kwargs)
def oldapi_request(self, method, endpoint, **kwargs)
Make a request to one of the old api endpoints. The url will be constructed of :data:`TWITCH_APIURL` and the given endpoint. :param method: the request method :type method: :class:`str` :param endpoint: the endpoint of the old api. The base url is autom...
3.802798
3.521194
1.079974
r = self.kraken_request('GET', 'streams/summary', params={'game': game.name}).json() game.viewers = r['viewers'] game.channels = r['channels'] return game
def fetch_viewers(self, game)
Query the viewers and channels of the given game and set them on the object :returns: the given game :rtype: :class:`models.Game` :raises: None
6.213282
5.452932
1.139439
r = self.kraken_request('GET', 'search/games', params={'query': query, 'type': 'suggest', 'live': live}) games = models.Game.wrap_search(r) for g in games: self.fe...
def search_games(self, query, live=True)
Search for games that are similar to the query :param query: the query string :type query: :class:`str` :param live: If true, only returns games that are live on at least one channel :type live: :class:`bool` :returns: A list of games :rtype: :class:...
5.516714
5.758042
0.958088
r = self.kraken_request('GET', 'games/top', params={'limit': limit, 'offset': offset}) return models.Game.wrap_topgames(r)
def top_games(self, limit=10, offset=0)
Return the current top games :param limit: the maximum amount of top games to query :type limit: :class:`int` :param offset: the offset in the top games :type offset: :class:`int` :returns: a list of top games :rtype: :class:`list` of :class:`models.Game` :raises...
6.622632
7.064692
0.937427
games = self.search_games(query=name, live=False) for g in games: if g.name == name: return g
def get_game(self, name)
Get the game instance for a game name :param name: the name of the game :type name: :class:`str` :returns: the game instance :rtype: :class:`models.Game` | None :raises: None
4.984153
7.070032
0.704969
r = self.kraken_request('GET', 'channels/' + name) return models.Channel.wrap_get_channel(r)
def get_channel(self, name)
Return the channel for the given name :param name: the channel name :type name: :class:`str` :returns: the model instance :rtype: :class:`models.Channel` :raises: None
10.280701
11.06635
0.929006
r = self.kraken_request('GET', 'search/channels', params={'query': query, 'limit': limit, 'offset': offset}) return models.Channel.wrap_search(r)
def search_channels(self, query, limit=25, offset=0)
Search for channels and return them :param query: the query string :type query: :class:`str` :param limit: maximum number of results :type limit: :class:`int` :param offset: offset for pagination :type offset: :class:`int` :returns: A list of channels :rt...
4.844533
5.397323
0.897581
if isinstance(channel, models.Channel): channel = channel.name r = self.kraken_request('GET', 'streams/' + channel) return models.Stream.wrap_get_stream(r)
def get_stream(self, channel)
Return the stream of the given channel :param channel: the channel that is broadcasting. Either name or models.Channel instance :type channel: :class:`str` | :class:`models.Channel` :returns: the stream or None, if the channel is offline :rtype: :class:`models.St...
6.581965
6.074293
1.083577
if isinstance(game, models.Game): game = game.name channelnames = [] cparam = None if channels: for c in channels: if isinstance(c, models.Channel): c = c.name channelnames.append(c) cparam ...
def get_streams(self, game=None, channels=None, limit=25, offset=0)
Return a list of streams queried by a number of parameters sorted by number of viewers descending :param game: the game or name of the game :type game: :class:`str` | :class:`models.Game` :param channels: list of models.Channels or channel names (can be mixed) :type channels: :c...
3.051919
3.00385
1.016002
r = self.kraken_request('GET', 'search/streams', params={'query': query, 'hls': hls, 'limit': limit, 'offset': offset}) return models.Stream.wr...
def search_streams(self, query, hls=False, limit=25, offset=0)
Search for streams and return them :param query: the query string :type query: :class:`str` :param hls: If true, only return streams that have hls stream :type hls: :class:`bool` :param limit: maximum number of results :type limit: :class:`int` :param offset: off...
4.178667
4.481748
0.932374
r = self.kraken_request('GET', 'streams/followed', params={'limit': limit, 'offset': offset}) return models.Stream.wrap_search(r)
def followed_streams(self, limit=25, offset=0)
Return the streams the current user follows. Needs authorization ``user_read``. :param limit: maximum number of results :type limit: :class:`int` :param offset: offset for pagination :type offset: :class:`int` :returns: A list of streams :rtype: :class:`list`of ...
6.178959
7.006773
0.881855
r = self.kraken_request('GET', 'user/' + name) return models.User.wrap_get_user(r)
def get_user(self, name)
Get the user for the given name :param name: The username :type name: :class:`str` :returns: the user instance :rtype: :class:`models.User` :raises: None
10.368141
10.419996
0.995024
if isinstance(channel, models.Channel): channel = channel.name token, sig = self.get_channel_access_token(channel) params = {'token': token, 'sig': sig, 'allow_audio_only': True, 'allow_source': True} r = self.usher_request( ...
def get_playlist(self, channel)
Return the playlist for the given channel :param channel: the channel :type channel: :class:`models.Channel` | :class:`str` :returns: the playlist :rtype: :class:`m3u8.M3U8` :raises: :class:`requests.HTTPError` if channel is offline.
4.114803
3.688247
1.115653
optionmap = {'chunked': 'source', 'high': 'high', 'medium': 'medium', 'low': 'low', 'mobile': 'mobile', 'audio_only': 'audio'} p = self.get_playlist(channel) options = [] for...
def get_quality_options(self, channel)
Get the available quality options for streams of the given channel Possible values in the list: * source * high * medium * low * mobile * audio :param channel: the channel or channel name :type channel: :class:`models.Channel` | :cla...
4.527193
3.890526
1.163645
if isinstance(channel, models.Channel): channel = channel.name r = self.oldapi_request( 'GET', 'channels/%s/access_token' % channel).json() return r['token'], r['sig']
def get_channel_access_token(self, channel)
Return the token and sig for the given channel :param channel: the channel or channel name to get the access token for :type channel: :class:`channel` | :class:`str` :returns: The token and sig for the given channel :rtype: (:class:`unicode`, :class:`unicode`) :raises: None
5.515802
4.629211
1.191521
r = self.oldapi_request( 'GET', 'channels/%s/chat_properties' % channel.name) json = r.json() servers = json['chat_servers'] try: r = self.get(TWITCH_STATUSURL) except requests.HTTPError: log.debug('Error getting chat server status. U...
def get_chat_server(self, channel)
Get an appropriate chat server for the given channel Usually the server is irc.twitch.tv. But because of the delicate twitch chat, they use a lot of servers. Big events are on special event servers. This method tries to find a good one. :param channel: the channel with the chat ...
5.82092
5.426075
1.072768
best = servers[0] # In case we sind no match with any status stats.sort() # gets sorted for performance for stat in stats: for server in servers: if server == stat: # found a chatserver that has the same address # tha...
def _find_best_chat_server(servers, stats)
Find the best from servers by comparing with the stats :param servers: a list if server adresses, e.g. ['0.0.0.0:80'] :type servers: :class:`list` of :class:`str` :param stats: list of server statuses :type stats: :class:`list` of :class:`chat.ChatServerStatus` :returns: the bes...
10.263266
10.011157
1.025183
r = self.get('http://static-cdn.jtvnw.net/emoticons/v1/%s/%s' % (emote.emoteid, size)) return r.content
def get_emote_picture(self, emote, size=1.0)
Return the picture for the given emote :param emote: the emote object :type emote: :class:`pytwitcherapi.chat.message.Emote` :param size: the size of the picture. Choices are: 1.0, 2.0, 3.0 :type size: :class:`float` :returns: A string resembling the picture...
3.304992
3.65089
0.905257
''' Escape `string`, which should be syntactically valid JSON (this is not verified), so that it is safe for inclusion in HTML <script> environments and as literal javascript. ''' for fro, to in replacements: string = string.replace(fro, to) return string
def escapejson(string)
Escape `string`, which should be syntactically valid JSON (this is not verified), so that it is safe for inclusion in HTML <script> environments and as literal javascript.
9.245752
2.475365
3.735106
string = _GLOB_PORTION_RE.sub(split_str, string) return string.strip()
def strip_glob(string, split_str=' ')
Strip glob portion in `string`. >>> strip_glob('*glob*like') 'glob like' >>> strip_glob('glob?') 'glo' >>> strip_glob('glob[seq]') 'glob' >>> strip_glob('glob[!seq]') 'glob' :type string: str :rtype: str
6.681695
13.52739
0.493938
date_interval = Interval(lower=lower, lower_value=start, upper_value=end, upper=upper) current = start if start in date_interval else start + delta while current in date_interval: yield current current = current + delta
def daterange(start, end, delta=timedelta(days=1), lower=Interval.CLOSED, upper=Interval.OPEN)
Returns a generator which creates the next value in the range on demand
3.494831
3.259611
1.072162
tid = self._get_txid() message = self._message_type(transaction_id=tid) tuples = [] for k, v in iteritems(dictionary): if isinstance(v, AppMessageNumber): tuples.append(AppMessageTuple(key=k, type=v.type, data=struct.pa...
def send_message(self, target_app, dictionary)
Send a message to the given app, which should be currently running on the Pebble (unless using a non-standard AppMessage endpoint, in which case its rules apply). AppMessage can only represent flat dictionaries with integer keys; as such, ``dictionary`` must be flat and have integer keys. ...
3.586821
3.122826
1.148582
with LOCK: try: item = REGISTRY[name] except KeyError: item = REGISTRY[name] = class_(*args, **kwargs) return item raise DuplicateMetricError("Metric {} already exists of type {}".format(name, type(item).__name__))
def new_metric(name, class_, *args, **kwargs)
Create a new metric of the given class. Raise DuplicateMetricError if the given name has been already registered before Internal function - use "new_<type> instead"
3.874614
3.229935
1.199595
with LOCK: old_metric = REGISTRY.pop(name, None) # look for the metric name in the tags and remove it for _, tags in py3comp.iteritems(TAGS): if name in tags: tags.remove(name) return old_metric
def delete_metric(name)
Remove the named metric
8.61539
8.234659
1.046235
if reservoir is None: reservoir = histogram.UniformReservoir(histogram.DEFAULT_UNIFORM_RESERVOIR_SIZE) return new_metric(name, histogram.Histogram, reservoir)
def new_histogram(name, reservoir=None)
Build a new histogram metric with a given reservoir object If the reservoir is not provided, a uniform reservoir with the default size is used
4.170587
3.180275
1.311392
reservoir = new_reservoir(reservoir_type, *reservoir_args, **reservoir_kwargs) return new_histogram(name, reservoir)
def new_histogram_with_implicit_reservoir(name, reservoir_type='uniform', *reservoir_args, **reservoir_kwargs)
Build a new histogram metric and a reservoir from the given parameters
1.89238
2.089351
0.905726
try: reservoir_cls = RESERVOIR_TYPES[reservoir_type] except KeyError: raise InvalidMetricError("Unknown reservoir type: {}".format(reservoir_type)) return reservoir_cls(*reservoir_args, **reservoir_kwargs)
def new_reservoir(reservoir_type='uniform', *reservoir_args, **reservoir_kwargs)
Build a new reservoir
2.184004
2.297718
0.95051
reservoir = new_reservoir(reservoir_type, *reservoir_args, **reservoir_kwargs) try: hmetric = new_histogram(name, reservoir) except DuplicateMetricError: hmetric = metric(name) if not isinstance(hmetric, histogram.Histogram): raise DuplicateMetricError( ...
def get_or_create_histogram(name, reservoir_type, *reservoir_args, **reservoir_kwargs)
Will return a histogram matching the given parameters or raise DuplicateMetricError if it can't be created due to a name collision with another histogram with different parameters.
2.497591
2.481489
1.006489
hmetric = get_or_create_histogram(name, reservoir_type, *reservoir_args, **reservoir_kwargs) def wrapper(f): @functools.wraps(f) def fun(*args, **kwargs): t1 = time.time() res = f(*args, **kwargs) t2 = time.time() hmetric.notify(t2-t1) ...
def with_histogram(name, reservoir_type="uniform", *reservoir_args, **reservoir_kwargs)
Time-measuring decorator: the time spent in the wrapped function is measured and added to the named metric. metric_args and metric_kwargs are passed to new_histogram()
2.433967
2.178612
1.11721
try: mmetric = new_meter(name, tick_interval) except DuplicateMetricError as e: mmetric = metric(name) if not isinstance(mmetric, meter.Meter): raise DuplicateMetricError("Metric {!r} already exists of type {}".format(name, type(mmetric).__name__)) if tick_int...
def with_meter(name, tick_interval=meter.DEFAULT_TICK_INTERVAL)
Call-counting decorator: each time the wrapped function is called the named meter is incremented by one. metric_args and metric_kwargs are passed to new_meter()
2.954516
2.730247
1.082142
hmetric = get_or_create_histogram(name, reservoir_type, *reservoir_args, **reservoir_kwargs) t1 = time.time() yield t2 = time.time() hmetric.notify(t2 - t1)
def timer(name, reservoir_type="uniform", *reservoir_args, **reservoir_kwargs)
Time-measuring context manager: the time spent in the wrapped block if measured and added to the named metric.
3.663231
2.950309
1.241643
with LOCK: # just to check if <name> exists metric(name) TAGS.setdefault(tag_name, set()).add(name)
def tag(name, tag_name)
Tag the named metric with the given tag.
13.533929
12.855344
1.052786
with LOCK: by_tag = TAGS.get(tag_name, None) if not by_tag: return False try: by_tag.remove(name) # remove the tag if no associations left if not by_tag: TAGS.pop(tag_name) return True except KeyError...
def untag(name, tag_name)
Remove the given tag from the given metric. Return True if the metric was tagged, False otherwise
3.572398
3.894577
0.917275
results = {} for name in names: # no lock - a metric could have been removed in the meanwhile try: results[name] = get(name) except InvalidMetricError: continue return results
def metrics_by_name_list(names)
Return a dictionary with {metric name: metric value} for all the metrics with the given names.
7.511246
7.318446
1.026344
'''make an imshow of the intranetwork connectivity''' masked_array = np.ma.array(params.C_YX, mask=params.C_YX==0) # if analysis_params.bw: # cmap = plt.get_cmap(gray, 20) # cmap.set_bad('k', 1.) # else: # cmap = plt.get_cmap('hot', 20) # cmap.set_bad('k', 0.5) # im ...
def connectivity(ax)
make an imshow of the intranetwork connectivity
2.671636
2.512243
1.063447
'''make an imshow of the intranetwork connectivity''' masked_array = np.ma.array(params.T_yX, mask=params.T_yX==0) # cmap = plt.get_cmap('hot', 20) # cmap.set_bad('k', 0.5) # im = ax.imshow(masked_array, cmap=cmap, vmin=0, interpolation='nearest') im = ax.pcolormesh(masked_array, cmap=cmap, vmin...
def cell_type_specificity(ax)
make an imshow of the intranetwork connectivity
2.758969
2.555153
1.079767
'''make a bunch of image plots, each showing the spatial normalized connectivity of synapses''' layers = ['L1', 'L2/3', 'L4', 'L5', 'L6'] ncols = len(params.y) / 4 #assess vlims vmin = 0 vmax = 0 for y in params.y: if quantity[y].max() > v...
def quantity_yXL(fig, left, bottom, top, quantity=params.L_yXL, label=r'$\mathcal{L}_{yXL}$')
make a bunch of image plots, each showing the spatial normalized connectivity of synapses
3.032773
2.748883
1.103275
self.last_response = self.session.get(proto + self.base_uri + url, headers=self.headers, cookies=self.cookies, allow_redirects=True, ...
def get(self, url, proto='http')
Load an url using the GET method. Keyword arguments: url -- the Universal Resource Location proto -- the protocol (default 'http')
3.693915
3.893151
0.948824
form = self.translator.fill_form(self.last_response_soup, form_name if form_name else url, data) self.last_response = self.session.post(proto + self.base_uri + url, headers=self.headers, ...
def post(self, url, data, proto='http', form_name=None)
Load an url using the POST method. Keyword arguments: url -- the Universal Resource Location data -- the form to be sent proto -- the protocol (default 'http') form_name -- the form name to search the default values
3.445646
4.158744
0.82853
if use_polling: from watchdog.observers.polling import PollingObserver as Observer Observer # fool pyflakes else: from watchdog.observers import Observer event_handler = RecordHandler(indexer) observer = Observer() observer.schedule(event_handler, path=indexer.record_p...
def watch_record(indexer, use_polling=False)
Start watching `cfstore.record_path`. :type indexer: rash.indexer.Indexer
2.453819
2.583163
0.949928
'''set up simple cell simulation with LFPs in the plane''' # Create cell cell = LFPy.Cell(morphology=morphology, **cell_parameters) # Align cell cell.set_rotation(**cell_rotation) # Define synapse parameters synapse_parameters = { 'idx' : cell.get_closest_idx(**closest_idx), ...
def run_sim(morphology='patdemo/cells/j4a.hoc', cell_rotation=dict(x=4.99, y=-4.33, z=3.14), closest_idx=dict(x=-200., y=0., z=800.))
set up simple cell simulation with LFPs in the plane
4.806626
4.342411
1.106903
occurr += [data['data'][cell_type]['occurrence']] return list(np.array(occurr)/np.sum(occurr))
def get_F_y(fname='binzegger_connectivity_table.json', y=['p23']): ''' Extract frequency of occurrences of those cell types that are modeled. The data set contains cell types that are not modeled (TCs etc.) The returned percentages are renormalized onto modeled cell-types, i.e. they sum up to 1 ''...
Extract frequency of occurrences of those cell types that are modeled. The data set contains cell types that are not modeled (TCs etc.) The returned percentages are renormalized onto modeled cell-types, i.e. they sum up to 1
5.93014
5.324026
1.113845
''' compute the layer specificity, defined as: :: L_yXL = k_yXL / k_yX ''' def _get_L_yXL_per_yXL(fname, x_in_X, X_index, y, layer): # Load data from json dictionary f = open(fname, 'r') data = json.load(f) f.close() ...
def get_L_yXL(fname, y, x_in_X, L)
compute the layer specificity, defined as: :: L_yXL = k_yXL / k_yX
3.13721
2.783329
1.127143
''' compute the cell type specificity, defined as: :: T_yX = K_yX / K_YX = F_y * k_yX / sum_y(F_y*k_yX) ''' def _get_k_yX_mul_F_y(y, y_index, X_index): # Load data from json dictionary f = open(fname, 'r') data = json.load(f) f.close() ...
def get_T_yX(fname, y, y_in_Y, x_in_X, F_y)
compute the cell type specificity, defined as: :: T_yX = K_yX / K_YX = F_y * k_yX / sum_y(F_y*k_yX)
3.469767
2.855422
1.21515
''' Compute the current amplitude corresponding to the exponential synapse model PSP amplitude Derivation using sympy: :: from sympy import * #define symbols t, tm, Cm, ts, Is, Vmax = symbols('t tm Cm ts Is Vmax') ...
def _compute_J(self)
Compute the current amplitude corresponding to the exponential synapse model PSP amplitude Derivation using sympy: :: from sympy import * #define symbols t, tm, Cm, ts, Is, Vmax = symbols('t tm Cm ts Is Vmax') #assume zero del...
5.029516
1.511882
3.326659
''' set up the detailed synaptic delay parameters, loc is mean delay, scale is std with low bound cutoff, assumes numpy.random.normal is used later ''' delays = {} #mean delays loc = np.zeros((len(self.y), len(self.X))) loc[:, 0] = self.del...
def _synDelayParams(self)
set up the detailed synaptic delay parameters, loc is mean delay, scale is std with low bound cutoff, assumes numpy.random.normal is used later
5.168845
2.729146
1.893942
''' return the cortical depth of each subpopulation ''' depths = self.layerBoundaries.mean(axis=1)[1:] depth_y = [] for y in self.y: if y in ['p23', 'b23', 'nb23']: depth_y = np.r_[depth_y, depths[0]] elif y in ['p4', 'ss4(L23)', '...
def _calcDepths(self)
return the cortical depth of each subpopulation
3.570748
3.109955
1.148167
''' Return dict with parameters for each population. The main operation is filling in cell type specific morphology ''' #cell type specific parameters going into LFPy.Cell yCellParams = {} for layer, morpho, _, _ in self.y_zip_list: yCellParams...
def _yCellParams(self)
Return dict with parameters for each population. The main operation is filling in cell type specific morphology
12.093578
6.112022
1.978654
if self.savefolder == None: return self.cells_path = os.path.join(self.savefolder, 'cells') if RANK == 0: if not os.path.isdir(self.cells_path): os.mkdir(self.cells_path) self.figures_path = os.path.join(self.savefolder, 'figures') ...
def _set_up_savefolder(self)
Create catalogs for different file output to clean up savefolder. Non-public method Parameters ---------- None Returns ------- None
1.795594
1.863609
0.963504
for cellindex in self.RANK_CELLINDICES: self.cellsim(cellindex) COMM.Barrier()
def run(self)
Distribute individual cell simulations across ranks. This method takes no keyword arguments. Parameters ---------- None Returns ------- None
28.264555
17.007229
1.661914
tic = time() if RANK == 0: pop_soma_pos = self.draw_rand_pos( min_r = self.electrodeParams['r_z'], **self.populationParams) else: pop_soma_pos = None if RANK == 0: print('found cell positions in %.2f s' % (time...
def set_pop_soma_pos(self)
Set `pop_soma_pos` using draw_rand_pos(). This method takes no keyword arguments. Parameters ---------- None Returns ------- numpy.ndarray (x,y,z) coordinates of each neuron in the population See also -------- PopulationS...
5.934256
5.458103
1.087238
min_cell_interdist = np.zeros(self.POPULATION_SIZE) for i in range(self.POPULATION_SIZE): cell_interdist = np.sqrt((x[i] - x)**2 + (y[i] - y)**2 + (z[i] - z)**2) cell_interdist[i] = np.inf min_cell_interdist[i] = cell_...
def calc_min_cell_interdist(self, x, y, z)
Calculate cell interdistance from input coordinates. Parameters ---------- x, y, z : numpy.ndarray xyz-coordinates of each cell-body. Returns ------- min_cell_interdist : np.nparray For each cell-body center, the distance to nearest neighboring...
2.072679
2.283026
0.907865
#compute the total LFP of cells on this RANK if self.RANK_CELLINDICES.size > 0: for i, cellindex in enumerate(self.RANK_CELLINDICES): if i == 0: data = self.output[cellindex][measure] else: data += self.output[c...
def calc_signal_sum(self, measure='LFP')
Superimpose each cell's contribution to the compound population signal, i.e., the population CSD or LFP Parameters ---------- measure : str {'LFP', 'CSD'}: Either 'LFP' or 'CSD'. Returns ------- numpy.ndarray The populations-specific co...
5.728333
6.087488
0.941001
try: assert(self.recordSingleContribFrac <= 1 and self.recordSingleContribFrac >= 0) except AssertionError as ae: raise ae, 'recordSingleContribFrac {} not in [0, 1]'.format( self.recordSingleContribFrac)...
def collectSingleContribs(self, measure='LFP')
Collect single cell data and save them to HDF5 file. The function will also return signals generated by all cells Parameters ---------- measure : str {'LFP', 'CSD'}: Either 'LFP' or 'CSD'. Returns ------- numpy.ndarray output of all neu...
2.864629
2.825401
1.013884
#collect some measurements resolved per file and save to file for measure in ['LFP', 'CSD']: if measure in self.savelist: self.collectSingleContribs(measure) #calculate lfp from all cell contribs lfp = self.calc_signal_sum(measure='LFP') #c...
def collect_data(self)
Collect LFPs, CSDs and soma traces from each simulated population, and save to file. Parameters ---------- None Returns ------- None
2.724818
2.675167
1.01856
tic = time() #containers for synapse idxs existing on this rank synIdx = {} #ok then, we will draw random numbers across ranks, which have to #be unique per cell. Now, we simply record the random state, #change the seed per cell, and put the original state bac...
def get_all_synIdx(self)
Auxilliary function to set up class attributes containing synapse locations given as LFPy.Cell compartment indices This function takes no inputs. Parameters ---------- None Returns ------- synIdx : dict `output[cellindex][populationindex][...
7.138203
6.688941
1.067165
tic = time() #container SpCells = {} #ok then, we will draw random numbers across ranks, which have to #be unique per cell. Now, we simply record the random state, #change the seed per cell, and put the original state back below. randomstate = np.random...
def get_all_SpCells(self)
For each postsynaptic cell existing on this RANK, load or compute the presynaptic cell index for each synaptic connection This function takes no kwargs. Parameters ---------- None Returns ------- SpCells : dict `output[cellindex][populatio...
9.61069
8.222883
1.168774
tic = time() #ok then, we will draw random numbers across ranks, which have to #be unique per cell. Now, we simply record the random state, #change the seed per cell, and put the original state back below. randomstate = np.random.get_state() #container ...
def get_all_synDelays(self)
Create and load arrays of connection delays per connection on this rank Get random normally distributed synaptic delays, returns dict of nested list of same shape as SpCells. Delays are rounded to dt. This function takes no kwargs. Parameters ---------- None ...
5.356894
4.898142
1.093658