code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
'''Returns a TensorFluent for the exp function. Args: x: The input fluent. Returns: A TensorFluent wrapping the exp function. ''' return cls._unary_op(x, tf.exp, tf.float32)
def exp(cls, x: 'TensorFluent') -> 'TensorFluent'
Returns a TensorFluent for the exp function. Args: x: The input fluent. Returns: A TensorFluent wrapping the exp function.
4.516644
2.836829
1.592145
'''Returns a TensorFluent for the log function. Args: x: The input fluent. Returns: A TensorFluent wrapping the log function. ''' return cls._unary_op(x, tf.log, tf.float32)
def log(cls, x: 'TensorFluent') -> 'TensorFluent'
Returns a TensorFluent for the log function. Args: x: The input fluent. Returns: A TensorFluent wrapping the log function.
4.784052
3.00282
1.593186
'''Returns a TensorFluent for the sqrt function. Args: x: The input fluent. Returns: A TensorFluent wrapping the sqrt function. ''' return cls._unary_op(x, tf.sqrt, tf.float32)
def sqrt(cls, x: 'TensorFluent') -> 'TensorFluent'
Returns a TensorFluent for the sqrt function. Args: x: The input fluent. Returns: A TensorFluent wrapping the sqrt function.
4.550086
2.744988
1.657598
'''Returns a TensorFluent for the cos function. Args: x: The input fluent. Returns: A TensorFluent wrapping the cos function. ''' return cls._unary_op(x, tf.cos, tf.float32)
def cos(cls, x: 'TensorFluent') -> 'TensorFluent'
Returns a TensorFluent for the cos function. Args: x: The input fluent. Returns: A TensorFluent wrapping the cos function.
4.875265
2.904587
1.678471
'''Returns a TensorFluent for the sin function. Args: x: The input fluent. Returns: A TensorFluent wrapping the sin function. ''' return cls._unary_op(x, tf.sin, tf.float32)
def sin(cls, x: 'TensorFluent') -> 'TensorFluent'
Returns a TensorFluent for the sin function. Args: x: The input fluent. Returns: A TensorFluent wrapping the sin function.
4.517767
2.823978
1.599788
'''Returns a TensorFluent for the tan function. Args: x: The input fluent. Returns: A TensorFluent wrapping the tan function. ''' return cls._unary_op(x, tf.tan, tf.float32)
def tan(cls, x: 'TensorFluent') -> 'TensorFluent'
Returns a TensorFluent for the tan function. Args: x: The input fluent. Returns: A TensorFluent wrapping the tan function.
4.702561
2.840815
1.655356
'''Returns a TensorFluent for the arccos function. Args: x: The input fluent. Returns: A TensorFluent wrapping the arccos function. ''' return cls._unary_op(x, tf.acos, tf.float32)
def acos(cls, x: 'TensorFluent') -> 'TensorFluent'
Returns a TensorFluent for the arccos function. Args: x: The input fluent. Returns: A TensorFluent wrapping the arccos function.
4.923141
2.8744
1.712754
'''Returns a TensorFluent for the arcsin function. Args: x: The input fluent. Returns: A TensorFluent wrapping the arcsin function. ''' return cls._unary_op(x, tf.asin, tf.float32)
def asin(cls, x: 'TensorFluent') -> 'TensorFluent'
Returns a TensorFluent for the arcsin function. Args: x: The input fluent. Returns: A TensorFluent wrapping the arcsin function.
4.405972
2.743922
1.60572
'''Returns a TensorFluent for the arctan function. Args: x: The input fluent. Returns: A TensorFluent wrapping the arctan function. ''' return cls._unary_op(x, tf.atan2, tf.float32)
def atan(cls, x: 'TensorFluent') -> 'TensorFluent'
Returns a TensorFluent for the arctan function. Args: x: The input fluent. Returns: A TensorFluent wrapping the arctan function.
4.967032
3.092549
1.606129
'''Returns a TensorFluent for the round function. Args: x: The input fluent. Returns: A TensorFluent wrapping the round function. ''' return cls._unary_op(x, tf.round, tf.float32)
def round(cls, x: 'TensorFluent') -> 'TensorFluent'
Returns a TensorFluent for the round function. Args: x: The input fluent. Returns: A TensorFluent wrapping the round function.
4.484727
2.771298
1.618277
'''Returns a TensorFluent for the ceil function. Args: x: The input fluent. Returns: A TensorFluent wrapping the ceil function. ''' return cls._unary_op(x, tf.ceil, tf.float32)
def ceil(cls, x: 'TensorFluent') -> 'TensorFluent'
Returns a TensorFluent for the ceil function. Args: x: The input fluent. Returns: A TensorFluent wrapping the ceil function.
4.653915
2.830716
1.644077
'''Returns a TensorFluent for the floor function. Args: x: The input fluent. Returns: A TensorFluent wrapping the floor function. ''' return cls._unary_op(x, tf.floor, tf.float32)
def floor(cls, x: 'TensorFluent') -> 'TensorFluent'
Returns a TensorFluent for the floor function. Args: x: The input fluent. Returns: A TensorFluent wrapping the floor function.
4.286167
2.658901
1.612007
'''Returns a TensorFluent for the pow function.TensorFluent Args: x: The first operand. y: The second operand. Returns: A TensorFluent wrapping the pow function. ''' return cls._binary_op(x, y, tf.pow, tf.float32)
def pow(cls, x: 'TensorFluent', y: 'TensorFluent') -> 'TensorFluent'
Returns a TensorFluent for the pow function.TensorFluent Args: x: The first operand. y: The second operand. Returns: A TensorFluent wrapping the pow function.
4.248164
2.577148
1.648397
'''Returns a TensorFluent for the maximum function.TensorFluent Args: x: The first operand. y: The second operand. Returns: A TensorFluent wrapping the maximum function. ''' return cls._binary_op(x, y, tf.maximum, tf.float32)
def max(cls, x: 'TensorFluent', y: 'TensorFluent') -> 'TensorFluent'
Returns a TensorFluent for the maximum function.TensorFluent Args: x: The first operand. y: The second operand. Returns: A TensorFluent wrapping the maximum function.
4.273356
2.456799
1.7394
'''Returns a TensorFluent for the minimum function. Args: x: The first operand. y: The second operand. Returns: A TensorFluent wrapping the minimum function. ''' return cls._binary_op(x, y, tf.minimum, tf.float32)
def min(cls, x: 'TensorFluent', y: 'TensorFluent') -> 'TensorFluent'
Returns a TensorFluent for the minimum function. Args: x: The first operand. y: The second operand. Returns: A TensorFluent wrapping the minimum function.
3.587368
2.424076
1.479891
'''Returns a TensorFluent for the control op if-then-else. Args: condition: Boolean fluent for the if condition. true_case: Fluent returned in the true clause. false_case: Fluent returned in the false clause. Returns: A TensorFluent wrapping the ...
def if_then_else(cls, condition: 'TensorFluent', true_case: 'TensorFluent', false_case: 'TensorFluent') -> 'TensorFluent'
Returns a TensorFluent for the control op if-then-else. Args: condition: Boolean fluent for the if condition. true_case: Fluent returned in the true clause. false_case: Fluent returned in the false clause. Returns: A TensorFluent wrapping the if-then-els...
3.478944
1.939701
1.793546
'''Returns a TensorFluent for the binary `op` applied to fluents `x` and `y`. Args: x: The first operand. y: The second operand. op: The binary operator. dtype: The output's data type. Returns: A TensorFluent wrapping the binary opera...
def _binary_op(cls, x: 'TensorFluent', y: 'TensorFluent', op: Callable[[tf.Tensor, tf.Tensor], tf.Tensor], dtype: tf.DType) -> 'TensorFluent'
Returns a TensorFluent for the binary `op` applied to fluents `x` and `y`. Args: x: The first operand. y: The second operand. op: The binary operator. dtype: The output's data type. Returns: A TensorFluent wrapping the binary operator's outpu...
2.544109
2.135292
1.191458
'''Returns a TensorFluent for the unary `op` applied to fluent `x`. Args: x: The input fluent. op: The unary operation. dtype: The output's data type. Returns: A TensorFluent wrapping the unary operator's output. ''' x = x.cast(dt...
def _unary_op(cls, x: 'TensorFluent', op: Callable[[tf.Tensor], tf.Tensor], dtype: tf.DType) -> 'TensorFluent'
Returns a TensorFluent for the unary `op` applied to fluent `x`. Args: x: The input fluent. op: The unary operation. dtype: The output's data type. Returns: A TensorFluent wrapping the unary operator's output.
4.577319
2.666796
1.716411
'''Returns a TensorFluent for the aggregation `op` applied to fluent `x`. Args: op: The aggregation operation. x: The input fluent. vars_list: The list of variables to be aggregated over. Returns: A TensorFluent wrapping the aggregation operator'...
def _aggregation_op(cls, op: Callable[[tf.Tensor, Optional[Sequence[int]]], tf.Tensor], x: 'TensorFluent', vars_list: List[str]) -> 'TensorFluent'
Returns a TensorFluent for the aggregation `op` applied to fluent `x`. Args: op: The aggregation operation. x: The input fluent. vars_list: The list of variables to be aggregated over. Returns: A TensorFluent wrapping the aggregation operator's output.
4.007829
2.594442
1.544775
'''Maps the `vars_list` into a list of axis indices corresponding to the `fluent` scope. Args: x: The fluent. vars_list: The list of variables to be aggregated over. Returns: List[int]: a list of axis. ''' axis = [] for var in...
def _varslist2axis(cls, fluent: 'TensorFluent', vars_list: List[str]) -> List[int]
Maps the `vars_list` into a list of axis indices corresponding to the `fluent` scope. Args: x: The fluent. vars_list: The list of variables to be aggregated over. Returns: List[int]: a list of axis.
4.172816
2.211805
1.886611
'''Returns a TensorFluent for the cast operation with given `dtype`. Args: dtype: The output's data type. Returns: A TensorFluent wrapping the cast operation. ''' if self.dtype == dtype: return self t = tf.cast(self.tensor, dtype) ...
def cast(self, dtype: tf.DType) -> 'TensorFluent'
Returns a TensorFluent for the cast operation with given `dtype`. Args: dtype: The output's data type. Returns: A TensorFluent wrapping the cast operation.
4.363482
3.119241
1.398892
'''Returns a TensorFluent for the reshape operation with given `shape`. Args: shape: The output's shape. Returns: A TensorFluent wrapping the reshape operation. ''' t = tf.reshape(self.tensor, shape) scope = self.scope.as_list() batch = s...
def reshape(self, shape: tf.TensorShape) -> 'TensorFluent'
Returns a TensorFluent for the reshape operation with given `shape`. Args: shape: The output's shape. Returns: A TensorFluent wrapping the reshape operation.
5.055279
3.255586
1.552801
'''Returns a TensorFluent for the transpose operation with given `permutation`. Args: permutation: The output's shape permutation. Returns: A TensorFluent wrapping the transpose operation. ''' if permutation == []: return self t = tf....
def transpose(self, permutation: Optional[List[int]] = None) -> 'TensorFluent'
Returns a TensorFluent for the transpose operation with given `permutation`. Args: permutation: The output's shape permutation. Returns: A TensorFluent wrapping the transpose operation.
5.388636
3.353243
1.606992
'''Returns the TensorFluent for the sum aggregation function. Args: vars_list: The list of variables to be aggregated over. Returns: A TensorFluent wrapping the sum aggregation function. ''' operand = self if operand.dtype == tf.bool: ...
def sum(self, vars_list: List[str]) -> 'TensorFluent'
Returns the TensorFluent for the sum aggregation function. Args: vars_list: The list of variables to be aggregated over. Returns: A TensorFluent wrapping the sum aggregation function.
3.860653
2.545917
1.51641
'''Returns the TensorFluent for the avg aggregation function. Args: vars_list: The list of variables to be aggregated over. Returns: A TensorFluent wrapping the avg aggregation function. ''' operand = self if operand.dtype == tf.bool: ...
def avg(self, vars_list: List[str]) -> 'TensorFluent'
Returns the TensorFluent for the avg aggregation function. Args: vars_list: The list of variables to be aggregated over. Returns: A TensorFluent wrapping the avg aggregation function.
3.920318
2.588112
1.51474
'''Returns the TensorFluent for the prod aggregation function. Args: vars_list: The list of variables to be aggregated over. Returns: A TensorFluent wrapping the prod aggregation function. ''' operand = self if operand.dtype == tf.bool: ...
def prod(self, vars_list: List[str]) -> 'TensorFluent'
Returns the TensorFluent for the prod aggregation function. Args: vars_list: The list of variables to be aggregated over. Returns: A TensorFluent wrapping the prod aggregation function.
4.029094
2.566427
1.569924
'''Returns the TensorFluent for the maximum aggregation function. Args: vars_list: The list of variables to be aggregated over. Returns: A TensorFluent wrapping the maximum aggregation function. ''' return self._aggregation_op(tf.reduce_max, self, vars_l...
def maximum(self, vars_list: List[str]) -> 'TensorFluent'
Returns the TensorFluent for the maximum aggregation function. Args: vars_list: The list of variables to be aggregated over. Returns: A TensorFluent wrapping the maximum aggregation function.
4.050725
2.26424
1.789
'''Returns the TensorFluent for the minimum aggregation function. Args: vars_list: The list of variables to be aggregated over. Returns: A TensorFluent wrapping the minimum aggregation function. ''' return self._aggregation_op(tf.reduce_min, self, vars_l...
def minimum(self, vars_list: List[str]) -> 'TensorFluent'
Returns the TensorFluent for the minimum aggregation function. Args: vars_list: The list of variables to be aggregated over. Returns: A TensorFluent wrapping the minimum aggregation function.
4.109628
2.269955
1.810445
'''Returns the TensorFluent for the forall aggregation function. Args: vars_list: The list of variables to be aggregated over. Returns: A TensorFluent wrapping the forall aggregation function. ''' return self._aggregation_op(tf.reduce_all, self, vars_lis...
def forall(self, vars_list: List[str]) -> 'TensorFluent'
Returns the TensorFluent for the forall aggregation function. Args: vars_list: The list of variables to be aggregated over. Returns: A TensorFluent wrapping the forall aggregation function.
5.034381
2.421512
2.079024
'''Returns the TensorFluent for the exists aggregation function. Args: vars_list: The list of variables to be aggregated over. Returns: A TensorFluent wrapping the exists aggregation function. ''' return self._aggregation_op(tf.reduce_any, self, vars_lis...
def exists(self, vars_list: List[str]) -> 'TensorFluent'
Returns the TensorFluent for the exists aggregation function. Args: vars_list: The list of variables to be aggregated over. Returns: A TensorFluent wrapping the exists aggregation function.
4.868258
2.451206
1.986066
newlist = sources.copy() if not isinstance(exclude, list): exclude = [exclude] for source in exclude: if not section: newlist.remove(source) else: pos = newlist.index(source) + 1 if pos == len(sources): return [] n...
def exclude_sources(exclude, section=False)
Returns a narrower list of sources. If the exclude parameter is a list, every one of its items will be removed from the returned list. If it's just a function (or a function's name) and 'section' is set to False (default), a copy of the sources list without this element will be returned. If it'...
3.124769
3.072611
1.016975
if l_sources is None: l_sources = sources if song.lyrics and not CONFIG['overwrite']: logger.debug('%s already has embedded lyrics', song) return None runtimes = {} source = None for l_source in l_sources: start = time.time() try: lyrics = l...
def get_lyrics(song, l_sources=None)
Searches for lyrics of a single song and returns a Result object with the various stats collected in the process. The optional parameter 'sources' specifies an alternative list of sources. If not present, the main list will be used.
3.247842
3.130548
1.037467
if l_sources is None: l_sources = sources if song.lyrics and not CONFIG['overwrite']: logger.debug('%s already has embedded lyrics', song) return None runtimes = {} queue = Queue() pool = [LyrThread(source, song, queue) for source in l_sources] for thread in pool: ...
def get_lyrics_threaded(song, l_sources=None)
Launches a pool of threads to search for the lyrics of a single song. The optional parameter 'sources' specifies an alternative list of sources. If not present, the main list will be used.
3.323365
3.344445
0.993697
found = result.source is not None if found: if hasattr(result.song, 'filename'): audiofile = eyed3.load(result.song.filename) audiofile.tag.lyrics.set(result.song.lyrics) audiofile.tag.save() print(f'{id_source(result.source)} Lyrics added for {result...
def process_result(result)
Process a result object by: 1. Saving the lyrics to the corresponding file(if applicable). 2. Printing the lyrics or the corresponding error/success message. 3. Returning a boolean indicating if the lyrics were found or not.
4.126541
4.021026
1.026241
if not hasattr(songs, '__iter__'): result = get_lyrics_threaded(songs) process_result(result) else: start = time.time() stats = run_mp(songs) end = time.time() if CONFIG['print_stats']: stats.print_stats() total_time = end - start ...
def run(songs)
Calls get_lyrics_threaded for a song or list of songs.
3.155053
2.745389
1.149219
stats = Stats() if CONFIG['debug']: good = open('found', 'w') bad = open('notfound', 'w') logger.debug('Launching a pool of %d processes\n', CONFIG['jobcount']) chunksize = math.ceil(len(songs) / os.cpu_count()) try: with Pool(CONFIG['jobcount']) as pool: fo...
def run_mp(songs)
Concurrently calls get_lyrics to fetch the lyrics of a large list of songs.
3.743221
3.622377
1.03336
if isinstance(options, str): return options return "\n".join(options)
def parse_setup(options: Union[List, str]) -> str
Convert potentially a list of commands into a single string. This creates a single string with newlines between each element of the list so that they will all run after each other in a bash script.
5.152653
5.010273
1.028418
logger.debug("Create Scheduler File Function") if job.scheduler_options is None: scheduler_options: Dict[str, Any] = {} else: scheduler_options = deepcopy(job.scheduler_options) try: setup_string = parse_setup(scheduler_options["setup"]) del scheduler_options["setup...
def create_scheduler_file(scheduler: str, job: Job) -> str
Substitute values into a template scheduler file.
3.120315
3.025924
1.031194
if self.__hardware_source: self.__data_item_states_changed_event_listener = self.__hardware_source.data_item_states_changed_event.listen(self.__data_item_states_changed) self.__acquisition_state_changed_event_listener = self.__hardware_source.acquisition_state_changed_event.list...
def initialize_state(self)
Call this to initialize the state of the UI after everything has been connected.
2.784077
2.619185
1.062956
if self.__hardware_source: if self.is_playing: self.__hardware_source.stop_playing() else: self.__hardware_source.start_playing()
def handle_play_clicked(self)
Call this when the user clicks the play/pause button.
4.259181
3.598356
1.183646
'''Maps RDDL range types to TensorFlow dtypes.''' range2dtype = { 'real': tf.float32, 'int': tf.int32, 'bool': tf.bool } return range2dtype[range_type]
def range_type_to_dtype(range_type: str) -> Optional[tf.DType]
Maps RDDL range types to TensorFlow dtypes.
3.240502
2.391882
1.354791
'''Maps python types to TensorFlow dtypes.''' dtype = None if python_type == float: dtype = tf.float32 elif python_type == int: dtype = tf.int32 elif python_type == bool: dtype = tf.bool return dtype
def python_type_to_dtype(python_type: type) -> Optional[tf.DType]
Maps python types to TensorFlow dtypes.
2.142069
1.982681
1.08039
if _type == DependencyTypes.AFTER: return 'after' elif _type == DependencyTypes.AFTER_ANY: return 'afterany' elif _type == DependencyTypes.AFTER_CORR: return 'aftercorr' elif _type == DependencyTypes.AFTER_NOT_OK: return 'afternoto...
def get_dependency_type(_type)
Get the dependency type string for SlurmPrinter :rtype: str
2.64478
2.643804
1.000369
username, userid, uname = get_user_information() header = '''\ # This Slurm batch script was generated # By user: %s (%s) # On host: %s # At date: %s # Using: Pyqueue v%s ''' % (username, userid, uname, datetime.now().strftime('%a. %B %w %X %Y'), __version__) return header
def get_header()
Makes the header section for the scripts :rtype: str
7.776523
7.646287
1.017033
options = job.get_options().copy() job_name = options.pop('name', None) job_account = options.pop('account', None) job_walltime = options.pop('walltime', None) job_mem_per_cpu = options.pop('mem_per_cpu', None) job_memory = options.pop('memory', None) jo...
def generate(self, job)
Generates a job submission script from a job object :param job: An instance of JobInterface :type job: pyqueue.job.JobInterface
1.950611
1.908815
1.021897
from subprocess import Popen, PIPE script = self._printer.generate(job) process = Popen('sbatch', stdout=PIPE, stdin=PIPE, stderr=PIPE) stdout, sterr = process.communicate(input=script) process.stdin.close()
def submit(self, job)
Submits a given job :param job: The job to submit :type job: pyqueue.job.JobInterface
4.071256
4.434159
0.918157
script = self._printer.generate(job) stdin, stdout, stderr = self._ssh.exec_command('sbatch') stdin.write(script) stdin.flush() stdin.channel.shutdown_write() return stdout.read()
def submit(self, job)
Submits a given job :param job: The job to submit :type job: pyqueue.job.JobInterface
4.612618
5.371779
0.858676
# qdbus org.mpris.MediaPlayer2.<name> /org/mpris/MediaPlayer2\ # org.freedesktop.DBus.Properties.Get org.mpris.MediaPlayer2.Player Metadat bus_name = 'org.mpris.MediaPlayer2.' + name path = '/org/mpris/MediaPlayer2' interface = 'org.mpris.MediaPlayer2.Player' address = DBusAddress(path, bus...
def get_info_mpris2(name)
Get the current playing song from an mpris2 compliant player.
3.248425
3.225171
1.00721
# mpris_version 2 try: return get_info_mpris2('clementine') except DBusErrorResponse: bus_name = 'org.mpris.clementine' path = '/Player' interface = 'org.freedesktop.MediaPlayer' return dbus_get_metadata(path, bus_name, interface)
def get_current_clementine()
Get the current song from clementine.
6.831336
6.467272
1.056293
result = subprocess.run('cmus-remote -Q'.split(' '), check=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) info = {} for line in result.stdout.decode().split('\n'): line = line.split(' ') if line[0] != 'tag': continue key = line[1...
def get_current_cmus()
Get the current song from cmus.
2.635918
2.472953
1.065899
if not filename: logger.error('No filename specified') return None if not os.path.exists(filename): logger.error("Err: File '%s' does not exist", filename) return None if os.path.isdir(filename): logger.error("Err: File '%s' ...
def from_filename(cls, filename)
Class constructor using the path to the corresponding mp3 file. The metadata will be read from this file to create the song object, so it must at least contain valid ID3 tags for artist and title.
2.664415
2.577463
1.033735
recv = [t.strip() for t in name.split(separator)] if len(recv) < 2: logger.error('Wrong format!') return None if reverse: title = recv[0] artist = ''.join(recv[1:]) else: artist = recv[0] title = ''.join(re...
def from_string(cls, name, separator='-', reverse=False)
Class constructor using a string with the artist and title. This should be used when parsing user input, since all the information must be specified in a single string formatted as: '{artist} - {title}'.
2.767041
2.671232
1.035867
response = get_lastfm('track.getInfo', artist=self.artist, track=self.title) if response: try: self.album = response['track']['album']['title'] logger.debug('Found album %s from lastfm', self.album) except Exc...
def fetch_album_name(self)
Get the name of the album from lastfm.
3.096926
2.655597
1.166188
#find the offset to the closest monday days_after_monday = metric_date.isoweekday() - 1 return metric_date - datetime.timedelta(days=days_after_monday)
def _get_closest_week(self, metric_date)
Gets the closest monday to the date provided.
4.305769
3.676796
1.171065
dates = [metric_date] start_date = metric_date end_date = metric_date + delta while start_date.month < end_date.month or start_date.year < end_date.year: days_in_month = calendar.monthrange(start_date.year, start_date.month)[1] #shift along to the next m...
def _get_daily_date_range(self, metric_date, delta)
Get the range of months that we need to use as keys to scan redis.
3.803717
3.578839
1.062835
dates = [metric_date] end_date = metric_date + delta #Figure out how many years our metric range spans spanning_years = end_date.year - metric_date.year for i in range(spanning_years): #for the weekly keys, we only care about the year dates.append...
def _get_weekly_date_range(self, metric_date, delta)
Gets the range of years that we need to use as keys to get metrics from redis.
4.166763
3.651934
1.140974
keys = self._analytics_backend.keys() for key in itertools.chain(*keys): with self._analytics_backend.map() as conn: if key.startswith(self._prefix): conn.delete(key)
def clear_all(self)
Deletes all ``sandsnake`` related data from redis. .. warning:: Very expensive and destructive operation. Use with causion
6.738006
6.759581
0.996808
return self._analytics_backend.incr(self._prefix + ":" + "analy:%s:count:%s" % (unique_identifier, metric), inc_amt)
def track_count(self, unique_identifier, metric, inc_amt=1, **kwargs)
Tracks a metric just by count. If you track a metric this way, you won't be able to query the metric by day, week or month. :param unique_identifier: Unique string indetifying the object this metric is for :param metric: A unique name for the metric you want to track :param inc_amt: The...
9.687266
10.791857
0.897646
metric = [metric] if isinstance(metric, basestring) else metric unique_identifier = [unique_identifier] if not isinstance(unique_identifier, (types.ListType, types.TupleType, types.GeneratorType,)) else unique_identifier results = [] if date is None: date = datetime....
def track_metric(self, unique_identifier, metric, date=None, inc_amt=1, **kwargs)
Tracks a metric for a specific ``unique_identifier`` for a certain date. The redis backend supports lists for both ``unique_identifier`` and ``metric`` allowing for tracking of multiple metrics for multiple unique_identifiers efficiently. Not all backends may support this. :param unique_identif...
2.523985
2.541501
0.993108
conn = kwargs.get("connection", None) date_generator = (from_date + datetime.timedelta(days=i) for i in itertools.count()) metric_key_date_range = self._get_daily_date_range(from_date, datetime.timedelta(days=limit)) #generate a list of mondays in between the start date and the ...
def get_metric_by_day(self, unique_identifier, metric, from_date, limit=30, **kwargs)
Returns the ``metric`` for ``unique_identifier`` segmented by day starting from``from_date`` :param unique_identifier: Unique string indetifying the object this metric is for :param metric: A unique name for the metric you want to track :param from_date: A python date object :pa...
3.920243
4.089816
0.958538
conn = kwargs.get("connection", None) closest_monday_from_date = self._get_closest_week(from_date) metric_key_date_range = self._get_weekly_date_range(closest_monday_from_date, datetime.timedelta(weeks=limit)) date_generator = (closest_monday_from_date + datetime.timedelta(days...
def get_metric_by_week(self, unique_identifier, metric, from_date, limit=10, **kwargs)
Returns the ``metric`` for ``unique_identifier`` segmented by week starting from``from_date`` :param unique_identifier: Unique string indetifying the object this metric is for :param metric: A unique name for the metric you want to track :param from_date: A python date object :p...
3.685076
3.772671
0.976782
conn = kwargs.get("connection", None) first_of_month = datetime.date(year=from_date.year, month=from_date.month, day=1) metric_key_date_range = self._get_weekly_date_range( first_of_month, relativedelta(months=limit)) date_generator = (first_of_month + relativedelta...
def get_metric_by_month(self, unique_identifier, metric, from_date, limit=10, **kwargs)
Returns the ``metric`` for ``unique_identifier`` segmented by month starting from``from_date``. It will retrieve metrics data starting from the 1st of the month specified in ``from_date`` :param unique_identifier: Unique string indetifying the object this metric is for :param metric: A ...
3.733559
3.815272
0.978583
results = [] #validation of types: allowed_types = { "day": self.get_metric_by_day, "week": self.get_metric_by_week, "month": self.get_metric_by_month, } if group_by.lower() not in allowed_types: raise Exception("Allowed va...
def get_metrics(self, metric_identifiers, from_date, limit=10, group_by="week", **kwargs)
Retrieves a multiple metrics as efficiently as possible. :param metric_identifiers: a list of tuples of the form `(unique_identifier, metric_name`) identifying which metrics to retrieve. For example [('user:1', 'people_invited',), ('user:2', 'people_invited',), ('user:1', 'comments_posted',), ('user:2'...
4.636509
4.453858
1.04101
result = None if start_date and end_date: start_date, end_date = (start_date, end_date,) if start_date < end_date else (end_date, start_date,) start_date = start_date if hasattr(start_date, 'date') else datetime.datetime.combine(start_date, datetime.time()) ...
def get_count(self, unique_identifier, metric, start_date=None, end_date=None, **kwargs)
Gets the count for the ``metric`` for ``unique_identifier``. You can specify a ``start_date`` and an ``end_date``, to only get metrics within that time range. :param unique_identifier: Unique string indetifying the object this metric is for :param metric: A unique name for the metric you want t...
2.527573
2.519883
1.003052
parsed_results = [] results = [ self.get_count(unique_identifier, metric, **kwargs) for unique_identifier, metric in metric_identifiers] for result in results: try: parsed_result = int(result) except TypeError: ...
def get_counts(self, metric_identifiers, **kwargs)
Retrieves a multiple metrics as efficiently as possible. :param metric_identifiers: a list of tuples of the form `(unique_identifier, metric_name`) identifying which metrics to retrieve. For example [('user:1', 'people_invited',), ('user:2', 'people_invited',), ('user:1', 'comments_posted',), ('user:2'...
3.092156
2.835154
1.090648
metric = [metric] if isinstance(metric, basestring) else metric unique_identifier = [unique_identifier] if not isinstance(unique_identifier, (types.ListType, types.TupleType, types.GeneratorType,)) else unique_identifier results = [] with self._analytics_backend.map() as conn: ...
def set_metric_by_day(self, unique_identifier, metric, date, count, sync_agg=True, update_counter=True)
Sets the count for the ``metric`` for ``unique_identifier``. You must specify a ``date`` for the ``count`` to be set on. Useful for resetting a metric count to 0 or decrementing a metric. The redis backend supports lists for both ``unique_identifier`` and ``metric`` allowing for the setting of ...
3.722323
3.755949
0.991047
self.sync_week_metric(unique_identifier, metric, start_date, end_date) self.sync_month_metric(unique_identifier, metric, start_date, end_date)
def sync_agg_metric(self, unique_identifier, metric, start_date, end_date)
Uses the count for each day in the date range to recalculate the counters for the associated weeks and months for the ``metric`` for ``unique_identifier``. Useful for updating the counters for week and month after using set_metric_by_day. The redis backend supports lists for both ``unique_identifier`` ...
1.993221
2.071814
0.962066
metric = [metric] if isinstance(metric, basestring) else metric unique_identifier = [unique_identifier] if not isinstance(unique_identifier, (types.ListType, types.TupleType, types.GeneratorType,)) else unique_identifier closest_monday_from_date = self._get_closest_week(start_date) ...
def sync_week_metric(self, unique_identifier, metric, start_date, end_date)
Uses the count for each day in the date range to recalculate the counters for the weeks for the ``metric`` for ``unique_identifier``. Useful for updating the counters for week and month after using set_metric_by_day. The redis backend supports lists for both ``unique_identifier`` and ``metric``...
3.323615
3.348563
0.99255
metric = [metric] if isinstance(metric, basestring) else metric unique_identifier = [unique_identifier] if not isinstance(unique_identifier, (types.ListType, types.TupleType, types.GeneratorType,)) else unique_identifier num_months = self._num_months(start_date, end_date) first_...
def sync_month_metric(self, unique_identifier, metric, start_date, end_date)
Uses the count for each day in the date range to recalculate the counters for the months for the ``metric`` for ``unique_identifier``. Useful for updating the counters for week and month after using set_metric_by_day. The redis backend supports lists for both ``unique_identifier`` and ``metric`` allowi...
3.403451
3.43132
0.991878
if not user_string[0] == "@": return False parts = user_string[1:].split(":") localpart_chars = ascii_lowercase + digits + "._-=" if not (len(parts) == 2 and all([i in localpart_chars for i in parts[0]])): return False return True
def is_full_mxid(user_string)
Returns True if a string is a valid mxid.
3.213126
3.034042
1.059025
def wrapper(self, *args, **kwargs): try: return method(self, *args, **kwargs) except exceptions.MatrixError as e: if isinstance(e.original_exception, matrix_client.errors.MatrixRequestError): self._handle_request_exception(e) ...
def intent(method)
Helps object methods handle MatrixRequestError. Args: method(function): Object method to be wrapped Method's object must have _handle_request_exception method that deals with specific status codes and errcodes.
4.200217
3.342288
1.256689
variables = set() for cmd in self._cmd: for var in self.__formatter.parse(cmd): logger.debug("Checking variable: %s", var) # creates and requires are special class values if var[1] is not None and var[1] not in ["creates", "requires"]:...
def get_variables(self) -> Set[str]
Find all the variables specified in a format string. This returns a list of all the different variables specified in a format string, that is the variables inside the braces.
7.643689
7.750949
0.986162
return_string = "( \\\n" for command in self: return_string += '"' + str(command) + '" \\\n' return_string += ")" return return_string
def as_bash_array(self) -> str
Return a representation as a bash array. This creates a string formatted as a bash array containing all the commands in the job.
4.374711
3.627485
1.20599
if not doc: return {} out = {} for s in doc.split('\n'): s = s.strip().split(':', maxsplit=1) if len(s) == 2: out[s[0]] = s[1] return out
def parse_doc(doc)
Parse docstrings to dict, it should look like: key: value
2.438171
2.478077
0.983897
return dict(ChainMap(*dicts))
def combine_dictionaries(dicts: List[Dict[str, Any]]) -> Dict[str, Any]
Merge a list of dictionaries into a single dictionary. Where there are collisions the first value in the list will be set as this function is using ChainMap to combine the dicts.
10.250975
13.618278
0.752737
logger.debug("Yielding from zip iterator") if isinstance(variables, list): for item in variables: yield list(variable_matrix(item, parent, "zip")) else: yield list(variable_matrix(variables, parent, "zip"))
def iterator_zip(variables: VarType, parent: str = None) -> Iterable[VarMatrix]
Apply the zip operator to a set of variables. This uses the python zip iterator to combine multiple lists of variables such that the nth variable in each list is aligned. Args: variables: The variables object parent: Unused
3.893763
4.413471
0.882245
logger.debug("Yielding from product iterator") if isinstance(variables, list): raise ValueError( f"Product only takes mappings of values, got {variables} of type {type(variables)}" ) yield list(variable_matrix(variables, parent, "product"))
def iterator_product(variables: VarType, parent: str = None) -> Iterable[VarMatrix]
Apply the product operator to a set of variables. This uses the python itertools.product iterator to combine multiple variables such that all possible combinations are generated. This is the default iterator however this is a method of manually specifying the option. Args: variables: The varia...
8.771964
10.151667
0.864091
logger.debug("Yielding from append iterator") if not isinstance(variables, list): raise ValueError( f"Append keyword only takes a list of arguments, got {variables} of type {type(variables)}" ) # Create a single list containing all the values yield list( chain.f...
def iterator_chain(variables: VarType, parent: str = None) -> Iterable[VarMatrix]
This successively appends each element of an array to a single list of values. This takes a list of values and puts all the values generated for each element in the list into a single list of values. It uses the :func:`itertools.chain` function to achieve this. This function is particularly useful for spec...
6.911376
7.054558
0.979704
assert parent is not None if isinstance(variables, (int, float)): yield [{parent: i} for i in np.arange(variables)] elif isinstance(variables, dict): if variables.get("stop"): yield [{parent: i} for i in arange(**variables)] else: raise ValueError(f"Stop...
def iterator_arange(variables: VarType, parent: str) -> Iterable[VarMatrix]
Create a list of values using the :func:`numpy.arange` function. Args: variables: The input variables for the creation of the range parent: The variable for which the values are being generated. Returns: A list of dictionaries mapping the parent to each value.
4.252134
4.580403
0.928332
if isinstance(variables, dict): if variables.get("times"): times = int(variables["times"]) del variables["times"] yield list(variable_matrix(variables, parent, "product")) * times else: raise ValueError(f"times is a required keyword for the repe...
def iterator_cycle(variables: VarType, parent: str) -> Iterable[VarMatrix]
Cycle through a list of values a specified number of times Args: variables: The input variables for the creation of the range parent: The variable for which the values are being generated. Returns: A list of dictionaries mapping the parent to each value.
5.390285
6.209666
0.868047
_iters: Dict[str, Callable] = {"product": product, "zip": zip} _special_keys: Dict[str, Callable[[VarType, Any], Iterable[VarMatrix]]] = { "zip": iterator_zip, "product": iterator_product, "arange": iterator_arange, "chain": iterator_chain, "append": iterator_chain, ...
def variable_matrix( variables: VarType, parent: str = None, iterator: str = "product" ) -> Iterable[Dict[str, YamlValue]]
Process the variables into a list of the appropriate combinations. This function performs recursive processing of the input variables, creating an iterator which has all the combinations of variables specified in the input.
3.741323
3.862695
0.968579
if sys.version_info >= (3, 6): # An implementation specific detail of py3.6 is the retention of order # within a dictionary. In py3.7 this becomes the documented behaviour. return list(dict.fromkeys(my_list)) # Slower method of order preserving unique list in older python versions ...
def uniqueify(my_list: Any) -> List[Any]
Remove duplicate entries in a list retaining order.
5.941367
5.544772
1.071526
assert command is not None if isinstance(command, str): command_list = [Command(command, variables=variables) for variables in matrix] elif isinstance(command, list): command_list = [Command(command, variables=variables) for variables in matrix] else: if command.get("command...
def process_command(command: CommandInput, matrix: VarMatrix) -> List[Command]
Generate all combinations of commands given a variable matrix. Processes the commands to be sequences of strings.
3.051342
3.032244
1.006298
logger.debug("Input file: %s", filename) with open(filename, "r") as stream: structure = yaml.safe_load(stream) return structure
def read_file(filename: PathLike = "experiment.yml") -> Dict[str, Any]
Read and parse yaml file.
3.978492
3.495878
1.138052
logger.debug("Running commands in bash shell") # iterate through command groups for job in jobs: # Check shell exists if shutil.which(job.shell) is None: raise ProcessLookupError(f"The shell '{job.shell}' was not found.") failed = False for command in job: ...
def run_bash_jobs( jobs: Iterator[Job], directory: PathLike = Path.cwd(), dry_run: bool = False ) -> None
Submit commands to the bash shell. This function runs the commands iteratively but handles errors in the same way as with the pbs_commands function. A command will run for all combinations of variables in the variable matrix, however if any one of those commands fails then the next command will not run...
3.312978
3.334779
0.993462
submit_job = True logger.debug("Creating commands in %s files.", scheduler) # Check scheduler submit command exists if scheduler == "pbs": submit_executable = "qsub" elif scheduler == "slurm": submit_executable = "sbatch" else: raise ValueError("scheduler can only t...
def run_scheduler_jobs( scheduler: str, jobs: Iterator[Job], directory: PathLike = Path.cwd(), basename: str = "experi", dry_run: bool = False, ) -> None
Submit a series of commands to a batch scheduler. This takes a list of strings which are the contents of the pbs files, writes the files to disk and submits the job to the scheduler. Files which match the pattern of the resulting files <basename>_<index>.pbs are deleted before writing the new files. T...
3.538061
3.328469
1.06297
# Scheduler value from command line has first priority if scheduler is not None: if scheduler in ["shell", "pbs", "slurm"]: return scheduler raise ValueError( "Argument scheduler only supports input values of ['shell', 'pbs', 'slurm']" ) # Next priority...
def determine_scheduler( scheduler: Optional[str], experiment_definition: Dict[str, YamlValue] ) -> str
Determine the scheduler to use to run the jobs.
3.519939
3.292315
1.069138
if not isinstance(data, list): name = self.__class__.__name__ msg = "did not pass validation against callable: %s" % name reason = 'expected a list but got %s' % safe_repr(data) raise Invalid(self.schema, tree, reason=reason, pair='value', msg=msg)
def safe_type(self, data, tree)
Make sure that the incoming data complies with the class type we are expecting it to be. In this case, classes that inherit from this base class expect data to be of type ``list``.
6.869047
6.460588
1.063223
new_context = { 'model': context['model'], 'session': context['session'], 'user': context.get('user'), 'ignore_auth': context.get('ignore_auth', False), 'use_cache': context.get('use_cache', False), } if 'validate' in context: new_context['validate'] = c...
def get_context(context)
An internal context generator. Accepts a CKAN context. CKAN's internals put various things into the context which makes reusing it for multiple API calls inadvisable. This function adds more fine grain control on the context from our plugin logic side.
2.442091
2.152345
1.134619
def _wrapped(*args, **kwargs): data = _get_request_unique_cache() return func(data, *args, **kwargs) return _wrapped
def request_uniq(func)
return unique dict for each uwsgi request. note: won't work on non-uwsgi cases
5.466238
4.669603
1.1706
name = getattr(obj, '__name__', getattr(obj.__class__, '__name__')) if name == 'ndict': name = 'dict' return name or repr(obj)
def safe_repr(obj)
Try to get ``__name__`` first, ``__class__.__name__`` second and finally, if we can't get anything acceptable, fallback to user a ``repr()`` call.
4.517421
4.286357
1.053907
keys = sorted(data.keys()) new_data = {} for number, key in enumerate(keys): new_data[number] = data[key] return new_data
def re_sort(data)
A data with keys that are not enumerated sequentially will be re sorted and sequentially ordered. For example:: >>> data = {16: ('1', 'b'), 3: ('1', 'a')} >>> re_sort(data) >>> {0: ('1', 'a'), 1: ('1', 'b')}
2.682859
3.296836
0.813768
required_items = required_items or [] new_data = {} for k, v in data.items(): if v[0] in required_items: new_data[k] = v continue for required_item in required_items: key = getattr(required_item, '_object', False) if key: i...
def sift(data, required_items=None)
Receive a ``data`` object that will be in the form of a normalized structure (e.g. ``{0: {'a': 0}}``) and filter out keys that match the ``required_items``.
3.099046
3.524647
0.87925
if isinstance(data, ndict): # OK, we have something that looks like {0: ('a', 'b')} # or something that is a regular dictionary # so try to return 'a' regardless of the length for item in data: return repr(data[item][0]) elif isinstance(data, dict): for i...
def data_item(data)
When trying to return a meaningful error about an unexpected data item we cannot just `repr(data)` as that could show a gigantic data struture. This utility should try to get the key of the first item or the single item in the data structure.
4.684504
4.323232
1.083565
message = message or assertion if not assertion: raise AssertionError(message) return True
def ensure(assertion, message=None)
Checks an assertion argument for truth-ness. Will return ``True`` or explicitly raise ``AssertionError``. This is to deal with environments using ``python -O` or ``PYTHONOPTIMIZE=``. :param assertion: some value to evaluate for truth-ness :param message: optional message used for raising AssertionError
5.670211
14.04275
0.403782
'''Returns a copy of the fluent shape, ignoring batch size if in batch mode.''' return tuple(self._shape.as_list()[1:] if self._batch else self._shape.as_list()[:])
def fluent_shape(self) -> Sequence[int]
Returns a copy of the fluent shape, ignoring batch size if in batch mode.
7.218834
3.674336
1.964664
'''It broadcasts the fluent shapes if any input is in batch mode. It handles input shapes in different modes, expanding its dimensions if necessary. It outputs a tuple with new shapes. If no input shape is in batch mode, return (None, None). If an input shape does not need to be...
def broadcast(cls, shape1: 'TensorFluentShape', shape2: 'TensorFluentShape') -> Tuple[Reshaping, Reshaping]
It broadcasts the fluent shapes if any input is in batch mode. It handles input shapes in different modes, expanding its dimensions if necessary. It outputs a tuple with new shapes. If no input shape is in batch mode, return (None, None). If an input shape does not need to be changed, r...
2.799811
1.632231
1.715328
# check for chr ref is_chr_query = chrom.startswith('chr') if is_chr_query and chr_reffa is None: chr_reffa = reffa # check bam ref type bam_header = subprocess.check_output("samtools view -H {}".format(bam), shell=True) is_chr_bam = bam_header.find('SN:chr') != -1 if is_chr_b...
def run(bam, chrom, pos1, pos2, reffa, chr_reffa, parameters)
Run mpileup on given chrom and pos
2.465099
2.462398
1.001097
if os.path.exists(fname): with open(fname) as f: code = compile(f.read(), os.path.basename(fname), 'exec') exec(code, _globals, _locals) return True else: return False
def execfile(fname, _globals, _locals)
Usage: execfile('path/to/file.py', globals(), locals())
1.87949
1.87203
1.003985
dir_name = rel_path(rel_name, check=False) if not os.path.exists(dir_name): os.makedirs(dir_name, exist_ok=True) return dir_name
def auto_directory(rel_name)
if you're using py.path you make do that as: py.path.local(full_path).ensure_dir()
2.517033
2.435087
1.033652