repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_documentation_string stringlengths 1 47.2k | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|
ihmeuw/vivarium | src/vivarium/framework/randomness.py | IndexMap.clip_to_seconds | 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 | 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 | Clips UTC datetime in nanoseconds to seconds. | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/randomness.py#L157-L159 |
ihmeuw/vivarium | src/vivarium/framework/randomness.py | IndexMap.spread | 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 | 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 | Spreads out integer values to give smaller values more weight. | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/randomness.py#L161-L163 |
ihmeuw/vivarium | src/vivarium/framework/randomness.py | IndexMap.shift | 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 | 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) | Shifts floats so that the first 10 decimal digits are significant. | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/randomness.py#L165-L170 |
ihmeuw/vivarium | src/vivarium/framework/randomness.py | RandomnessStream.copy_with_additional_key | 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 | 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... | 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
-------
RandomnessStream
A new RandomnessStream with a combined key. | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/randomness.py#L421-L439 |
ihmeuw/vivarium | src/vivarium/framework/randomness.py | RandomnessStream._key | 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 | 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... | 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 seed random number generation. | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/randomness.py#L441-L454 |
ihmeuw/vivarium | src/vivarium/framework/randomness.py | RandomnessStream.get_draw | 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 | 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... | 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 indexes the returned `pandas.Series`.
additional_key :
Any additional... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/randomness.py#L456-L478 |
ihmeuw/vivarium | src/vivarium/framework/randomness.py | RandomnessStream.filter_for_rate | 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 | 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... | 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
some event to happen, we create and return the sub-population for whom
the event occurred.
Parameters
----------
population :
... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/randomness.py#L496-L528 |
ihmeuw/vivarium | src/vivarium/framework/randomness.py | RandomnessStream.filter_for_probability | def filter_for_probability(self, population: Union[pd.DataFrame, pd.Series, Index],
probability: Array, additional_key: Any=None) -> Index:
"""Decide an event outcome for each individual in a population from probabilities.
Given a population or its index and an array of a... | python | def filter_for_probability(self, population: Union[pd.DataFrame, pd.Series, Index],
probability: Array, additional_key: Any=None) -> Index:
"""Decide an event outcome for each individual in a population from probabilities.
Given a population or its index and an array of a... | Decide an event outcome for each individual in a population from probabilities.
Given a population or its index and an array of associated probabilities
for some event to happen, we create and return the sub-population for whom
the event occurred.
Parameters
----------
... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/randomness.py#L530-L556 |
ihmeuw/vivarium | src/vivarium/framework/randomness.py | RandomnessStream.choice | def choice(self, index: Index, choices: Array, p: Array=None, additional_key: Any=None) -> pd.Series:
"""Decides between a weighted or unweighted set of choices.
Given a a set of choices with or without corresponding weights,
returns an indexed set of decisions from those choices. This is
... | python | def choice(self, index: Index, choices: Array, p: Array=None, additional_key: Any=None) -> pd.Series:
"""Decides between a weighted or unweighted set of choices.
Given a a set of choices with or without corresponding weights,
returns an indexed set of decisions from those choices. This is
... | Decides between a weighted or unweighted set of choices.
Given a a set of choices with or without corresponding weights,
returns an indexed set of decisions from those choices. This is
simply a vectorized way to make decisions with some book-keeping.
Parameters
----------
... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/randomness.py#L558-L594 |
ihmeuw/vivarium | src/vivarium/framework/randomness.py | RandomnessManager.get_randomness_stream | def get_randomness_stream(self, decision_point: str, for_initialization: bool=False) -> RandomnessStream:
"""Provides a new source of random numbers for the given decision point.
Parameters
----------
decision_point :
A unique identifier for a stream of random numbers. Typi... | python | def get_randomness_stream(self, decision_point: str, for_initialization: bool=False) -> RandomnessStream:
"""Provides a new source of random numbers for the given decision point.
Parameters
----------
decision_point :
A unique identifier for a stream of random numbers. Typi... | Provides a new source of random numbers for the given decision point.
Parameters
----------
decision_point :
A unique identifier for a stream of random numbers. Typically represents
a decision that needs to be made each time step like 'moves_left' or
'gets_d... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/randomness.py#L630-L657 |
ihmeuw/vivarium | src/vivarium/framework/randomness.py | RandomnessManager.register_simulants | 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 | 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.
... | 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.
Raises
------
RandomnessError :
If ... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/randomness.py#L659-L675 |
ihmeuw/vivarium | src/vivarium/framework/randomness.py | RandomnessInterface.get_stream | def get_stream(self, decision_point: str, for_initialization: bool = False) -> RandomnessStream:
"""Provides a new source of random numbers for the given decision point.
``vivarium`` provides a framework for Common Random Numbers which allows for variance reduction
when modeling counter-factual... | python | def get_stream(self, decision_point: str, for_initialization: bool = False) -> RandomnessStream:
"""Provides a new source of random numbers for the given decision point.
``vivarium`` provides a framework for Common Random Numbers which allows for variance reduction
when modeling counter-factual... | Provides a new source of random numbers for the given decision point.
``vivarium`` provides a framework for Common Random Numbers which allows for variance reduction
when modeling counter-factual scenarios. Users interested in causal analysis and comparisons
between simulation scenarios should ... | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/randomness.py#L687-L713 |
tjcsl/ion | intranet/apps/groups/models.py | GroupManager.student_visible | 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 | 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) | Return a list of groups that are student-visible. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/groups/models.py#L11-L19 |
tjcsl/ion | intranet/apps/preferences/fields.py | PhoneFormField.to_python | def to_python(self, value):
"""Returns a Unicode object."""
if value in self.empty_values:
return ""
value = force_text(value).strip()
return value | python | def to_python(self, value):
"""Returns a Unicode object."""
if value in self.empty_values:
return ""
value = force_text(value).strip()
return value | Returns a Unicode object. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/preferences/fields.py#L39-L44 |
agoragames/kairos | kairos/timeseries.py | _resolve_time | 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 | 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... | Resolve the time in seconds of a configuration value. | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/timeseries.py#L44-L63 |
agoragames/kairos | kairos/timeseries.py | RelativeTime.step_size | 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 | 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... | 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, | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/timeseries.py#L73-L85 |
agoragames/kairos | kairos/timeseries.py | RelativeTime.buckets | def buckets(self, start, end):
'''
Calculate the buckets within a starting and ending timestamp.
'''
start_bucket = self.to_bucket(start)
end_bucket = self.to_bucket(end)
return range(start_bucket, end_bucket+1) | python | def buckets(self, start, end):
'''
Calculate the buckets within a starting and ending timestamp.
'''
start_bucket = self.to_bucket(start)
end_bucket = self.to_bucket(end)
return range(start_bucket, end_bucket+1) | Calculate the buckets within a starting and ending timestamp. | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/timeseries.py#L99-L105 |
agoragames/kairos | kairos/timeseries.py | RelativeTime.ttl | def ttl(self, steps, relative_time=None):
'''
Return the ttl given the number of steps, None if steps is not defined
or we're otherwise unable to calculate one. If relative_time is defined,
then return a ttl that is the number of seconds from now that the
record should be expired.
'''
if ste... | python | def ttl(self, steps, relative_time=None):
'''
Return the ttl given the number of steps, None if steps is not defined
or we're otherwise unable to calculate one. If relative_time is defined,
then return a ttl that is the number of seconds from now that the
record should be expired.
'''
if ste... | Return the ttl given the number of steps, None if steps is not defined
or we're otherwise unable to calculate one. If relative_time is defined,
then return a ttl that is the number of seconds from now that the
record should be expired. | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/timeseries.py#L114-L133 |
agoragames/kairos | kairos/timeseries.py | GregorianTime.step_size | def step_size(self, t0, t1=None):
'''
Return the time in seconds for each step. Requires that we know a time
relative to which we should calculate to account for variable length
intervals (e.g. February)
'''
tb0 = self.to_bucket( t0 )
if t1:
tb1 = self.to_bucket( t1, steps=1 ) # NOTE: ... | python | def step_size(self, t0, t1=None):
'''
Return the time in seconds for each step. Requires that we know a time
relative to which we should calculate to account for variable length
intervals (e.g. February)
'''
tb0 = self.to_bucket( t0 )
if t1:
tb1 = self.to_bucket( t1, steps=1 ) # NOTE: ... | Return the time in seconds for each step. Requires that we know a time
relative to which we should calculate to account for variable length
intervals (e.g. February) | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/timeseries.py#L155-L169 |
agoragames/kairos | kairos/timeseries.py | GregorianTime.to_bucket | 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 | 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)
... | Calculate the bucket from a timestamp. | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/timeseries.py#L171-L189 |
agoragames/kairos | kairos/timeseries.py | GregorianTime.from_bucket | 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 | 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... | Calculate the timestamp given a bucket. | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/timeseries.py#L191-L206 |
agoragames/kairos | kairos/timeseries.py | GregorianTime.buckets | def buckets(self, start, end):
'''
Calculate the buckets within a starting and ending timestamp.
'''
rval = [ self.to_bucket(start) ]
step = 1
# In theory there's already been a check that end>start
# TODO: Not a fan of an unbound while loop here
while True:
bucket = self.to_bucke... | python | def buckets(self, start, end):
'''
Calculate the buckets within a starting and ending timestamp.
'''
rval = [ self.to_bucket(start) ]
step = 1
# In theory there's already been a check that end>start
# TODO: Not a fan of an unbound while loop here
while True:
bucket = self.to_bucke... | Calculate the buckets within a starting and ending timestamp. | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/timeseries.py#L208-L227 |
agoragames/kairos | kairos/timeseries.py | GregorianTime.normalize | 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 | 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) ) | Normalize a timestamp according to the interval configuration. Optionally
can be used to calculate the timestamp N steps away. | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/timeseries.py#L229-L235 |
agoragames/kairos | kairos/timeseries.py | GregorianTime.ttl | def ttl(self, steps, relative_time=None):
'''
Return the ttl given the number of steps, None if steps is not defined
or we're otherwise unable to calculate one. If relative_time is defined,
then return a ttl that is the number of seconds from now that the
record should be expired.
'''
if ste... | python | def ttl(self, steps, relative_time=None):
'''
Return the ttl given the number of steps, None if steps is not defined
or we're otherwise unable to calculate one. If relative_time is defined,
then return a ttl that is the number of seconds from now that the
record should be expired.
'''
if ste... | Return the ttl given the number of steps, None if steps is not defined
or we're otherwise unable to calculate one. If relative_time is defined,
then return a ttl that is the number of seconds from now that the
record should be expired. | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/timeseries.py#L237-L264 |
agoragames/kairos | kairos/timeseries.py | Timeseries.bulk_insert | def bulk_insert(self, inserts, intervals=0, **kwargs):
'''
Perform a bulk insert. The format of the inserts must be:
{
timestamp : {
name: [ values ],
...
},
...
}
If the timestamp should be auto-generated, then "timestamp" should be None.
Backends can implem... | python | def bulk_insert(self, inserts, intervals=0, **kwargs):
'''
Perform a bulk insert. The format of the inserts must be:
{
timestamp : {
name: [ values ],
...
},
...
}
If the timestamp should be auto-generated, then "timestamp" should be None.
Backends can implem... | Perform a bulk insert. The format of the inserts must be:
{
timestamp : {
name: [ values ],
...
},
...
}
If the timestamp should be auto-generated, then "timestamp" should be None.
Backends can implement this in any number of ways, the default being to
perform a ... | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/timeseries.py#L413-L437 |
agoragames/kairos | kairos/timeseries.py | Timeseries.insert | def insert(self, name, value, timestamp=None, intervals=0, **kwargs):
'''
Insert a value for the timeseries "name". For each interval in the
configuration, will insert the value into a bucket for the interval
"timestamp". If time is not supplied, will default to time.time(), else it
should be a floa... | python | def insert(self, name, value, timestamp=None, intervals=0, **kwargs):
'''
Insert a value for the timeseries "name". For each interval in the
configuration, will insert the value into a bucket for the interval
"timestamp". If time is not supplied, will default to time.time(), else it
should be a floa... | Insert a value for the timeseries "name". For each interval in the
configuration, will insert the value into a bucket for the interval
"timestamp". If time is not supplied, will default to time.time(), else it
should be a floating point value.
If "intervals" is less than 0, inserts the value into times... | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/timeseries.py#L439-L472 |
agoragames/kairos | kairos/timeseries.py | Timeseries._batch_insert | 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 | 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... | Support for batch insert. Default implementation is non-optimized and
is a simple loop over values. | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/timeseries.py#L474-L482 |
agoragames/kairos | kairos/timeseries.py | Timeseries._normalize_timestamps | 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 | 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... | Helper for the subclasses to generate a list of timestamps. | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/timeseries.py#L484-L497 |
agoragames/kairos | kairos/timeseries.py | Timeseries.iterate | def iterate(self, name, interval, **kwargs):
'''
Returns a generator that iterates over all the intervals and returns
data for various timestamps, in the form:
( unix_timestamp, data )
This will check for all timestamp buckets that might exist between
the first and last timestamp in a series... | python | def iterate(self, name, interval, **kwargs):
'''
Returns a generator that iterates over all the intervals and returns
data for various timestamps, in the form:
( unix_timestamp, data )
This will check for all timestamp buckets that might exist between
the first and last timestamp in a series... | Returns a generator that iterates over all the intervals and returns
data for various timestamps, in the form:
( unix_timestamp, data )
This will check for all timestamp buckets that might exist between
the first and last timestamp in a series. Each timestamp bucket will
be fetched separately to... | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/timeseries.py#L521-L545 |
agoragames/kairos | kairos/timeseries.py | Timeseries.get | def get(self, name, interval, **kwargs):
'''
Get the set of values for a named timeseries and interval. If timestamp
supplied, will fetch data for the period of time in which that timestamp
would have fallen, else returns data for "now". If the timeseries
resolution was not defined, then returns a s... | python | def get(self, name, interval, **kwargs):
'''
Get the set of values for a named timeseries and interval. If timestamp
supplied, will fetch data for the period of time in which that timestamp
would have fallen, else returns data for "now". If the timeseries
resolution was not defined, then returns a s... | Get the set of values for a named timeseries and interval. If timestamp
supplied, will fetch data for the period of time in which that timestamp
would have fallen, else returns data for "now". If the timeseries
resolution was not defined, then returns a simple list of values for the
interval, else retur... | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/timeseries.py#L547-L611 |
agoragames/kairos | kairos/timeseries.py | Timeseries.series | def series(self, name, interval, **kwargs):
'''
Return all the data in a named time series for a given interval. If steps
not defined and there are none in the config, defaults to 1.
Returns an ordered dict of interval timestamps to a single interval, which
matches the return value in get().
I... | python | def series(self, name, interval, **kwargs):
'''
Return all the data in a named time series for a given interval. If steps
not defined and there are none in the config, defaults to 1.
Returns an ordered dict of interval timestamps to a single interval, which
matches the return value in get().
I... | Return all the data in a named time series for a given interval. If steps
not defined and there are none in the config, defaults to 1.
Returns an ordered dict of interval timestamps to a single interval, which
matches the return value in get().
If transform is defined, will utilize one of `[mean, coun... | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/timeseries.py#L619-L719 |
agoragames/kairos | kairos/timeseries.py | Timeseries._join_results | 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 | 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... | Join a list of results. Supports both get and series. | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/timeseries.py#L727-L745 |
agoragames/kairos | kairos/timeseries.py | Timeseries._process_transform | 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 | 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... | Process transforms on the data. | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/timeseries.py#L747-L755 |
agoragames/kairos | kairos/timeseries.py | Histogram._transform | def _transform(self, data, transform, step_size):
'''
Transform the data. If the transform is not supported by this series,
returns the data unaltered.
'''
if transform=='mean':
total = sum( k*v for k,v in data.items() )
count = sum( data.values() )
data = float(total)/float(count)... | python | def _transform(self, data, transform, step_size):
'''
Transform the data. If the transform is not supported by this series,
returns the data unaltered.
'''
if transform=='mean':
total = sum( k*v for k,v in data.items() )
count = sum( data.values() )
data = float(total)/float(count)... | Transform the data. If the transform is not supported by this series,
returns the data unaltered. | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/timeseries.py#L855-L876 |
agoragames/kairos | kairos/timeseries.py | Histogram._condense | 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 | 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 | Condense by adding together all of the lists. | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/timeseries.py#L885-L893 |
agoragames/kairos | kairos/timeseries.py | Histogram._join | def _join(self, rows):
'''
Join multiple rows worth of data into a single result.
'''
rval = {}
for row in rows:
if row:
for value,count in row.items():
rval[ value ] = count + rval.get(value,0)
return rval | python | def _join(self, rows):
'''
Join multiple rows worth of data into a single result.
'''
rval = {}
for row in rows:
if row:
for value,count in row.items():
rval[ value ] = count + rval.get(value,0)
return rval | Join multiple rows worth of data into a single result. | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/timeseries.py#L895-L904 |
agoragames/kairos | kairos/timeseries.py | Count._join | def _join(self, rows):
'''
Join multiple rows worth of data into a single result.
'''
rval = 0
for row in rows:
if row: rval += row
return rval | python | def _join(self, rows):
'''
Join multiple rows worth of data into a single result.
'''
rval = 0
for row in rows:
if row: rval += row
return rval | Join multiple rows worth of data into a single result. | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/timeseries.py#L939-L946 |
agoragames/kairos | kairos/timeseries.py | Gauge._transform | def _transform(self, data, transform, step_size):
'''
Transform the data. If the transform is not supported by this series,
returns the data unaltered.
'''
if callable(transform):
data = transform(data, step_size)
return data | python | def _transform(self, data, transform, step_size):
'''
Transform the data. If the transform is not supported by this series,
returns the data unaltered.
'''
if callable(transform):
data = transform(data, step_size)
return data | Transform the data. If the transform is not supported by this series,
returns the data unaltered. | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/timeseries.py#L957-L964 |
agoragames/kairos | kairos/timeseries.py | Gauge._condense | 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 | 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 | Condense by returning the last real value of the gauge. | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/timeseries.py#L971-L979 |
agoragames/kairos | kairos/timeseries.py | Set._transform | def _transform(self, data, transform, step_size):
'''
Transform the data. If the transform is not supported by this series,
returns the data unaltered.
'''
if transform=='mean':
total = sum( data )
count = len( data )
data = float(total)/float(count) if count>0 else 0
elif tran... | python | def _transform(self, data, transform, step_size):
'''
Transform the data. If the transform is not supported by this series,
returns the data unaltered.
'''
if transform=='mean':
total = sum( data )
count = len( data )
data = float(total)/float(count) if count>0 else 0
elif tran... | Transform the data. If the transform is not supported by this series,
returns the data unaltered. | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/timeseries.py#L998-L1019 |
agoragames/kairos | kairos/timeseries.py | Set._condense | def _condense(self, data):
'''
Condense by or-ing all of the sets.
'''
if data:
return reduce(operator.ior, data.values())
return set() | python | def _condense(self, data):
'''
Condense by or-ing all of the sets.
'''
if data:
return reduce(operator.ior, data.values())
return set() | Condense by or-ing all of the sets. | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/timeseries.py#L1026-L1032 |
tjcsl/ion | intranet/middleware/profiler.py | stdev | def stdev(x):
r"""Calculate standard deviation of data x[]:
std = sqrt(\sum_i (x_i - mean)^2 \over n-1)
https://wiki.python.org/moin/NumericAndScientificRecipes
"""
from math import sqrt
n = len(x)
mean = sum(x) / float(n)
std = sqrt(sum((a - mean)**2 for a in x) / float(n - 1))
... | python | def stdev(x):
r"""Calculate standard deviation of data x[]:
std = sqrt(\sum_i (x_i - mean)^2 \over n-1)
https://wiki.python.org/moin/NumericAndScientificRecipes
"""
from math import sqrt
n = len(x)
mean = sum(x) / float(n)
std = sqrt(sum((a - mean)**2 for a in x) / float(n - 1))
... | r"""Calculate standard deviation of data x[]:
std = sqrt(\sum_i (x_i - mean)^2 \over n-1)
https://wiki.python.org/moin/NumericAndScientificRecipes | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/middleware/profiler.py#L304-L313 |
tjcsl/ion | intranet/apps/users/management/commands/dynamic_groups.py | Command.handle | def handle(self, **options):
""" Create "Class of 20[16-19]" groups """
students_grp, _ = Group.objects.get_or_create(name="Students")
sg_prop = students_grp.properties
sg_prop.student_visible = True
sg_prop.save()
students_grp.save()
for gr in [settings.SENIOR_... | python | def handle(self, **options):
""" Create "Class of 20[16-19]" groups """
students_grp, _ = Group.objects.get_or_create(name="Students")
sg_prop = students_grp.properties
sg_prop.student_visible = True
sg_prop.save()
students_grp.save()
for gr in [settings.SENIOR_... | Create "Class of 20[16-19]" groups | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/management/commands/dynamic_groups.py#L13-L36 |
tjcsl/ion | intranet/apps/dataimport/management/commands/year_cleanup.py | Command.handle | def handle(self, *args, **options):
do_run = options["run"]
if do_run:
if not options["confirm"]:
self.ask("===== WARNING! =====\n\n"
"This script will DESTROY data! Ensure that you have a properly backed-up copy of your database before proceeding.\n... | python | def handle(self, *args, **options):
do_run = options["run"]
if do_run:
if not options["confirm"]:
self.ask("===== WARNING! =====\n\n"
"This script will DESTROY data! Ensure that you have a properly backed-up copy of your database before proceeding.\n... | EIGHTH:
EighthBlock: filtered
EighthSignup: absences removed
EighthActivity: keep
ANNOUNCEMENTS:
AnnouncementRequest: filtered
USERS:
User: graduated students deleted | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/dataimport/management/commands/year_cleanup.py#L33-L80 |
tjcsl/ion | intranet/apps/api/authentication.py | ApiBasicAuthentication.authenticate_credentials | 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 | 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... | Authenticate the userid and password. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/api/authentication.py#L13-L21 |
tjcsl/ion | intranet/apps/bus/consumers.py | check_internal_ip | 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 | 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 | request is an AsgiRequest | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/bus/consumers.py#L8-L11 |
tjcsl/ion | intranet/apps/polls/views.py | handle_sap | def handle_sap(q):
question_votes = votes = Answer.objects.filter(question=q)
users = q.get_users_voted()
num_users_votes = {u.id: votes.filter(user=u).count() for u in users}
user_scale = {u.id: (1 / num_users_votes[u.id]) for u in users}
choices = []
for c in q.choice_set.all().order_by("num")... | python | def handle_sap(q):
question_votes = votes = Answer.objects.filter(question=q)
users = q.get_users_voted()
num_users_votes = {u.id: votes.filter(user=u).count() for u in users}
user_scale = {u.id: (1 / num_users_votes[u.id]) for u in users}
choices = []
for c in q.choice_set.all().order_by("num")... | Clear vote | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/polls/views.py#L217-L297 |
tjcsl/ion | intranet/apps/events/views.py | events_view | 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 | 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 = ... | Events homepage.
Shows a list of events occurring in the next week, month, and
future. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/events/views.py#L23-L89 |
tjcsl/ion | intranet/apps/events/views.py | join_event_view | 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 | 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... | 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 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/events/views.py#L94-L119 |
tjcsl/ion | intranet/apps/events/views.py | event_roster_view | def event_roster_view(request, id):
"""Show the event roster. Users with hidden eighth period permissions will not be displayed.
Users will be able to view all other users, along with a count of the number of hidden users.
(Same as 8th roster page.) Admins will see a full roster at the bottom.
id: even... | python | def event_roster_view(request, id):
"""Show the event roster. Users with hidden eighth period permissions will not be displayed.
Users will be able to view all other users, along with a count of the number of hidden users.
(Same as 8th roster page.) Admins will see a full roster at the bottom.
id: even... | Show the event roster. Users with hidden eighth period permissions will not be displayed.
Users will be able to view all other users, along with a count of the number of hidden users.
(Same as 8th roster page.) Admins will see a full roster at the bottom.
id: event id | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/events/views.py#L124-L151 |
tjcsl/ion | intranet/apps/events/views.py | add_event_view | 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 | 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... | 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. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/events/views.py#L156-L190 |
tjcsl/ion | intranet/apps/events/views.py | modify_event_view | 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 | 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:
... | Modify event page. You may only modify an event if you were the creator or you are an
administrator.
id: event id | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/events/views.py#L230-L264 |
tjcsl/ion | intranet/apps/events/views.py | delete_event_view | 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 | 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 ... | 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 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/events/views.py#L269-L289 |
tjcsl/ion | intranet/apps/events/views.py | show_event_view | 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 | 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:
... | 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. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/events/views.py#L294-L309 |
tjcsl/ion | intranet/apps/notifications/views.py | android_setup_view | def android_setup_view(request):
"""Set up a GCM session.
This does *not* require a valid login session. Instead, a token from the client
session is sent to the Android backend, which queries a POST request to this view.
The "android_gcm_rand" is randomly set when the Android app is detected through
... | python | def android_setup_view(request):
"""Set up a GCM session.
This does *not* require a valid login session. Instead, a token from the client
session is sent to the Android backend, which queries a POST request to this view.
The "android_gcm_rand" is randomly set when the Android app is detected through
... | Set up a GCM session.
This does *not* require a valid login session. Instead, a token from the client
session is sent to the Android backend, which queries a POST request to this view.
The "android_gcm_rand" is randomly set when the Android app is detected through
the user agent. If it has the same val... | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/notifications/views.py#L22-L49 |
tjcsl/ion | intranet/apps/notifications/views.py | chrome_getdata_view | 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 | 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.
"""
... | 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. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/notifications/views.py#L53-L91 |
tjcsl/ion | intranet/apps/notifications/views.py | chrome_setup_view | def chrome_setup_view(request):
"""Set up a browser-side GCM session.
This *requires* a valid login session. A "token" POST parameter is saved under the "gcm_token"
parameter in the logged in user's NotificationConfig.
"""
logger.debug(request.POST)
token = None
if request.method == "POST":... | python | def chrome_setup_view(request):
"""Set up a browser-side GCM session.
This *requires* a valid login session. A "token" POST parameter is saved under the "gcm_token"
parameter in the logged in user's NotificationConfig.
"""
logger.debug(request.POST)
token = None
if request.method == "POST":... | Set up a browser-side GCM session.
This *requires* a valid login session. A "token" POST parameter is saved under the "gcm_token"
parameter in the logged in user's NotificationConfig. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/notifications/views.py#L95-L112 |
tjcsl/ion | intranet/apps/lostfound/views.py | lostitem_add_view | 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 | 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... | Add a lostitem. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/lostfound/views.py#L46-L63 |
tjcsl/ion | intranet/apps/lostfound/views.py | lostitem_modify_view | 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 | 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()
... | Modify a lostitem.
id: lostitem id | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/lostfound/views.py#L68-L92 |
tjcsl/ion | intranet/apps/lostfound/views.py | lostitem_delete_view | 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 | 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, "... | Delete a lostitem.
id: lostitem id | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/lostfound/views.py#L97-L119 |
tjcsl/ion | intranet/apps/lostfound/views.py | lostitem_view | 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 | 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"}) | View a lostitem.
id: lostitem id | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/lostfound/views.py#L124-L131 |
tjcsl/ion | intranet/apps/lostfound/views.py | founditem_modify_view | 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 | 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... | Modify a founditem.
id: founditem id | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/lostfound/views.py#L158-L182 |
tjcsl/ion | intranet/apps/lostfound/views.py | founditem_delete_view | 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 | 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... | Delete a founditem.
id: founditem id | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/lostfound/views.py#L187-L209 |
tjcsl/ion | intranet/apps/lostfound/views.py | founditem_view | 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 | 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"}) | View a founditem.
id: founditem id | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/lostfound/views.py#L214-L221 |
tjcsl/ion | intranet/apps/files/views.py | files_view | 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 | 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) | The main filecenter view. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/files/views.py#L49-L55 |
tjcsl/ion | intranet/apps/files/views.py | files_auth | 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 | 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.
... | Display authentication for filecenter. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/files/views.py#L62-L98 |
tjcsl/ion | intranet/apps/files/views.py | get_authinfo | 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 | 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
... | Get authentication info from the encrypted message. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/files/views.py#L102-L122 |
tjcsl/ion | intranet/apps/files/views.py | windows_dir_format | def windows_dir_format(host_dir, user):
"""Format a string for the location of the user's folder on the Windows (TJ03) fileserver."""
if user and user.grade:
grade = int(user.grade)
else:
return host_dir
if grade in range(9, 13):
win_path = "/{}/".format(user.username)
else:... | python | def windows_dir_format(host_dir, user):
"""Format a string for the location of the user's folder on the Windows (TJ03) fileserver."""
if user and user.grade:
grade = int(user.grade)
else:
return host_dir
if grade in range(9, 13):
win_path = "/{}/".format(user.username)
else:... | Format a string for the location of the user's folder on the Windows (TJ03) fileserver. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/files/views.py#L125-L136 |
tjcsl/ion | intranet/apps/files/views.py | files_type | def files_type(request, fstype=None):
"""Do all processing (directory listing, file downloads) for a given filesystem."""
try:
host = Host.objects.get(code=fstype)
except Host.DoesNotExist:
messages.error(request, "Could not find host in database.")
return redirect("files")
if h... | python | def files_type(request, fstype=None):
"""Do all processing (directory listing, file downloads) for a given filesystem."""
try:
host = Host.objects.get(code=fstype)
except Host.DoesNotExist:
messages.error(request, "Could not find host in database.")
return redirect("files")
if h... | Do all processing (directory listing, file downloads) for a given filesystem. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/files/views.py#L141-L353 |
tjcsl/ion | intranet/apps/itemreg/templatetags/texthighlight.py | highlight | 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 | 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 | Highlight str1 with the contents of str2. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/itemreg/templatetags/texthighlight.py#L9-L19 |
tjcsl/ion | intranet/apps/eighth/management/commands/import_attendance.py | Command.handle | 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 | 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... | Exported "eighth_absentees" table in CSV format. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/management/commands/import_attendance.py#L14-L48 |
tjcsl/ion | intranet/apps/auth/backends.py | KerberosAuthenticationBackend.kinit_timeout_handle | 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 | 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))
... | Check if the user exists before we throw an error. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/auth/backends.py#L29-L47 |
tjcsl/ion | intranet/apps/auth/backends.py | KerberosAuthenticationBackend.get_kerberos_ticket | 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 | 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
""... | 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 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/auth/backends.py#L51-L109 |
tjcsl/ion | intranet/apps/auth/backends.py | KerberosAuthenticationBackend.authenticate | def authenticate(self, request, username=None, password=None):
"""Authenticate a username-password pair.
Creates a new user if one is not already in the database.
Args:
username
The username of the `User` to authenticate.
password
The pas... | python | def authenticate(self, request, username=None, password=None):
"""Authenticate a username-password pair.
Creates a new user if one is not already in the database.
Args:
username
The username of the `User` to authenticate.
password
The pas... | Authenticate a username-password pair.
Creates a new user if one is not already in the database.
Args:
username
The username of the `User` to authenticate.
password
The password of the `User` to authenticate.
Returns:
`User` | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/auth/backends.py#L112-L148 |
tjcsl/ion | intranet/apps/auth/backends.py | KerberosAuthenticationBackend.get_user | def get_user(self, user_id):
"""Returns a user, given his or her user id. Required for a custom authentication backend.
Args:
user_id
The user id of the user to fetch.
Returns:
User or None
"""
try:
return User.objects.get(id=us... | python | def get_user(self, user_id):
"""Returns a user, given his or her user id. Required for a custom authentication backend.
Args:
user_id
The user id of the user to fetch.
Returns:
User or None
"""
try:
return User.objects.get(id=us... | Returns a user, given his or her user id. Required for a custom authentication backend.
Args:
user_id
The user id of the user to fetch.
Returns:
User or None | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/auth/backends.py#L150-L161 |
tjcsl/ion | intranet/apps/auth/backends.py | MasterPasswordAuthenticationBackend.authenticate | def authenticate(self, request, username=None, password=None):
"""Authenticate a username-password pair.
Creates a new user if one is not already in the database.
Args:
username
The username of the `User` to authenticate.
password
The mas... | python | def authenticate(self, request, username=None, password=None):
"""Authenticate a username-password pair.
Creates a new user if one is not already in the database.
Args:
username
The username of the `User` to authenticate.
password
The mas... | Authenticate a username-password pair.
Creates a new user if one is not already in the database.
Args:
username
The username of the `User` to authenticate.
password
The master password.
Returns:
`User` | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/auth/backends.py#L170-L200 |
tjcsl/ion | intranet/apps/dashboard/views.py | get_fcps_emerg | 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 | 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"]
... | Return FCPS emergency information. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/dashboard/views.py#L25-L37 |
tjcsl/ion | intranet/apps/dashboard/views.py | gen_schedule | 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 | 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... | Generate a list of information about a block and a student's current activity signup.
Returns:
schedule
no_signup_today | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/dashboard/views.py#L40-L108 |
tjcsl/ion | intranet/apps/dashboard/views.py | gen_sponsor_schedule | def gen_sponsor_schedule(user, sponsor=None, num_blocks=6, surrounding_blocks=None, given_date=None):
r"""Return a list of :class:`EighthScheduledActivity`\s in which the
given user is sponsoring.
Returns:
Dictionary with:
activities
no_attendance_today
num_acts
... | python | def gen_sponsor_schedule(user, sponsor=None, num_blocks=6, surrounding_blocks=None, given_date=None):
r"""Return a list of :class:`EighthScheduledActivity`\s in which the
given user is sponsoring.
Returns:
Dictionary with:
activities
no_attendance_today
num_acts
... | r"""Return a list of :class:`EighthScheduledActivity`\s in which the
given user is sponsoring.
Returns:
Dictionary with:
activities
no_attendance_today
num_acts | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/dashboard/views.py#L111-L182 |
tjcsl/ion | intranet/apps/dashboard/views.py | find_birthdays | 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 | 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_... | Return information on user birthdays. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/dashboard/views.py#L185-L254 |
tjcsl/ion | intranet/apps/dashboard/views.py | find_visible_birthdays | 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 | 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... | Return only the birthdays visible to current user. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/dashboard/views.py#L257-L264 |
tjcsl/ion | intranet/apps/dashboard/views.py | get_announcements_list | def get_announcements_list(request, context):
"""
An announcement will be shown if:
* It is not expired
* unless ?show_expired=1
* It is visible to the user
* There are no groups on the announcement (so it is public)
* The user's groups are in union with the groups on the
an... | python | def get_announcements_list(request, context):
"""
An announcement will be shown if:
* It is not expired
* unless ?show_expired=1
* It is visible to the user
* There are no groups on the announcement (so it is public)
* The user's groups are in union with the groups on the
an... | An announcement will be shown if:
* It is not expired
* unless ?show_expired=1
* It is visible to the user
* There are no groups on the announcement (so it is public)
* The user's groups are in union with the groups on the
announcement (at least one matches)
* The user submitt... | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/dashboard/views.py#L279-L337 |
tjcsl/ion | intranet/apps/dashboard/views.py | paginate_announcements_list | def paginate_announcements_list(request, context, items):
"""
***TODO*** Migrate to django Paginator (see lostitems)
"""
# pagination
if "start" in request.GET:
try:
start_num = int(request.GET.get("start"))
except ValueError:
start_num = 0
else:
... | python | def paginate_announcements_list(request, context, items):
"""
***TODO*** Migrate to django Paginator (see lostitems)
"""
# pagination
if "start" in request.GET:
try:
start_num = int(request.GET.get("start"))
except ValueError:
start_num = 0
else:
... | ***TODO*** Migrate to django Paginator (see lostitems) | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/dashboard/views.py#L340-L374 |
tjcsl/ion | intranet/apps/dashboard/views.py | add_widgets_context | def add_widgets_context(request, context):
"""
WIDGETS:
* Eighth signup (STUDENT)
* Eighth attendance (TEACHER or ADMIN)
* Bell schedule (ALL)
* Birthdays (ALL)
* Administration (ADMIN)
* Links (ALL)
* Seniors (STUDENT; graduation countdown if senior, link to destinations otherwise)
... | python | def add_widgets_context(request, context):
"""
WIDGETS:
* Eighth signup (STUDENT)
* Eighth attendance (TEACHER or ADMIN)
* Bell schedule (ALL)
* Birthdays (ALL)
* Administration (ADMIN)
* Links (ALL)
* Seniors (STUDENT; graduation countdown if senior, link to destinations otherwise)
... | WIDGETS:
* Eighth signup (STUDENT)
* Eighth attendance (TEACHER or ADMIN)
* Bell schedule (ALL)
* Birthdays (ALL)
* Administration (ADMIN)
* Links (ALL)
* Seniors (STUDENT; graduation countdown if senior, link to destinations otherwise) | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/dashboard/views.py#L385-L434 |
tjcsl/ion | intranet/apps/dashboard/views.py | dashboard_view | def dashboard_view(request, show_widgets=True, show_expired=False, ignore_dashboard_types=None, show_welcome=False):
"""Process and show the dashboard, which includes activities, events, and widgets."""
user = request.user
announcements_admin = user.has_admin_permission("announcements")
events_admin =... | python | def dashboard_view(request, show_widgets=True, show_expired=False, ignore_dashboard_types=None, show_welcome=False):
"""Process and show the dashboard, which includes activities, events, and widgets."""
user = request.user
announcements_admin = user.has_admin_permission("announcements")
events_admin =... | Process and show the dashboard, which includes activities, events, and widgets. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/dashboard/views.py#L438-L559 |
tjcsl/ion | intranet/apps/eighth/models.py | EighthActivity._name_with_flags | 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 | 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)"
... | Generate the name with flags. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L289-L301 |
tjcsl/ion | intranet/apps/eighth/models.py | EighthActivity.restricted_activities_available_to_user | def restricted_activities_available_to_user(cls, user):
"""Find the restricted activities available to the given user."""
if not user:
return []
activities = set(user.restricted_activity_set.values_list("id", flat=True))
if user and user.grade and user.grade.number and user... | python | def restricted_activities_available_to_user(cls, user):
"""Find the restricted activities available to the given user."""
if not user:
return []
activities = set(user.restricted_activity_set.values_list("id", flat=True))
if user and user.grade and user.grade.number and user... | Find the restricted activities available to the given user. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L304-L322 |
tjcsl/ion | intranet/apps/eighth/models.py | EighthActivity.get_active_schedulings | def get_active_schedulings(self):
"""Return EighthScheduledActivity's of this activity since the beginning of the year."""
blocks = EighthBlock.objects.get_blocks_this_year()
scheduled_activities = EighthScheduledActivity.objects.filter(activity=self)
scheduled_activities = scheduled_act... | python | def get_active_schedulings(self):
"""Return EighthScheduledActivity's of this activity since the beginning of the year."""
blocks = EighthBlock.objects.get_blocks_this_year()
scheduled_activities = EighthScheduledActivity.objects.filter(activity=self)
scheduled_activities = scheduled_act... | Return EighthScheduledActivity's of this activity since the beginning of the year. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L342-L348 |
tjcsl/ion | intranet/apps/eighth/models.py | EighthActivity.frequent_users | def frequent_users(self):
"""Return a QuerySet of user id's and counts that have signed up for this activity more than
`settings.SIMILAR_THRESHOLD` times. This is be used for suggesting activities to users."""
key = "eighthactivity_{}:frequent_users".format(self.id)
cached = cache.get(ke... | python | def frequent_users(self):
"""Return a QuerySet of user id's and counts that have signed up for this activity more than
`settings.SIMILAR_THRESHOLD` times. This is be used for suggesting activities to users."""
key = "eighthactivity_{}:frequent_users".format(self.id)
cached = cache.get(ke... | Return a QuerySet of user id's and counts that have signed up for this activity more than
`settings.SIMILAR_THRESHOLD` times. This is be used for suggesting activities to users. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L358-L369 |
tjcsl/ion | intranet/apps/eighth/models.py | EighthBlockQuerySet.this_year | def this_year(self):
""" Get EighthBlocks from this school year only. """
start_date, end_date = get_date_range_this_year()
return self.filter(date__gte=start_date, date__lte=end_date) | python | def this_year(self):
""" Get EighthBlocks from this school year only. """
start_date, end_date = get_date_range_this_year()
return self.filter(date__gte=start_date, date__lte=end_date) | Get EighthBlocks from this school year only. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L384-L387 |
tjcsl/ion | intranet/apps/eighth/models.py | EighthBlockManager.get_upcoming_blocks | def get_upcoming_blocks(self, max_number=-1):
"""Gets the X number of upcoming blocks (that will take place in the future). If there is no
block in the future, the most recent block will be returned.
Returns: A QuerySet of `EighthBlock` objects
"""
now = datetime.datetime.now(... | python | def get_upcoming_blocks(self, max_number=-1):
"""Gets the X number of upcoming blocks (that will take place in the future). If there is no
block in the future, the most recent block will be returned.
Returns: A QuerySet of `EighthBlock` objects
"""
now = datetime.datetime.now(... | Gets the X number of upcoming blocks (that will take place in the future). If there is no
block in the future, the most recent block will be returned.
Returns: A QuerySet of `EighthBlock` objects | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L395-L414 |
tjcsl/ion | intranet/apps/eighth/models.py | EighthBlockManager.get_next_upcoming_blocks | def get_next_upcoming_blocks(self):
"""Gets the next upccoming blocks. (Finds the other blocks that are occurring on the day of
the first upcoming block.)
Returns: A QuerySet of `EighthBlock` objects.
"""
next_block = EighthBlock.objects.get_first_upcoming_block()
if ... | python | def get_next_upcoming_blocks(self):
"""Gets the next upccoming blocks. (Finds the other blocks that are occurring on the day of
the first upcoming block.)
Returns: A QuerySet of `EighthBlock` objects.
"""
next_block = EighthBlock.objects.get_first_upcoming_block()
if ... | Gets the next upccoming blocks. (Finds the other blocks that are occurring on the day of
the first upcoming block.)
Returns: A QuerySet of `EighthBlock` objects. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L426-L440 |
tjcsl/ion | intranet/apps/eighth/models.py | EighthBlockManager.get_blocks_this_year | def get_blocks_this_year(self):
"""Get a list of blocks that occur this school year."""
date_start, date_end = get_date_range_this_year()
return EighthBlock.objects.filter(date__gte=date_start, date__lte=date_end) | python | def get_blocks_this_year(self):
"""Get a list of blocks that occur this school year."""
date_start, date_end = get_date_range_this_year()
return EighthBlock.objects.filter(date__gte=date_start, date__lte=date_end) | Get a list of blocks that occur this school year. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L453-L458 |
tjcsl/ion | intranet/apps/eighth/models.py | EighthBlock.save | def save(self, *args, **kwargs):
"""Capitalize the first letter of the block name."""
letter = getattr(self, "block_letter", None)
if letter and len(letter) >= 1:
self.block_letter = letter[:1].upper() + letter[1:]
super(EighthBlock, self).save(*args, **kwargs) | python | def save(self, *args, **kwargs):
"""Capitalize the first letter of the block name."""
letter = getattr(self, "block_letter", None)
if letter and len(letter) >= 1:
self.block_letter = letter[:1].upper() + letter[1:]
super(EighthBlock, self).save(*args, **kwargs) | Capitalize the first letter of the block name. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L505-L511 |
tjcsl/ion | intranet/apps/eighth/models.py | EighthBlock.next_blocks | def next_blocks(self, quantity=-1):
"""Get the next blocks in order."""
blocks = (EighthBlock.objects.get_blocks_this_year().order_by(
"date", "block_letter").filter(Q(date__gt=self.date) | (Q(date=self.date) & Q(block_letter__gt=self.block_letter))))
if quantity == -1:
r... | python | def next_blocks(self, quantity=-1):
"""Get the next blocks in order."""
blocks = (EighthBlock.objects.get_blocks_this_year().order_by(
"date", "block_letter").filter(Q(date__gt=self.date) | (Q(date=self.date) & Q(block_letter__gt=self.block_letter))))
if quantity == -1:
r... | Get the next blocks in order. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L513-L519 |
tjcsl/ion | intranet/apps/eighth/models.py | EighthBlock.previous_blocks | def previous_blocks(self, quantity=-1):
"""Get the previous blocks in order."""
blocks = (EighthBlock.objects.get_blocks_this_year().order_by(
"-date", "-block_letter").filter(Q(date__lt=self.date) | (Q(date=self.date) & Q(block_letter__lt=self.block_letter))))
if quantity == -1:
... | python | def previous_blocks(self, quantity=-1):
"""Get the previous blocks in order."""
blocks = (EighthBlock.objects.get_blocks_this_year().order_by(
"-date", "-block_letter").filter(Q(date__lt=self.date) | (Q(date=self.date) & Q(block_letter__lt=self.block_letter))))
if quantity == -1:
... | Get the previous blocks in order. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L521-L527 |
tjcsl/ion | intranet/apps/eighth/models.py | EighthBlock.get_surrounding_blocks | def get_surrounding_blocks(self):
"""Get the blocks around the one given.
Returns: a list of all of those blocks.
"""
next = self.next_blocks()
prev = self.previous_blocks()
surrounding_blocks = list(chain(prev, [self], next))
return surrounding_blocks | python | def get_surrounding_blocks(self):
"""Get the blocks around the one given.
Returns: a list of all of those blocks.
"""
next = self.next_blocks()
prev = self.previous_blocks()
surrounding_blocks = list(chain(prev, [self], next))
return surrounding_blocks | Get the blocks around the one given.
Returns: a list of all of those blocks. | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L529-L540 |
tjcsl/ion | intranet/apps/eighth/models.py | EighthBlock.signup_time_future | def signup_time_future(self):
"""Is the signup time in the future?"""
now = datetime.datetime.now()
return (now.date() < self.date or (self.date == now.date() and self.signup_time > now.time())) | python | def signup_time_future(self):
"""Is the signup time in the future?"""
now = datetime.datetime.now()
return (now.date() < self.date or (self.date == now.date() and self.signup_time > now.time())) | Is the signup time in the future? | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L546-L549 |
tjcsl/ion | intranet/apps/eighth/models.py | EighthBlock.date_in_past | def date_in_past(self):
"""Is the block's date in the past?
(Has it not yet happened?)
"""
now = datetime.datetime.now()
return (now.date() > self.date) | python | def date_in_past(self):
"""Is the block's date in the past?
(Has it not yet happened?)
"""
now = datetime.datetime.now()
return (now.date() > self.date) | Is the block's date in the past?
(Has it not yet happened?) | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L551-L558 |
tjcsl/ion | intranet/apps/eighth/models.py | EighthBlock.in_clear_absence_period | def in_clear_absence_period(self):
"""Is the current date in the block's clear absence period?
(Should info on clearing the absence show?)
"""
now = datetime.datetime.now()
two_weeks = self.date + datetime.timedelta(days=settings.CLEAR_ABSENCE_DAYS)
return now.date() <=... | python | def in_clear_absence_period(self):
"""Is the current date in the block's clear absence period?
(Should info on clearing the absence show?)
"""
now = datetime.datetime.now()
two_weeks = self.date + datetime.timedelta(days=settings.CLEAR_ABSENCE_DAYS)
return now.date() <=... | Is the current date in the block's clear absence period?
(Should info on clearing the absence show?) | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L560-L568 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.