_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q16800
get_institute_trend_graph_url
train
def get_institute_trend_graph_url(institute, start, end): """ Institute trend graph for machine category. """ filename = get_institute_trend_graph_filename(institute, start, end) urls = { 'graph_url':
python
{ "resource": "" }
q16801
get_institutes_trend_graph_urls
train
def get_institutes_trend_graph_urls(start, end): """ Get all institute trend graphs. """ graph_list = [] for institute in Institute.objects.all():
python
{ "resource": "" }
q16802
PersonManager._create_user
train
def _create_user( self, username, email, short_name, full_name, institute, password, is_admin, **extra_fields): """Creates a new active person. """ # Create Person person = self.model( username=username, email=email, short_name=short_name,
python
{ "resource": "" }
q16803
PersonManager.create_user
train
def create_user( self, username, email, short_name, full_name, institute, password=None, **extra_fields): """ Creates a new ordinary person. """ return self._create_user( username=username, email=email,
python
{ "resource": "" }
q16804
PersonManager.create_superuser
train
def create_superuser( self, username, email, short_name, full_name, institute, password, **extra_fields): """ Creates a new person with super powers. """ return self._create_user( username=username, email=email,
python
{ "resource": "" }
q16805
do_application_actions_plus
train
def do_application_actions_plus(parser, token): """ Render actions available with extra text. """ nodelist = parser.parse(('end_application_actions',))
python
{ "resource": "" }
q16806
run
train
def run(cmds, **kwargs): """ Wrapper around subprocess.run, with unicode decoding of output. Additional kwargs are passed to subprocess.run. """ proc = sp.Popen(cmds, bufsize=-1, stdout=sp.PIPE,
python
{ "resource": "" }
q16807
symlink
train
def symlink(target, linkname): """ Create a symlink to `target` called `linkname`. Converts `target` and `linkname` to absolute paths; creates `dirname(linkname)` if needed. """ target = os.path.abspath(target)
python
{ "resource": "" }
q16808
upload
train
def upload(host, user, local_dir, remote_dir, rsync_options=RSYNC_OPTIONS): """ Upload a file or directory via rsync. Parameters ---------- host : str or None If None, omit the host part and just transfer locally user : str or None If None, omit the user part local_dir : str If a directory, a trailing "/" will be added. remote_dir : str If a directory, a trailing "/" will be added. """ if user is None: user = "" else: user = user + "@" if host is None or host == 'localhost':
python
{ "resource": "" }
q16809
local_link
train
def local_link(local_fn, remote_fn, staging): """ Creates a symlink to a local staging area. The link name is built from `remote_fn`, but the absolute path is put inside the staging directory. Example ------- If we have the following initial setup:: cwd="/home/user"
python
{ "resource": "" }
q16810
stage
train
def stage(x, staging): """ Stage an object to the `staging` directory. If the object is a Track and is one of the types that needs an index file (bam, vcfTabix), then the index file will be staged as well. Returns a list of the linknames created. """ linknames = [] # Objects that don't represent a file shouldn't be staged non_file_objects = ( track.ViewTrack, track.CompositeTrack, track.AggregateTrack, track.SuperTrack, genome.Genome, ) if isinstance(x, non_file_objects): return linknames # If it's an object representing a file, then render it. # # Track objects don't represent files, but their documentation does linknames.append(x.render(staging)) if hasattr(x, 'source') and hasattr(x, 'filename'): def _stg(x, ext=''): # A remote track hosted elsewhere does not need staging. This is # defined by a track with a url, but no source or filename. if ( x.source is None and x.filename is None
python
{ "resource": "" }
q16811
stage_hub
train
def stage_hub(hub, staging=None): """ Stage a hub by symlinking all its connected files to a local directory. """ linknames = [] if staging is None: staging
python
{ "resource": "" }
q16812
upload_hub
train
def upload_hub(hub, host, remote_dir, user=None, port=22, rsync_options=RSYNC_OPTIONS, staging=None): """ Renders, stages, and uploads a hub. """ hub.render() if staging is None: staging = tempfile.mkdtemp()
python
{ "resource": "" }
q16813
get_project_members
train
def get_project_members(machine, project_id): """ Returns list of usernames given a project id """ try: project = Project.objects.get(pid=project_id) except Project.DoesNotExist:
python
{ "resource": "" }
q16814
get_projects
train
def get_projects(machine): """ Returns list of project ids """
python
{ "resource": "" }
q16815
get_project
train
def get_project(username, project, machine_name=None): """ Used in the submit filter to make sure user is in project """ try: account = Account.objects.get( username=username, date_deleted__isnull=True) except Account.DoesNotExist: return "Account '%s' not found" % username if project is None: project = account.default_project else: try: project = Project.objects.get(pid=project) except Project.DoesNotExist: project = account.default_project if
python
{ "resource": "" }
q16816
get_users_projects
train
def get_users_projects(user): """ List projects a user is part of """ person = user
python
{ "resource": "" }
q16817
redirect_to
train
def redirect_to(request, url, permanent=True, query_string=False, **kwargs): r""" Redirect to a given URL. The given url may contain dict-style string formatting, which will be interpolated against the params in the URL. For example, to redirect from ``/foo/<id>/`` to ``/bar/<id>/``, you could use the following URLconf:: urlpatterns = patterns('', (r'^foo/(?P<id>\d+)/$', 'django.views.generic.simple.redirect_to', {'url' : '/bar/%(id)s/'}), ) If the given url is ``None``, a HttpResponseGone (410) will be issued. If the ``permanent`` argument is False, then the response will have a 302 HTTP status code. Otherwise, the status code will be 301. If the ``query_string`` argument is True, then the GET query string from the request is appended to the URL. """
python
{ "resource": "" }
q16818
assert_strong_password
train
def assert_strong_password(username, password, old_password=None): """Raises ValueError if the password isn't strong. Returns the password otherwise.""" # test the length try: minlength = settings.MIN_PASSWORD_LENGTH except AttributeError: minlength = 12 if len(password) < minlength: raise ValueError(
python
{ "resource": "" }
q16819
_lookup
train
def _lookup(cls: str) -> LdapObjectClass: """ Lookup module.class. """ if isinstance(cls, str): module_name, _, name = cls.rpartition(".") module = importlib.import_module(module_name) try: cls = getattr(module, name)
python
{ "resource": "" }
q16820
DataStore.save_account
train
def save_account(self, account: Account) -> None: """ Account was saved. """ person = account.person if self._primary_group == 'institute': lgroup = self._get_group(person.institute.group.name) elif self._primary_group == 'default_project': if account.default_project is None: lgroup = self._get_group(self._default_primary_group) else: lgroup = self._get_group(account.default_project.group.name) else: raise RuntimeError("Unknown value of PRIMARY_GROUP.") if account.default_project is None: default_project = "none" else: default_project = account.default_project.pid try: luser = self._get_account(account.username) changes = changeset(luser, {}) new_user = False except ObjectDoesNotExist: new_user = True luser = self._account_class() changes = changeset(luser, { 'uid': account.username })
python
{ "resource": "" }
q16821
DataStore.delete_account
train
def delete_account(self, account): """ Account was deleted. """ try: luser = self._get_account(account.username) groups = luser['groups'].load(database=self._database) for group in groups: changes = changeset(group, {})
python
{ "resource": "" }
q16822
DataStore.set_account_password
train
def set_account_password(self, account, raw_password): """ Account's password was changed. """ luser = self._get_account(account.username) changes = changeset(luser, {
python
{ "resource": "" }
q16823
DataStore.add_account_to_group
train
def add_account_to_group(self, account, group): """ Add account to group. """ lgroup: OpenldapGroup = self._get_group(group.name) person: OpenldapAccount = self._get_account(account.username)
python
{ "resource": "" }
q16824
DataStore.save_group
train
def save_group(self, group): """ Group was saved. """ # If group already exists, take over existing group rather then error. try: lgroup = self._get_group(group.name) changes = changeset(lgroup, {}) except ObjectDoesNotExist: lgroup = self._group_class()
python
{ "resource": "" }
q16825
DataStore.delete_group
train
def delete_group(self, group): """ Group was deleted. """ try: lgroup = self._get_group(group.name) delete(lgroup, database=self._database)
python
{ "resource": "" }
q16826
DataStore.get_group_details
train
def get_group_details(self, group): """ Get the group details. """ result = {} try: lgroup = self._get_group(group.name) lgroup = preload(lgroup, database=self._database) except ObjectDoesNotExist: return
python
{ "resource": "" }
q16827
_rank
train
def _rank(sample): """ Assign numeric ranks to all values in the sample. The ranks begin with 1 for the smallest value. When there are groups of tied values, assign a rank equal to the midpoint of unadjusted rankings. E.g.:: >>> rank({3: 1, 5: 4, 9: 1})
python
{ "resource": "" }
q16828
_tie_correct
train
def _tie_correct(sample): """ Returns the tie correction value for U. See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.tiecorrect.html """ tc = 0 n = sum(sample.values()) if n < 2: return
python
{ "resource": "" }
q16829
ndtr
train
def ndtr(a): """ Returns the area under the Gaussian probability density function, integrated from minus infinity to x. See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.ndtr.html#scipy.special.ndtr """ sqrth = math.sqrt(2) / 2 x = float(a) * sqrth z = abs(x) if
python
{ "resource": "" }
q16830
mann_whitney_u
train
def mann_whitney_u(sample1, sample2, use_continuity=True): """ Computes the Mann-Whitney rank test on both samples. Each sample is expected to be of the form:: {1: 5, 2: 20, 3: 12, ...} Returns a named tuple with: ``u`` equal to min(U for sample1, U for sample2), and ``p`` equal to the p-value. """ # Merge dictionaries, adding values if keys match. sample = sample1.copy() for k, v in sample2.items(): sample[k] = sample.get(k, 0) + v # Create a ranking dictionary using same keys for lookups. ranks = _rank(sample) sum_of_ranks = sum([sample1[k] * ranks[k] for k, v in sample1.items()]) n1 = sum(sample1.values()) n2 = sum(sample2.values()) # Calculate Mann-Whitney U for both samples. u1 =
python
{ "resource": "" }
q16831
get_pings
train
def get_pings(sc, app=None, build_id=None, channel=None, doc_type='saved_session', fraction=1.0, schema=None, source_name='telemetry', source_version='4', submission_date=None, version=None): """ Returns a RDD of Telemetry submissions for a given filtering criteria. :param sc: an instance of SparkContext :param app: an application name, e.g.: "Firefox" :param channel: a channel name, e.g.: "nightly" :param version: the application version, e.g.: "40.0a1" :param build_id: a build_id or a range of build_ids, e.g.: "20150601000000" or ("20150601000000", "20150610999999") :param submission_date: a submission date or a range of submission dates, e.g: "20150601" or ("20150601", "20150610") :param source_name: source name, set to "telemetry" by default :param source_version: source version, set to "4" by default :param doc_type: ping type, set to "saved_session" by default :param schema: (deprecated) version of the schema to use :param fraction: the fraction of pings to return, set to 1.0 by default """ if schema: print("The 'schema' parameter is deprecated. " "Version 4 is now the only schema supported.") if schema != "v4": raise ValueError("Invalid schema version") dataset = Dataset.from_source('telemetry') filters = ( ('docType', doc_type), ('sourceName', source_name), ('sourceVersion', source_version), ('appName', app),
python
{ "resource": "" }
q16832
get_pings_properties
train
def get_pings_properties(pings, paths, only_median=False, with_processes=False, histograms_url=None, additional_histograms=None): """ Returns a RDD of a subset of properties of pings. Child histograms are automatically merged with the parent histogram. If one of the paths points to a keyedHistogram name without supplying the actual key, returns a dict of all available subhistograms for that property. :param with_processes: should separate parent and child histograms be included as well? :param paths: paths to properties in the payload, with levels separated by "/". These can be supplied either as a list, eg. ["application/channel", "payload/info/subsessionStartDate"], or as the values of a dict keyed by custom identifiers, eg. {"channel": "application/channel", "ssd": "payload/info/subsessionStartDate"}. :param histograms_url: see histogram.Histogram constructor :param additional_histograms: see histogram.Histogram constructor The returned RDD contains a dict for each ping with the required properties as values,
python
{ "resource": "" }
q16833
get_one_ping_per_client
train
def get_one_ping_per_client(pings): """ Returns a single ping for each client in the RDD. THIS METHOD IS NOT RECOMMENDED: The ping to be returned is essentially selected at random. It is also expensive as it requires data to be shuffled around. It should be run only after extracting a subset with get_pings_properties. """ if isinstance(pings.first(), binary_type): pings = pings.map(lambda p: json.loads(p.decode('utf-8'))) filtered = pings.filter(lambda p: "clientID" in p or "clientId" in p) if
python
{ "resource": "" }
q16834
admin_required
train
def admin_required(function=None): """ Decorator for views that checks that the user is an administrator, redirecting to the log-in page if necessary. """ def check_perms(user): # if user not logged in, show login form if not user.is_authenticated: return False # if this site doesn't allow admin access, fail if settings.ADMIN_IGNORED: raise PermissionDenied # check if the user has admin rights if
python
{ "resource": "" }
q16835
SlurmDataStore._read_output
train
def _read_output(self, command): """ Read CSV delimited input from Slurm. """ cmd = [] cmd.extend(self._prefix) cmd.extend([self._path, "-iP"]) cmd.extend(command) command = cmd logger.debug("Cmd %s" % command) null = open('/dev/null', 'w') process = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=null) null.close() results = [] reader = csv.reader(_input_csv(process.stdout), delimiter=str("|")) try: headers = next(reader) logger.debug("<-- headers %s" % headers) except StopIteration: logger.debug("Cmd %s headers not found" % command) headers = [] for row in reader: _output_csv(row) logger.debug("<-- row %s" % row) this_row = {} i = 0 for i in range(0, len(headers)): key =
python
{ "resource": "" }
q16836
SlurmDataStore.get_project
train
def get_project(self, projectname): """ Get the project details from Slurm. """ cmd = ["list", "accounts", "where", "name=%s" % projectname] results = self._read_output(cmd) if len(results) == 0: return None elif len(results) > 1: logger.error( "Command returned multiple results for '%s'." % projectname) raise RuntimeError( "Command returned multiple results for '%s'." % projectname) the_result = results[0] the_project = the_result["Account"] if projectname.lower() != the_project.lower():
python
{ "resource": "" }
q16837
SlurmDataStore.get_users_in_project
train
def get_users_in_project(self, projectname): """ Get list of users in project from Slurm. """ cmd = ["list", "assoc", "where", "account=%s" % projectname] results = self._read_output(cmd) user_list = [] for result in
python
{ "resource": "" }
q16838
SlurmDataStore.get_projects_in_user
train
def get_projects_in_user(self, username): """ Get list of projects in user from Slurm. """ cmd = ["list", "assoc", "where", "user=%s" %
python
{ "resource": "" }
q16839
TrackDb.add_tracks
train
def add_tracks(self, track): """ Add a track or iterable of tracks. Parameters ---------- track : iterable or Track Iterable of :class:`Track` objects, or a single :class:`Track` object. """ from trackhub import BaseTrack
python
{ "resource": "" }
q16840
loggable
train
def loggable(obj): """Return "True" if the obj implements the minimum Logger API required by the 'trace' decorator. """ if isinstance(obj, logging.Logger): return True else: return (inspect.isclass(obj) and inspect.ismethod(getattr(obj,
python
{ "resource": "" }
q16841
_formatter_self
train
def _formatter_self(name, value): """Format the "self" variable and value on instance methods. """ __mname = value.__module__ if __mname != '__main__':
python
{ "resource": "" }
q16842
_formatter_class
train
def _formatter_class(name, value): """Format the "klass" variable and value on class methods. """ __mname = value.__module__ if __mname != '__main__': return "%s
python
{ "resource": "" }
q16843
get_formatter
train
def get_formatter(name): """Return the named formatter function. See the function "set_formatter" for details. """ if name in ('self', 'instance', 'this'): return af_self elif name == 'class': return af_class elif name in ('named', 'param', 'parameter'): return af_named elif name in ('default', 'optional'): return
python
{ "resource": "" }
q16844
__lookup_builtin
train
def __lookup_builtin(name): """Lookup the parameter name and default parameter values for builtin functions. """ global __builtin_functions if __builtin_functions is None: builtins = dict() for proto in __builtins: pos = proto.find('(') name, params, defaults = proto[:pos], list(), dict() for param in proto[pos + 1:-1].split(','): pos = param.find('=') if not pos < 0: param, value = param[:pos], param[pos + 1:] try: defaults[param] = __builtin_defaults[value] except KeyError: raise ValueError( 'builtin function %s: parameter %s: '
python
{ "resource": "" }
q16845
application_list
train
def application_list(request): """ a user wants to see all applications possible. """ if util.is_admin(request): queryset = Application.objects.all() else: queryset = Application.objects.get_for_applicant(request.user) q_filter = ApplicationFilter(request.GET, queryset=queryset) table = ApplicationTable(q_filter.qs.order_by("-expires"))
python
{ "resource": "" }
q16846
profile_application_list
train
def profile_application_list(request): """ a logged in user wants to see all his pending applications. """ config = tables.RequestConfig(request, paginate={"per_page": 5}) person = request.user my_applications = Application.objects.get_for_applicant(person) my_applications = ApplicationTable(my_applications, prefix="mine-")
python
{ "resource": "" }
q16847
application_detail
train
def application_detail(request, application_id, state=None, label=None): """ A authenticated used is trying to access an application. """ application = base.get_application(pk=application_id)
python
{ "resource": "" }
q16848
application_unauthenticated
train
def application_unauthenticated(request, token, state=None, label=None): """ An somebody is trying to access an application. """ application = base.get_application(secret_token=token) if application.expires < datetime.datetime.now(): return render( template_name='kgapplications/common_expired.html', context={'application': application},
python
{ "resource": "" }
q16849
get_institute_usage
train
def get_institute_usage(institute, start, end): """Return a tuple of cpu hours and number of jobs for an institute for a given period Keyword arguments: institute -- start -- start date end -- end date """ try: cache = InstituteCache.objects.get(
python
{ "resource": "" }
q16850
get_project_usage
train
def get_project_usage(project, start, end): """Return a tuple of cpu hours and number of jobs for a project for a given period Keyword arguments: project -- start -- start date end -- end date """ try: cache = ProjectCache.objects.get(
python
{ "resource": "" }
q16851
get_person_usage
train
def get_person_usage(person, project, start, end): """Return a tuple of cpu hours and number of jobs for a person in a specific project Keyword arguments: person -- project -- The project the usage is from start -- start date end -- end date """ try:
python
{ "resource": "" }
q16852
get_machine_usage
train
def get_machine_usage(machine, start, end): """Return a tuple of cpu hours and number of jobs for a machine for a given period Keyword arguments: machine -- start -- start date end -- end date """ try: cache = MachineCache.objects.get(
python
{ "resource": "" }
q16853
get_machine_category_usage
train
def get_machine_category_usage(start, end): """Return a tuple of cpu hours and number of jobs for a given period Keyword arguments: start -- start date end -- end date
python
{ "resource": "" }
q16854
get_applicant_from_email
train
def get_applicant_from_email(email): """ Get applicant from email address. If the person exists, return (person, True) If multiple matches, return (None, True) Otherwise create applicant and return (applicant, False) """ try: applicant = Person.active.get(email=email) existing_person = True
python
{ "resource": "" }
q16855
_send_invitation
train
def _send_invitation(request, project): """ The logged in project leader OR administrator wants to invite somebody. """ form = forms.InviteUserApplicationForm(request.POST or None) if request.method == 'POST': if form.is_valid(): email = form.cleaned_data['email'] applicant, existing_person = get_applicant_from_email(email) # If applicant is None then there were multiple persons found. if applicant is None: return render( template_name='kgapplications/' 'project_common_invite_multiple.html', context={'form': form, 'email': email}, request=request) if existing_person and 'existing' not in request.POST: return render( template_name='kgapplications/' 'project_common_invite_existing.html',
python
{ "resource": "" }
q16856
send_invitation
train
def send_invitation(request, project_id=None): """ The logged in project leader wants to invite somebody to their project. """ project = None if project_id is not None: project = get_object_or_404(Project, id=project_id) if project is None: if not is_admin(request): return HttpResponseForbidden('<h1>Access
python
{ "resource": "" }
q16857
new_application
train
def new_application(request): """ A new application by a user to start a new project. """ # Note default kgapplications/index.html will display error if user logged # in. if not settings.ALLOW_REGISTRATIONS: return render( template_name='kgapplications/project_common_disabled.html', context={}, request=request) roles = {'is_applicant', 'is_authorised'} if not request.user.is_authenticated: attrs, _ = saml.parse_attributes(request) defaults = {'email': attrs['email']} form = forms.UnauthenticatedInviteUserApplicationForm( request.POST or None, initial=defaults) if request.method == 'POST': if form.is_valid(): email = form.cleaned_data['email'] applicant, existing_person = get_applicant_from_email(email) # If applicant is None then there were multiple persons found. # This should never happen as the
python
{ "resource": "" }
q16858
_get_ldflags
train
def _get_ldflags(): """Determine the correct link flags. This attempts dummy compiles similar to how autotools does feature detection. """ # windows gcc does not support linking with unresolved symbols if sys.platform == 'win32': # pragma: no cover (windows) prefix = getattr(sys, 'real_prefix', sys.prefix) libs = os.path.join(prefix, str('libs')) return str('-L{} -lpython{}{}').format(libs, *sys.version_info[:2]) cc = subprocess.check_output(('go', 'env', 'CC')).decode('UTF-8').strip() with _tmpdir() as tmpdir: testf = os.path.join(tmpdir, 'test.c') with io.open(testf, 'w') as f: f.write('int f(int); int main(void) { return f(0); }\n') for lflag in LFLAGS: # pragma: no
python
{ "resource": "" }
q16859
get_penalty_model
train
def get_penalty_model(specification): """Factory function for penaltymodel_maxgap. Args: specification (penaltymodel.Specification): The specification for the desired penalty model. Returns: :class:`penaltymodel.PenaltyModel`: Penalty model with the given specification. Raises: :class:`penaltymodel.ImpossiblePenaltyModel`: If the penalty cannot be built. Parameters: priority (int): -100 """ # check that the feasible_configurations are spin feasible_configurations = specification.feasible_configurations if specification.vartype is dimod.BINARY:
python
{ "resource": "" }
q16860
insert_feasible_configurations
train
def insert_feasible_configurations(cur, feasible_configurations, encoded_data=None): """Insert a group of feasible configurations into the cache. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. feasible_configurations (dict[tuple[int]): The set of feasible configurations. Each key should be a tuple of variable assignments. The values are the relative energies. encoded_data (dict, optional): If a dictionary is provided, it will be populated with the serialized data. This is useful for preventing encoding the same information many times. Examples: >>> feasible_configurations = {(-1, -1): 0.0, (+1, +1): 0.0} >>> with pmc.cache_connect(':memory:') as cur: ... pmc.insert_feasible_configurations(cur, feasible_configurations) """ if encoded_data is None: encoded_data = {} if 'num_variables' not in encoded_data: encoded_data['num_variables'] = len(next(iter(feasible_configurations))) if 'num_feasible_configurations' not in encoded_data:
python
{ "resource": "" }
q16861
_decode_config
train
def _decode_config(c, num_variables): """inverse of _serialize_config, always converts to spin.""" def bits(c): n = 1 << (num_variables - 1)
python
{ "resource": "" }
q16862
insert_ising_model
train
def insert_ising_model(cur, nodelist, edgelist, linear, quadratic, offset, encoded_data=None): """Insert an Ising model into the cache. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. nodelist (list): The nodes in the graph. edgelist (list): The edges in the graph. linear (dict): The linear bias associated with each node in nodelist. quadratic (dict): The quadratic bias associated with teach edge in edgelist. offset (float): The constant offset applied to the ising problem. encoded_data (dict, optional): If a dictionary is provided, it will be populated with the serialized data. This is useful for preventing encoding the same information many times. """ if encoded_data is None: encoded_data = {} # insert graph and partially populate encoded_data with graph info insert_graph(cur, nodelist, edgelist, encoded_data=encoded_data) # need to encode
python
{ "resource": "" }
q16863
_serialize_linear_biases
train
def _serialize_linear_biases(linear, nodelist): """Serializes the linear biases. Args: linear: a interable object where linear[v] is the bias associated with v. nodelist (list): an ordered iterable containing the nodes. Returns: str: base 64 encoded string of little endian 8 byte floats, one for each of the biases in linear. Ordered according to nodelist. Examples: >>> _serialize_linear_biases({1: -1, 2: 1, 3: 0}, [1, 2, 3]) 'AAAAAAAA8L8AAAAAAADwPwAAAAAAAAAA'
python
{ "resource": "" }
q16864
_serialize_quadratic_biases
train
def _serialize_quadratic_biases(quadratic, edgelist): """Serializes the quadratic biases. Args: quadratic (dict): a dict of the form {edge1: bias1, ...} where each edge is of the form (node1, node2). edgelist (list): a list of the form [(node1, node2), ...]. Returns: str: base 64 encoded string of little endian 8 byte floats, one for each of the edges in quadratic. Ordered by edgelist. Example: >>> _serialize_quadratic_biases({(0, 1): -1, (1, 2): 1, (0, 2): .4}, ... [(0, 1), (1, 2),
python
{ "resource": "" }
q16865
iter_ising_model
train
def iter_ising_model(cur): """Iterate over all of the Ising models in the cache. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. Yields: tuple: A 5-tuple consisting of: list: The nodelist for a graph in the cache. list: the edgelist for a graph in the cache. dict: The linear biases of an Ising Model in the cache. dict: The quadratic biases of an Ising Model in the cache. float: The constant offset of an Ising Model in the cache. """ select = \ """
python
{ "resource": "" }
q16866
_decode_linear_biases
train
def _decode_linear_biases(linear_string, nodelist): """Inverse of _serialize_linear_biases. Args: linear_string (str): base 64 encoded string of little endian 8 byte floats, one for each of the nodes in nodelist. nodelist (list): list of the form [node1, node2, ...]. Returns: dict: linear biases in a dict. Examples: >>> _decode_linear_biases('AAAAAAAA8L8AAAAAAADwPwAAAAAAAAAA',
python
{ "resource": "" }
q16867
_decode_quadratic_biases
train
def _decode_quadratic_biases(quadratic_string, edgelist): """Inverse of _serialize_quadratic_biases Args: quadratic_string (str) : base 64 encoded string of little endian 8 byte floats, one for each of the edges. edgelist (list): a list of edges of the form [(node1, node2), ...]. Returns: dict: J. A dict of the form {edge1: bias1, ...} where each edge is of the form (node1, node2). Example: >>> _decode_quadratic_biases('AAAAAAAA8L8AAAAAAADwP5qZmZmZmdk/', ...
python
{ "resource": "" }
q16868
insert_penalty_model
train
def insert_penalty_model(cur, penalty_model): """Insert a penalty model into the database. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. penalty_model (:class:`penaltymodel.PenaltyModel`): A penalty model to be stored in the database. Examples: >>> import networkx as nx >>> import penaltymodel.core as pm >>> import dimod >>> graph = nx.path_graph(3) >>> decision_variables = (0, 2) >>> feasible_configurations = {(-1, -1): 0., (+1, +1): 0.} >>> spec = pm.Specification(graph, decision_variables, feasible_configurations, dimod.SPIN) >>> linear = {v: 0 for v in graph} >>> quadratic = {edge: -1 for edge in graph.edges} >>> model = dimod.BinaryQuadraticModel(linear, quadratic, 0.0, vartype=dimod.SPIN) >>> widget = pm.PenaltyModel.from_specification(spec, model, 2., -2) >>> with pmc.cache_connect(':memory:') as cur: ... pmc.insert_penalty_model(cur, widget) """ encoded_data = {} linear, quadratic, offset = penalty_model.model.to_ising() nodelist = sorted(linear) edgelist = sorted(sorted(edge) for edge in penalty_model.graph.edges) insert_graph(cur, nodelist, edgelist, encoded_data) insert_feasible_configurations(cur, penalty_model.feasible_configurations, encoded_data) insert_ising_model(cur, nodelist, edgelist, linear, quadratic, offset, encoded_data) encoded_data['decision_variables'] = json.dumps(penalty_model.decision_variables, separators=(',', ':')) encoded_data['classical_gap'] = penalty_model.classical_gap encoded_data['ground_energy'] = penalty_model.ground_energy insert = \ """ INSERT OR IGNORE INTO penalty_model( decision_variables, classical_gap, ground_energy,
python
{ "resource": "" }
q16869
PenaltyModel.from_specification
train
def from_specification(cls, specification, model, classical_gap, ground_energy): """Construct a PenaltyModel from a Specification. Args: specification (:class:`.Specification`): A specification that was used to generate the model. model (:class:`dimod.BinaryQuadraticModel`): A binary quadratic model that has ground states that match the feasible_configurations. classical_gap (numeric): The difference in classical energy between the ground state and the first excited state. Must be positive. ground_energy (numeric): The minimum energy of all possible configurations. Returns: :class:`.PenaltyModel` """ # Author note:
python
{ "resource": "" }
q16870
get_penalty_model
train
def get_penalty_model(specification, database=None): """Factory function for penaltymodel_cache. Args: specification (penaltymodel.Specification): The specification for the desired penalty model. database (str, optional): The path to the desired sqlite database file. If None, will use the default. Returns: :class:`penaltymodel.PenaltyModel`: Penalty model with the given specification. Raises: :class:`penaltymodel.MissingPenaltyModel`: If the penalty model is not in the cache. Parameters: priority (int): 100 """ # only handles index-labelled nodes if not _is_index_labelled(specification.graph): relabel_applied = True mapping, inverse_mapping = _graph_canonicalization(specification.graph) specification = specification.relabel_variables(mapping, inplace=False) else: relabel_applied = False # connect to the database. Note that once the connection is made it cannot be
python
{ "resource": "" }
q16871
cache_penalty_model
train
def cache_penalty_model(penalty_model, database=None): """Caching function for penaltymodel_cache. Args: penalty_model (:class:`penaltymodel.PenaltyModel`): Penalty model to be cached. database (str, optional): The path to the desired sqlite database file. If None, will use the default. """ # only handles index-labelled nodes if not _is_index_labelled(penalty_model.graph): mapping, __ = _graph_canonicalization(penalty_model.graph) penalty_model = penalty_model.relabel_variables(mapping, inplace=False)
python
{ "resource": "" }
q16872
get_penalty_model
train
def get_penalty_model(specification): """Retrieve a PenaltyModel from one of the available factories. Args: specification (:class:`.Specification`): The specification for the desired PenaltyModel. Returns: :class:`.PenaltyModel`/None: A PenaltyModel as returned by the highest priority factory, or None if no factory could produce it. Raises: :exc:`ImpossiblePenaltyModel`: If the specification describes a penalty model that cannot be built by any factory. """ # Iterate through the available factories until one gives a penalty model for factory in iter_factories(): try:
python
{ "resource": "" }
q16873
iter_factories
train
def iter_factories(): """Iterate through all factories identified by the factory entrypoint. Yields: function: A function that accepts a :class:`.Specification` and returns a :class:`.PenaltyModel`. """ # retrieve all of
python
{ "resource": "" }
q16874
generate_bqm
train
def generate_bqm(graph, table, decision, linear_energy_ranges=None, quadratic_energy_ranges=None, min_classical_gap=2, precision=7, max_decision=8, max_variables=10, return_auxiliary=False): """Get a binary quadratic model with specific ground states. Args: graph (:obj:`~networkx.Graph`): Defines the structure of the generated binary quadratic model. table (iterable): Iterable of valid configurations (of spin-values). Each configuration is a tuple of variable assignments ordered by `decision`. decision (list/tuple): The variables in the binary quadratic model which have specified configurations. linear_energy_ranges (dict, optional): Dict of the form {v: (min, max, ...} where min and max are the range of values allowed to v. The default range is [-2, 2]. quadratic_energy_ranges (dict, optional): Dict of the form {(u, v): (min, max), ...} where min and max are the range of values allowed to (u, v). The default range is [-1, 1]. min_classical_gap (float): The minimum energy gap between the highest feasible state and the lowest infeasible state. precision (int, optional, default=7): Values returned by the optimization solver are rounded to `precision` digits of precision. max_decision (int, optional, default=4): Maximum number of decision variables allowed. The algorithm is valid for arbitrary sizes of problem but can be extremely slow. max_variables (int, optional, default=4): Maximum number of variables allowed. The algorithm is valid for arbitrary sizes of problem but can be extremely slow. return_auxiliary (bool, optional, False): If True, the auxiliary configurations are returned for each configuration in table. Returns: If return_auxiliary is False: :obj:`dimod.BinaryQuadraticModel`: The binary quadratic model. float: The classical gap. If return_auxiliary is True: :obj:`dimod.BinaryQuadraticModel`: The binary quadratic model. float: The classical gap. dict: The auxiliary configurations, keyed on the configurations in table. Raises: ImpossiblePenaltyModel: If the penalty model cannot be built. Normally due to a non-zero infeasible gap. """ # Developer note: This function is input checking and output formatting. The logic is # in _generate_ising if not isinstance(graph, nx.Graph): raise TypeError("expected input graph to be a NetworkX Graph.") if not set().union(*table).issubset({-1, 1}): raise ValueError("expected table to be spin-valued") if not isinstance(decision, list): decision =
python
{ "resource": "" }
q16875
get_penalty_model
train
def get_penalty_model(specification): """Factory function for penaltymodel-lp. Args: specification (penaltymodel.Specification): The specification for the desired penalty model. Returns: :class:`penaltymodel.PenaltyModel`: Penalty model with the given specification. Raises: :class:`penaltymodel.ImpossiblePenaltyModel`: If the penalty cannot be built. Parameters: priority (int): -100 """ # check that the feasible_configurations are spin feasible_configurations = specification.feasible_configurations if specification.vartype is dimod.BINARY: feasible_configurations = {tuple(2 * v - 1 for v in config): en for config, en in iteritems(feasible_configurations)} # convert ising_quadratic_ranges to the form we expect ising_quadratic_ranges = specification.ising_quadratic_ranges
python
{ "resource": "" }
q16876
get_item
train
def get_item(dictionary, tuple_key, default_value): """Grab values from a dictionary using an unordered tuple as a key. Dictionary should not contain None, 0, or False as dictionary values. Args: dictionary: Dictionary that uses two-element tuple as keys tuple_key: Unordered tuple of two elements default_value: Value that is returned when the tuple_key is not found in the dictionary
python
{ "resource": "" }
q16877
limitReal
train
def limitReal(x, max_denominator=1000000): """Creates an pysmt Real constant from x. Args: x (number): A number to be cast to a pysmt constant. max_denominator (int, optional): The maximum size of the denominator. Default 1000000. Returns: A
python
{ "resource": "" }
q16878
Theta.from_graph
train
def from_graph(cls, graph, linear_energy_ranges, quadratic_energy_ranges): """Create Theta from a graph and energy ranges. Args: graph (:obj:`networkx.Graph`): Provides the structure for Theta. linear_energy_ranges (dict): A dict of the form {v: (min, max), ...} where min and max are the range of values allowed to v. quadratic_energy_ranges (dict): A dict of the form {(u, v): (min, max), ...} where min and max are the range of values allowed to (u, v). Returns: :obj:`.Theta` """ get_env().enable_infix_notation = True # not sure why we need this here theta = cls.empty(dimod.SPIN) theta.add_offset(Symbol('offset', REAL)) def Linear(v): """Create a Symbol for the linear bias including the energy range constraints.""" bias = Symbol('h_{}'.format(v), REAL) min_, max_ = linear_energy_ranges[v] theta.assertions.add(LE(bias, limitReal(max_))) theta.assertions.add(GE(bias, limitReal(min_))) return bias def Quadratic(u,
python
{ "resource": "" }
q16879
Theta.to_bqm
train
def to_bqm(self, model): """Given a pysmt model, return a bqm. Adds the values of the biases as determined by the SMT solver to a bqm. Args: model: A pysmt model. Returns: :obj:`dimod.BinaryQuadraticModel`
python
{ "resource": "" }
q16880
SpinTimes
train
def SpinTimes(spin, bias): """Define our own multiplication for bias times spins. This allows for cleaner log code as well as value checking. Args: spin (int): -1 or 1 bias (:class:`pysmt.shortcuts.Symbol`): The bias
python
{ "resource": "" }
q16881
_elimination_trees
train
def _elimination_trees(theta, decision_variables): """From Theta and the decision variables, determine the elimination order and the induced trees. """ # auxiliary variables are any variables that are not decision auxiliary_variables = set(n for n in theta.linear if n not in decision_variables) # get the adjacency of the auxiliary subgraph adj = {v: {u for u in theta.adj[v] if u in auxiliary_variables} for v in theta.adj if v in auxiliary_variables} # get the elimination order that minimizes treewidth tw, order = dnx.treewidth_branch_and_bound(adj) ancestors = {} for n in order: ancestors[n] = set(adj[n]) # now make v simplicial by making its neighborhood a clique, then # continue neighbors = adj[n] for u, v in itertools.combinations(neighbors, 2): adj[u].add(v) adj[v].add(u) for v in neighbors: adj[v].discard(n) del adj[n]
python
{ "resource": "" }
q16882
Table.energy_upperbound
train
def energy_upperbound(self, spins): """A formula for an upper bound on the energy of Theta with spins fixed. Args: spins (dict): Spin values for a subset of the variables in Theta. Returns: Formula that upper bounds the energy with spins fixed. """ subtheta = self.theta.copy() subtheta.fix_variables(spins) # ok, let's start eliminating variables trees = self._trees if not trees: # if there are no variables to eliminate, then the offset of
python
{ "resource": "" }
q16883
Table.energy
train
def energy(self, spins, break_aux_symmetry=True): """A formula for the exact energy of Theta with spins fixed. Args: spins (dict): Spin values for a subset of the variables in Theta. break_aux_symmetry (bool, optional): Default True. If True, break the aux variable symmetry by setting all aux variable to 1 for one of the feasible configurations. If the energy ranges are not symmetric then this can make finding models impossible. Returns: Formula for the exact energy of Theta with spins fixed.
python
{ "resource": "" }
q16884
Table.message
train
def message(self, tree, spins, subtheta, auxvars): """Determine the energy of the elimination tree. Args: tree (dict): The current elimination tree spins (dict): The current fixed spins subtheta (dict): Theta with spins fixed. auxvars (dict): The auxiliary variables for the given spins. Returns: The formula for the energy of the tree. """ energy_sources = set() for v, children in tree.items(): aux = auxvars[v] assert all(u in spins for u in self._ancestors[v]) # build an iterable over all of the energies contributions # that we can exactly determine given v and our known spins # in these contributions we assume that v is positive def energy_contributions(): yield subtheta.linear[v] for u, bias in subtheta.adj[v].items():
python
{ "resource": "" }
q16885
Table.message_upperbound
train
def message_upperbound(self, tree, spins, subtheta): """Determine an upper bound on the energy of the elimination tree. Args: tree (dict): The current elimination tree spins (dict): The current fixed spins subtheta (dict): Theta with spins fixed. Returns: The formula for the energy of the tree. """ energy_sources = set() for v, subtree in tree.items(): assert all(u in spins for u in self._ancestors[v]) # build an iterable over all of the energies contributions # that we can exactly determine given v and our known spins # in these contributions we assume that v is positive def energy_contributions(): yield subtheta.linear[v] for u, bias in subtheta.adj[v].items(): if u in spins: yield Times(limitReal(spins[u]), bias) energy = Plus(energy_contributions()) # if there are no more variables in the order, we can
python
{ "resource": "" }
q16886
Table.set_energy
train
def set_energy(self, spins, target_energy): """Set the energy of Theta with spins fixed to target_energy. Args: spins (dict): Spin values for a subset of the variables in Theta. target_energy (float): The desired energy for Theta with spins fixed. Notes:
python
{ "resource": "" }
q16887
PandABlocksManagerController._poll_loop
train
def _poll_loop(self): """At self.poll_period poll for changes""" next_poll = time.time() while True: next_poll += self._poll_period timeout = next_poll - time.time() if timeout < 0: timeout = 0 try: return self._stop_queue.get(timeout=timeout) except TimeoutError: # No stop, no problem
python
{ "resource": "" }
q16888
camel_to_title
train
def camel_to_title(name): """Takes a camelCaseFieldName and returns an Title Case Field Name Args: name (str): E.g. camelCaseFieldName
python
{ "resource": "" }
q16889
snake_to_camel
train
def snake_to_camel(name): """Takes a snake_field_name and returns a camelCaseFieldName Args: name (str): E.g. snake_field_name or SNAKE_FIELD_NAME Returns: str: camelCase
python
{ "resource": "" }
q16890
Serializable.from_dict
train
def from_dict(cls, d, ignore=()): """Create an instance from a serialized version of cls Args: d(dict): Endpoints of cls to set ignore(tuple): Keys to ignore Returns: Instance of this class """ filtered = {} for k, v in d.items(): if k == "typeid": assert v == cls.typeid, \ "Dict has typeid %s but %s has typeid %s" % \
python
{ "resource": "" }
q16891
Serializable.lookup_subclass
train
def lookup_subclass(cls, d): """Look up a class based on a serialized dictionary containing a typeid Args: d (dict): Dictionary with key "typeid" Returns: Serializable subclass
python
{ "resource": "" }
q16892
Process.start
train
def start(self, timeout=None): """Start the process going Args: timeout (float): Maximum amount of time to wait for each spawned process. None means forever """ assert self.state == STOPPED, "Process already started" self.state = STARTING
python
{ "resource": "" }
q16893
Process.stop
train
def stop(self, timeout=None): """Stop the process and wait for it to finish Args: timeout (float): Maximum amount of time to wait for each spawned object. None means forever """ assert self.state == STARTED, "Process not started" self.state = STOPPING # Allow every controller a chance to clean up self._run_hook(ProcessStopHook, timeout=timeout) for s in self._spawned: if not s.ready(): self.log.debug(
python
{ "resource": "" }
q16894
Process.spawn
train
def spawn(self, function, *args, **kwargs): # type: (Callable[..., Any], *Any, **Any) -> Spawned """Runs the function in a worker thread, returning a Result object Args: function: Function to run args: Positional arguments to run the function with kwargs: Keyword arguments to run the function with Returns: Spawned: Something you can call wait(timeout) on to see when it's finished executing """ assert self.state != STOPPED,
python
{ "resource": "" }
q16895
Process.add_controller
train
def add_controller(self, controller, timeout=None): # type: (Controller, float) -> None """Add a controller to be hosted by this process Args: controller (Controller): Its controller timeout (float): Maximum amount of time to wait for each spawned
python
{ "resource": "" }
q16896
Process.block_view
train
def block_view(self, mri): # type: (str) -> Block """Get a Block view from a Controller with given mri"""
python
{ "resource": "" }
q16897
BasicController.update_title
train
def update_title(self, _, info): # type: (object, TitleInfo) -> None """Set the label of the Block Meta object"""
python
{ "resource": "" }
q16898
BasicController.update_health
train
def update_health(self, reporter, info): # type: (object, HealthInfo) -> None """Set the health attribute. Called from part""" with self.changes_squashed: alarm = info.alarm if alarm.is_ok(): self._faults.pop(reporter, None) else: self._faults[reporter] = alarm if self._faults: # Sort them by severity
python
{ "resource": "" }
q16899
PandABlocksMaker.make_parts_for
train
def make_parts_for(self, field_name, field_data): """Create the relevant parts for this field Args: field_name (str): Short field name, e.g. VAL field_data (FieldData): Field data object """ typ = field_data.field_type subtyp = field_data.field_subtype if typ in ("read", "xadc"): writeable = False else: writeable = True if typ == "time" or typ in ("param", "read") and subtyp == "time": self._make_time_parts(field_name, field_data, writeable) elif typ == "write" and subtyp == "action": self._make_action_part(field_name, field_data)
python
{ "resource": "" }