_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | 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': urlparse.urljoin(GRAPH_URL, filename + ".png"),
'data_url': urlparse.urljoin(GRAPH_URL, fi... | 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():
urls = get_institute_trend_graph_url(institute, start, end)
urls['institute'] = institute
graph_list.append(urls)
return graph_list | 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, full_na... | 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,
short_name=short_name, full_name=full_name,
... | 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,
institute=institute, password=password,
... | 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',))
parser.delete_first_token()
return ApplicationActionsPlus(nodelist) | 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, stderr=sp.STDOUT,
close_fds=sys.platform != 'win32')
for line in proc.stdout:
... | 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)
linkname = os.path.abspath(linkname)
if not os.path.exists(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 : s... | 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"
local... | 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'... | 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 = tempfile.mkdtemp()
for obj, level in hub.leaves(base.HubComponent, intermediate=True):
linknames.extend(stage(obj, stagin... | 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()
staging, linknames = stage_hub(hub, staging=staging)
local_dir = os.path.joi... | 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:
return 'Project not found'
return [x.username for x in project.group.members.all()] | python | {
"resource": ""
} |
q16814 | get_projects | train | def get_projects(machine):
"""
Returns list of project ids
"""
query = Project.active.all()
return [x.pid for x in query] | 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 fo... | python | {
"resource": ""
} |
q16816 | get_users_projects | train | def get_users_projects(user):
"""
List projects a user is part of
"""
person = user
projects = person.projects.filter(is_active=True)
return 0, [x.pid for x in projects] | 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... | 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) < minl... | 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)
except AttributeError:
raise Attribute... | 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_proj... | 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, {})
changes = 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, {
'password': raw_password,
})
save(changes, database=self._database) | 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)
changes = changeset(lgroup, {})
changes = lgroup.add_member(changes, person)
sa... | 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)
except ObjectDoesNotExist:
# it doesn't matter if it doesn't exist
pass | 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 result
for i, j in lgroup.items():
... | 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})
{3: 1.0, 5: 3.5, 9: 6.0}
... | 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 1.0 # Avoid a ``ZeroDivisionError``.
for k in sorted(sample.keys()... | 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)
... | 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`` equ... | 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 in... | 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 point... | 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
... | 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
# ... | 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')
proces... | 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(
... | 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 results:
if result["User"] != "":
... | 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" % username]
results = self._read_output(cmd)
project_list = []
for result in results:
project_list.append(result["Account"])
... | 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
if isins... | 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, 'debug', None))
... | 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__':
return '%s = <%s.%s object at 0x%x>' \
% (name, __mname, value.__class__.__name__, id(value))
else:
return '%s = <%s obj... | 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 = <type '%s.%s'>" % (name, __mname, value.__name__)
else:
return "%s = <type '%s'>" % (name, value.__name__) | 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
... | 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 ... | 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)
t... | 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_app... | 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)
state_machine = base.get_state_machine(application)
return state_machine.process(request, application, state, la... | 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_ex... | 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(
institute=institute,... | 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(
project=project, date=datetime... | 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:
cache = PersonCache.obje... | 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(
machine=machine, date=datetim... | 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
"""
cache = MachineCategoryCache.objects.get(
date=datetime.date.today(),
start=start, end=end)
retur... | 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)
exis... | 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']
applic... | 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):
re... | 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',
... | 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_pre... | 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.
Ra... | 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_configu... | 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)
for __ in range(num_variables):
yield 1 if c & n else -1
n >>= 1
return tuple(bits(c)) | 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... | 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 end... | 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:
st... | 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 ... | 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:
... | 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), ...].
... | 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
... | 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.BinaryQuadr... | 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 ... | 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 ... | 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 h... | 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 the factories with
factories = (entry.load() for entry in ite... | 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:
... | 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... | 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 e... | 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 Real constant with the given... | 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: ... | 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`
"""
linear = ((v, float(model.get_py_v... | 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
Returns:
spins * bias
"""
if not isinstance(spin, in... | 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)
... | 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.
"""
subt... | 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 variab... | 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 auxiliar... | 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:
... | 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:
Add... | 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... | 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
Returns:
str: Title Case converted name. E.g. Camel Case Field Name
"""
split = re.findall(r"[A-Z]?[a-z0-9]+|[A-Z]+(?=[A-Z]|$)", name)
ret = " ... | 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 converted name. E.g. capsFieldName
"""
ret = "".join(x.title() for x in name.split("_"))
ret = ret[0].lower... | 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():
... | 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
"""
try:
typeid = d["typeid"]
except KeyError:
... | 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
shou... | 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... | 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: Key... | 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
object.... | 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"""
controller = self.get_controller(mri)
block = controller.block_view()
return block | python | {
"resource": ""
} |
q16897 | BasicController.update_title | train | def update_title(self, _, info):
# type: (object, TitleInfo) -> None
"""Set the label of the Block Meta object"""
with self._lock:
self._block.meta.set_label(info.title) | 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:
... | 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
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.