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 |
|---|---|---|---|---|---|---|---|
spencerahill/aospy | aospy/calc.py | _add_metadata_as_attrs_da | def _add_metadata_as_attrs_da(data, units, description, dtype_out_vert):
"""Add metadata attributes to DataArray"""
if dtype_out_vert == 'vert_int':
if units != '':
units = '(vertical integral of {0}): {0} kg m^-2)'.format(units)
else:
units = '(vertical integral of quant... | python | def _add_metadata_as_attrs_da(data, units, description, dtype_out_vert):
"""Add metadata attributes to DataArray"""
if dtype_out_vert == 'vert_int':
if units != '':
units = '(vertical integral of {0}): {0} kg m^-2)'.format(units)
else:
units = '(vertical integral of quant... | Add metadata attributes to DataArray | https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/calc.py#L606-L615 |
spencerahill/aospy | aospy/calc.py | Calc._dir_out | def _dir_out(self):
"""Create string of the data directory to save individual .nc files."""
return os.path.join(self.proj.direc_out, self.proj.name,
self.model.name, self.run.name, self.name) | python | def _dir_out(self):
"""Create string of the data directory to save individual .nc files."""
return os.path.join(self.proj.direc_out, self.proj.name,
self.model.name, self.run.name, self.name) | Create string of the data directory to save individual .nc files. | https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/calc.py#L67-L70 |
spencerahill/aospy | aospy/calc.py | Calc._dir_tar_out | def _dir_tar_out(self):
"""Create string of the data directory to store a tar file."""
return os.path.join(self.proj.tar_direc_out, self.proj.name,
self.model.name, self.run.name) | python | def _dir_tar_out(self):
"""Create string of the data directory to store a tar file."""
return os.path.join(self.proj.tar_direc_out, self.proj.name,
self.model.name, self.run.name) | Create string of the data directory to store a tar file. | https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/calc.py#L72-L75 |
spencerahill/aospy | aospy/calc.py | Calc._file_name | def _file_name(self, dtype_out_time, extension='nc'):
"""Create the name of the aospy file."""
if dtype_out_time is None:
dtype_out_time = ''
out_lbl = utils.io.data_out_label(self.intvl_out, dtype_out_time,
dtype_vert=self.dtype_out_vert)
... | python | def _file_name(self, dtype_out_time, extension='nc'):
"""Create the name of the aospy file."""
if dtype_out_time is None:
dtype_out_time = ''
out_lbl = utils.io.data_out_label(self.intvl_out, dtype_out_time,
dtype_vert=self.dtype_out_vert)
... | Create the name of the aospy file. | https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/calc.py#L77-L91 |
spencerahill/aospy | aospy/calc.py | Calc._print_verbose | def _print_verbose(*args):
"""Print diagnostic message."""
try:
return '{0} {1} ({2})'.format(args[0], args[1], ctime())
except IndexError:
return '{0} ({1})'.format(args[0], ctime()) | python | def _print_verbose(*args):
"""Print diagnostic message."""
try:
return '{0} {1} ({2})'.format(args[0], args[1], ctime())
except IndexError:
return '{0} ({1})'.format(args[0], ctime()) | Print diagnostic message. | https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/calc.py#L100-L105 |
spencerahill/aospy | aospy/calc.py | Calc._to_desired_dates | def _to_desired_dates(self, arr):
"""Restrict the xarray DataArray or Dataset to the desired months."""
times = utils.times.extract_months(
arr[internal_names.TIME_STR], self.months
)
return arr.sel(time=times) | python | def _to_desired_dates(self, arr):
"""Restrict the xarray DataArray or Dataset to the desired months."""
times = utils.times.extract_months(
arr[internal_names.TIME_STR], self.months
)
return arr.sel(time=times) | Restrict the xarray DataArray or Dataset to the desired months. | https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/calc.py#L254-L259 |
spencerahill/aospy | aospy/calc.py | Calc._add_grid_attributes | def _add_grid_attributes(self, ds):
"""Add model grid attributes to a dataset"""
for name_int, names_ext in self._grid_attrs.items():
ds_coord_name = set(names_ext).intersection(set(ds.coords) |
set(ds.data_vars))
model_attr... | python | def _add_grid_attributes(self, ds):
"""Add model grid attributes to a dataset"""
for name_int, names_ext in self._grid_attrs.items():
ds_coord_name = set(names_ext).intersection(set(ds.coords) |
set(ds.data_vars))
model_attr... | Add model grid attributes to a dataset | https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/calc.py#L261-L295 |
spencerahill/aospy | aospy/calc.py | Calc._get_input_data | def _get_input_data(self, var, start_date, end_date):
"""Get the data for a single variable over the desired date range."""
logging.info(self._print_verbose("Getting input data:", var))
if isinstance(var, (float, int)):
return var
else:
cond_pfull = ((not hasattr... | python | def _get_input_data(self, var, start_date, end_date):
"""Get the data for a single variable over the desired date range."""
logging.info(self._print_verbose("Getting input data:", var))
if isinstance(var, (float, int)):
return var
else:
cond_pfull = ((not hasattr... | Get the data for a single variable over the desired date range. | https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/calc.py#L297-L329 |
spencerahill/aospy | aospy/calc.py | Calc._get_all_data | def _get_all_data(self, start_date, end_date):
"""Get the needed data from all of the vars in the calculation."""
return [self._get_input_data(var, start_date, end_date)
for var in _replace_pressure(self.variables,
self.dtype_in_vert)] | python | def _get_all_data(self, start_date, end_date):
"""Get the needed data from all of the vars in the calculation."""
return [self._get_input_data(var, start_date, end_date)
for var in _replace_pressure(self.variables,
self.dtype_in_vert)] | Get the needed data from all of the vars in the calculation. | https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/calc.py#L331-L335 |
spencerahill/aospy | aospy/calc.py | Calc._compute | def _compute(self, data):
"""Perform the calculation."""
local_ts = self._local_ts(*data)
dt = local_ts[internal_names.TIME_WEIGHTS_STR]
# Convert dt to units of days to prevent overflow
dt = dt / np.timedelta64(1, 'D')
return local_ts, dt | python | def _compute(self, data):
"""Perform the calculation."""
local_ts = self._local_ts(*data)
dt = local_ts[internal_names.TIME_WEIGHTS_STR]
# Convert dt to units of days to prevent overflow
dt = dt / np.timedelta64(1, 'D')
return local_ts, dt | Perform the calculation. | https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/calc.py#L341-L347 |
spencerahill/aospy | aospy/calc.py | Calc._compute_full_ts | def _compute_full_ts(self, data):
"""Perform calculation and create yearly timeseries at each point."""
# Get results at each desired timestep and spatial point.
full_ts, dt = self._compute(data)
# Vertically integrate.
vert_types = ('vert_int', 'vert_av')
if self.dtype_o... | python | def _compute_full_ts(self, data):
"""Perform calculation and create yearly timeseries at each point."""
# Get results at each desired timestep and spatial point.
full_ts, dt = self._compute(data)
# Vertically integrate.
vert_types = ('vert_int', 'vert_av')
if self.dtype_o... | Perform calculation and create yearly timeseries at each point. | https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/calc.py#L349-L363 |
spencerahill/aospy | aospy/calc.py | Calc._full_to_yearly_ts | def _full_to_yearly_ts(self, arr, dt):
"""Average the full timeseries within each year."""
time_defined = self.def_time and not ('av' in self.dtype_in_time)
if time_defined:
arr = utils.times.yearly_average(arr, dt)
return arr | python | def _full_to_yearly_ts(self, arr, dt):
"""Average the full timeseries within each year."""
time_defined = self.def_time and not ('av' in self.dtype_in_time)
if time_defined:
arr = utils.times.yearly_average(arr, dt)
return arr | Average the full timeseries within each year. | https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/calc.py#L365-L370 |
spencerahill/aospy | aospy/calc.py | Calc._time_reduce | def _time_reduce(self, arr, reduction):
"""Perform the specified time reduction on a local time-series."""
if self.dtype_in_time == 'av' or not self.def_time:
return arr
reductions = {
'ts': lambda xarr: xarr,
'av': lambda xarr: xarr.mean(internal_names.YEAR_S... | python | def _time_reduce(self, arr, reduction):
"""Perform the specified time reduction on a local time-series."""
if self.dtype_in_time == 'av' or not self.def_time:
return arr
reductions = {
'ts': lambda xarr: xarr,
'av': lambda xarr: xarr.mean(internal_names.YEAR_S... | Perform the specified time reduction on a local time-series. | https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/calc.py#L372-L385 |
spencerahill/aospy | aospy/calc.py | Calc.region_calcs | def region_calcs(self, arr, func):
"""Perform a calculation for all regions."""
# Get pressure values for data output on hybrid vertical coordinates.
bool_pfull = (self.def_vert and self.dtype_in_vert ==
internal_names.ETA_STR and self.dtype_out_vert is False)
if bo... | python | def region_calcs(self, arr, func):
"""Perform a calculation for all regions."""
# Get pressure values for data output on hybrid vertical coordinates.
bool_pfull = (self.def_vert and self.dtype_in_vert ==
internal_names.ETA_STR and self.dtype_out_vert is False)
if bo... | Perform a calculation for all regions. | https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/calc.py#L387-L419 |
spencerahill/aospy | aospy/calc.py | Calc._apply_all_time_reductions | def _apply_all_time_reductions(self, data):
"""Apply all requested time reductions to the data."""
logging.info(self._print_verbose("Applying desired time-"
"reduction methods."))
reduc_specs = [r.split('.') for r in self.dtype_out_time]
reduced =... | python | def _apply_all_time_reductions(self, data):
"""Apply all requested time reductions to the data."""
logging.info(self._print_verbose("Applying desired time-"
"reduction methods."))
reduc_specs = [r.split('.') for r in self.dtype_out_time]
reduced =... | Apply all requested time reductions to the data. | https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/calc.py#L421-L433 |
spencerahill/aospy | aospy/calc.py | Calc.compute | def compute(self, write_to_tar=True):
"""Perform all desired calculations on the data and save externally."""
data = self._get_all_data(self.start_date, self.end_date)
logging.info('Computing timeseries for {0} -- '
'{1}.'.format(self.start_date, self.end_date))
full... | python | def compute(self, write_to_tar=True):
"""Perform all desired calculations on the data and save externally."""
data = self._get_all_data(self.start_date, self.end_date)
logging.info('Computing timeseries for {0} -- '
'{1}.'.format(self.start_date, self.end_date))
full... | Perform all desired calculations on the data and save externally. | https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/calc.py#L435-L450 |
spencerahill/aospy | aospy/calc.py | Calc._save_files | def _save_files(self, data, dtype_out_time):
"""Save the data to netcdf files in direc_out."""
path = self.path_out[dtype_out_time]
if not os.path.isdir(self.dir_out):
os.makedirs(self.dir_out)
if 'reg' in dtype_out_time:
try:
reg_data = xr.open_da... | python | def _save_files(self, data, dtype_out_time):
"""Save the data to netcdf files in direc_out."""
path = self.path_out[dtype_out_time]
if not os.path.isdir(self.dir_out):
os.makedirs(self.dir_out)
if 'reg' in dtype_out_time:
try:
reg_data = xr.open_da... | Save the data to netcdf files in direc_out. | https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/calc.py#L452-L468 |
spencerahill/aospy | aospy/calc.py | Calc._write_to_tar | def _write_to_tar(self, dtype_out_time):
"""Add the data to the tar file in tar_out_direc."""
# When submitted in parallel and the directory does not exist yet
# multiple processes may try to create a new directory; this leads
# to an OSError for all processes that tried to make the
... | python | def _write_to_tar(self, dtype_out_time):
"""Add the data to the tar file in tar_out_direc."""
# When submitted in parallel and the directory does not exist yet
# multiple processes may try to create a new directory; this leads
# to an OSError for all processes that tried to make the
... | Add the data to the tar file in tar_out_direc. | https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/calc.py#L470-L514 |
spencerahill/aospy | aospy/calc.py | Calc._update_data_out | def _update_data_out(self, data, dtype):
"""Append the data of the given dtype_out to the data_out attr."""
try:
self.data_out.update({dtype: data})
except AttributeError:
self.data_out = {dtype: data} | python | def _update_data_out(self, data, dtype):
"""Append the data of the given dtype_out to the data_out attr."""
try:
self.data_out.update({dtype: data})
except AttributeError:
self.data_out = {dtype: data} | Append the data of the given dtype_out to the data_out attr. | https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/calc.py#L516-L521 |
spencerahill/aospy | aospy/calc.py | Calc.save | def save(self, data, dtype_out_time, dtype_out_vert=False,
save_files=True, write_to_tar=False):
"""Save aospy data to data_out attr and to an external file."""
self._update_data_out(data, dtype_out_time)
if save_files:
self._save_files(data, dtype_out_time)
if w... | python | def save(self, data, dtype_out_time, dtype_out_vert=False,
save_files=True, write_to_tar=False):
"""Save aospy data to data_out attr and to an external file."""
self._update_data_out(data, dtype_out_time)
if save_files:
self._save_files(data, dtype_out_time)
if w... | Save aospy data to data_out attr and to an external file. | https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/calc.py#L523-L531 |
spencerahill/aospy | aospy/calc.py | Calc._load_from_disk | def _load_from_disk(self, dtype_out_time, dtype_out_vert=False,
region=False):
"""Load aospy data saved as netcdf files on the file system."""
ds = xr.open_dataset(self.path_out[dtype_out_time])
if region:
arr = ds[region.name]
# Use region-specifi... | python | def _load_from_disk(self, dtype_out_time, dtype_out_vert=False,
region=False):
"""Load aospy data saved as netcdf files on the file system."""
ds = xr.open_dataset(self.path_out[dtype_out_time])
if region:
arr = ds[region.name]
# Use region-specifi... | Load aospy data saved as netcdf files on the file system. | https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/calc.py#L533-L555 |
spencerahill/aospy | aospy/calc.py | Calc._load_from_tar | def _load_from_tar(self, dtype_out_time, dtype_out_vert=False):
"""Load data save in tarball form on the file system."""
path = os.path.join(self.dir_tar_out, 'data.tar')
utils.io.dmget([path])
with tarfile.open(path, 'r') as data_tar:
ds = xr.open_dataset(
da... | python | def _load_from_tar(self, dtype_out_time, dtype_out_vert=False):
"""Load data save in tarball form on the file system."""
path = os.path.join(self.dir_tar_out, 'data.tar')
utils.io.dmget([path])
with tarfile.open(path, 'r') as data_tar:
ds = xr.open_dataset(
da... | Load data save in tarball form on the file system. | https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/calc.py#L557-L565 |
spencerahill/aospy | aospy/calc.py | Calc.load | def load(self, dtype_out_time, dtype_out_vert=False, region=False,
plot_units=False, mask_unphysical=False):
"""Load the data from the object if possible or from disk."""
msg = ("Loading data from disk for object={0}, dtype_out_time={1}, "
"dtype_out_vert={2}, and region="
... | python | def load(self, dtype_out_time, dtype_out_vert=False, region=False,
plot_units=False, mask_unphysical=False):
"""Load the data from the object if possible or from disk."""
msg = ("Loading data from disk for object={0}, dtype_out_time={1}, "
"dtype_out_vert={2}, and region="
... | Load the data from the object if possible or from disk. | https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/calc.py#L567-L591 |
spencerahill/aospy | aospy/examples/example_obj_lib.py | conv_precip_frac | def conv_precip_frac(precip_largescale, precip_convective):
"""Fraction of total precip that is from convection parameterization.
Parameters
----------
precip_largescale, precip_convective : xarray.DataArrays
Precipitation from grid-scale condensation and from convective
parameterizatio... | python | def conv_precip_frac(precip_largescale, precip_convective):
"""Fraction of total precip that is from convection parameterization.
Parameters
----------
precip_largescale, precip_convective : xarray.DataArrays
Precipitation from grid-scale condensation and from convective
parameterizatio... | Fraction of total precip that is from convection parameterization.
Parameters
----------
precip_largescale, precip_convective : xarray.DataArrays
Precipitation from grid-scale condensation and from convective
parameterization, respectively.
Returns
-------
xarray.DataArray | https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/examples/example_obj_lib.py#L52-L67 |
aresch/rencode | rencode/rencode_orig.py | dumps | def dumps(x, float_bits=DEFAULT_FLOAT_BITS):
"""
Dump data structure to str.
Here float_bits is either 32 or 64.
"""
with lock:
if float_bits == 32:
encode_func[float] = encode_float32
elif float_bits == 64:
encode_func[float] = encode_float64
else:
... | python | def dumps(x, float_bits=DEFAULT_FLOAT_BITS):
"""
Dump data structure to str.
Here float_bits is either 32 or 64.
"""
with lock:
if float_bits == 32:
encode_func[float] = encode_float32
elif float_bits == 64:
encode_func[float] = encode_float64
else:
... | Dump data structure to str.
Here float_bits is either 32 or 64. | https://github.com/aresch/rencode/blob/5c928f14567fabc9efb8bbb8ac5e0eef03c61541/rencode/rencode_orig.py#L404-L419 |
pteichman/cobe | cobe/tokenizers.py | MegaHALTokenizer.join | def join(self, words):
"""Capitalize the first alpha character in the reply and the
first alpha character that follows one of [.?!] and a
space."""
chars = list(u"".join(words))
start = True
for i in xrange(len(chars)):
char = chars[i]
if char.isa... | python | def join(self, words):
"""Capitalize the first alpha character in the reply and the
first alpha character that follows one of [.?!] and a
space."""
chars = list(u"".join(words))
start = True
for i in xrange(len(chars)):
char = chars[i]
if char.isa... | Capitalize the first alpha character in the reply and the
first alpha character that follows one of [.?!] and a
space. | https://github.com/pteichman/cobe/blob/b0dc2a707035035b9a689105c8f833894fb59eb7/cobe/tokenizers.py#L31-L51 |
pteichman/cobe | cobe/brain.py | Brain.start_batch_learning | def start_batch_learning(self):
"""Begin a series of batch learn operations. Data will not be
committed to the database until stop_batch_learning is
called. Learn text using the normal learn(text) method."""
self._learning = True
self.graph.cursor().execute("PRAGMA journal_mode=... | python | def start_batch_learning(self):
"""Begin a series of batch learn operations. Data will not be
committed to the database until stop_batch_learning is
called. Learn text using the normal learn(text) method."""
self._learning = True
self.graph.cursor().execute("PRAGMA journal_mode=... | Begin a series of batch learn operations. Data will not be
committed to the database until stop_batch_learning is
called. Learn text using the normal learn(text) method. | https://github.com/pteichman/cobe/blob/b0dc2a707035035b9a689105c8f833894fb59eb7/cobe/brain.py#L80-L87 |
pteichman/cobe | cobe/brain.py | Brain.stop_batch_learning | def stop_batch_learning(self):
"""Finish a series of batch learn operations."""
self._learning = False
self.graph.commit()
self.graph.cursor().execute("PRAGMA journal_mode=truncate")
self.graph.ensure_indexes() | python | def stop_batch_learning(self):
"""Finish a series of batch learn operations."""
self._learning = False
self.graph.commit()
self.graph.cursor().execute("PRAGMA journal_mode=truncate")
self.graph.ensure_indexes() | Finish a series of batch learn operations. | https://github.com/pteichman/cobe/blob/b0dc2a707035035b9a689105c8f833894fb59eb7/cobe/brain.py#L89-L95 |
pteichman/cobe | cobe/brain.py | Brain.learn | def learn(self, text):
"""Learn a string of text. If the input is not already
Unicode, it will be decoded as utf-8."""
if type(text) != types.UnicodeType:
# Assume that non-Unicode text is encoded as utf-8, which
# should be somewhat safe in the modern world.
... | python | def learn(self, text):
"""Learn a string of text. If the input is not already
Unicode, it will be decoded as utf-8."""
if type(text) != types.UnicodeType:
# Assume that non-Unicode text is encoded as utf-8, which
# should be somewhat safe in the modern world.
... | Learn a string of text. If the input is not already
Unicode, it will be decoded as utf-8. | https://github.com/pteichman/cobe/blob/b0dc2a707035035b9a689105c8f833894fb59eb7/cobe/brain.py#L114-L125 |
pteichman/cobe | cobe/brain.py | Brain._to_edges | def _to_edges(self, tokens):
"""This is an iterator that returns the nodes of our graph:
"This is a test" -> "None This" "This is" "is a" "a test" "test None"
Each is annotated with a boolean that tracks whether whitespace was
found between the two tokens."""
# prepend self.order Nones
chain = ... | python | def _to_edges(self, tokens):
"""This is an iterator that returns the nodes of our graph:
"This is a test" -> "None This" "This is" "is a" "a test" "test None"
Each is annotated with a boolean that tracks whether whitespace was
found between the two tokens."""
# prepend self.order Nones
chain = ... | This is an iterator that returns the nodes of our graph:
"This is a test" -> "None This" "This is" "is a" "a test" "test None"
Each is annotated with a boolean that tracks whether whitespace was
found between the two tokens. | https://github.com/pteichman/cobe/blob/b0dc2a707035035b9a689105c8f833894fb59eb7/cobe/brain.py#L127-L152 |
pteichman/cobe | cobe/brain.py | Brain._to_graph | def _to_graph(self, contexts):
"""This is an iterator that returns each edge of our graph
with its two nodes"""
prev = None
for context in contexts:
if prev is None:
prev = context
continue
yield prev[0], context[1], context[0]
... | python | def _to_graph(self, contexts):
"""This is an iterator that returns each edge of our graph
with its two nodes"""
prev = None
for context in contexts:
if prev is None:
prev = context
continue
yield prev[0], context[1], context[0]
... | This is an iterator that returns each edge of our graph
with its two nodes | https://github.com/pteichman/cobe/blob/b0dc2a707035035b9a689105c8f833894fb59eb7/cobe/brain.py#L154-L165 |
pteichman/cobe | cobe/brain.py | Brain.reply | def reply(self, text, loop_ms=500, max_len=None):
"""Reply to a string of text. If the input is not already
Unicode, it will be decoded as utf-8."""
if type(text) != types.UnicodeType:
# Assume that non-Unicode text is encoded as utf-8, which
# should be somewhat safe in ... | python | def reply(self, text, loop_ms=500, max_len=None):
"""Reply to a string of text. If the input is not already
Unicode, it will be decoded as utf-8."""
if type(text) != types.UnicodeType:
# Assume that non-Unicode text is encoded as utf-8, which
# should be somewhat safe in ... | Reply to a string of text. If the input is not already
Unicode, it will be decoded as utf-8. | https://github.com/pteichman/cobe/blob/b0dc2a707035035b9a689105c8f833894fb59eb7/cobe/brain.py#L197-L303 |
pteichman/cobe | cobe/brain.py | Brain.init | def init(filename, order=3, tokenizer=None):
"""Initialize a brain. This brain's file must not already exist.
Keyword arguments:
order -- Order of the forward/reverse Markov chains (integer)
tokenizer -- One of Cobe, MegaHAL (default Cobe). See documentation
for cobe.tokenizers for details. (strin... | python | def init(filename, order=3, tokenizer=None):
"""Initialize a brain. This brain's file must not already exist.
Keyword arguments:
order -- Order of the forward/reverse Markov chains (integer)
tokenizer -- One of Cobe, MegaHAL (default Cobe). See documentation
for cobe.tokenizers for details. (strin... | Initialize a brain. This brain's file must not already exist.
Keyword arguments:
order -- Order of the forward/reverse Markov chains (integer)
tokenizer -- One of Cobe, MegaHAL (default Cobe). See documentation
for cobe.tokenizers for details. (string) | https://github.com/pteichman/cobe/blob/b0dc2a707035035b9a689105c8f833894fb59eb7/cobe/brain.py#L389-L408 |
mk-fg/python-pulse-control | pulsectl/pulsectl.py | connect_to_cli | def connect_to_cli(server=None, as_file=True, socket_timeout=1.0, attempts=5, retry_delay=0.3):
'''Returns connected CLI interface socket (as file object, unless as_file=False),
where one can send same commands (as lines) as to "pacmd" tool
or pulseaudio startup files (e.g. "default.pa").
"server" option can b... | python | def connect_to_cli(server=None, as_file=True, socket_timeout=1.0, attempts=5, retry_delay=0.3):
'''Returns connected CLI interface socket (as file object, unless as_file=False),
where one can send same commands (as lines) as to "pacmd" tool
or pulseaudio startup files (e.g. "default.pa").
"server" option can b... | Returns connected CLI interface socket (as file object, unless as_file=False),
where one can send same commands (as lines) as to "pacmd" tool
or pulseaudio startup files (e.g. "default.pa").
"server" option can be specified to use non-standard unix socket path
(when passed absolute path string) or remote tcp... | https://github.com/mk-fg/python-pulse-control/blob/902d5e9e5591b89c356e5194a370212e23fb0e93/pulsectl/pulsectl.py#L818-L877 |
mk-fg/python-pulse-control | pulsectl/pulsectl.py | PulseExtStreamRestoreInfo.struct_from_value | def struct_from_value( cls, name, volume,
channel_list=None, mute=False, device=None ):
'Same arguments as with class instance init.'
chan_map = c.PA_CHANNEL_MAP()
if not channel_list: c.pa.channel_map_init_mono(chan_map)
else:
if not is_str(channel_list):
channel_list = b','.join(map(c.force_bytes, c... | python | def struct_from_value( cls, name, volume,
channel_list=None, mute=False, device=None ):
'Same arguments as with class instance init.'
chan_map = c.PA_CHANNEL_MAP()
if not channel_list: c.pa.channel_map_init_mono(chan_map)
else:
if not is_str(channel_list):
channel_list = b','.join(map(c.force_bytes, c... | Same arguments as with class instance init. | https://github.com/mk-fg/python-pulse-control/blob/902d5e9e5591b89c356e5194a370212e23fb0e93/pulsectl/pulsectl.py#L287-L302 |
mk-fg/python-pulse-control | pulsectl/pulsectl.py | Pulse.connect | def connect(self, autospawn=False, wait=False):
'''Connect to pulseaudio server.
"autospawn" option will start new pulse daemon, if necessary.
Specifying "wait" option will make function block until pulseaudio server appears.'''
if self._loop_closed:
raise PulseError('Eventloop object was already'
' de... | python | def connect(self, autospawn=False, wait=False):
'''Connect to pulseaudio server.
"autospawn" option will start new pulse daemon, if necessary.
Specifying "wait" option will make function block until pulseaudio server appears.'''
if self._loop_closed:
raise PulseError('Eventloop object was already'
' de... | Connect to pulseaudio server.
"autospawn" option will start new pulse daemon, if necessary.
Specifying "wait" option will make function block until pulseaudio server appears. | https://github.com/mk-fg/python-pulse-control/blob/902d5e9e5591b89c356e5194a370212e23fb0e93/pulsectl/pulsectl.py#L387-L401 |
mk-fg/python-pulse-control | pulsectl/pulsectl.py | Pulse._pulse_poll | def _pulse_poll(self, timeout=None):
'''timeout should be in seconds (float),
0 for non-blocking poll and None (default) for no timeout.'''
with self._pulse_loop() as loop:
ts = c.mono_time()
ts_deadline = timeout and (ts + timeout)
while True:
delay = max(0, int((ts_deadline - ts) * 1000000)) if ts... | python | def _pulse_poll(self, timeout=None):
'''timeout should be in seconds (float),
0 for non-blocking poll and None (default) for no timeout.'''
with self._pulse_loop() as loop:
ts = c.mono_time()
ts_deadline = timeout and (ts + timeout)
while True:
delay = max(0, int((ts_deadline - ts) * 1000000)) if ts... | timeout should be in seconds (float),
0 for non-blocking poll and None (default) for no timeout. | https://github.com/mk-fg/python-pulse-control/blob/902d5e9e5591b89c356e5194a370212e23fb0e93/pulsectl/pulsectl.py#L484-L498 |
mk-fg/python-pulse-control | pulsectl/pulsectl.py | Pulse._pulse_method_call | def _pulse_method_call(pulse_op, func=None, index_arg=True):
'''Creates following synchronous wrapper for async pa_operation callable:
wrapper(index, ...) -> pulse_op(index, [*]args_func(...))
index_arg=False: wrapper(...) -> pulse_op([*]args_func(...))'''
def _wrapper(self, *args, **kws):
if index_arg:
... | python | def _pulse_method_call(pulse_op, func=None, index_arg=True):
'''Creates following synchronous wrapper for async pa_operation callable:
wrapper(index, ...) -> pulse_op(index, [*]args_func(...))
index_arg=False: wrapper(...) -> pulse_op([*]args_func(...))'''
def _wrapper(self, *args, **kws):
if index_arg:
... | Creates following synchronous wrapper for async pa_operation callable:
wrapper(index, ...) -> pulse_op(index, [*]args_func(...))
index_arg=False: wrapper(...) -> pulse_op([*]args_func(...)) | https://github.com/mk-fg/python-pulse-control/blob/902d5e9e5591b89c356e5194a370212e23fb0e93/pulsectl/pulsectl.py#L577-L598 |
mk-fg/python-pulse-control | pulsectl/pulsectl.py | Pulse.stream_restore_write | def stream_restore_write( obj_name_or_list,
mode='merge', apply_immediately=False, **obj_kws ):
'''Update module-stream-restore db entry for specified name.
Can be passed PulseExtStreamRestoreInfo object or list of them as argument,
or name string there and object init keywords (e.g. volume, mute, channel_l... | python | def stream_restore_write( obj_name_or_list,
mode='merge', apply_immediately=False, **obj_kws ):
'''Update module-stream-restore db entry for specified name.
Can be passed PulseExtStreamRestoreInfo object or list of them as argument,
or name string there and object init keywords (e.g. volume, mute, channel_l... | Update module-stream-restore db entry for specified name.
Can be passed PulseExtStreamRestoreInfo object or list of them as argument,
or name string there and object init keywords (e.g. volume, mute, channel_list, etc).
"mode" is PulseUpdateEnum value of
'merge' (default), 'replace' or 'set' (replaces ALL... | https://github.com/mk-fg/python-pulse-control/blob/902d5e9e5591b89c356e5194a370212e23fb0e93/pulsectl/pulsectl.py#L675-L692 |
mk-fg/python-pulse-control | pulsectl/pulsectl.py | Pulse.stream_restore_delete | def stream_restore_delete(obj_name_or_list):
'''Can be passed string name,
PulseExtStreamRestoreInfo object or a list of any of these.'''
if is_str(obj_name_or_list, PulseExtStreamRestoreInfo):
obj_name_or_list = [obj_name_or_list]
name_list = list((obj.name if isinstance( obj,
PulseExtStreamRestoreInfo ... | python | def stream_restore_delete(obj_name_or_list):
'''Can be passed string name,
PulseExtStreamRestoreInfo object or a list of any of these.'''
if is_str(obj_name_or_list, PulseExtStreamRestoreInfo):
obj_name_or_list = [obj_name_or_list]
name_list = list((obj.name if isinstance( obj,
PulseExtStreamRestoreInfo ... | Can be passed string name,
PulseExtStreamRestoreInfo object or a list of any of these. | https://github.com/mk-fg/python-pulse-control/blob/902d5e9e5591b89c356e5194a370212e23fb0e93/pulsectl/pulsectl.py#L695-L704 |
mk-fg/python-pulse-control | pulsectl/pulsectl.py | Pulse.default_set | def default_set(self, obj):
'Set passed sink or source to be used as default one by pulseaudio server.'
assert_pulse_object(obj)
method = {
PulseSinkInfo: self.sink_default_set,
PulseSourceInfo: self.source_default_set }.get(type(obj))
if not method: raise NotImplementedError(type(obj))
method(obj) | python | def default_set(self, obj):
'Set passed sink or source to be used as default one by pulseaudio server.'
assert_pulse_object(obj)
method = {
PulseSinkInfo: self.sink_default_set,
PulseSourceInfo: self.source_default_set }.get(type(obj))
if not method: raise NotImplementedError(type(obj))
method(obj) | Set passed sink or source to be used as default one by pulseaudio server. | https://github.com/mk-fg/python-pulse-control/blob/902d5e9e5591b89c356e5194a370212e23fb0e93/pulsectl/pulsectl.py#L707-L714 |
mk-fg/python-pulse-control | pulsectl/pulsectl.py | Pulse.event_listen | def event_listen(self, timeout=None, raise_on_disconnect=True):
'''Does not return until PulseLoopStop
gets raised in event callback or timeout passes.
timeout should be in seconds (float),
0 for non-blocking poll and None (default) for no timeout.
raise_on_disconnect causes PulseDisconnected exceptions... | python | def event_listen(self, timeout=None, raise_on_disconnect=True):
'''Does not return until PulseLoopStop
gets raised in event callback or timeout passes.
timeout should be in seconds (float),
0 for non-blocking poll and None (default) for no timeout.
raise_on_disconnect causes PulseDisconnected exceptions... | Does not return until PulseLoopStop
gets raised in event callback or timeout passes.
timeout should be in seconds (float),
0 for non-blocking poll and None (default) for no timeout.
raise_on_disconnect causes PulseDisconnected exceptions by default.
Do not run any pulse operations from these callbacks. | https://github.com/mk-fg/python-pulse-control/blob/902d5e9e5591b89c356e5194a370212e23fb0e93/pulsectl/pulsectl.py#L785-L795 |
mk-fg/python-pulse-control | pulsectl/pulsectl.py | Pulse.event_listen_stop | def event_listen_stop(self):
'''Stop event_listen() loop from e.g. another thread.
Does nothing if libpulse poll is not running yet, so might be racey with
event_listen() - be sure to call it in a loop until event_listen returns or something.'''
self._loop_stop = True
c.pa.mainloop_wakeup(self._loop) | python | def event_listen_stop(self):
'''Stop event_listen() loop from e.g. another thread.
Does nothing if libpulse poll is not running yet, so might be racey with
event_listen() - be sure to call it in a loop until event_listen returns or something.'''
self._loop_stop = True
c.pa.mainloop_wakeup(self._loop) | Stop event_listen() loop from e.g. another thread.
Does nothing if libpulse poll is not running yet, so might be racey with
event_listen() - be sure to call it in a loop until event_listen returns or something. | https://github.com/mk-fg/python-pulse-control/blob/902d5e9e5591b89c356e5194a370212e23fb0e93/pulsectl/pulsectl.py#L797-L802 |
mk-fg/python-pulse-control | pulsectl/pulsectl.py | Pulse.set_poll_func | def set_poll_func(self, func, func_err_handler=None):
'''Can be used to integrate pulse client into existing eventloop.
Function will be passed a list of pollfd structs and timeout value (seconds, float),
which it is responsible to use and modify (set poll flags) accordingly,
returning int value >= 0 with ... | python | def set_poll_func(self, func, func_err_handler=None):
'''Can be used to integrate pulse client into existing eventloop.
Function will be passed a list of pollfd structs and timeout value (seconds, float),
which it is responsible to use and modify (set poll flags) accordingly,
returning int value >= 0 with ... | Can be used to integrate pulse client into existing eventloop.
Function will be passed a list of pollfd structs and timeout value (seconds, float),
which it is responsible to use and modify (set poll flags) accordingly,
returning int value >= 0 with number of fds that had any new events within timeout.
fu... | https://github.com/mk-fg/python-pulse-control/blob/902d5e9e5591b89c356e5194a370212e23fb0e93/pulsectl/pulsectl.py#L805-L815 |
mk-fg/python-pulse-control | pulsectl/lookup.py | pulse_obj_lookup | def pulse_obj_lookup(pulse, obj_lookup, prop_default=None):
'''Return set of pulse object(s) with proplist values matching lookup-string.
Pattern syntax:
[ { 'sink' | 'source' | 'sink-input' | 'source-output' } [ / ... ] ':' ]
[ proplist-key-name (non-empty) [ / ... ] ':' ] [ ':' (for regexp match) ]
[ pro... | python | def pulse_obj_lookup(pulse, obj_lookup, prop_default=None):
'''Return set of pulse object(s) with proplist values matching lookup-string.
Pattern syntax:
[ { 'sink' | 'source' | 'sink-input' | 'source-output' } [ / ... ] ':' ]
[ proplist-key-name (non-empty) [ / ... ] ':' ] [ ':' (for regexp match) ]
[ pro... | Return set of pulse object(s) with proplist values matching lookup-string.
Pattern syntax:
[ { 'sink' | 'source' | 'sink-input' | 'source-output' } [ / ... ] ':' ]
[ proplist-key-name (non-empty) [ / ... ] ':' ] [ ':' (for regexp match) ]
[ proplist-key-value ]
Examples:
- sink:alsa.driver_name:snd_hd... | https://github.com/mk-fg/python-pulse-control/blob/902d5e9e5591b89c356e5194a370212e23fb0e93/pulsectl/lookup.py#L23-L93 |
bukun/TorCMS | torcms/model/link_model.py | MLink.update | def update(uid, post_data):
'''
Updat the link.
'''
entry = TabLink.update(
name=post_data['name'],
link=post_data['link'],
order=post_data['order'],
logo=post_data['logo'] if 'logo' in post_data else '',
).where(TabLink.uid == uid)... | python | def update(uid, post_data):
'''
Updat the link.
'''
entry = TabLink.update(
name=post_data['name'],
link=post_data['link'],
order=post_data['order'],
logo=post_data['logo'] if 'logo' in post_data else '',
).where(TabLink.uid == uid)... | Updat the link. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/link_model.py#L44-L58 |
bukun/TorCMS | torcms/model/link_model.py | MLink.create_link | def create_link(id_link, post_data):
'''
Add record in link.
'''
if MLink.get_by_uid(id_link):
return False
try:
the_order = int(post_data['order'])
except:
the_order = 999
TabLink.create(name=post_data['name'],
... | python | def create_link(id_link, post_data):
'''
Add record in link.
'''
if MLink.get_by_uid(id_link):
return False
try:
the_order = int(post_data['order'])
except:
the_order = 999
TabLink.create(name=post_data['name'],
... | Add record in link. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/link_model.py#L61-L76 |
bukun/TorCMS | torcms/handlers/wiki_handler.py | WikiHandler.recent | def recent(self):
'''
List recent wiki.
'''
kwd = {
'pager': '',
'title': 'Recent Pages',
}
self.render('wiki_page/wiki_list.html',
view=MWiki.query_recent(),
format_date=tools.format_date,
... | python | def recent(self):
'''
List recent wiki.
'''
kwd = {
'pager': '',
'title': 'Recent Pages',
}
self.render('wiki_page/wiki_list.html',
view=MWiki.query_recent(),
format_date=tools.format_date,
... | List recent wiki. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/wiki_handler.py#L61-L73 |
bukun/TorCMS | torcms/handlers/wiki_handler.py | WikiHandler.refresh | def refresh(self):
'''
List the wikis of dated.
'''
kwd = {
'pager': '',
'title': '最近文档',
}
self.render('wiki_page/wiki_list.html',
view=MWiki.query_dated(16),
format_date=tools.format_date,
... | python | def refresh(self):
'''
List the wikis of dated.
'''
kwd = {
'pager': '',
'title': '最近文档',
}
self.render('wiki_page/wiki_list.html',
view=MWiki.query_dated(16),
format_date=tools.format_date,
... | List the wikis of dated. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/wiki_handler.py#L75-L87 |
bukun/TorCMS | torcms/handlers/wiki_handler.py | WikiHandler.view_or_add | def view_or_add(self, title):
'''
To judge if there is a post of the title.
Then, to show, or to add.
'''
postinfo = MWiki.get_by_wiki(title)
if postinfo:
if postinfo.kind == self.kind:
self.view(postinfo)
else:
retu... | python | def view_or_add(self, title):
'''
To judge if there is a post of the title.
Then, to show, or to add.
'''
postinfo = MWiki.get_by_wiki(title)
if postinfo:
if postinfo.kind == self.kind:
self.view(postinfo)
else:
retu... | To judge if there is a post of the title.
Then, to show, or to add. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/wiki_handler.py#L89-L101 |
bukun/TorCMS | torcms/handlers/wiki_handler.py | WikiHandler.update | def update(self, uid):
'''
Update the wiki.
'''
postinfo = MWiki.get_by_uid(uid)
if self.check_post_role()['EDIT'] or postinfo.user_name == self.get_current_user():
pass
else:
return False
post_data = self.get_post_data()
post_data[... | python | def update(self, uid):
'''
Update the wiki.
'''
postinfo = MWiki.get_by_uid(uid)
if self.check_post_role()['EDIT'] or postinfo.user_name == self.get_current_user():
pass
else:
return False
post_data = self.get_post_data()
post_data[... | Update the wiki. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/wiki_handler.py#L105-L130 |
bukun/TorCMS | torcms/handlers/wiki_handler.py | WikiHandler.view | def view(self, view):
'''
View the wiki.
'''
kwd = {
'pager': '',
'editable': self.editable(),
}
self.render('wiki_page/wiki_view.html',
postinfo=view,
kwd=kwd,
userinfo=self.userinfo) | python | def view(self, view):
'''
View the wiki.
'''
kwd = {
'pager': '',
'editable': self.editable(),
}
self.render('wiki_page/wiki_view.html',
postinfo=view,
kwd=kwd,
userinfo=self.userinfo) | View the wiki. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/wiki_handler.py#L150-L162 |
bukun/TorCMS | torcms/handlers/wiki_handler.py | WikiHandler.add | def add(self, title=''):
'''
Add wiki
'''
post_data = self.get_post_data()
if title == '':
pass
else:
post_data['title'] = title
post_data['user_name'] = self.get_current_user()
if MWiki.get_by_wiki(post_data['title']):
... | python | def add(self, title=''):
'''
Add wiki
'''
post_data = self.get_post_data()
if title == '':
pass
else:
post_data['title'] = title
post_data['user_name'] = self.get_current_user()
if MWiki.get_by_wiki(post_data['title']):
... | Add wiki | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/wiki_handler.py#L188-L208 |
bukun/TorCMS | torcms/handlers/filter_handler.py | echo_html_fenye_str | def echo_html_fenye_str(rec_num, fenye_num):
'''
生成分页的导航
'''
pagination_num = int(math.ceil(rec_num * 1.0 / 10))
if pagination_num == 1 or pagination_num == 0:
fenye_str = ''
elif pagination_num > 1:
pager_mid, pager_pre, pager_next, pager_last, pager_home = '', '', '', '', ''... | python | def echo_html_fenye_str(rec_num, fenye_num):
'''
生成分页的导航
'''
pagination_num = int(math.ceil(rec_num * 1.0 / 10))
if pagination_num == 1 or pagination_num == 0:
fenye_str = ''
elif pagination_num > 1:
pager_mid, pager_pre, pager_next, pager_last, pager_home = '', '', '', '', ''... | 生成分页的导航 | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/filter_handler.py#L17-L70 |
bukun/TorCMS | torcms/handlers/filter_handler.py | FilterHandler.echo_html | def echo_html(self, url_str):
'''
Show the HTML
'''
logger.info('info echo html: {0}'.format(url_str))
condition = self.gen_redis_kw()
url_arr = self.parse_url(url_str)
sig = url_arr[0]
num = (len(url_arr) - 2) // 2
catinfo = MCategory.get_by_... | python | def echo_html(self, url_str):
'''
Show the HTML
'''
logger.info('info echo html: {0}'.format(url_str))
condition = self.gen_redis_kw()
url_arr = self.parse_url(url_str)
sig = url_arr[0]
num = (len(url_arr) - 2) // 2
catinfo = MCategory.get_by_... | Show the HTML | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/filter_handler.py#L110-L159 |
bukun/TorCMS | torcms/handlers/filter_handler.py | FilterHandler.echo_html_list_str | def echo_html_list_str(self, catid, infos):
'''
生成 list 后的 HTML 格式的字符串
'''
zhiding_str = ''
tuiguang_str = ''
imgname = 'fixed/zhanwei.png'
kwd = {
'imgname': imgname,
'zhiding': zhiding_str,
'tuiguang': tuiguang_str,
}... | python | def echo_html_list_str(self, catid, infos):
'''
生成 list 后的 HTML 格式的字符串
'''
zhiding_str = ''
tuiguang_str = ''
imgname = 'fixed/zhanwei.png'
kwd = {
'imgname': imgname,
'zhiding': zhiding_str,
'tuiguang': tuiguang_str,
}... | 生成 list 后的 HTML 格式的字符串 | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/filter_handler.py#L161-L180 |
bukun/TorCMS | torcms/handlers/filter_handler.py | FilterHandler.list | def list(self, catid):
'''
页面打开后的渲染方法,不包含 list 的查询结果与分页导航
'''
logger.info('Infocat input: {0}'.format(catid))
condition = self.gen_redis_kw()
sig = catid
bread_title = ''
bread_crumb_nav_str = '<li>当前位置:<a href="/">信息</a></li>'
_catinfo = MCategor... | python | def list(self, catid):
'''
页面打开后的渲染方法,不包含 list 的查询结果与分页导航
'''
logger.info('Infocat input: {0}'.format(catid))
condition = self.gen_redis_kw()
sig = catid
bread_title = ''
bread_crumb_nav_str = '<li>当前位置:<a href="/">信息</a></li>'
_catinfo = MCategor... | 页面打开后的渲染方法,不包含 list 的查询结果与分页导航 | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/filter_handler.py#L182-L246 |
bukun/TorCMS | torcms/script/autocrud/fetch_html_dic.py | gen_html_dic | def gen_html_dic():
'''
生成 Filter .
'''
if WORK_BOOK:
pass
else:
return False
html_dics = {}
for wk_sheet in WORK_BOOK:
for column in FILTER_COLUMNS:
kkey, kval = __write_filter_dic(wk_sheet, column)
if kkey:
html_dics[kkey] =... | python | def gen_html_dic():
'''
生成 Filter .
'''
if WORK_BOOK:
pass
else:
return False
html_dics = {}
for wk_sheet in WORK_BOOK:
for column in FILTER_COLUMNS:
kkey, kval = __write_filter_dic(wk_sheet, column)
if kkey:
html_dics[kkey] =... | 生成 Filter . | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/autocrud/fetch_html_dic.py#L69-L86 |
bukun/TorCMS | torcms/script/autocrud/fetch_html_dic.py | gen_array_crud | def gen_array_crud():
'''
Return the dictionay of the switcher form XLXS file.
if valud of the column of the row is `1`, it will be added to the array.
'''
if WORK_BOOK:
pass
else:
return False
papa_id = 0
switch_dics = {}
kind_dics = {}
for work_sheet in WORK... | python | def gen_array_crud():
'''
Return the dictionay of the switcher form XLXS file.
if valud of the column of the row is `1`, it will be added to the array.
'''
if WORK_BOOK:
pass
else:
return False
papa_id = 0
switch_dics = {}
kind_dics = {}
for work_sheet in WORK... | Return the dictionay of the switcher form XLXS file.
if valud of the column of the row is `1`, it will be added to the array. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/autocrud/fetch_html_dic.py#L89-L132 |
bukun/TorCMS | torcms/script/autocrud/fetch_html_dic.py | __get_switch_arr | def __get_switch_arr(work_sheet, row_num):
'''
if valud of the column of the row is `1`, it will be added to the array.
'''
u_dic = []
for col_idx in FILTER_COLUMNS:
cell_val = work_sheet['{0}{1}'.format(col_idx, row_num)].value
if cell_val in [1, '1']:
# Appending the ... | python | def __get_switch_arr(work_sheet, row_num):
'''
if valud of the column of the row is `1`, it will be added to the array.
'''
u_dic = []
for col_idx in FILTER_COLUMNS:
cell_val = work_sheet['{0}{1}'.format(col_idx, row_num)].value
if cell_val in [1, '1']:
# Appending the ... | if valud of the column of the row is `1`, it will be added to the array. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/autocrud/fetch_html_dic.py#L135-L146 |
bukun/TorCMS | torcms/model/usage_model.py | MUsage.add_or_update | def add_or_update(user_id, post_id, kind):
'''
Create the record if new, else update it.
'''
rec = MUsage.query_by_signature(user_id, post_id)
cate_rec = MInfor2Catalog.get_first_category(post_id)
if cate_rec:
cat_id = cate_rec.tag_id
else:
... | python | def add_or_update(user_id, post_id, kind):
'''
Create the record if new, else update it.
'''
rec = MUsage.query_by_signature(user_id, post_id)
cate_rec = MInfor2Catalog.get_first_category(post_id)
if cate_rec:
cat_id = cate_rec.tag_id
else:
... | Create the record if new, else update it. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/usage_model.py#L92-L120 |
bukun/TorCMS | torcms/script/script_sendemail_all.py | run_send_all | def run_send_all(*args):
'''
Send email to all user.
'''
for user_rec in MUser.query_all():
email_add = user_rec.user_email
send_mail([email_add],
"{0}|{1}".format(SMTP_CFG['name'], email_cfg['title']),
email_cfg['content']) | python | def run_send_all(*args):
'''
Send email to all user.
'''
for user_rec in MUser.query_all():
email_add = user_rec.user_email
send_mail([email_add],
"{0}|{1}".format(SMTP_CFG['name'], email_cfg['title']),
email_cfg['content']) | Send email to all user. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/script_sendemail_all.py#L11-L19 |
bukun/TorCMS | torcms/script/script_sendemail_all.py | run_send_nologin | def run_send_nologin(*args):
'''
Send email to who not logged in recently.
'''
for user_rec in MUser.query_nologin():
email_add = user_rec.user_email
print(email_add)
send_mail([email_add],
"{0}|{1}".format(SMTP_CFG['name'], email_cfg['title']),
... | python | def run_send_nologin(*args):
'''
Send email to who not logged in recently.
'''
for user_rec in MUser.query_nologin():
email_add = user_rec.user_email
print(email_add)
send_mail([email_add],
"{0}|{1}".format(SMTP_CFG['name'], email_cfg['title']),
... | Send email to who not logged in recently. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/script_sendemail_all.py#L22-L32 |
bukun/TorCMS | torcms/script/script_gen_category.py | gen_xlsx_category | def gen_xlsx_category():
'''
Genereting catetory from xlsx file.
'''
if os.path.exists(XLSX_FILE):
pass
else:
return
# 在分类中排序
order_index = 1
all_cate_arr = []
for sheet_ranges in load_workbook(filename=XLSX_FILE):
kind_sig = str(sheet_ranges['A1'].value).st... | python | def gen_xlsx_category():
'''
Genereting catetory from xlsx file.
'''
if os.path.exists(XLSX_FILE):
pass
else:
return
# 在分类中排序
order_index = 1
all_cate_arr = []
for sheet_ranges in load_workbook(filename=XLSX_FILE):
kind_sig = str(sheet_ranges['A1'].value).st... | Genereting catetory from xlsx file. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/script_gen_category.py#L14-L74 |
bukun/TorCMS | torcms/script/script_gen_category.py | gen_category | def gen_category(yaml_file, sig):
'''
Genereting catetory from YAML file.
'''
out_dic = yaml.load(open(yaml_file))
for key in out_dic:
if key.endswith('00'):
uid = key[1:]
cur_dic = out_dic[key]
porder = cur_dic['order']
cat_dic = {
... | python | def gen_category(yaml_file, sig):
'''
Genereting catetory from YAML file.
'''
out_dic = yaml.load(open(yaml_file))
for key in out_dic:
if key.endswith('00'):
uid = key[1:]
cur_dic = out_dic[key]
porder = cur_dic['order']
cat_dic = {
... | Genereting catetory from YAML file. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/script_gen_category.py#L76-L125 |
bukun/TorCMS | torcms/script/script_gen_category.py | gen_yaml_category | def gen_yaml_category():
'''
find YAML.
'''
for wroot, _, wfiles in os.walk('./database/meta'):
for wfile in wfiles:
if wfile.endswith('.yaml'):
gen_category(os.path.join(wroot, wfile), wfile[0]) | python | def gen_yaml_category():
'''
find YAML.
'''
for wroot, _, wfiles in os.walk('./database/meta'):
for wfile in wfiles:
if wfile.endswith('.yaml'):
gen_category(os.path.join(wroot, wfile), wfile[0]) | find YAML. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/script_gen_category.py#L128-L135 |
bukun/TorCMS | torcms/script/script_migrate.py | run_migrate | def run_migrate(*args):
'''
running some migration.
'''
print('Begin migrate ...')
torcms_migrator = migrate.PostgresqlMigrator(config.DB_CON)
memo_field = migrate.TextField(null=False, default='', help_text='Memo', )
try:
migrate.migrate(torcms_migrator.add_column('tabpost', 'mem... | python | def run_migrate(*args):
'''
running some migration.
'''
print('Begin migrate ...')
torcms_migrator = migrate.PostgresqlMigrator(config.DB_CON)
memo_field = migrate.TextField(null=False, default='', help_text='Memo', )
try:
migrate.migrate(torcms_migrator.add_column('tabpost', 'mem... | running some migration. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/script_migrate.py#L15-L49 |
bukun/TorCMS | torcms/core/tools.py | diff_table | def diff_table(rawinfo, newinfo):
'''
Generate the difference as the table format.
:param rawinfo:
:param newinfo:
:return:
'''
return HtmlDiff.make_table(HtmlDiff(), rawinfo.split('\n'), newinfo.split('\n'),
context=True,
numline... | python | def diff_table(rawinfo, newinfo):
'''
Generate the difference as the table format.
:param rawinfo:
:param newinfo:
:return:
'''
return HtmlDiff.make_table(HtmlDiff(), rawinfo.split('\n'), newinfo.split('\n'),
context=True,
numline... | Generate the difference as the table format.
:param rawinfo:
:param newinfo:
:return: | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/core/tools.py#L89-L98 |
bukun/TorCMS | torcms/core/tools.py | get_uudd | def get_uudd(lenth):
'''
随机获取给定位数的整数
'''
sel_arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
rarr = random.sample(sel_arr, lenth)
while rarr[0] == '0':
rarr = random.sample(sel_arr, lenth)
return int(''.join(rarr)) | python | def get_uudd(lenth):
'''
随机获取给定位数的整数
'''
sel_arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
rarr = random.sample(sel_arr, lenth)
while rarr[0] == '0':
rarr = random.sample(sel_arr, lenth)
return int(''.join(rarr)) | 随机获取给定位数的整数 | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/core/tools.py#L209-L217 |
bukun/TorCMS | torcms/core/tools.py | markdown2html | def markdown2html(markdown_text):
'''
Convert markdown text to HTML. with extensions.
:param markdown_text: The markdown text.
:return: The HTML text.
'''
html = markdown.markdown(
markdown_text,
extensions=[
WikiLinkExtension(base_url='/wiki/', end_url=''),
... | python | def markdown2html(markdown_text):
'''
Convert markdown text to HTML. with extensions.
:param markdown_text: The markdown text.
:return: The HTML text.
'''
html = markdown.markdown(
markdown_text,
extensions=[
WikiLinkExtension(base_url='/wiki/', end_url=''),
... | Convert markdown text to HTML. with extensions.
:param markdown_text: The markdown text.
:return: The HTML text. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/core/tools.py#L228-L247 |
bukun/TorCMS | torcms/core/tools.py | gen_pager_purecss | def gen_pager_purecss(cat_slug, page_num, current):
'''
Generate pager of purecss.
'''
if page_num == 1:
return ''
pager_shouye = '''<li class="pure-menu-item {0}">
<a class="pure-menu-link" href="{1}"><< 首页</a></li>'''.format(
'hidden' if current <= 1 else '', cat_slug
... | python | def gen_pager_purecss(cat_slug, page_num, current):
'''
Generate pager of purecss.
'''
if page_num == 1:
return ''
pager_shouye = '''<li class="pure-menu-item {0}">
<a class="pure-menu-link" href="{1}"><< 首页</a></li>'''.format(
'hidden' if current <= 1 else '', cat_slug
... | Generate pager of purecss. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/core/tools.py#L251-L288 |
bukun/TorCMS | torcms/core/tools.py | get_cfg | def get_cfg():
'''
Get the configure value.
'''
cfg_var = dir(cfg)
if 'DB_CFG' in cfg_var:
db_cfg = cfg.DB_CFG
else:
db_cfg = ConfigDefault.DB_CFG
if 'SMTP_CFG' in cfg_var:
smtp_cfg = cfg.SMTP_CFG
else:
smtp_cfg = ConfigDefault.SMTP_CFG
if 'SITE_CF... | python | def get_cfg():
'''
Get the configure value.
'''
cfg_var = dir(cfg)
if 'DB_CFG' in cfg_var:
db_cfg = cfg.DB_CFG
else:
db_cfg = ConfigDefault.DB_CFG
if 'SMTP_CFG' in cfg_var:
smtp_cfg = cfg.SMTP_CFG
else:
smtp_cfg = ConfigDefault.SMTP_CFG
if 'SITE_CF... | Get the configure value. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/core/tools.py#L359-L416 |
bukun/TorCMS | torcms/handlers/page_handler.py | PageHandler.view_or_add | def view_or_add(self, slug):
'''
When access with the slug, It will add the page if there is no record in database.
'''
rec_page = MWiki.get_by_uid(slug)
if rec_page:
if rec_page.kind == self.kind:
self.view(rec_page)
else:
... | python | def view_or_add(self, slug):
'''
When access with the slug, It will add the page if there is no record in database.
'''
rec_page = MWiki.get_by_uid(slug)
if rec_page:
if rec_page.kind == self.kind:
self.view(rec_page)
else:
... | When access with the slug, It will add the page if there is no record in database. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/page_handler.py#L65-L77 |
bukun/TorCMS | torcms/handlers/page_handler.py | PageHandler.to_add | def to_add(self, citiao):
'''
To Add page.
'''
kwd = {
'cats': MCategory.query_all(),
'slug': citiao,
'pager': '',
}
self.render('wiki_page/page_add.html',
kwd=kwd,
userinfo=self.userinfo) | python | def to_add(self, citiao):
'''
To Add page.
'''
kwd = {
'cats': MCategory.query_all(),
'slug': citiao,
'pager': '',
}
self.render('wiki_page/page_add.html',
kwd=kwd,
userinfo=self.userinfo) | To Add page. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/page_handler.py#L81-L93 |
bukun/TorCMS | torcms/handlers/page_handler.py | PageHandler.__could_edit | def __could_edit(self, slug):
'''
Test if the user could edit the page.
'''
page_rec = MWiki.get_by_uid(slug)
if not page_rec:
return False
if self.check_post_role()['EDIT']:
return True
elif page_rec.user_name == self.userinfo.user_name:
... | python | def __could_edit(self, slug):
'''
Test if the user could edit the page.
'''
page_rec = MWiki.get_by_uid(slug)
if not page_rec:
return False
if self.check_post_role()['EDIT']:
return True
elif page_rec.user_name == self.userinfo.user_name:
... | Test if the user could edit the page. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/page_handler.py#L96-L108 |
bukun/TorCMS | torcms/handlers/page_handler.py | PageHandler.update | def update(self, slug):
'''
Update the page.
'''
post_data = self.get_post_data()
post_data['user_name'] = self.userinfo.user_name
pageinfo = MWiki.get_by_uid(slug)
cnt_old = tornado.escape.xhtml_unescape(pageinfo.cnt_md).strip()
cnt_new = post_data['c... | python | def update(self, slug):
'''
Update the page.
'''
post_data = self.get_post_data()
post_data['user_name'] = self.userinfo.user_name
pageinfo = MWiki.get_by_uid(slug)
cnt_old = tornado.escape.xhtml_unescape(pageinfo.cnt_md).strip()
cnt_new = post_data['c... | Update the page. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/page_handler.py#L112-L133 |
bukun/TorCMS | torcms/handlers/page_handler.py | PageHandler.to_modify | def to_modify(self, uid):
'''
Try to modify the page.
'''
kwd = {
'pager': '',
}
self.render('wiki_page/page_edit.html',
postinfo=MWiki.get_by_uid(uid),
kwd=kwd,
cfg=CMS_CFG,
use... | python | def to_modify(self, uid):
'''
Try to modify the page.
'''
kwd = {
'pager': '',
}
self.render('wiki_page/page_edit.html',
postinfo=MWiki.get_by_uid(uid),
kwd=kwd,
cfg=CMS_CFG,
use... | Try to modify the page. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/page_handler.py#L137-L150 |
bukun/TorCMS | torcms/handlers/page_handler.py | PageHandler.view | def view(self, rec):
'''
View the page.
'''
kwd = {
'pager': '',
}
self.render('wiki_page/page_view.html',
postinfo=rec,
kwd=kwd,
author=rec.user_name,
format_date=tools.format_da... | python | def view(self, rec):
'''
View the page.
'''
kwd = {
'pager': '',
}
self.render('wiki_page/page_view.html',
postinfo=rec,
kwd=kwd,
author=rec.user_name,
format_date=tools.format_da... | View the page. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/page_handler.py#L153-L167 |
bukun/TorCMS | torcms/handlers/page_handler.py | PageHandler.ajax_count_plus | def ajax_count_plus(self, slug):
'''
post count plus one via ajax.
'''
output = {
'status': 1 if MWiki.view_count_plus(slug) else 0,
}
return json.dump(output, self) | python | def ajax_count_plus(self, slug):
'''
post count plus one via ajax.
'''
output = {
'status': 1 if MWiki.view_count_plus(slug) else 0,
}
return json.dump(output, self) | post count plus one via ajax. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/page_handler.py#L169-L177 |
bukun/TorCMS | torcms/handlers/page_handler.py | PageHandler.list | def list(self):
'''
View the list of the pages.
'''
kwd = {
'pager': '',
'title': '单页列表',
}
self.render('wiki_page/page_list.html',
kwd=kwd,
view=MWiki.query_recent(),
view_all=MWiki.query... | python | def list(self):
'''
View the list of the pages.
'''
kwd = {
'pager': '',
'title': '单页列表',
}
self.render('wiki_page/page_list.html',
kwd=kwd,
view=MWiki.query_recent(),
view_all=MWiki.query... | View the list of the pages. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/page_handler.py#L179-L193 |
bukun/TorCMS | torcms/handlers/page_handler.py | PageHandler.add_page | def add_page(self, slug):
'''
Add new page.
'''
post_data = self.get_post_data()
post_data['user_name'] = self.userinfo.user_name
if MWiki.get_by_uid(slug):
self.set_status(400)
return False
else:
MWiki.create_page(slug, post... | python | def add_page(self, slug):
'''
Add new page.
'''
post_data = self.get_post_data()
post_data['user_name'] = self.userinfo.user_name
if MWiki.get_by_uid(slug):
self.set_status(400)
return False
else:
MWiki.create_page(slug, post... | Add new page. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/page_handler.py#L197-L212 |
bukun/TorCMS | torcms/handlers/log_handler.py | LogHandler.add | def add(self, **kwargs):
'''
in infor.
'''
post_data = {}
for key in self.request.arguments:
post_data[key] = self.get_arguments(key)[0]
MLog.add(post_data)
kwargs.pop('uid', None) # delete `uid` if exists in kwargs
self.redirect('/log/') | python | def add(self, **kwargs):
'''
in infor.
'''
post_data = {}
for key in self.request.arguments:
post_data[key] = self.get_arguments(key)[0]
MLog.add(post_data)
kwargs.pop('uid', None) # delete `uid` if exists in kwargs
self.redirect('/log/') | in infor. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/log_handler.py#L63-L76 |
bukun/TorCMS | torcms/handlers/log_handler.py | LogHandler.list | def list(self, cur_p=''):
'''
View the list of the Log.
'''
if cur_p == '':
current_page_number = 1
else:
current_page_number = int(cur_p)
current_page_number = 1 if current_page_number < 1 else current_page_number
pager_num = int(MLog.t... | python | def list(self, cur_p=''):
'''
View the list of the Log.
'''
if cur_p == '':
current_page_number = 1
else:
current_page_number = int(cur_p)
current_page_number = 1 if current_page_number < 1 else current_page_number
pager_num = int(MLog.t... | View the list of the Log. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/log_handler.py#L78-L110 |
bukun/TorCMS | torcms/handlers/log_handler.py | LogHandler.user_log_list | def user_log_list(self, userid, cur_p=''):
'''
View the list of the Log.
'''
if cur_p == '':
current_page_number = 1
else:
current_page_number = int(cur_p)
current_page_number = 1 if current_page_number < 1 else current_page_number
pager... | python | def user_log_list(self, userid, cur_p=''):
'''
View the list of the Log.
'''
if cur_p == '':
current_page_number = 1
else:
current_page_number = int(cur_p)
current_page_number = 1 if current_page_number < 1 else current_page_number
pager... | View the list of the Log. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/log_handler.py#L112-L149 |
bukun/TorCMS | torcms/handlers/log_handler.py | LogHandler.pageview | def pageview(self, cur_p=''):
'''
View the list of the Log.
'''
if cur_p == '':
current_page_number = 1
else:
current_page_number = int(cur_p)
current_page_number = 1 if current_page_number < 1 else current_page_number
pager_num = int(ML... | python | def pageview(self, cur_p=''):
'''
View the list of the Log.
'''
if cur_p == '':
current_page_number = 1
else:
current_page_number = int(cur_p)
current_page_number = 1 if current_page_number < 1 else current_page_number
pager_num = int(ML... | View the list of the Log. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/log_handler.py#L151-L183 |
bukun/TorCMS | torcms/model/post_hist_model.py | MPostHist.delete | def delete(uid):
'''
Delete by uid
'''
del_count = TabPostHist.delete().where(TabPostHist.uid == uid)
try:
del_count.execute()
return False
except:
return True | python | def delete(uid):
'''
Delete by uid
'''
del_count = TabPostHist.delete().where(TabPostHist.uid == uid)
try:
del_count.execute()
return False
except:
return True | Delete by uid | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post_hist_model.py#L25-L35 |
bukun/TorCMS | torcms/model/post_hist_model.py | MPostHist.update_cnt | def update_cnt(uid, post_data):
'''
Update the content by ID.
'''
entry = TabPostHist.update(
user_name=post_data['user_name'],
cnt_md=tornado.escape.xhtml_escape(post_data['cnt_md']),
time_update=tools.timestamp(),
).where(TabPostHist.uid == u... | python | def update_cnt(uid, post_data):
'''
Update the content by ID.
'''
entry = TabPostHist.update(
user_name=post_data['user_name'],
cnt_md=tornado.escape.xhtml_escape(post_data['cnt_md']),
time_update=tools.timestamp(),
).where(TabPostHist.uid == u... | Update the content by ID. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post_hist_model.py#L38-L47 |
bukun/TorCMS | torcms/model/post_hist_model.py | MPostHist.query_by_postid | def query_by_postid(postid, limit=5):
'''
Query history of certian records.
'''
recs = TabPostHist.select().where(
TabPostHist.post_id == postid
).order_by(
TabPostHist.time_update.desc()
).limit(limit)
return recs | python | def query_by_postid(postid, limit=5):
'''
Query history of certian records.
'''
recs = TabPostHist.select().where(
TabPostHist.post_id == postid
).order_by(
TabPostHist.time_update.desc()
).limit(limit)
return recs | Query history of certian records. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post_hist_model.py#L50-L59 |
bukun/TorCMS | torcms/model/post_hist_model.py | MPostHist.get_last | def get_last(postid, limit=10):
'''
Get the last one of the records.
'''
recs = TabPostHist.select().where(
TabPostHist.post_id == postid
).order_by(TabPostHist.time_update.desc()).limit(limit)
if recs.count():
return recs.get()
return None | python | def get_last(postid, limit=10):
'''
Get the last one of the records.
'''
recs = TabPostHist.select().where(
TabPostHist.post_id == postid
).order_by(TabPostHist.time_update.desc()).limit(limit)
if recs.count():
return recs.get()
return None | Get the last one of the records. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post_hist_model.py#L62-L71 |
bukun/TorCMS | torcms/model/post_hist_model.py | MPostHist.create_post_history | def create_post_history(raw_data):
'''
Create the history of certain post.
'''
uid = tools.get_uuid()
TabPostHist.create(
uid=uid,
title=raw_data.title,
post_id=raw_data.uid,
user_name=raw_data.user_name,
cnt_md=raw_data... | python | def create_post_history(raw_data):
'''
Create the history of certain post.
'''
uid = tools.get_uuid()
TabPostHist.create(
uid=uid,
title=raw_data.title,
post_id=raw_data.uid,
user_name=raw_data.user_name,
cnt_md=raw_data... | Create the history of certain post. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/post_hist_model.py#L74-L88 |
bukun/TorCMS | torcms/handlers/list_handler.py | ListHandler.ajax_list_catalog | def ajax_list_catalog(self, catid):
'''
Get posts of certain catid. In Json.
根据分类ID(catid)获取 该分类下 post 的相关信息,返回Json格式
'''
out_arr = {}
for catinfo in MPost2Catalog.query_postinfo_by_cat(catid):
out_arr[catinfo.uid] = catinfo.title
json.dump(out_arr, ... | python | def ajax_list_catalog(self, catid):
'''
Get posts of certain catid. In Json.
根据分类ID(catid)获取 该分类下 post 的相关信息,返回Json格式
'''
out_arr = {}
for catinfo in MPost2Catalog.query_postinfo_by_cat(catid):
out_arr[catinfo.uid] = catinfo.title
json.dump(out_arr, ... | Get posts of certain catid. In Json.
根据分类ID(catid)获取 该分类下 post 的相关信息,返回Json格式 | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/list_handler.py#L57-L67 |
bukun/TorCMS | torcms/handlers/list_handler.py | ListHandler.ajax_subcat_arr | def ajax_subcat_arr(self, pid):
'''
Get the sub category.
ToDo: The menu should display by order. Error fond in DRR.
根据父类ID(pid)获取子类,返回Json格式
'''
out_arr = {}
for catinfo in MCategory.query_sub_cat(pid):
out_arr[catinfo.uid] = catinfo.name
jso... | python | def ajax_subcat_arr(self, pid):
'''
Get the sub category.
ToDo: The menu should display by order. Error fond in DRR.
根据父类ID(pid)获取子类,返回Json格式
'''
out_arr = {}
for catinfo in MCategory.query_sub_cat(pid):
out_arr[catinfo.uid] = catinfo.name
jso... | Get the sub category.
ToDo: The menu should display by order. Error fond in DRR.
根据父类ID(pid)获取子类,返回Json格式 | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/list_handler.py#L69-L79 |
bukun/TorCMS | torcms/handlers/list_handler.py | ListHandler.ajax_kindcat_arr | def ajax_kindcat_arr(self, kind_sig):
'''
Get the sub category.
根据kind值(kind_sig)获取相应分类,返回Json格式
'''
out_arr = {}
for catinfo in MCategory.query_kind_cat(kind_sig):
out_arr[catinfo.uid] = catinfo.name
json.dump(out_arr, self) | python | def ajax_kindcat_arr(self, kind_sig):
'''
Get the sub category.
根据kind值(kind_sig)获取相应分类,返回Json格式
'''
out_arr = {}
for catinfo in MCategory.query_kind_cat(kind_sig):
out_arr[catinfo.uid] = catinfo.name
json.dump(out_arr, self) | Get the sub category.
根据kind值(kind_sig)获取相应分类,返回Json格式 | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/list_handler.py#L81-L90 |
bukun/TorCMS | torcms/handlers/list_handler.py | ListHandler.list_catalog | def list_catalog(self, cat_slug, **kwargs):
'''
listing the posts via category
根据分类(cat_slug)显示分类列表
'''
post_data = self.get_post_data()
tag = post_data.get('tag', '')
def get_pager_idx():
'''
Get the pager index.
'''
... | python | def list_catalog(self, cat_slug, **kwargs):
'''
listing the posts via category
根据分类(cat_slug)显示分类列表
'''
post_data = self.get_post_data()
tag = post_data.get('tag', '')
def get_pager_idx():
'''
Get the pager index.
'''
... | listing the posts via category
根据分类(cat_slug)显示分类列表 | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/list_handler.py#L92-L155 |
bukun/TorCMS | torcms/core/tool/send_email.py | send_mail | def send_mail(to_list, sub, content, cc=None):
'''
Sending email via Python.
'''
sender = SMTP_CFG['name'] + "<" + SMTP_CFG['user'] + ">"
msg = MIMEText(content, _subtype='html', _charset='utf-8')
msg['Subject'] = sub
msg['From'] = sender
msg['To'] = ";".join(to_list)
if cc:
... | python | def send_mail(to_list, sub, content, cc=None):
'''
Sending email via Python.
'''
sender = SMTP_CFG['name'] + "<" + SMTP_CFG['user'] + ">"
msg = MIMEText(content, _subtype='html', _charset='utf-8')
msg['Subject'] = sub
msg['From'] = sender
msg['To'] = ";".join(to_list)
if cc:
... | Sending email via Python. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/core/tool/send_email.py#L12-L31 |
bukun/TorCMS | torcms/handlers/search_handler.py | gen_pager_bootstrap_url | def gen_pager_bootstrap_url(cat_slug, page_num, current):
'''
pager for searching results.
'''
pager = ''
if page_num == 1 or page_num == 0:
pager = ''
elif page_num > 1:
pager_mid, pager_pre, pager_next, pager_last, pager_home = '', '', '', '', ''
pager = '<ul class="pa... | python | def gen_pager_bootstrap_url(cat_slug, page_num, current):
'''
pager for searching results.
'''
pager = ''
if page_num == 1 or page_num == 0:
pager = ''
elif page_num > 1:
pager_mid, pager_pre, pager_next, pager_last, pager_home = '', '', '', '', ''
pager = '<ul class="pa... | pager for searching results. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/search_handler.py#L14-L68 |
bukun/TorCMS | torcms/handlers/search_handler.py | SearchHandler.search | def search(self, keyword, p_index=''):
'''
perform searching.
'''
if p_index == '' or p_index == '-1':
current_page_number = 1
else:
current_page_number = int(p_index)
res_all = self.ysearch.get_all_num(keyword)
results = self.ysearch.searc... | python | def search(self, keyword, p_index=''):
'''
perform searching.
'''
if p_index == '' or p_index == '-1':
current_page_number = 1
else:
current_page_number = int(p_index)
res_all = self.ysearch.get_all_num(keyword)
results = self.ysearch.searc... | perform searching. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/search_handler.py#L122-L152 |
bukun/TorCMS | torcms/handlers/search_handler.py | SearchHandler.search_cat | def search_cat(self, catid, keyword, p_index=1):
'''
Searching according the kind.
'''
catid = 'sid' + catid
logger.info('-' * 20)
logger.info('search cat')
logger.info('catid: {0}'.format(catid))
logger.info('keyword: {0}'.format(keyword))
# cati... | python | def search_cat(self, catid, keyword, p_index=1):
'''
Searching according the kind.
'''
catid = 'sid' + catid
logger.info('-' * 20)
logger.info('search cat')
logger.info('catid: {0}'.format(catid))
logger.info('keyword: {0}'.format(keyword))
# cati... | Searching according the kind. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/search_handler.py#L154-L195 |
bukun/TorCMS | torcms/handlers/post_ajax_handler.py | PostAjaxHandler.viewinfo | def viewinfo(self, postinfo):
'''
View the info
'''
out_json = {
'uid': postinfo.uid,
'time_update': postinfo.time_update,
'title': postinfo.title,
'cnt_html': tornado.escape.xhtml_unescape(postinfo.cnt_html),
}
self.write(... | python | def viewinfo(self, postinfo):
'''
View the info
'''
out_json = {
'uid': postinfo.uid,
'time_update': postinfo.time_update,
'title': postinfo.title,
'cnt_html': tornado.escape.xhtml_unescape(postinfo.cnt_html),
}
self.write(... | View the info | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_ajax_handler.py#L42-L53 |
bukun/TorCMS | torcms/handlers/post_ajax_handler.py | PostAjaxHandler.count_plus | def count_plus(self, uid):
'''
Ajax request, that the view count will plus 1.
'''
self.set_header("Content-Type", "application/json")
output = {
# ToDo: Test the following codes.
# MPost.__update_view_count_by_uid(uid) else 0,
'status': 1 if MP... | python | def count_plus(self, uid):
'''
Ajax request, that the view count will plus 1.
'''
self.set_header("Content-Type", "application/json")
output = {
# ToDo: Test the following codes.
# MPost.__update_view_count_by_uid(uid) else 0,
'status': 1 if MP... | Ajax request, that the view count will plus 1. | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_ajax_handler.py#L55-L66 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.