_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q15600 | setup_simulation_from_model_specification | train | def setup_simulation_from_model_specification(model_specification_file: str) -> InteractiveContext:
"""Construct a simulation from a model specification file and call its setup
method.
Parameters
----------
model_specification_file
The path to a model specification file.
Returns
--... | python | {
"resource": ""
} |
q15601 | InteractiveContext.setup | train | def setup(self):
"""Setup the simulation and initialize its population."""
super().setup()
self._start_time = self.clock.time
self.initialize_simulants() | python | {
"resource": ""
} |
q15602 | InteractiveContext.initialize_simulants | train | def initialize_simulants(self):
"""Initialize this simulation's population. Should not be called
directly."""
super().initialize_simulants()
self._initial_population = self.population.get_population(True) | python | {
"resource": ""
} |
q15603 | InteractiveContext.reset | train | def reset(self):
"""Reset the simulation to its initial state."""
warnings.warn("This reset method is very crude. It should work for "
"many simple simulations, but we make no guarantees. In "
"particular, if you have components that manage their "
... | python | {
"resource": ""
} |
q15604 | InteractiveContext.run | train | def run(self, with_logging: bool=True) -> int:
"""Run the simulation for the time duration specified in the
configuration
Parameters
----------
with_logging
Whether or not to log the simulation steps. Only works in an ipython
environment.
Returns... | python | {
"resource": ""
} |
q15605 | InteractiveContext.run_for | train | def run_for(self, duration: Timedelta, with_logging: bool=True) -> int:
"""Run the simulation for the given time duration.
Parameters
----------
duration
The length of time to run the simulation for. Should be the same
type as the simulation clock's step size (u... | python | {
"resource": ""
} |
q15606 | InteractiveContext.run_until | train | def run_until(self, end_time: Time, with_logging=True) -> int:
"""Run the simulation until the provided end time.
Parameters
----------
end_time
The time to run the simulation until. The simulation will run until
its clock is greater than or equal to the provided... | python | {
"resource": ""
} |
q15607 | InteractiveContext.step | train | def step(self, step_size: Timedelta=None):
"""Advance the simulation one step.
Parameters
----------
step_size
An optional size of step to take. Must be the same type as the
simulation clock's step size (usually a pandas.Timedelta).
"""
old_step_s... | python | {
"resource": ""
} |
q15608 | InteractiveContext.take_steps | train | def take_steps(self, number_of_steps: int=1, step_size: Timedelta=None, with_logging: bool=True):
"""Run the simulation for the given number of steps.
Parameters
----------
number_of_steps
The number of steps to take.
step_size
An optional size of step to... | python | {
"resource": ""
} |
q15609 | InteractiveContext.get_population | train | def get_population(self, untracked: bool=False) -> pd.DataFrame:
"""Get a copy of the population state table."""
return self.population.get_population(untracked) | python | {
"resource": ""
} |
q15610 | InteractiveContext.get_listeners | train | def get_listeners(self, event_type: str) -> List[Callable]:
"""Get all listeners of a particular type of event."""
if event_type not in self.events:
raise ValueError(f'No event {event_type} in system.')
return self.events.get_listeners(event_type) | python | {
"resource": ""
} |
q15611 | InteractiveContext.get_emitter | train | def get_emitter(self, event_type: str) -> Callable:
"""Get the callable that emits the given type of events."""
if event_type not in self.events:
raise ValueError(f'No event {event_type} in system.')
return self.events.get_emitter(event_type) | python | {
"resource": ""
} |
q15612 | InteractiveContext.get_components | train | def get_components(self) -> List:
"""Get a list of all components in the simulation."""
return [component for component in self.component_manager._components + self.component_manager._managers] | python | {
"resource": ""
} |
q15613 | LookupTableInterface.build_table | train | def build_table(self, data, key_columns=('sex',), parameter_columns=(['age', 'age_group_start', 'age_group_end'],
['year', 'year_start', 'year_end']),
value_columns=None) -> LookupTable:
"""Construct a LookupTable from ... | python | {
"resource": ""
} |
q15614 | ResultsWriter.add_sub_directory | train | def add_sub_directory(self, key, path):
"""Adds a sub-directory to the results directory.
Parameters
----------
key: str
A look-up key for the directory path.
path: str
The relative path from the root of the results directory to the sub-directory.
... | python | {
"resource": ""
} |
q15615 | ResultsWriter.write_output | train | def write_output(self, data, file_name, key=None):
"""Writes output data to disk.
Parameters
----------
data: pandas.DataFrame or dict
The data to write to disk.
file_name: str
The name of the file to write.
key: str, optional
The look... | python | {
"resource": ""
} |
q15616 | ResultsWriter.copy_file | train | def copy_file(self, src_path, file_name, key=None):
"""Copies a file unmodified to a location inside the ouput directory.
Parameters
----------
src_path: str
Path to the src file
file_name: str
name of the destination file
"""
path = os.pa... | python | {
"resource": ""
} |
q15617 | replace_combiner | train | def replace_combiner(value, mutator, *args, **kwargs):
"""Replaces the output of the source or mutator with the output
of the subsequent mutator. This is the default combiner.
"""
args = list(args) + [value]
return mutator(*args, **kwargs) | python | {
"resource": ""
} |
q15618 | set_combiner | train | def set_combiner(value, mutator, *args, **kwargs):
"""Expects the output of the source to be a set to which
the result of each mutator is added.
"""
value.add(mutator(*args, **kwargs))
return value | python | {
"resource": ""
} |
q15619 | list_combiner | train | def list_combiner(value, mutator, *args, **kwargs):
"""Expects the output of the source to be a list to which
the result of each mutator is appended.
"""
value.append(mutator(*args, **kwargs))
return value | python | {
"resource": ""
} |
q15620 | ValuesInterface.register_value_producer | train | def register_value_producer(self, value_name: str, source: Callable[..., pd.DataFrame]=None,
preferred_combiner: Callable=replace_combiner,
preferred_post_processor: Callable[..., pd.DataFrame]=None) -> Pipeline:
"""Marks a ``Callable`` as the prod... | python | {
"resource": ""
} |
q15621 | ValuesInterface.register_rate_producer | train | def register_rate_producer(self, rate_name: str, source: Callable[..., pd.DataFrame]=None) -> Pipeline:
"""Marks a ``Callable`` as the producer of a named rate.
This is a convenience wrapper around ``register_value_producer`` that makes sure
rate data is appropriately scaled to the size of the ... | python | {
"resource": ""
} |
q15622 | ValuesInterface.register_value_modifier | train | def register_value_modifier(self, value_name: str, modifier: Callable, priority: int=5):
"""Marks a ``Callable`` as the modifier of a named value.
Parameters
----------
value_name :
The name of the dynamic value pipeline to be modified.
modifier :
A funct... | python | {
"resource": ""
} |
q15623 | run | train | def run(model_specification, results_directory, verbose, log, with_debugger):
"""Run a simulation from the command line.
The simulation itself is defined by the given MODEL_SPECIFICATION yaml file.
Within the results directory, which defaults to ~/vivarium_results if none
is provided, a subdirectory w... | python | {
"resource": ""
} |
q15624 | profile | train | def profile(model_specification, results_directory, process):
"""Run a simulation based on the provided MODEL_SPECIFICATION and profile
the run.
"""
model_specification = Path(model_specification)
results_directory = Path(results_directory)
out_stats_file = results_directory / f'{model_specific... | python | {
"resource": ""
} |
q15625 | Event.split | train | def split(self, new_index):
"""Create a new event which is a copy of this one but with a new index.
"""
new_event = Event(new_index, self.user_data)
new_event.time = self.time
new_event.step_size = self.step_size
return new_event | python | {
"resource": ""
} |
q15626 | _EventChannel.emit | train | def emit(self, event):
"""Notifies all listeners to this channel that an event has occurred.
Parameters
----------
event : Event
The event to be emitted.
"""
if hasattr(event, 'time'):
event.step_size = self.manager.step_size()
event.t... | python | {
"resource": ""
} |
q15627 | EventManager.setup | train | def setup(self, builder):
"""Performs this components simulation setup.
Parameters
----------
builder : vivarium.framework.engine.Builder
Object giving access to core framework functionality.
"""
self.clock = builder.time.clock()
self.step_size = buil... | python | {
"resource": ""
} |
q15628 | EventManager.register_listener | train | def register_listener(self, name, listener, priority=5):
"""Registers a new listener to the named event.
Parameters
----------
name : str
The name of the event.
listener : Callable
The consumer of the named event.
priority : int
Number... | python | {
"resource": ""
} |
q15629 | EventInterface.get_emitter | train | def get_emitter(self, name: str) -> Callable[[Event], Event]:
"""Gets and emitter for a named event.
Parameters
----------
name :
The name of the event he requested emitter will emit.
Users may provide their own named events by requesting an emitter with this fun... | python | {
"resource": ""
} |
q15630 | EventInterface.register_listener | train | def register_listener(self, name: str, listener: Callable[[Event], None], priority: int=5) -> None:
"""Registers a callable as a listener to a events with the given name.
The listening callable will be called with a named ``Event`` as it's only argument any time the
event emitter is invoked fro... | python | {
"resource": ""
} |
q15631 | PopulationView.get | train | def get(self, index: pd.Index, query: str='', omit_missing_columns: bool=False) -> pd.DataFrame:
"""For the rows in ``index`` get the columns from the simulation's population which this view is configured.
The result may be further filtered by the view's query.
Parameters
----------
... | python | {
"resource": ""
} |
q15632 | PopulationView.update | train | def update(self, pop: Union[pd.DataFrame, pd.Series]):
"""Update the simulation's state to match ``pop``
Parameters
----------
pop :
The data which should be copied into the simulation's state. If ``pop`` is a DataFrame only those columns
included in the view... | python | {
"resource": ""
} |
q15633 | PopulationManager.get_view | train | def get_view(self, columns: Sequence[str], query: str=None) -> PopulationView:
"""Return a configured PopulationView
Notes
-----
Client code should only need this (and only through the version exposed as
``population_view`` on the builder during setup) if it uses dynamically
... | python | {
"resource": ""
} |
q15634 | PopulationInterface.get_view | train | def get_view(self, columns: Sequence[str], query: str = None) -> PopulationView:
"""Get a time-varying view of the population state table.
The requested population view can be used to view the current state or to update the state
with new values.
Parameters
----------
c... | python | {
"resource": ""
} |
q15635 | PopulationInterface.initializes_simulants | train | def initializes_simulants(self, initializer: Callable[[SimulantData], None],
creates_columns: Sequence[str]=(),
requires_columns: Sequence[str]=()):
"""Marks a callable as a source of initial state information for new simulants.
Parameters
... | python | {
"resource": ""
} |
q15636 | ensure_dir_exists | train | def ensure_dir_exists(directory):
"""Se asegura de que un directorio exista."""
if directory and not os.path.exists(directory):
os.makedirs(directory) | python | {
"resource": ""
} |
q15637 | traverse_dict | train | def traverse_dict(dicc, keys, default_value=None):
"""Recorre un diccionario siguiendo una lista de claves, y devuelve
default_value en caso de que alguna de ellas no exista.
Args:
dicc (dict): Diccionario a ser recorrido.
keys (list): Lista de claves a ser recorrida. Puede contener
... | python | {
"resource": ""
} |
q15638 | parse_value | train | def parse_value(cell):
"""Extrae el valor de una celda de Excel como texto."""
value = cell.value
# stripea espacios en strings
if isinstance(value, string_types):
value = value.strip()
# convierte a texto ISO 8601 las fechas
if isinstance(value, (datetime)):
value = value.isof... | python | {
"resource": ""
} |
q15639 | sheet_to_table | train | def sheet_to_table(worksheet):
"""Transforma una hoja de libro de Excel en una lista de diccionarios.
Args:
worksheet (Workbook.worksheet): Hoja de cálculo de un archivo XLSX
según los lee `openpyxl`
Returns:
list_of_dicts: Lista de diccionarios, con tantos elementos como
... | python | {
"resource": ""
} |
q15640 | string_to_list | train | def string_to_list(string, sep=",", filter_empty=False):
"""Transforma una string con elementos separados por `sep` en una lista."""
return [value.strip() for value in string.split(sep)
if (not filter_empty or value)] | python | {
"resource": ""
} |
q15641 | generate_distribution_ids | train | def generate_distribution_ids(catalog):
"""Genera identificadores para las distribuciones que no los tienen.
Los identificadores de distribuciones se generan concatenando el id del
dataset al que pertenecen con el índice posicional de la distribución en el
dataset: distribution_identifier = "{dataset_i... | python | {
"resource": ""
} |
q15642 | BasePopulation.on_initialize_simulants | train | def on_initialize_simulants(self, pop_data: SimulantData):
"""Called by the simulation whenever new simulants are added.
This component is responsible for creating and filling four columns
in the population state table:
'age' :
The age of the simulant in fractional years.
... | python | {
"resource": ""
} |
q15643 | BasePopulation.age_simulants | train | def age_simulants(self, event: Event):
"""Updates simulant age on every time step.
Parameters
----------
event :
An event object emitted by the simulation containing an index
representing the simulants affected by the event and timing
information.
... | python | {
"resource": ""
} |
q15644 | random | train | def random(key: str, index: Index, index_map: IndexMap=None) -> pd.Series:
"""Produces an indexed `pandas.Series` of uniformly distributed random numbers.
The index passed in typically corresponds to a subset of rows in a
`pandas.DataFrame` for which a probabilistic draw needs to be made.
Parameters
... | python | {
"resource": ""
} |
q15645 | get_hash | train | def get_hash(key: str) -> int:
"""Gets a hash of the provided key.
Parameters
----------
key :
A string used to create a seed for the random number generator.
Returns
-------
int
A hash of the provided key.
"""
# 4294967295 == 2**32 - 1 which is the maximum allowabl... | python | {
"resource": ""
} |
q15646 | _set_residual_probability | train | def _set_residual_probability(p: np.ndarray) -> np.ndarray:
"""Turns any use of `RESIDUAL_CHOICE` into a residual probability.
Parameters
----------
p :
Array where each row is a set of probability weights and potentially
a `RESIDUAL_CHOICE` placeholder.
Returns
-------
np.... | python | {
"resource": ""
} |
q15647 | IndexMap.update | train | def update(self, new_keys: Index):
"""Adds the new keys to the mapping.
Parameters
----------
new_keys :
The new index to hash.
"""
if not self._map.index.intersection(new_keys).empty:
raise KeyError("Non-unique keys in index.")
mapping_u... | python | {
"resource": ""
} |
q15648 | IndexMap.convert_to_ten_digit_int | train | def convert_to_ten_digit_int(self, column: pd.Series) -> pd.Series:
"""Converts a column of datetimes, integers, or floats into a column of 10 digit integers.
Parameters
----------
column :
A series of datetimes, integers, or floats.
Returns
-------
... | python | {
"resource": ""
} |
q15649 | IndexMap.digit | train | def digit(m: Union[int, pd.Series], n: int) -> Union[int, pd.Series]:
"""Returns the nth digit of each number in m."""
return (m // (10 ** n)) % 10 | python | {
"resource": ""
} |
q15650 | IndexMap.clip_to_seconds | train | def clip_to_seconds(m: Union[int, pd.Series]) -> Union[int, pd.Series]:
"""Clips UTC datetime in nanoseconds to seconds."""
return m // pd.Timedelta(1, unit='s').value | python | {
"resource": ""
} |
q15651 | IndexMap.spread | train | def spread(self, m: Union[int, pd.Series]) -> Union[int, pd.Series]:
"""Spreads out integer values to give smaller values more weight."""
return (m * 111_111) % self.TEN_DIGIT_MODULUS | python | {
"resource": ""
} |
q15652 | IndexMap.shift | train | def shift(self, m: Union[float, pd.Series]) -> Union[int, pd.Series]:
"""Shifts floats so that the first 10 decimal digits are significant."""
out = m % 1 * self.TEN_DIGIT_MODULUS // 1
if isinstance(out, pd.Series):
return out.astype(int)
return int(out) | python | {
"resource": ""
} |
q15653 | RandomnessStream.copy_with_additional_key | train | def copy_with_additional_key(self, key: Any) -> 'RandomnessStream':
"""Creates a copy of this stream that combines this streams key with a new one.
Parameters
----------
key :
The additional key to describe the new stream with.
Returns
-------
Random... | python | {
"resource": ""
} |
q15654 | RandomnessStream._key | train | def _key(self, additional_key: Any=None) -> str:
"""Construct a hashable key from this object's state.
Parameters
----------
additional_key :
Any additional information used to seed random number generation.
Returns
-------
str
A key to s... | python | {
"resource": ""
} |
q15655 | RandomnessStream.get_draw | train | def get_draw(self, index: Index, additional_key: Any=None) -> pd.Series:
"""Get an indexed sequence of floats pulled from a uniform distribution over [0.0, 1.0)
Parameters
----------
index :
An index whose length is the number of random draws made
and which index... | python | {
"resource": ""
} |
q15656 | RandomnessStream.filter_for_rate | train | def filter_for_rate(self, population: Union[pd.DataFrame, pd.Series, Index],
rate: Array, additional_key: Any=None) -> Index:
"""Decide an event outcome for each individual in a population from rates.
Given a population or its index and an array of associated rates for
s... | python | {
"resource": ""
} |
q15657 | RandomnessManager.register_simulants | train | def register_simulants(self, simulants: pd.DataFrame):
"""Adds new simulants to the randomness mapping.
Parameters
----------
simulants :
A table with state data representing the new simulants. Each simulant should
pass through this function exactly once.
... | python | {
"resource": ""
} |
q15658 | GroupManager.student_visible | train | def student_visible(self):
"""Return a list of groups that are student-visible.
"""
group_ids = set()
for group in Group.objects.all():
if group.properties.student_visible:
group_ids.add(group.id)
return Group.objects.filter(id__in=group_ids) | python | {
"resource": ""
} |
q15659 | PhoneFormField.to_python | train | def to_python(self, value):
"""Returns a Unicode object."""
if value in self.empty_values:
return ""
value = force_text(value).strip()
return value | python | {
"resource": ""
} |
q15660 | _resolve_time | train | def _resolve_time(value):
'''
Resolve the time in seconds of a configuration value.
'''
if value is None or isinstance(value,(int,long)):
return value
if NUMBER_TIME.match(value):
return long(value)
simple = SIMPLE_TIME.match(value)
if SIMPLE_TIME.match(value):
multiplier = long( simple.grou... | python | {
"resource": ""
} |
q15661 | RelativeTime.step_size | train | def step_size(self, t0=None, t1=None):
'''
Return the time in seconds of a step. If a begin and end timestamp,
return the time in seconds between them after adjusting for what buckets
they alias to. If t1 and t0 resolve to the same bucket,
'''
if t0!=None and t1!=None:
tb0 = self.to_bucket... | python | {
"resource": ""
} |
q15662 | GregorianTime.to_bucket | train | def to_bucket(self, timestamp, steps=0):
'''
Calculate the bucket from a timestamp.
'''
dt = datetime.utcfromtimestamp( timestamp )
if steps!=0:
if self._step == 'daily':
dt = dt + timedelta(days=steps)
elif self._step == 'weekly':
dt = dt + timedelta(weeks=steps)
... | python | {
"resource": ""
} |
q15663 | GregorianTime.from_bucket | train | def from_bucket(self, bucket, native=False):
'''
Calculate the timestamp given a bucket.
'''
# NOTE: this is due to a bug somewhere in strptime that does not process
# the week number of '%Y%U' correctly. That bug could be very specific to
# the combination of python and ubuntu that I was testin... | python | {
"resource": ""
} |
q15664 | GregorianTime.normalize | train | def normalize(self, timestamp, steps=0):
'''
Normalize a timestamp according to the interval configuration. Optionally
can be used to calculate the timestamp N steps away.
'''
# So far, the only commonality with RelativeTime
return self.from_bucket( self.to_bucket(timestamp, steps) ) | python | {
"resource": ""
} |
q15665 | Timeseries._batch_insert | train | def _batch_insert(self, inserts, intervals, **kwargs):
'''
Support for batch insert. Default implementation is non-optimized and
is a simple loop over values.
'''
for timestamp,names in inserts.iteritems():
for name,values in names.iteritems():
for value in values:
self._inse... | python | {
"resource": ""
} |
q15666 | Timeseries._normalize_timestamps | train | def _normalize_timestamps(self, timestamp, intervals, config):
'''
Helper for the subclasses to generate a list of timestamps.
'''
rval = [timestamp]
if intervals<0:
while intervals<0:
rval.append( config['i_calc'].normalize(timestamp, intervals) )
intervals += 1
elif inter... | python | {
"resource": ""
} |
q15667 | Timeseries._join_results | train | def _join_results(self, results, coarse, join):
'''
Join a list of results. Supports both get and series.
'''
rval = OrderedDict()
i_keys = set()
for res in results:
i_keys.update( res.keys() )
for i_key in sorted(i_keys):
if coarse:
rval[i_key] = join( [res.get(i_key) fo... | python | {
"resource": ""
} |
q15668 | Timeseries._process_transform | train | def _process_transform(self, data, transform, step_size):
'''
Process transforms on the data.
'''
if isinstance(transform, (list,tuple,set)):
return { t : self._transform(data,t,step_size) for t in transform }
elif isinstance(transform, dict):
return { tn : self._transform(data,tf,step_s... | python | {
"resource": ""
} |
q15669 | Histogram._condense | train | def _condense(self, data):
'''
Condense by adding together all of the lists.
'''
rval = {}
for resolution,histogram in data.items():
for value,count in histogram.items():
rval[ value ] = count + rval.get(value,0)
return rval | python | {
"resource": ""
} |
q15670 | Gauge._condense | train | def _condense(self, data):
'''
Condense by returning the last real value of the gauge.
'''
if data:
data = filter(None,data.values())
if data:
return data[-1]
return None | python | {
"resource": ""
} |
q15671 | Set._condense | train | def _condense(self, data):
'''
Condense by or-ing all of the sets.
'''
if data:
return reduce(operator.ior, data.values())
return set() | python | {
"resource": ""
} |
q15672 | ApiBasicAuthentication.authenticate_credentials | train | def authenticate_credentials(self, userid, password, request=None):
"""Authenticate the userid and password."""
user = auth.authenticate(username=userid, password=password)
if user is None or (user and not user.is_active):
raise exceptions.AuthenticationFailed("Invalid username/pas... | python | {
"resource": ""
} |
q15673 | check_internal_ip | train | def check_internal_ip(request):
""" request is an AsgiRequest """
remote_addr = (request.META["HTTP_X_FORWARDED_FOR"] if "HTTP_X_FORWARDED_FOR" in request.META else request.META.get("REMOTE_ADDR", ""))
return remote_addr in settings.INTERNAL_IPS | python | {
"resource": ""
} |
q15674 | events_view | train | def events_view(request):
"""Events homepage.
Shows a list of events occurring in the next week, month, and
future.
"""
is_events_admin = request.user.has_admin_permission('events')
if request.method == "POST":
if "approve" in request.POST and is_events_admin:
event_id = ... | python | {
"resource": ""
} |
q15675 | join_event_view | train | def join_event_view(request, id):
"""Join event page. If a POST request, actually add or remove the attendance of the current
user. Otherwise, display a page with confirmation.
id: event id
"""
event = get_object_or_404(Event, id=id)
if request.method == "POST":
if not event.show_att... | python | {
"resource": ""
} |
q15676 | add_event_view | train | def add_event_view(request):
"""Add event page.
Currently, there is an approval process for events. If a user is an
events administrator, they can create events directly. Otherwise,
their event is added in the system but must be approved.
"""
is_events_admin = request.user.has_admin_permission... | python | {
"resource": ""
} |
q15677 | modify_event_view | train | def modify_event_view(request, id=None):
"""Modify event page. You may only modify an event if you were the creator or you are an
administrator.
id: event id
"""
event = get_object_or_404(Event, id=id)
is_events_admin = request.user.has_admin_permission('events')
if not is_events_admin:
... | python | {
"resource": ""
} |
q15678 | delete_event_view | train | def delete_event_view(request, id):
"""Delete event page. You may only delete an event if you were the creator or you are an
administrator. Confirmation page if not POST.
id: event id
"""
event = get_object_or_404(Event, id=id)
if not request.user.has_admin_permission('events'):
raise ... | python | {
"resource": ""
} |
q15679 | show_event_view | train | def show_event_view(request):
""" Unhide an event that was hidden by the logged-in user.
events_hidden in the user model is the related_name for
"users_hidden" in the EventUserMap model.
"""
if request.method == "POST":
event_id = request.POST.get("event_id")
if event_id:
... | python | {
"resource": ""
} |
q15680 | chrome_getdata_view | train | def chrome_getdata_view(request):
"""Get the data of the last notification sent to the current user.
This is needed because Chrome, as of version 44, doesn't support
sending a data payload to a notification. Thus, information on what
the notification is actually for must be manually fetched.
"""
... | python | {
"resource": ""
} |
q15681 | lostitem_add_view | train | def lostitem_add_view(request):
"""Add a lostitem."""
if request.method == "POST":
form = LostItemForm(request.POST)
logger.debug(form)
if form.is_valid():
obj = form.save()
obj.user = request.user
# SAFE HTML
obj.description = safe_html(ob... | python | {
"resource": ""
} |
q15682 | lostitem_modify_view | train | def lostitem_modify_view(request, item_id=None):
"""Modify a lostitem.
id: lostitem id
"""
if request.method == "POST":
lostitem = get_object_or_404(LostItem, id=item_id)
form = LostItemForm(request.POST, instance=lostitem)
if form.is_valid():
obj = form.save()
... | python | {
"resource": ""
} |
q15683 | lostitem_delete_view | train | def lostitem_delete_view(request, item_id):
"""Delete a lostitem.
id: lostitem id
"""
if request.method == "POST":
try:
a = LostItem.objects.get(id=item_id)
if request.POST.get("full_delete", False):
a.delete()
messages.success(request, "... | python | {
"resource": ""
} |
q15684 | lostitem_view | train | def lostitem_view(request, item_id):
"""View a lostitem.
id: lostitem id
"""
lostitem = get_object_or_404(LostItem, id=item_id)
return render(request, "itemreg/item_view.html", {"item": lostitem, "type": "lost"}) | python | {
"resource": ""
} |
q15685 | founditem_modify_view | train | def founditem_modify_view(request, item_id=None):
"""Modify a founditem.
id: founditem id
"""
if request.method == "POST":
founditem = get_object_or_404(FoundItem, id=item_id)
form = FoundItemForm(request.POST, instance=founditem)
if form.is_valid():
obj = form.save... | python | {
"resource": ""
} |
q15686 | founditem_delete_view | train | def founditem_delete_view(request, item_id):
"""Delete a founditem.
id: founditem id
"""
if request.method == "POST":
try:
a = FoundItem.objects.get(id=item_id)
if request.POST.get("full_delete", False):
a.delete()
messages.success(reques... | python | {
"resource": ""
} |
q15687 | founditem_view | train | def founditem_view(request, item_id):
"""View a founditem.
id: founditem id
"""
founditem = get_object_or_404(FoundItem, id=item_id)
return render(request, "itemreg/item_view.html", {"item": founditem, "type": "found"}) | python | {
"resource": ""
} |
q15688 | files_view | train | def files_view(request):
"""The main filecenter view."""
hosts = Host.objects.visible_to_user(request.user)
context = {"hosts": hosts}
return render(request, "files/home.html", context) | python | {
"resource": ""
} |
q15689 | files_auth | train | def files_auth(request):
"""Display authentication for filecenter."""
if "password" in request.POST:
"""
Encrypt the password with AES mode CFB.
Create a random 32 char key, stored in a CLIENT-side cookie.
Create a random 32 char IV, stored in a SERVER-side session.
... | python | {
"resource": ""
} |
q15690 | get_authinfo | train | def get_authinfo(request):
"""Get authentication info from the encrypted message."""
if (("files_iv" not in request.session) or ("files_text" not in request.session) or ("files_key" not in request.COOKIES)):
return False
"""
Decrypt the password given the SERVER-side IV, SERVER-side
... | python | {
"resource": ""
} |
q15691 | highlight | train | def highlight(str1, str2):
"""Highlight str1 with the contents of str2."""
print('------------------------------')
try:
str2 = str2[0]
except IndexError:
str2 = None
if str1 and str2:
return str1.replace(str2, "<b>{}</b>".format(str2))
else:
return str1 | python | {
"resource": ""
} |
q15692 | Command.handle | train | def handle(self, **options):
"""Exported "eighth_absentees" table in CSV format."""
with open('eighth_absentees.csv', 'r') as absopen:
absences = csv.reader(absopen)
for row in absences:
bid, uid = row
try:
usr = User.objects.g... | python | {
"resource": ""
} |
q15693 | KerberosAuthenticationBackend.kinit_timeout_handle | train | def kinit_timeout_handle(username, realm):
"""Check if the user exists before we throw an error."""
try:
u = User.objects.get(username__iexact=username)
except User.DoesNotExist:
logger.warning("kinit timed out for {}@{} (invalid user)".format(username, realm))
... | python | {
"resource": ""
} |
q15694 | KerberosAuthenticationBackend.get_kerberos_ticket | train | def get_kerberos_ticket(username, password):
"""Attempts to create a Kerberos ticket for a user.
Args:
username
The username.
password
The password.
Returns:
Boolean indicating success or failure of ticket creation
""... | python | {
"resource": ""
} |
q15695 | get_fcps_emerg | train | def get_fcps_emerg(request):
"""Return FCPS emergency information."""
try:
emerg = get_emerg()
except Exception:
logger.info("Unable to fetch FCPS emergency info")
emerg = {"status": False}
if emerg["status"] or ("show_emerg" in request.GET):
msg = emerg["message"]
... | python | {
"resource": ""
} |
q15696 | gen_schedule | train | def gen_schedule(user, num_blocks=6, surrounding_blocks=None):
"""Generate a list of information about a block and a student's current activity signup.
Returns:
schedule
no_signup_today
"""
no_signup_today = None
schedule = []
if surrounding_blocks is None:
surrounding... | python | {
"resource": ""
} |
q15697 | find_birthdays | train | def find_birthdays(request):
"""Return information on user birthdays."""
today = date.today()
custom = False
yr_inc = 0
if "birthday_month" in request.GET and "birthday_day" in request.GET:
try:
mon = int(request.GET["birthday_month"])
day = int(request.GET["birthday_... | python | {
"resource": ""
} |
q15698 | find_visible_birthdays | train | def find_visible_birthdays(request, data):
"""Return only the birthdays visible to current user.
"""
if request.user and (request.user.is_teacher or request.user.is_eighthoffice or request.user.is_eighth_admin):
return data
data['today']['users'] = [u for u in data['today']['users'] if u['public... | python | {
"resource": ""
} |
q15699 | EighthActivity._name_with_flags | train | def _name_with_flags(self, include_restricted, title=None):
"""Generate the name with flags."""
name = "Special: " if self.special else ""
name += self.name
if title:
name += " - {}".format(title)
if include_restricted and self.restricted:
name += " (R)"
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.