code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
report_id = 0
out_report_buffer = (ctypes.c_uint8 * self.internal_max_out_report_len)()
out_report_buffer[:] = packet[:]
result = iokit.IOHIDDeviceSetReport(self.device_handle,
K_IO_HID_REPORT_TYPE_OUTPUT,
report_id,
... | def Write(self, packet) | See base class. | 5.643875 | 5.489023 | 1.028211 |
result = None
while result is None:
try:
result = self.read_queue.get(timeout=60)
except queue.Empty:
continue
return result | def Read(self) | See base class. | 4.690294 | 3.855665 | 1.216468 |
Hierarchy.init_hierarchy(self)
self.hierarchy.hook_change_view(self, args, kwargs)
return super(HierarchicalModelAdmin, self).change_view(*args, **kwargs) | def change_view(self, *args, **kwargs) | Renders detailed model edit page. | 6.824929 | 6.125051 | 1.114265 |
if getattr(obj, Hierarchy.UPPER_LEVEL_MODEL_ATTR, False):
return ''
return super(HierarchicalModelAdmin, self).action_checkbox(obj) | def action_checkbox(self, obj) | Renders checkboxes.
Disable checkbox for parent item navigation link. | 7.940918 | 6.546265 | 1.213046 |
result_repr = '' # For items without children.
ch_count = getattr(obj, Hierarchy.CHILD_COUNT_MODEL_ATTR, 0)
is_parent_link = getattr(obj, Hierarchy.UPPER_LEVEL_MODEL_ATTR, False)
if is_parent_link or ch_count: # For items with children and parent links.
icon = '... | def hierarchy_nav(self, obj) | Renders hierarchy navigation elements (folders). | 3.755187 | 3.655689 | 1.027217 |
self._hierarchy.hook_get_queryset(self, request)
return super(HierarchicalChangeList, self).get_queryset(request) | def get_queryset(self, request) | Constructs a query set.
:param request:
:return: | 9.144376 | 11.478032 | 0.796685 |
super(HierarchicalChangeList, self).get_results(request)
self._hierarchy.hook_get_results(self) | def get_results(self, request) | Gets query set results.
:param request:
:return: | 15.383844 | 20.390158 | 0.754474 |
if not settings.DEBUG:
return
try:
self.lookup_opts.get_field(field_name)
except FieldDoesNotExist as e:
raise AdmirarchyConfigurationError(e) | def check_field_exists(self, field_name) | Implements field exists check for debugging purposes.
:param field_name:
:return: | 9.277223 | 9.710654 | 0.955365 |
hierarchy = getattr(model_admin, 'hierarchy')
if hierarchy:
if not isinstance(hierarchy, Hierarchy):
hierarchy = AdjacencyList() # For `True` and etc. TODO heuristics maybe.
else:
hierarchy = NoHierarchy()
model_admin.hierarchy = hiera... | def init_hierarchy(cls, model_admin) | Initializes model admin with hierarchy data. | 10.781883 | 10.552934 | 1.021695 |
val = request.GET.get(cls.PARENT_ID_QS_PARAM, False)
pid = val or None
try:
del changelist.params[cls.PARENT_ID_QS_PARAM]
except KeyError:
pass
return pid | def get_pid_from_request(cls, changelist, request) | Gets parent ID from query string.
:param changelist:
:param request:
:return: | 4.92452 | 5.024359 | 0.980129 |
changelist.check_field_exists(self.pid_field)
self.pid = self.get_pid_from_request(changelist, request)
changelist.params[self.pid_field] = self.pid | def hook_get_queryset(self, changelist, request) | Triggered by `ChangeList.get_queryset()`. | 5.407947 | 5.563585 | 0.972026 |
result_list = list(changelist.result_list)
if self.pid:
# Render to upper level link.
parent = changelist.model.objects.get(pk=self.pid)
parent = changelist.model(pk=getattr(parent, self.pid_field_real, None))
setattr(parent, self.UPPER_LEVEL_MOD... | def hook_get_results(self, changelist) | Triggered by `ChangeList.get_results()`. | 3.366816 | 3.297638 | 1.020978 |
changelist.check_field_exists(self.left_field)
changelist.check_field_exists(self.right_field)
self.pid = self.get_pid_from_request(changelist, request)
# Get parent item first.
qs = changelist.root_queryset
if self.pid:
self.parent = qs.get(pk=self... | def hook_get_queryset(self, changelist, request) | Triggered by `ChangeList.get_queryset()`. | 4.307618 | 4.28705 | 1.004798 |
# Poor NestedSet guys they've punished themselves once chosen that approach,
# and now we punish them again with all those DB hits.
result_list = list(changelist.result_list)
# Get children stats.
filter_kwargs = {'%s' % self.left_field: models.F('%s' % self.right_fie... | def hook_get_results(self, changelist) | Triggered by `ChangeList.get_results()`. | 5.051749 | 4.953619 | 1.01981 |
with io.open(os.path.join(PATH_BASE, fpath)) as f:
return f.read() | def read_file(fpath) | Reads a file within package directories. | 4.12299 | 4.175684 | 0.987381 |
contents = read_file(os.path.join('admirarchy', '__init__.py'))
version = re.search('VERSION = \(([^)]+)\)', contents)
version = version.group(1).replace(', ', '.').strip()
return version | def get_version() | Returns version number, without module import (which can lead to ImportError
if some dependencies are unavailable before install. | 4.684727 | 4.651999 | 1.007035 |
data = json.loads(update)
NetworkTables.getEntry(data["k"]).setValue(data["v"]) | def process_update(self, update) | Process an incoming update from a remote NetworkTables | 15.076891 | 8.624455 | 1.748156 |
if isinstance(data, dict):
data = json.dumps(data)
self.update_callback(data) | def _send_update(self, data) | Send a NetworkTables update via the stored send_update callback | 4.34211 | 4.030689 | 1.077263 |
self._send_update({"k": key, "v": value, "n": isNew}) | def _nt_on_change(self, key, value, isNew) | NetworkTables global listener callback | 7.349909 | 5.767208 | 1.274431 |
NetworkTables.removeGlobalListener(self._nt_on_change)
NetworkTables.removeConnectionListener(self._nt_connected) | def close(self) | Clean up NetworkTables listeners | 12.671768 | 6.737095 | 1.880895 |
try:
from shapely.geometry import Point
except ImportError: # pragma: no cover
raise ImportError("Finding climate zone of lat/long points requires shapely.")
(
iecc_climate_zones,
iecc_moisture_regimes,
ba_climate_zones,
ca_climate_zones,
) = cached... | def get_lat_long_climate_zones(latitude, longitude) | Get climate zones that contain lat/long coordinates.
Parameters
----------
latitude : float
Latitude of point.
longitude : float
Longitude of point.
Returns
-------
climate_zones: dict of str
Region ids for each climate zone type. | 1.804645 | 1.81211 | 0.995881 |
conn = metadata_db_connection_proxy.get_connection()
cur = conn.cursor()
cur.execute(
,
(zcta,),
)
row = cur.fetchone()
if row is None:
raise UnrecognizedZCTAError(zcta)
return {col[0]: row[i] for i, col in enumerate(cur.description)} | def get_zcta_metadata(zcta) | Get metadata about a ZIP Code Tabulation Area (ZCTA).
Parameters
----------
zcta : str
ID of ZIP Code Tabulation Area
Returns
-------
metadata : dict
Dict of data about the ZCTA, including lat/long coordinates. | 3.636614 | 4.380488 | 0.830185 |
valid_zcta_or_raise(zcta)
conn = metadata_db_connection_proxy.get_connection()
cur = conn.cursor()
cur.execute(
,
(zcta,),
)
# match existence checked in validate_zcta_or_raise(zcta)
latitude, longitude = cur.fetchone()
return float(latitude), float(longitude) | def zcta_to_lat_long(zcta) | Get location of ZCTA centroid
Retrieves latitude and longitude of centroid of ZCTA
to use for matching with weather station.
Parameters
----------
zcta : str
ID of the target ZCTA.
Returns
-------
latitude : float
Latitude of centroid of ZCTA.
longitude : float
... | 6.526155 | 7.442756 | 0.876846 |
conn = metadata_db_connection_proxy.get_connection()
cur = conn.cursor()
if state is None:
cur.execute(
)
else:
cur.execute(
,
(state,),
)
return [row[0] for row in cur.fetchall()] | def get_zcta_ids(state=None) | Get ids of all supported ZCTAs, optionally by state.
Parameters
----------
state : str, optional
Select zipcodes only from this state or territory, given as 2-letter
abbreviation (e.g., ``'CA'``, ``'PR'``).
Returns
-------
results : list of str
List of all supported sel... | 4.726732 | 5.656682 | 0.835602 |
conn = metadata_db_connection_proxy.get_connection()
cur = conn.cursor()
cur.execute(
,
(zcta,),
)
(exists,) = cur.fetchone()
if exists:
return True
else:
raise UnrecognizedZCTAError(zcta) | def valid_zcta_or_raise(zcta) | Check if ZCTA is valid and raise eeweather.UnrecognizedZCTAError if not. | 5.153374 | 4.38732 | 1.174606 |
conn = metadata_db_connection_proxy.get_connection()
cur = conn.cursor()
cur.execute(
,
(usaf_id,),
)
(exists,) = cur.fetchone()
if exists:
return True
else:
raise UnrecognizedUSAFIDError(usaf_id) | def valid_usaf_id_or_raise(usaf_id) | Check if USAF ID is valid and raise eeweather.UnrecognizedUSAFIDError if not. | 4.470725 | 3.942305 | 1.134038 |
if len(rankings) == 0:
raise ValueError("Requires at least one ranking.")
combined_ranking = rankings[0]
for ranking in rankings[1:]:
filtered_ranking = ranking[~ranking.index.isin(combined_ranking.index)]
combined_ranking = pd.concat([combined_ranking, filtered_ranking])
... | def combine_ranked_stations(rankings) | Combine :any:`pandas.DataFrame` s of candidate weather stations to form
a hybrid ranking dataframe.
Parameters
----------
rankings : list of :any:`pandas.DataFrame`
Dataframes of ranked weather station candidates and metadata.
All ranking dataframes should have the same columns and must... | 2.429315 | 2.389035 | 1.016861 |
def _test_station(station):
if coverage_range is None:
return True, []
else:
start_date, end_date = coverage_range
try:
tempC, warnings = eeweather.mockable.load_isd_hourly_temp_data(
station, start_date, end_date
... | def select_station(
candidates,
coverage_range=None,
min_fraction_coverage=0.9,
distance_warnings=(50000, 200000),
rank=1,
) | Select a station from a list of candidates that meets given data
quality criteria.
Parameters
----------
candidates : :any:`pandas.DataFrame`
A dataframe of the form given by :any:`eeweather.rank_stations` or
:any:`eeweather.combine_ranked_stations`, specifically having at least
... | 3.695121 | 3.33463 | 1.108105 |
from shapely.geometry import Point
# load ISD history which contains metadata
isd_history = pd.read_csv(
os.path.join(download_path, "isd-history.csv"),
dtype=str,
parse_dates=["BEGIN", "END"],
)
hasGEO = (
isd_history.LAT.notnull() & isd_history.LON.notnull() ... | def _load_isd_station_metadata(download_path) | Collect metadata for US isd stations. | 3.259032 | 3.204434 | 1.017038 |
isd_inventory = pd.read_csv(
os.path.join(download_path, "isd-inventory.csv"), dtype=str
)
# filter to stations with metadata
station_keep = [usaf in isd_station_metadata for usaf in isd_inventory.USAF]
isd_inventory = isd_inventory[station_keep]
# filter by year
year_keep = i... | def _load_isd_file_metadata(download_path, isd_station_metadata) | Collect data counts for isd files. | 2.249501 | 2.198641 | 1.023133 |
return {
"elevation": self.elevation,
"latitude": self.latitude,
"longitude": self.longitude,
"icao_code": self.icao_code,
"name": self.name,
"quality": self.quality,
"wban_ids": self.wban_ids,
"recent_wban_... | def json(self) | Return a JSON-serializeable object containing station metadata. | 2.682091 | 2.482807 | 1.080265 |
return get_isd_filenames(self.usaf_id, year, with_host=with_host) | def get_isd_filenames(self, year=None, with_host=False) | Get filenames of raw ISD station data. | 5.733649 | 5.247089 | 1.092729 |
return get_gsod_filenames(self.usaf_id, year, with_host=with_host) | def get_gsod_filenames(self, year=None, with_host=False) | Get filenames of raw GSOD station data. | 5.837594 | 5.162084 | 1.13086 |
return load_isd_hourly_temp_data(
self.usaf_id,
start,
end,
read_from_cache=read_from_cache,
write_to_cache=write_to_cache,
error_on_missing_years=error_on_missing_years,
) | def load_isd_hourly_temp_data(
self,
start,
end,
read_from_cache=True,
write_to_cache=True,
error_on_missing_years=True,
) | Load resampled hourly ISD temperature data from start date to end date (inclusive).
This is the primary convenience method for loading resampled hourly ISD temperature data.
Parameters
----------
start : datetime.datetime
The earliest date from which to load data.
e... | 1.811496 | 2.203705 | 0.822023 |
return load_isd_daily_temp_data(
self.usaf_id,
start,
end,
read_from_cache=read_from_cache,
write_to_cache=write_to_cache,
) | def load_isd_daily_temp_data(
self, start, end, read_from_cache=True, write_to_cache=True
) | Load resampled daily ISD temperature data from start date to end date (inclusive).
This is the primary convenience method for loading resampled daily ISD temperature data.
Parameters
----------
start : datetime.datetime
The earliest date from which to load data.
end... | 2.248005 | 2.635903 | 0.852841 |
return load_gsod_daily_temp_data(
self.usaf_id,
start,
end,
read_from_cache=read_from_cache,
write_to_cache=write_to_cache,
) | def load_gsod_daily_temp_data(
self, start, end, read_from_cache=True, write_to_cache=True
) | Load resampled daily GSOD temperature data from start date to end date (inclusive).
This is the primary convenience method for loading resampled daily GSOD temperature data.
Parameters
----------
start : datetime.datetime
The earliest date from which to load data.
e... | 2.291216 | 2.671808 | 0.857553 |
return load_tmy3_hourly_temp_data(
self.usaf_id,
start,
end,
read_from_cache=read_from_cache,
write_to_cache=write_to_cache,
) | def load_tmy3_hourly_temp_data(
self, start, end, read_from_cache=True, write_to_cache=True
) | Load hourly TMY3 temperature data from start date to end date (inclusive).
This is the primary convenience method for loading hourly TMY3 temperature data.
Parameters
----------
start : datetime.datetime
The earliest date from which to load data.
end : datetime.date... | 2.204472 | 2.577309 | 0.855339 |
return load_cz2010_hourly_temp_data(
self.usaf_id,
start,
end,
read_from_cache=read_from_cache,
write_to_cache=write_to_cache,
) | def load_cz2010_hourly_temp_data(
self, start, end, read_from_cache=True, write_to_cache=True
) | Load hourly CZ2010 temperature data from start date to end date (inclusive).
This is the primary convenience method for loading hourly CZ2010 temperature data.
Parameters
----------
start : datetime.datetime
The earliest date from which to load data.
end : datetime.... | 2.200026 | 2.6295 | 0.836671 |
import matplotlib.pyplot as plt
except ImportError:
raise ImportError("Plotting requires matplotlib.")
try:
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import cartopy.io.img_tiles as cimgt
except ImportError:
raise ImportError("Plotting requ... | def plot_station_mapping(
target_latitude,
target_longitude,
isd_station,
distance_meters,
target_label="target",
): # pragma: no cover
try | Plots this mapping on a map. | 2.194499 | 2.201848 | 0.996663 |
''' Execute the ViewPDF worker '''
# Just a small check to make sure we haven't been called on the wrong file type
if (input_data['meta']['type_tag'] != 'pdf'):
return {'error': self.__class__.__name__+': called on '+input_data['meta']['type_tag']}
view = {}
view['s... | def execute(self, input_data) | Execute the ViewPDF worker | 8.022357 | 6.790846 | 1.181349 |
''' Execute '''
view = {}
# Grab logs from Bro
view['bro_logs'] = {key: input_data['pcap_bro'][key] for key in input_data['pcap_bro'].keys() if '_log' in key}
# Grab logs from Bro
view['extracted_files'] = input_data['pcap_bro']['extracted_files']
return view | def execute(self, input_data) | Execute | 6.804274 | 6.9672 | 0.976615 |
''' Cache aware add_node '''
if node_id not in self.node_cache:
self.workbench.add_node(node_id, name, labels)
self.node_cache.add(node_id) | def add_node(self, node_id, name, labels) | Cache aware add_node | 4.494831 | 3.54321 | 1.268576 |
''' Cache aware add_rel '''
if (source_id, target_id) not in self.rel_cache:
self.workbench.add_rel(source_id, target_id, rel)
self.rel_cache.add((source_id, target_id)) | def add_rel(self, source_id, target_id, rel) | Cache aware add_rel | 3.663903 | 3.011048 | 1.21682 |
''' Build up a graph (nodes and edges from a Bro conn.log) '''
conn_log = list(stream)
print 'Entering conn_log_graph...(%d rows)' % len(conn_log)
for row in stream:
# Add the connection id with service as one of the labels
self.add_node(row['uid'], row['uid'][:6... | def conn_log_graph(self, stream) | Build up a graph (nodes and edges from a Bro conn.log) | 4.35788 | 3.503526 | 1.243856 |
''' Build up a graph (nodes and edges from a Bro dns.log) '''
dns_log = list(stream)
print 'Entering dns_log_graph...(%d rows)' % len(dns_log)
for row in dns_log:
# Skip '-' hosts
if (row['id.orig_h'] == '-'):
continue
# A... | def dns_log_graph(self, stream) | Build up a graph (nodes and edges from a Bro dns.log) | 4.447901 | 3.687624 | 1.20617 |
''' Build up a graph (nodes and edges from a Bro weird.log) '''
weird_log = list(stream)
print 'Entering weird_log_graph...(%d rows)' % len(weird_log)
# Here we're just going to capture that something weird
# happened between two hosts
weird_pairs = set()
for row... | def weird_log_graph(self, stream) | Build up a graph (nodes and edges from a Bro weird.log) | 4.695921 | 3.93346 | 1.19384 |
''' Build up a graph (nodes and edges from a Bro files.log) '''
file_log = list(stream)
print 'Entering file_log_graph...(%d rows)' % len(file_log)
for row in file_log:
# If the mime-type is interesting add the uri and the host->uri->host relationships
if row['mi... | def files_log_graph(self, stream) | Build up a graph (nodes and edges from a Bro files.log) | 5.807598 | 5.063147 | 1.147033 |
''' This client calls a bunch of help commands from workbench '''
# Grab server args
args = client_helper.grab_server_args()
# Start up workbench connection
workbench = zerorpc.Client(timeout=300, heartbeat=60)
workbench.connect('tcp://'+args['server']+':'+args['port'])
# Call help me... | def run() | This client calls a bunch of help commands from workbench | 5.743828 | 4.492917 | 1.278418 |
''' Execute the URL worker '''
string_output = input_data['strings']['string_list']
flatten = ' '.join(string_output)
urls = self.url_match.findall(flatten)
return {'url_list': urls} | def execute(self, input_data) | Execute the URL worker | 10.138373 | 8.333384 | 1.216597 |
@functools.wraps(func)
def wrapper(*args, **kwargs):
class ReprToStr(str):
def __repr__(self):
return str(self)
return ReprToStr(func(*args, **kwargs))
return wrapper | def r_to_s(func) | Decorator method for Workbench methods returning a str | 3.556727 | 3.23292 | 1.100159 |
file_list = []
for dirname, dirnames, filenames in os.walk(path):
for filename in filenames:
file_list.append(os.path.join(dirname, filename))
return file_list | def all_files_in_directory(path) | Recursively ist all files under a directory | 1.755031 | 1.709278 | 1.026767 |
# Grab server args
args = client_helper.grab_server_args()
# Start up workbench connection
workbench = zerorpc.Client(timeout=300, heartbeat=60)
workbench.connect('tcp://'+args['server']+':'+args['port'])
# Grab all the filenames from the data directory
data_dir = os.path.joi... | def run() | This client pushes a big directory of different files into Workbench. | 3.963502 | 3.827732 | 1.03547 |
# Go through the existing python files in the plugin directory
self.plugin_path = os.path.realpath(self.plugin_dir)
sys.path.append(self.plugin_dir)
print '<<< Plugin Manager >>>'
for f in [os.path.join(self.plugin_dir, child) for child in os.listdir(self.plugin_dir)]:
... | def load_all_plugins(self) | Load all the plugins in the plugin directory | 3.802788 | 3.712479 | 1.024326 |
if f.endswith('.py'):
plugin_name = os.path.splitext(os.path.basename(f))[0]
print '- %s %sREMOVED' % (plugin_name, color.Red)
print '\t%sNote: still in memory, restart Workbench to remove...%s' % \
(color.Yellow, color.Normal) | def remove_plugin(self, f) | Remvoing a deleted plugin.
Args:
f: the filepath for the plugin. | 6.251019 | 6.793651 | 0.920127 |
if f.endswith('.py'):
# Just the basename without extension
plugin_name = os.path.splitext(os.path.basename(f))[0]
# It's possible the plugin has been modified and needs to be reloaded
if plugin_name in sys.modules:
try:
... | def add_plugin(self, f) | Adding and verifying plugin.
Args:
f: the filepath for the plugin. | 3.847662 | 3.846271 | 1.000362 |
# Check for the test method first
test_method = self.plugin_test_validation(handler)
if not test_method:
return None
# Here we iterate through the classes found in the module and pick
# the first one that satisfies the validation
for name, plugin_cl... | def validate(self, handler) | Validate the plugin, each plugin must have the following:
1) The worker class must have an execute method: execute(self, input_data).
2) The worker class must have a dependencies list (even if it's empty).
3) The file must have a top level test() method.
Args:
ha... | 6.108175 | 4.880185 | 1.251628 |
try:
getattr(plugin_class, 'dependencies')
getattr(plugin_class, 'execute')
except AttributeError:
return False
return True | def plugin_class_validation(self, plugin_class) | Plugin validation
Every workbench plugin must have a dependencies list (even if it's empty).
Every workbench plugin must have an execute method.
Args:
plugin_class: The loaded plugun class.
Returns:
True if dependencies and execute are present, else F... | 4.979489 | 2.806573 | 1.774224 |
# Temp sanity check for old clients
if len(filename) > 1000:
print 'switched bytes/filename... %s %s' % (sample_bytes[:100], filename[:100])
exit(1)
sample_info = {}
# Compute the MD5 hash
sample_info['md5'] = hashlib.md5(sample_bytes).hexdiges... | def store_sample(self, sample_bytes, filename, type_tag) | Store a sample into the datastore.
Args:
filename: Name of the file.
sample_bytes: Actual bytes of sample.
type_tag: Type of sample ('exe','pcap','pdf','json','swf', or ...)
Returns:
md5 digest of the sample. | 5.330761 | 5.290895 | 1.007535 |
try:
coll_stats = self.database.command('collStats', 'fs.chunks')
sample_storage_size = coll_stats['size']/1024.0/1024.0
return sample_storage_size
except pymongo.errors.OperationFailure:
return 0 | def sample_storage_size(self) | Get the storage size of the samples storage collection. | 3.618238 | 3.314319 | 1.091699 |
# Do we need to start deleting stuff?
while self.sample_storage_size() > self.samples_cap:
# This should return the 'oldest' record in samples
record = self.database[self.sample_collection].find().sort('import_time',pymongo.ASCENDING).limit(1)[0]
self.remov... | def expire_data(self) | Expire data within the samples collection. | 8.875263 | 7.611228 | 1.166075 |
# Grab the sample
record = self.database[self.sample_collection].find_one({'md5': md5})
if not record:
return
# Delete it
print 'Deleting sample: %s (%.2f MB)...' % (record['md5'], record['length']/1024.0/1024.0)
self.database[self.sample_collection... | def remove_sample(self, md5) | Delete a specific sample | 4.272246 | 4.414144 | 0.967854 |
if isinstance(data, dict):
for k in data.keys():
if (k.startswith('__')):
del data[k]
elif isinstance(data[k], bson.objectid.ObjectId):
del data[k]
elif isinstance(data[k], datetime.datetime):
... | def clean_for_serialization(self, data) | Clean data in preparation for serialization.
Deletes items having key either a BSON, datetime, dict or a list instance, or
starting with __.
Args:
data: Sample data to be serialized.
Returns:
Cleaned data dictionary. | 1.828081 | 1.775879 | 1.029395 |
data = self.data_to_unicode(data)
if isinstance(data, dict):
for k in dict(data).keys():
if k == '_id':
del data[k]
continue
if '.' in k:
new_k = k.replace('.', '_')
data[... | def clean_for_storage(self, data) | Clean data in preparation for storage.
Deletes items with key having a '.' or is '_id'. Also deletes those items
whose value is a dictionary or a list.
Args:
data: Sample data dictionary to be cleaned.
Returns:
Cleaned data dictionary. | 1.951422 | 1.97641 | 0.987356 |
print 'Notice: Performing slow md5 search...'
starts_with = '%s.*' % partial_md5
sample_info = self.database[collection].find_one({'md5': {'$regex' : starts_with}},{'md5':1})
return sample_info['md5'] if sample_info else None | def get_full_md5(self, partial_md5, collection) | Support partial/short md5s, return the full md5 with this method | 5.970208 | 5.558329 | 1.074101 |
# Support 'short' md5s but don't waste performance if the full md5 is provided
if len(md5) < 32:
md5 = self.get_full_md5(md5, self.sample_collection)
# Grab the sample
sample_info = self.database[self.sample_collection].find_one({'md5': md5})
if not sample_... | def get_sample(self, md5) | Get the sample from the data store.
This method first fetches the data from datastore, then cleans it for serialization
and then updates it with 'raw_bytes' item.
Args:
md5: The md5 digest of the sample to be fetched from datastore.
Returns:
The sample ... | 4.335234 | 4.239025 | 1.022696 |
# Convert size to MB
size = size * 1024 * 1024
# Grab all the samples of type=type_tag, sort by import_time (newest to oldest)
cursor = self.database[self.sample_collection].find({'type_tag': type_tag},
{'md5': 1,'length': 1}).sort('import_time',pymongo.DESCENDING)... | def get_sample_window(self, type_tag, size=10) | Get a window of samples not to exceed size (in MB).
Args:
type_tag: Type of sample ('exe','pcap','pdf','json','swf', or ...).
size: Size of samples in MBs.
Returns:
a list of md5s. | 3.703562 | 3.458199 | 1.070951 |
# The easiest thing is to simply get the sample and if that
# succeeds than return True, else return False
sample = self.get_sample(md5)
return True if sample else False | def has_sample(self, md5) | Checks if data store has this sample.
Args:
md5: The md5 digest of the required sample.
Returns:
True if sample with this md5 is present, else False. | 8.263669 | 7.746045 | 1.066824 |
cursor = self.database[self.sample_collection].find(predicate, {'_id':0, 'md5':1})
return [item['md5'] for item in cursor] | def _list_samples(self, predicate=None) | List all samples that meet the predicate or all if predicate is not specified.
Args:
predicate: Match samples against this predicate (or all if not specified)
Returns:
List of the md5s for the matching samples | 4.826869 | 4.702625 | 1.02642 |
if 'tags' not in self.database.collection_names():
print 'Warning: Searching on non-existance tags collection'
return None
if not tags:
cursor = self.database['tags'].find({}, {'_id':0, 'md5':1})
else:
cursor = self.database['tags'].find({... | def tag_match(self, tags=None) | List all samples that match the tags or all if tags are not specified.
Args:
tags: Match samples against these tags (or all if not specified)
Returns:
List of the md5s for the matching samples | 3.0567 | 3.110232 | 0.982788 |
if 'tags' not in self.database.collection_names():
print 'Warning: Searching on non-existance tags collection'
return None
cursor = self.database['tags'].find({}, {'_id':0, 'md5':1, 'tags':1})
return [item for item in cursor] | def tags_all(self) | List of the tags and md5s for all samples
Args:
None
Returns:
List of the tags and md5s for all samples | 5.213841 | 5.009595 | 1.040771 |
# Make sure the md5 and time stamp is on the data before storing
results['md5'] = md5
results['__time_stamp'] = datetime.datetime.utcnow()
# If the data doesn't have a 'mod_time' field add one now
if 'mod_time' not in results:
results['mod_time'] = results[... | def store_work_results(self, results, collection, md5) | Store the output results of the worker.
Args:
results: a dictionary.
collection: the database collection to store the results in.
md5: the md5 of sample data to be updated. | 5.642869 | 5.588582 | 1.009714 |
if type_tag:
cursor = self.database[self.sample_collection].find({'type_tag': type_tag}, {'md5': 1, '_id': 0})
else:
cursor = self.database[self.sample_collection].find({}, {'md5': 1, '_id': 0})
return [match.values()[0] for match in cursor] | def all_sample_md5s(self, type_tag=None) | Return a list of all md5 matching the type_tag ('exe','pdf', etc).
Args:
type_tag: the type of sample.
Returns:
a list of matching samples. | 2.450661 | 2.60094 | 0.942222 |
print 'Dropping all of the worker output collections... Whee!'
# Get all the collections in the workbench database
all_c = self.database.collection_names()
# Remove collections that we don't want to cap
try:
all_c.remove('system.indexes')
... | def clear_worker_output(self) | Drops all of the worker output collections | 5.792021 | 5.091163 | 1.137662 |
# Only run every 30 seconds
if (time.time() - self.last_ops_run) < 30:
return
try:
# Reset last ops run
self.last_ops_run = time.time()
print 'Running Periodic Ops'
# Get all the collections in the workbench database
... | def periodic_ops(self) | Run periodic operations on the the data store.
Operations like making sure collections are capped and indexes are set up. | 5.415003 | 5.199052 | 1.041537 |
# Fixme: This is total horseshit
if isinstance(s, unicode):
return s
if isinstance(s, str):
return unicode(s, errors='ignore')
# Just return the original object
return s | def to_unicode(self, s) | Convert an elementary datatype to unicode.
Args:
s: the datatype to be unicoded.
Returns:
Unicoded data. | 6.965971 | 6.959923 | 1.000869 |
if isinstance(data, dict):
return {self.to_unicode(k): self.to_unicode(v) for k, v in data.iteritems()}
if isinstance(data, list):
return [self.to_unicode(l) for l in data]
else:
return self.to_unicode(data) | def data_to_unicode(self, data) | Recursively convert a list or dictionary to unicode.
Args:
data: The data to be unicoded.
Returns:
Unicoded data. | 1.809545 | 1.944681 | 0.93051 |
# Spin up SWF class
swf = SWF()
# Get the raw_bytes
raw_bytes = input_data['sample']['raw_bytes']
# Parse it
swf.parse(StringIO(raw_bytes))
# Header info
head = swf.header
output = {'version':head.version,'file_length':h... | def execute(self, input_data) | # Map all tag names to indexes
tag_map = {tag.name:index for tag,index in enumerate(swf.tags)}
# FileAttribute Info
file_attr_tag = swf.tags[tag_map] | 4.573547 | 3.160434 | 1.447127 |
workbench_conf = ConfigParser.ConfigParser()
config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'config.ini')
workbench_conf.read(config_path)
server = workbench_conf.get('workbench', 'server_uri')
port = workbench_conf.get('workbench', 'server_port')
# Collect ar... | def grab_server_args() | Grab server info from configuration file | 2.207516 | 2.159277 | 1.02234 |
is_inline_image = False
if isinstance(attachment, MIMEBase):
name = attachment.get_filename()
content = attachment.get_payload(decode=True)
mimetype = attachment.get_content_type()
if attachment.get_content_maintype() == 'image' and attachment['C... | def _make_attachment(self, attachment, str_encoding=None) | Returns EmailMessage.attachments item formatted for sending with Mailjet
Returns mailjet_dict, is_inline_image | 2.799328 | 2.602508 | 1.075627 |
# Index the data (which needs to be a dict/object) if it's not
# we're going to toss an exception
if not isinstance(data, dict):
raise RuntimeError('Index failed, data needs to be a dict!')
try:
self.els_search.index(index=index_name, doc_type=doc_type,... | def index_data(self, data, index_name, doc_type) | Take an arbitrary dictionary of data and index it with ELS.
Args:
data: data to be Indexed. Should be a dictionary.
index_name: Name of the index.
doc_type: The type of the document.
Raises:
RuntimeError: When the Indexing fails. | 4.139696 | 4.217268 | 0.981606 |
try:
results = self.els_search.search(index=index_name, body=query)
return results
except Exception, error:
error_str = 'Query failed: %s\n' % str(error)
error_str += '\nIs there a dynamic script in the query?, see www.elasticsearch.org'
... | def search(self, index_name, query) | Search the given index_name with the given ELS query.
Args:
index_name: Name of the Index
query: The string to be searched.
Returns:
List of results.
Raises:
RuntimeError: When the search query fails. | 5.711612 | 5.330615 | 1.071473 |
print 'ELS Stub Indexer getting called...'
print '%s %s %s %s' % (self, data, index_name, doc_type) | def index_data(self, data, index_name, doc_type) | Index data in Stub Indexer. | 11.889063 | 9.086274 | 1.308464 |
''' Execute method '''
my_ssdeep = input_data['meta_deep']['ssdeep']
my_md5 = input_data['meta_deep']['md5']
# For every PE sample in the database compute my ssdeep fuzzy match
sample_set = self.workbench.generate_sample_set('exe')
results = self.workbench.set_work_reque... | def execute(self, input_data) | Execute method | 5.260616 | 5.288243 | 0.994776 |
''' Do CLI formatting and coloring based on the type_tag '''
input_data = input_data['help_base']
type_tag = input_data['type_tag']
# Standard help text
if type_tag == 'help':
output = '%s%s%s' % (color.LightBlue, input_data['help'], color.Normal)
# Worker
... | def execute(self, input_data) | Do CLI formatting and coloring based on the type_tag | 3.625933 | 3.189293 | 1.136908 |
# Load the configuration file relative to this script location
config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'config.ini')
workbench_conf = ConfigParser.ConfigParser()
config_ini = workbench_conf.read(config_path)
if not config_ini:
print 'Could not locate con... | def run() | Run the workbench server | 3.667121 | 3.556499 | 1.031104 |
# If the sample comes in with an unknown type_tag try to determine it
if type_tag == 'unknown':
print 'Info: Unknown File -- Trying to Determine Type...'
type_tag = self.guess_type_tag(input_bytes, filename)
# Do we have a compressed sample? If so decompress it... | def store_sample(self, input_bytes, filename, type_tag) | Store a sample into the DataStore.
Args:
input_bytes: the actual bytes of the sample e.g. f.read()
filename: name of the file (used purely as meta data not for lookup)
type_tag: ('exe','pcap','pdf','json','swf', or ...)
Returns:
the... | 4.035972 | 3.736255 | 1.080218 |
# First we try a sample, if we can't find one we try getting a sample_set.
sample = self.data_store.get_sample(md5)
if not sample:
return {'sample_set': {'md5_list': self.get_sample_set(md5)}}
return {'sample': sample} | def get_sample(self, md5) | Get a sample from the DataStore.
Args:
md5: the md5 of the sample
Returns:
A dictionary of meta data about the sample which includes
a ['raw_bytes'] key that contains the raw bytes.
Raises:
Workbench.DataNotFound if the ... | 5.177376 | 5.025409 | 1.03024 |
try:
self.get_sample_set(md5)
return True
except WorkBench.DataNotFound:
return False | def is_sample_set(self, md5) | Does the md5 represent a sample_set?
Args:
md5: the md5 of the sample_set
Returns:
True/False | 5.995274 | 6.592416 | 0.90942 |
md5_list = self.data_store.get_sample_window(type_tag, size)
return self.store_sample_set(md5_list) | def get_sample_window(self, type_tag, size) | Get a sample from the DataStore.
Args:
type_tag: the type of samples ('pcap','exe','pdf')
size: the size of the window in MegaBytes (10 = 10MB)
Returns:
A sample_set handle which represents the newest samples within the size window | 5.666338 | 4.85612 | 1.166845 |
total_bytes = ""
for md5 in md5_list:
total_bytes += self.get_sample(md5)['sample']['raw_bytes']
self.remove_sample(md5)
# Store it
return self.store_sample(total_bytes, filename, type_tag) | def combine_samples(self, md5_list, filename, type_tag) | Combine samples together. This may have various use cases the most significant
involving a bunch of sample 'chunks' got uploaded and now we combine them together
Args:
md5_list: The list of md5s to combine, order matters!
filename: name of the file (used purely a... | 3.853004 | 3.912822 | 0.984712 |
# Get the max_rows if specified
max_rows = kwargs.get('max_rows', None) if kwargs else None
# Grab the sample and it's raw bytes
sample = self.get_sample(md5)['sample']
raw_bytes = sample['raw_bytes']
# Figure out the type of file to be streamed
type_t... | def stream_sample(self, md5, kwargs=None) | Stream the sample by giving back a generator, typically used on 'logs'.
Args:
md5: the md5 of the sample
kwargs: a way of specifying subsets of samples (None for all)
max_rows: the maximum number of rows to return
Returns:
A gen... | 3.31711 | 3.123775 | 1.061891 |
# First we try a sample, if we can't find one we try getting a sample_set.
sample = self.data_store.get_sample(md5)
if not sample:
raise WorkBench.DataNotFound("Could not find %s in the data store", md5)
if not compress:
return sample['raw_bytes']
... | def get_dataframe(self, md5, compress='lz4') | Return a dataframe from the DataStore. This is just a convenience method
that uses get_sample internally.
Args:
md5: the md5 of the dataframe
compress: compression to use: (defaults to 'lz4' but can be set to None)
Returns:
A msgpack'd ... | 6.000704 | 4.748344 | 1.263747 |
mime_to_type = {'application/jar': 'jar',
'application/java-archive': 'jar',
'application/octet-stream': 'data',
'application/pdf': 'pdf',
'application/vnd.ms-cab-compressed': 'cab',
... | def guess_type_tag(self, input_bytes, filename) | Try to guess the type_tag for this sample | 2.954673 | 2.913931 | 1.013982 |
if not tags: return
tag_set = set(self.get_tags(md5)) if self.get_tags(md5) else set()
if isinstance(tags, str):
tags = [tags]
for tag in tags:
tag_set.add(tag)
self.data_store.store_work_results({'tags': list(tag_set)}, 'tags', md5) | def add_tags(self, md5, tags) | Add tags to this sample | 3.192143 | 3.13435 | 1.018438 |
if isinstance(tags, str):
tags = [tags]
tag_set = set(tags)
self.data_store.store_work_results({'tags': list(tag_set)}, 'tags', md5) | def set_tags(self, md5, tags) | Set the tags for this sample | 5.953156 | 5.814674 | 1.023816 |
tag_data = self.data_store.get_work_results('tags', md5)
return tag_data['tags'] if tag_data else None | def get_tags(self, md5) | Get tags for this sample | 6.353239 | 5.961695 | 1.065677 |
generator = self.stream_sample(md5)
for row in generator:
self.indexer.index_data(row, index_name) | def index_sample(self, md5, index_name) | Index a stored sample with the Indexer.
Args:
md5: the md5 of the sample
index_name: the name of the index
Returns:
Nothing | 5.584145 | 6.504391 | 0.858519 |
# Grab the data
if subfield:
data = self.work_request(worker_name, md5)[worker_name][subfield]
else:
data = self.work_request(worker_name, md5)[worker_name]
# Okay now index the data
self.indexer.index_data(data, index_name=index_name, doc_type=... | def index_worker_output(self, worker_name, md5, index_name, subfield) | Index worker output with the Indexer.
Args:
worker_name: 'strings', 'pe_features', whatever
md5: the md5 of the sample
index_name: the name of the index
subfield: index just this subfield (None for all)
Returns:
Noth... | 3.772829 | 3.891419 | 0.969525 |
self.neo_db.add_node(node_id, name, labels) | def add_node(self, node_id, name, labels) | Add a node to the graph with name and labels.
Args:
node_id: the unique node_id e.g. 'www.evil4u.com'
name: the display name of the node e.g. 'evil4u'
labels: a list of labels e.g. ['domain','evil']
Returns:
Nothing | 4.156846 | 5.283195 | 0.786805 |
self.neo_db.add_rel(source_id, target_id, rel) | def add_rel(self, source_id, target_id, rel) | Add a relationship: source, target must already exist (see add_node)
'rel' is the name of the relationship 'contains' or whatever.
Args:
source_id: the unique node_id of the source
target_id: the unique node_id of the target
rel: name of the relati... | 4.101128 | 4.450578 | 0.921482 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.