query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Get features (for regression) based on this bikedata's weather data | def get_weather_features(self):
if self.weather_features is None:
raise Exception("Weather features not made yet.")
### self.make_weather_features()
else:
return self.weather_features | [
"def load_weather():\n filename = (\n \"https://api.featurelabs.com/datasets/daily-min-temperatures.csv?library=evalml&version=\"\n + evalml.__version__\n )\n X, y = load_data(filename, index=None, target=\"Temp\")\n return X, y",
"def compute_features(daily):\n\n features = {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Publish response to kafka topic | def publish_response(class_label):
client = KProducer(config=publisher_config)
client.produce(class_label, PUBLISHER_TOPIC) | [
"def publish_to_kafka(response, args):\n for persuasion in response:\n if args.get(\"push_to_es\", \"false\") == \"true\":\n watson_kafka_response = KafkaServices.publish_to_watson_kafka(persuasion)\n logger.info(watson_kafka_response)\n if args.get(\"push_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the ``BatchStats`` for a specific batch. | def get_batch_stats(self, batch):
return self.batch_stats[batch] | [
"def build_batch_stats():\n\n # We use the moving mean as an estimate of the mean in order to perform\n # a more numerically stable calculation of the batch mean.\n # Copy for better stability.\n shift = tf.add(self._moving_mean, 0)\n counts, shifted_sum_x, shifted_sum_x2, _ = tf.nn.suffici... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convenience method that sums up all the sentences across all batches. | def get_total_sentences(self):
# loop through batches and add up all their individual sentence counts
total_sentences = 0
for batch in self.batch_stats:
total_sentences += self.batch_stats[batch].total_sentences
return total_sentences | [
"def calculate_texts(self) -> None:\n texts = []\n for text in self.texts:\n paragraphs = list(filter(lambda x: x != \"\", text.split(\"\\n\\n\")))\n for paragraph in paragraphs:\n text = paragraph.replace(\"\\n\", \" \").strip()\n if len(text) > sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds ``documents`` to the document inventory, writing to disk in batches of 500,000. | def add_documents(self, documents):
# flag for StopIteration exceptions
more_documents = True
# loop while there are still documents in the iterator
while more_documents:
# increment batch number
batch = len(self.batch_stats) + 1
# count sentences
sentences_count = 0
# create temporary batch data file in the version directory
batch_file = os.path.join(self.file_base.get_version_path(self.version), "data.jl.gz.temp")
# try to read the next batch of files, catch exception and stop if there are no more
try:
# get next document before opening the file just to make sure it's there
document = documents.next()
# open the data file
with gzip.open(batch_file, "wb") as outfile:
# loop through DOCUMENT_BATCH_SIZE documents
for i in range(DocumentDatabase.DOCUMENT_BATCH_SIZE):
# count sentences in document
for paragraph in document["paragraphs"]:
sentences_count += len(paragraph["sentences"])
# write JSON to file one line at a time
outfile.write("%s\n" % json.dumps(document))
# if we are not done with this batch, retrieve the next document
if i < DocumentDatabase.DOCUMENT_BATCH_SIZE - 1:
document = documents.next()
except StopIteration:
# the end of the documents stream, set the flag to False
more_documents = False
# make sure the batch isn't empty
if sentences_count > 0:
# create the new batch in the file system
self.version_batches.create_latest_version()
# add the stats to the statistics hash
self.batch_stats[batch] = BatchStats(sentences_count)
# write the batch statistics to file
with codecs.open(self._get_batch_stat_file(batch), "wb", "utf-8") as outfile:
# write the JSON representation for the stats
outfile.write(json.dumps(self.batch_stats[batch].to_json()))
# move the temp data file to the correct location inside the version folder
os.rename(batch_file, self._get_batch_file(batch)) | [
"def upload(self, documents: List[Document], vectorise_func) -> None:\n\n # Add doc_store to documents\n for d in documents:\n d.doc_store = self\n # Check ID uniqueness\n check_duplicate_documents(documents)\n # Check type consistency\n check_document_types(docu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads a document database with the specified version from the directory. | def load(db_path="data/documents/trigrams", version=None):
# create database at the desired path and with the desired version
db = DocumentDatabase(db_path, version)
# loop through batches
for batch in db._get_batches():
# get the path to the stats file
stats_file = db._get_batch_stat_file(batch)
# load the stats
stats_json = json.loads(codecs.open(stats_file, "rb", "utf-8").read())
# save in the batch statistics hash
db.batch_stats[batch] = BatchStats(stats_json["total_sentences"])
# return the database
return db | [
"def load_db():\n return",
"def db_load(file_path=Path(\"./song_database.pkl\")):\n with open(file_path, mode=\"rb\") as database:\n return pickle.load(database)",
"def load_database(db_file):\n f = Path(db_file)\n if f.is_file():\n filehandle = open(db_file, 'rb')\n db = pi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the latest version of the documents inventory at the specified path. | def get_latest_version(db_path):
# create a file system and return latest version
return VersionedFile(db_path).get_latest_version() | [
"def current_version(self):\n try:\n return self.versions.latest()\n except DocumentVersion.DoesNotExist:\n return None",
"def get_current_version(file_path):\n\n raise RuntimeError('get_current_version function not implemented in Artella Abstract API!')",
"def get_latest_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A.K.I 가 생성된 유저를 조회하면서 stale user 를 삭제하는 메서드 | def delete_staleuser():
# 이 함수가 users.models 에서 쓰이기 때문에, global 선언은 로드될 때 충돌을 야기한다.
from users.models import ActivationKeyInfo
for aki in ActivationKeyInfo.objects.all():
if aki.user.is_active is False and aki.expires_at < timezone.now():
aki.delete() | [
"def forget(self, uid):",
"def delete_user(self):\n\n \tUser.user_list.remove(self)",
"def cleanup(self, lifetime):\n c = self.db.cursor()\n cur = c.execute(\"select login from users where created < date('now', ? || ' days')\",\n (-lifetime,))\n for (login,) in cur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns OAuth2 credentials if we have valid credentials in the session. This is a 'truthy' value. Return None if we don't have credentials, or if they have expired or are otherwise invalid. This is a 'falsy' value. | def valid_credentials():
if 'credentials' not in flask.session:
return None
credentials = client.OAuth2Credentials.from_json(
flask.session['credentials'])
if (credentials.invalid or
credentials.access_token_expired):
return None
return credentials | [
"def valid_credentials():\n if 'credentials' not in flask.session:\n return None\n\n credentials = client.OAuth2Credentials.from_json(\n flask.session['credentials'])\n\n if credentials.invalid or credentials.access_token_expired:\n return None\n return credentials",
"def valid_cr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read time in a humancompatible format and interpret as ISO format with local timezone. May throw exception if time can't be interpreted. In that case it will also flash a message explaining accepted formats. | def interpret_time( text ):
app.logger.debug("Decoding time '{}'".format(text))
time_formats = ["ha", "h:mma", "h:mm a", "H:mm"]
try:
as_arrow = arrow.get(text, time_formats).replace(tzinfo=tz.tzlocal())
as_arrow = as_arrow.replace(year=2016) #HACK see below
app.logger.debug("Succeeded interpreting time")
except:
app.logger.debug("Failed to interpret time")
flask.flash("Time '{}' didn't match accepted formats 13:30 or 1:30pm"
.format(text))
raise
return as_arrow.isoformat()
#HACK #Workaround
# isoformat() on raspberry Pi does not work for some dates
# far from now. It will fail with an overflow from time stamp out
# of range while checking for daylight savings time. Workaround is
# to force the date-time combination into the year 2016, which seems to
# get the timestamp into a reasonable range. This workaround should be
# removed when Arrow or Dateutil.tz is fixed.
# FIXME: Remove the workaround when arrow is fixed (but only after testing
# on raspberry Pi --- failure is likely due to 32-bit integers on that platform) | [
"def interpret_time( text ):\n app.logger.debug(\"Decoding time '{}'\".format(text))\n time_formats = [\"ha\", \"h:mma\", \"h:mm a\", \"H:mm\"]\n try: \n as_arrow = arrow.get(text, time_formats).replace(tzinfo=tz.tzlocal())\n as_arrow = as_arrow.replace(year=2016) #HACK see below\n ap... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert text of date to ISO format used internally, with the local time zone. | def interpret_date( text ):
try:
as_arrow = arrow.get(text, "MM/DD/YYYY").replace(
tzinfo=tz.tzlocal())
except:
flask.flash("Date '{}' didn't fit expected format 12/31/2001")
raise
return as_arrow.isoformat() | [
"def date_to_iso(string):\r\n\r\n # disregard tokenisation, if it's there, to make this an easier conversion for GUTime\r\n string = re.sub(r'<([^~]*)~.+?>', r'\\1 ', string)\r\n\r\n # Defaults\r\n d = None\r\n m = None\r\n y = None\r\n h = None\r\n min = None\r\n s = None\r\n fs = Non... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a google 'service' object, return a list of calendars. Each calendar is represented by a dict. The returned list is sorted to have the primary calendar first, and selected (that is, displayed in Google Calendars web app) calendars before unselected calendars. | def list_calendars(service):
app.logger.debug("Entering list_calendars")
calendar_list = service.calendarList().list().execute()["items"]
result = [ ]
for cal in calendar_list:
kind = cal["kind"]
id = cal["id"]
if "description" in cal:
desc = cal["description"]
else:
desc = "(no description)"
summary = cal["summary"]
# Optional binary attributes with False as default
selected = ("selected" in cal) and cal["selected"]
primary = ("primary" in cal) and cal["primary"]
result.append(
{ "kind": kind,
"id": id,
"summary": summary,
"selected": selected,
"primary": primary
})
return sorted(result, key=cal_sort_key) | [
"def list_calendars(service):\n app.logger.debug(\"Entering list_calendars with service\")\n calendar_list = service.calendarList().list().execute()[\"items\"]\n app.logger.debug(\"Got calendar list\")\n result = []\n for cal in calendar_list:\n kind = cal[\"kind\"]\n id = cal[\"id\"]\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A helper method that generates a dictionary of arguments needed to instantiate a BaseBoto object. The purpose of this method is to abstract out the code to handle optional CLI arguments and not duplicate the None handling code. | def __get_arguments(args=None, logger=None, stats=None):
if not args:
parser = get_parser()
add_boto_cli_arguments(parser)
# Parse only the known arguments added by add_boto_cli_arguments().
# We only need those arguments to create Boto object, nothing else.
# parse_known_args() return (Namespace, list of unknown arguments),
# we only care about the Namespace object here.
args = parser.parse_known_args()[0]
if not logger:
logger = get_logger(name=NAME)
if not stats:
stats = get_stats(prefix=NAME)
return {
'log_level': getattr(args, 'boto_log_level', DEFAULT['log_level']()),
'access_key': getattr(args, 'boto_access_key', DEFAULT['access_key']()),
'secret_key': getattr(args, 'boto_secret_key', DEFAULT['secret_key']()),
'region': getattr(args, 'boto_region', DEFAULT['region']()),
'logger': logger,
'stats': stats,
} | [
"def get_default_arg_dict(customizable_class: Any) -> Dict[str, Any]:\n init_arg_dicts = get_extra_argument_dicts(customizable_class)\n found_opts: Dict[str, Any] = {}\n for arg_group in init_arg_dicts:\n for arg_name, arg_attributes in arg_group[\"args\"].items():\n found_opts[arg_name] ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a usable Boto object without creating a class around it. In the context of a krux.cli (or similar) interface the 'args', 'logger' and 'stats' objects should already be present. If you don't have them, however, we'll attempt to provide usable ones for the boto setup. (If you omit the add_boto_cli_arguments() call during other cli setup, the Boto object will still work, but its cli options won't show up in help output) | def get_boto(args=None, logger=None, stats=None):
return Boto(**__get_arguments(args, logger, stats)) | [
"def get_boto3(args=None, logger=None, stats=None):\n return Boto3(**__get_arguments(args, logger, stats))",
"def __get_arguments(args=None, logger=None, stats=None):\n\n if not args:\n parser = get_parser()\n add_boto_cli_arguments(parser)\n # Parse only the known arguments added by ad... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a usable Boto3 object without creating a class around it. In the context of a krux.cli (or similar) interface the 'args', 'logger' and 'stats' objects should already be present. If you don't have them, however, we'll attempt to provide usable ones for the boto setup. (If you omit the add_boto_cli_arguments() call during other cli setup, the Boto object will still work, but its cli options won't show up in help output) | def get_boto3(args=None, logger=None, stats=None):
return Boto3(**__get_arguments(args, logger, stats)) | [
"def get_boto(args=None, logger=None, stats=None):\n return Boto(**__get_arguments(args, logger, stats))",
"def __get_arguments(args=None, logger=None, stats=None):\n\n if not args:\n parser = get_parser()\n add_boto_cli_arguments(parser)\n # Parse only the known arguments added by add_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract plastic class label from Image Name and return it | def ExtractLabel(ImgName):
# Each img has name notation "*****a0X*" where X is PlasticType
PlasticType = ImgName[7]
return {
'1': 0, # PET
'2': 1, # HDPE
'4': 2, # LDPE
'5': 3, # PP
'6': 4, # PS
'7': 5, # Other
}[PlasticType] | [
"def true_class_label(img_path):\n for i in img_path.split('/'):\n if i in classlabels:\n return i",
"def name_to_label(self, name):\n\t\t\treturn self.classes[name]",
"def find_label_from_image(image):\n print(\"detecting label\")\n image = Image.open(BytesIO(base64.b64decode(image))... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Support the following DHCP DeviceManager calls. self.plugin.release_dhcp_port(network.id, self.get_device_id(network)) | def release_dhcp_port(self, network_id, device_id):
LOG.debug("release_dhcp_port: %s %s", network_id, device_id) | [
"def release_dhcp_port(self, network_id, device_id):\n return self.call(self.context,\n self.make_msg('release_dhcp_port',\n network_id=network_id,\n device_id=device_id,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Construct and return an empty network model. | def empty_network(network_id=NETWORK_ID):
return make_net_model({"id": network_id,
"subnets": [],
"ports": [],
"tenant_id": "calico",
"mtu": neutron_constants.DEFAULT_NETWORK_MTU}) | [
"def create_model_one(self):\n self.network_1 = Model(inputs=self.shared.input, outputs=self.shared.output)\n self.network_1.compile(loss='sparse_categorical_crossentropy',\n optimizer='adam',\n metrics=['acc'])\n self.network_1.summar... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ensure that the cache has a NetModel and subnets for PORT. | def _ensure_net_and_subnets(self, port):
# Gather the subnet IDs that we need for this port, and get the
# NetModel if we already have it in the cache.
needed_subnet_ids = set()
net = None
for fixed_ip in port['fixed_ips']:
subnet_id = fixed_ip.get('subnet_id')
if subnet_id:
needed_subnet_ids.add(subnet_id)
if not net:
net = self.agent.cache.get_network_by_subnet_id(subnet_id)
LOG.debug("Needed subnet IDs: %s", needed_subnet_ids)
LOG.debug("Existing network model by subnet ID: %s", net)
# For each subnet that we need, get its data from SubnetWatcher and
# hold for adding into the cache.
new_subnets = {}
for subnet_id in needed_subnet_ids:
# Get data for this subnet from the SubnetWatchers.
subnet = (self.subnet_watcher.get_subnet(subnet_id) or
self.v1_subnet_watcher.get_subnet(subnet_id))
if subnet is None:
LOG.warning("No data for subnet %s", subnet_id)
raise SubnetIDNotFound()
new_subnets[subnet_id] = subnet
if not net:
# We don't already have a NetModel, so look for a cached NetModel
# with the right network ID. (In this case we must have new
# subnets to add into the cache, and the cached NetModel must have
# subnets other than the ones that we're adding in this iteration;
# otherwise we would have already found it when searching by
# subnet_id above.)
assert new_subnets
network_id = list(new_subnets.values())[0]['network_id']
net = self.agent.cache.get_network_by_id(network_id)
LOG.debug("Existing network model by network ID: %s", net)
if not net:
# We still have no NetModel for the relevant network ID, so create
# a new one. In this case we _must_ be adding new subnets.
assert new_subnets
net = empty_network(network_id)
LOG.debug("New network %s", net)
elif new_subnets:
# We have a NetModel that was already in the cache and are about to
# modify it. Cache replacement only works if the new NetModel is a
# distinct object from the existing one, so make a copy here.
net = copy_network(net)
LOG.debug("Copied network %s", net)
if new_subnets:
# Add the new subnets into the NetModel.
assert net
net.subnets = [s for s in net.subnets
if s.id not in new_subnets]
net.subnets += list(new_subnets.values())
# Add (or update) the NetModel in the cache.
LOG.debug("Net: %s", net)
_fix_network_cache_port_lookup(self.agent, net.id)
self.agent.cache.put(net)
return net.id | [
"def _check_config(self):\n\n if self._stb_ip == None:\n raise RuntimeError('Cannot do HTTP request without setting STB IP')",
"def _fix_network_cache_port_lookup(agent, network_id):\n\n # If there is an existing NetModel for this network ID, ensure that all\n # its ports are in the port_l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Start/stop/restart Dnsmasq for NETWORK_ID. | def _update_dnsmasq(self, network_id):
# Check whether we should really do the following processing.
if self.suppress_dnsmasq_updates:
LOG.debug("Don't update dnsmasq yet;"
" must be processing a snapshot")
self.dirty_networks.add(network_id)
return
self.dnsmasq_updater.update_network(network_id) | [
"def restart_dnsmasq(self, config):\n\n # TODO currently only supports systemd, add upstart support\n command = ['systemctl', 'restart', 'dnsmasq.service']\n try:\n self.run_command(command, config)\n except Exception, e:\n raise e",
"def startServices():\n # d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fix NetworkCache before removing or replacing a network. neutron.agent.dhcp.agent is bugged in that it adds the DHCP port into the cache without updating the cache's port_lookup dict, but then NetworkCache.remove() barfs if there is a port in network.ports but not in that dict... NetworkCache.put() implicitly does a remove() first if there is already a NetModel in the cache with the same ID. So a put() to update or replace a network also hits this problem. This method avoids that problem by ensuring that all of a network's ports are in the port_lookup dict. A caller should call this immediately before a remove() or a put(). | def _fix_network_cache_port_lookup(agent, network_id):
# If there is an existing NetModel for this network ID, ensure that all
# its ports are in the port_lookup dict.
if network_id in agent.cache.cache:
for port in agent.cache.cache[network_id].ports:
agent.cache.port_lookup[port.id] = network_id | [
"def _ensure_net_and_subnets(self, port):\n\n # Gather the subnet IDs that we need for this port, and get the\n # NetModel if we already have it in the cache.\n needed_subnet_ids = set()\n net = None\n for fixed_ip in port['fixed_ips']:\n subnet_id = fixed_ip.get('subne... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run the EtcdWatcher loop. | def run(self):
self.etcd.start() | [
"def watch_forever(self):\n\n while True:\n try:\n self.do_tick()\n if self.etcd_elector:\n self.etcd_elector.wait_until_elected()\n self.do_watch()\n except Exception:\n LOG.exception('%s: etcd threw excepti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compiles robot from given file and returns class object | def compile_robot(file_name, module_name = "contestant_module"):
global counter_module
module_name += str(counter_module)
counter_module += 1
mod = importCode(file_name, module_name)
compiled_class = None
for symbol in dir(mod):
if hasattr(getattr(mod, symbol), "act") and getattr(mod, symbol).__name__ != "RobotController":
compiled_class = getattr(mod, symbol)
print compiled_class
globals()[compiled_class.__name__] = compiled_class
if compiled_class is None:
raise KrakrobotException("Not found class with act() function named different than RobotController in provided .py")
return compiled_class, mod | [
"def compile(self, filename=None):\n\n code = CodeGen()\n code.append(\"\"\"\n # generated by Construct, this source is for inspection only! do not import!\n\n from construct import *\n from construct.lib import *\n from io import BytesIO\n import... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prepare normalized image and label. | def _prepare_image_and_label(self, data):
image = tf.io.decode_image(data['image/encoded'], channels=3)
label = tf.io.decode_image(data['image/segmentation/class/encoded'],
channels=1)
height = data['image/height']
width = data['image/width']
image = tf.reshape(image, (height, width, 3))
label = tf.reshape(label, (1, height, width))
label = tf.cast(label, tf.float32)
# Normalizes image with mean and std pixel values.
image = input_utils.normalize_image(image)
return image, label | [
"def prep_images(self):\n self.prep_score()\n self.prep_high_score()\n self.prep_level()\n self.prep_rockets()",
"def prep_image_data(arg_dict):\n cat_df = pd.read_csv(arg_dict['category_file'],\n skiprows=1,\n sep='\\s+')\n bbox_df... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses data for prediction. | def _parse_predict_data(self, data):
image, labels = self._parse_eval_data(data)
return {
'images': image,
'labels': labels
} | [
"def predict(self, datafile):",
"def predict(self, data):\n pass",
"def _parse_fit_and_predict_result(result):\n if len(result) > 1 and result[1] and not isinstance(result[1], str):\n # Scores object does not resemble a label prediction (always string)\n y = result[0]\n scores = r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If an iteriter_op is given an iterator as input, no exception should be thrown, and we should return the wrapped function's output. | def test_iteriter_op_1():
@ops.iteriter_op
def f(x):
return iter([4, 5, 6])
result = f(iter([1, 2, 3])) # Passing in an iterator, as expected
assert(isinstance(result, collections.abc.Iterator)), f"{result}"
assert(list(result) == [4, 5, 6]) | [
"def test_iteriter_op_3():\n\n @ops.iteriter_op\n def f(x):\n return [4, 5, 6] # Returning a list instead of an iterator\n\n with pytest.raises(ValueError):\n result = f(iter([1, 2, 3]))",
"def test_iteriter_op_2():\n\n @ops.iteriter_op\n def f(x):\n return iter([4, 5, 6])\n\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If an iteriter_op is given something besides an iterator as input, raise a ValueError. | def test_iteriter_op_2():
@ops.iteriter_op
def f(x):
return iter([4, 5, 6])
with pytest.raises(ValueError):
f([1, 2, 3]) # Passing in a list instead of an iterator | [
"def test_iteriter_op_3():\n\n @ops.iteriter_op\n def f(x):\n return [4, 5, 6] # Returning a list instead of an iterator\n\n with pytest.raises(ValueError):\n result = f(iter([1, 2, 3]))",
"def test_listiter_op_2():\n\n @ops.listiter_op\n def f(x):\n return iter([4, 5, 6])\n\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If an iteriter_op returns something besides an iterator as output, raise a ValueError. | def test_iteriter_op_3():
@ops.iteriter_op
def f(x):
return [4, 5, 6] # Returning a list instead of an iterator
with pytest.raises(ValueError):
result = f(iter([1, 2, 3])) | [
"def test_iteriter_op_2():\n\n @ops.iteriter_op\n def f(x):\n return iter([4, 5, 6])\n\n with pytest.raises(ValueError):\n f([1, 2, 3]) # Passing in a list instead of an iterator",
"def test_listiter_op_2():\n\n @ops.listiter_op\n def f(x):\n return iter([4, 5, 6])\n\n with... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If a listlist_op is given a list as input, no exception should be thrown, and we should return the wrapped function's output. | def test_listlist_op_1():
@ops.listlist_op
def f(x):
return [4, 5, 6]
result = f([1, 2, 3]) # Passing in a list, as expected
assert(isinstance(result, list)), f"{result}"
assert(result == [4, 5, 6]) | [
"def test_listlist_op_3():\n\n @ops.listlist_op\n def f(x):\n return iter([4, 5, 6]) # Returning an iterator instead of an list\n\n with pytest.raises(ValueError):\n result = f([1, 2, 3])",
"def test_listlist_op_2():\n\n @ops.listlist_op\n def f(x):\n return [4, 5, 6]\n\n w... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If a listlist_op is given something besides a list as input, raise a ValueError. | def test_listlist_op_2():
@ops.listlist_op
def f(x):
return [4, 5, 6]
with pytest.raises(ValueError):
f(iter([1, 2, 3])) # Passing in an iterator instead of an list | [
"def test_listlist_op_3():\n\n @ops.listlist_op\n def f(x):\n return iter([4, 5, 6]) # Returning an iterator instead of an list\n\n with pytest.raises(ValueError):\n result = f([1, 2, 3])",
"def is_listing(op):\n return isinstance(op, (list, tuple))",
"def test_listlist_op_1():\n\n @... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If a listlist_op returns something besides a list as output, raise a ValueError. | def test_listlist_op_3():
@ops.listlist_op
def f(x):
return iter([4, 5, 6]) # Returning an iterator instead of an list
with pytest.raises(ValueError):
result = f([1, 2, 3]) | [
"def test_listlist_op_2():\n\n @ops.listlist_op\n def f(x):\n return [4, 5, 6]\n\n with pytest.raises(ValueError):\n f(iter([1, 2, 3])) # Passing in an iterator instead of an list",
"def test_listlist_op_1():\n\n @ops.listlist_op\n def f(x):\n return [4, 5, 6]\n\n result = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If a listiter_op is given a list as input, no exception should be thrown, and we should return the wrapped function's output. | def test_listiter_op_1():
@ops.listiter_op
def f(x):
return iter([4, 5, 6])
result = f([1, 2, 3]) # Passing in a list, as expected
assert(isinstance(result, collections.abc.Iterator)), f"{result}"
assert(list(result) == [4, 5, 6]) | [
"def test_iterlist_op_1():\n\n @ops.iterlist_op\n def f(x):\n return [4, 5, 6]\n\n result = f(iter([1, 2, 3])) # Passing in an iterator, as expected\n\n assert(isinstance(result, list)), f\"{result}\"\n assert(result == [4, 5, 6])",
"def test_listlist_op_3():\n\n @ops.listlist_op\n de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If a listiter_op is given something besides a list as input, raise a ValueError. | def test_listiter_op_2():
@ops.listiter_op
def f(x):
return iter([4, 5, 6])
with pytest.raises(ValueError):
f(iter([1, 2, 3])) # Passing in an iterator instead of a list | [
"def test_listlist_op_2():\n\n @ops.listlist_op\n def f(x):\n return [4, 5, 6]\n\n with pytest.raises(ValueError):\n f(iter([1, 2, 3])) # Passing in an iterator instead of an list",
"def test_listlist_op_3():\n\n @ops.listlist_op\n def f(x):\n return iter([4, 5, 6]) # Returni... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If an iterlist_op is given an iterator as input, no exception should be thrown, and we should return the wrapped function's output. | def test_iterlist_op_1():
@ops.iterlist_op
def f(x):
return [4, 5, 6]
result = f(iter([1, 2, 3])) # Passing in an iterator, as expected
assert(isinstance(result, list)), f"{result}"
assert(result == [4, 5, 6]) | [
"def test_listiter_op_2():\n\n @ops.listiter_op\n def f(x):\n return iter([4, 5, 6])\n\n with pytest.raises(ValueError):\n f(iter([1, 2, 3])) # Passing in an iterator instead of a list",
"def test_listiter_op_1():\n\n @ops.listiter_op\n def f(x):\n return iter([4, 5, 6])\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If a pool of size 3 is used, the first 3 individuals in the input iterator should be collected into a list. | def test_pool():
pop = iter([ 'a', 'b', 'c', 'd', 'e' ])
pop = ops.pool(pop, size=3)
assert(len(pop) == 3)
assert(pop == [ 'a', 'b', 'c' ]) | [
"def n_wise(x: List[Any], size: Optional[int] = 2) -> Iterable:\n\n iterator = iter(x)\n\n return iter(lambda: tuple(islice(iterator, size)), ())",
"def batch_iterator(iterator, batch_size):\n it = iter(iterator)\n item = list(itertools.islice(it, batch_size))\n while item:\n yield item\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts a wave to a vector of prosodic features. offset (in ms) determines where the signal will be sampled. window_len is ignored. | def wav_to_prosodic(path, sr=16000, offset=10):
sound = parselmouth.Sound(path)
pitch = sound.to_pitch() #timestep, pitch_floor, pitch_ceiling
intensity = sound.to_intensity()
features = []
max_time = sound.get_total_duration()
for time in np.arange(0, max_time, 0.001):
f0 = pitch.get_value_at_time(time)
f0_nan = 0
if np.isnan(f0):
f0 = 0
f0_nan = 1
int_db = intensity.get_value(time)
if np.isnan(int_db):
int_db = 0
features.append([f0, f0_nan, int_db])
array_feats = np.array(features).T
print("SHAPE OF THE FEATURES:", array_feats.shape)
assert(not np.any(np.isnan(array_feats)))
return array_feats, max_time | [
"def _choose_wavelength_slice(self, offset):\n if 'WAVE' not in self.axes_wcs.wcs.ctype:\n raise cu.CubeError(2, \"Spectral dimension not present\")\n if self.data.ndim == 4:\n raise cu.CubeError(4, \"Can only work with 3D cubes\")\n\n axis = -2 if self.axes_wcs.wcs.ctype[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print percentage of rows that have been processed. | def _print_stat_rows(title,rows_before,rows_after):
self.strprint(str(title)+" : Percent of processed rows = %1.2F"\
%(np.abs(rows_before-rows_after)*100/rows_before)) | [
"def printProgress(self, percentage):\n #print '%s\\r' % ' '*20, # clean up row\n #print '%3d%% ' % percentage, # ending with comma prevents newline from being appended\n sys.stdout.flush()",
"def printProgress(self, percentage):\n print('%s\\r' % ' ' * 20,) # clean up row\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove raws with countries other then 'United Kingdom' then remove Country feature. | def _feature_country_process(self):
if 'Country' not in self._df_invoice_line.columns:
return
list_countries_keep = ['United Kingdom']
rows_before = self._df_invoice_line.shape[0]
df_invoice_line_new = pd.DataFrame()
for country in list_countries_keep :
df_invoice_line_new = df_invoice_line_new.append(\
self._df_invoice_line[self._df_invoice_line['Country']==country]\
, ignore_index=True)
self.df_invoice_line = df_invoice_line_new
del(df_invoice_line_new)
rows_after = self._df_invoice_line.shape[0]
_print_stat_rows("Countries filtering : ",rows_before, rows_after)
#-------------------------------------------------------------------------
# Due to the fact only one country is used, then this feature is dropped
#-------------------------------------------------------------------------
list_col_to_keep = [col for col in self._df_invoice_line.columns \
if col not in 'Country']
self._df_invoice_line = self._df_invoice_line[list_col_to_keep]
return | [
"def delete_countries() -> None:\n remove_all_countries()",
"def apply_feature_filter(self):\n self.features = set()\n for language in self.data.values():\n features_in_data = set(language.keys())\n features_to_keep = features_in_data & self.feature_filter\n self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds for each customer, RFM scores and encode scores. When this method is called during building data_model step, then dataframe handling new RFM features is dumped into a file. | def data_transform_rfm(self) :
is_built_step = False
if self._encoder_rfm is None:
is_built_step = True
#-------------------------------------------------------------------------
# RFM feature is built
#-------------------------------------------------------------------------
ser_invoice_date = self._df_invoice_line.InvoiceDate
self.df_invoice_line, df_RFM, self.df_RFM_quantiles, self._day_now \
= p5_util.p5_df_rfm_build(self.df_invoice_line, day_now = self._day_now\
, df_RFM_threshold=self.df_RFM_quantiles)
self._df_invoice_line.InvoiceDate = ser_invoice_date
#-------------------------------------------------------------------------
# RFM score is added to dataframe
#-------------------------------------------------------------------------
df_merged = pd.merge(self.df_invoice_line\
, df_RFM[['CustomerID','RFM']], how='left', on=['CustomerID'])
self._df_invoice_line \
= pd.DataFrame(df_merged.values, index = self._df_invoice_line.index\
, columns=df_merged.columns)
#self._df_invoice_line \
#= pd.concat([ self.df_invoice_line,df_RFM[['CustomerID','RFM']] ], axis=1\
#,join='inner')
#-------------------------------------------------------------------------
# RFM encoding
#-------------------------------------------------------------------------
self._encoder_rfm, df_RFM_encoded \
= p5_util.df_rfm_one_hot_encode(df_RFM,'RFM', encoder=self._encoder_rfm)
#-------------------------------------------------------------------------
# Encoded RFM features are renamed
#-------------------------------------------------------------------------
df_customers_rfm, list_col_unchanged \
= p5_util.df_rename_columns(df_RFM_encoded, df_RFM_encoded.columns\
, 'w_rfm_')
self.strprint("df_customers_rfm =" +str(df_customers_rfm.shape))
#-------------------------------------------------------------------------
# dataframe with RFM encoded values per customer is dumped
#-------------------------------------------------------------------------
if is_built_step is True:
p5_util.object_dump(df_customers_rfm, self.df_customers_rfm_fileName)
else :
self._df_customers_rfm = df_customers_rfm.copy()
return | [
"def df_customers_fileRead(self):\n \n #-------------------------------------------------------------------------\n # RFM features are restored\n #-------------------------------------------------------------------------\n df_customers_rfm \\\n = p5_util.object_load(self.df_customer... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates new features from Description feature thanks to NLTK, a NLP package. NLP features are handled into a dataframe. A PCA reduction is applied on this dataframe. Features from dataframe are renamed with root ane w_nlp. When this method is called during building data_model step, then dataframe handling new NLP feature is dumped into a file. | def data_transform_nlp(self):
df_invoice_line = None
is_build_step = False
if self._vectorizer_nlp is None:
is_build_step = True
list_no_words=['SET','PACK']
df_invoice_line, csr_matrix_weights, self._vectorizer_nlp \
= p5_util.nlp_process(self.df_invoice_line\
, 'Description' , vectorizer= self._vectorizer_nlp\
, list_no_words=list_no_words, is_verbose= self.is_verbose)
if df_invoice_line is None:
self.strprint("***ERROR : NLP process interrupted!")
return
#-------------------------------------------------------------------------
# NLP weights are cumulated (sumerized) per customer
#-------------------------------------------------------------------------
if csr_matrix_weights is None:
csr_matrix_weights \
= p5_util.object_load('./data/matrix_weights_NLP.dump')
else:
pass
self.strprint("df_invoice_line : "+str(df_invoice_line.shape))
self.dbg_df = df_invoice_line.copy()
root_name = 'w_nlp_'
self._df_w_nlp = p5_util.df_nlp_sum_per_customer(df_invoice_line\
, csr_matrix_weights, root_name)
del(csr_matrix_weights)
#-------------------------------------------------------------------------
# Dimension reduction thanks to PCA
#-------------------------------------------------------------------------
self.strprint("self._df_w_nlp : "+str(self._df_w_nlp.shape))
root_name_pca = 'nlp_pca_'
n_dim = self._nlp_pca_ndim
df_customers_pca_nlp, self._pca_nlp \
= p5_util.df_pca_reduce(self._df_w_nlp, n_dim, root_name_pca\
, p_is_scale=False, pca=self._pca_nlp)
self.strprint("df_customers_pca_nlp : " +str(df_customers_pca_nlp.shape))
#-------------------------------------------------------------------------
# Backup of NLP features per customer
#-------------------------------------------------------------------------
if is_build_step is True:
p5_util.object_dump(df_customers_pca_nlp\
, self._df_customers_nlp_fileName)
else:
self._df_customers_pca_nlp = df_customers_pca_nlp.copy()
return | [
"def feature_description_nlp(self):\n \n #-------------------------------------------------------------------------\n # Returned dataframe is aggregated with weights from self.vectorizer\n #-------------------------------------------------------------------------\n list_no_words=['SET','PAC... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build dataframe df_customers from transformed data. Transformed data are issued from NLP, Time and RFM features. See data_transform(). These data are stored as dataframes attributes. | def df_customers_features_build(self):
df_customers_rfm = self._df_customers_rfm.copy()
df_customers_timeFeature = self._df_customers_timeFeature.copy()
df_customers_nlp = self._df_customers_pca_nlp.copy()
#-------------------------------------------------------------------------
# Dataframe are aggregated; note that indexes are customerID.
#-------------------------------------------------------------------------
df_customers = pd.DataFrame()
df_customers = pd.concat([df_customers,df_customers_rfm], axis=1)
df_customers = pd.concat([df_customers,df_customers_timeFeature]\
, join='inner', axis=1)
df_customers = pd.concat([df_customers,df_customers_nlp]\
, join='inner', axis=1)
self.strprint("All features : "+str(df_customers.shape))
self._df_customers = df_customers.copy()
return | [
"def features_customers(df_customers):\n for i in PREMIER_VALS:\n k = 'premier_' + str(i)\n df_customers[k] = np.where(df_customers['premier'] == i, 1, 0)\n\n df_customers['age'] = datetime.now().date().year - df_customers['yearOfBirth']\n df_customers['male'] = np.where(df_customers['gender'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build dataframe df_customers from transformed data. Transformed data are loaded from dumped files issued from NLP, Time and RFM features. See data_transform() | def df_customers_fileRead(self):
#-------------------------------------------------------------------------
# RFM features are restored
#-------------------------------------------------------------------------
df_customers_rfm \
= p5_util.object_load(self.df_customers_rfm_fileName)
self.strprint("RFM features : "+str(df_customers_rfm.shape))
#-------------------------------------------------------------------------
# Time features are restored
#-------------------------------------------------------------------------
df_customers_timeFeature \
= p5_util.object_load(self._df_customers_timeFeature_fileName)
self.strprint("Time features : "+str(df_customers_timeFeature.shape))
#-------------------------------------------------------------------------
# NLP features are restored
#-------------------------------------------------------------------------
df_customers_nlp = p5_util.object_load(self._df_customers_nlp_fileName)
self.strprint("NLP features : "+str(df_customers_nlp.shape))
if False:
df_customers_rfm = self._df_customers_rfm.copy()
df_customers_timeFeature = self._df_customers_timeFeature.copy()
df_customers_nlp = self._df_customers_pca_nlp.copy()
#-------------------------------------------------------------------------
# Dataframe are aggregated; note that indexes are customerID.
#-------------------------------------------------------------------------
df_customers = pd.DataFrame()
df_customers = pd.concat([df_customers,df_customers_rfm], axis=1)
df_customers = pd.concat([df_customers,df_customers_timeFeature]\
, join='inner', axis=1)
df_customers = pd.concat([df_customers,df_customers_nlp]\
, join='inner', axis=1)
self.strprint("All features : "+str(df_customers.shape))
#----------------------------------------------------------------------
# Dataframe is dumped into a file
#----------------------------------------------------------------------
p5_util.object_dump(df_customers, self._df_customers_fileName)
if False:
#----------------------------------------------------------------------
# Dataframe is copied as an attribute
#----------------------------------------------------------------------
self._df_customers = df_customers.copy()
return | [
"def df_customers_features_build(self):\n\n df_customers_rfm = self._df_customers_rfm.copy()\n df_customers_timeFeature = self._df_customers_timeFeature.copy()\n df_customers_nlp = self._df_customers_pca_nlp.copy()\n\n #-------------------------------------------------------------------------\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a new customer identifier from existing dataset. | def createCustomerID(self):
customerID = self._df_invoice_original.CustomerID.max()
customerID += 1
return int(customerID) | [
"def test_companies_company_id_data_customers_customer_id_get(self):\n pass",
"def create_customer(cls, api, **data):\n return api.create_customer(**data)",
"def create_customer(data):\n mandatory_params = ['customer_name', 'mobile_number']\n result = api_utils.check_required_params(mandator... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Drop from df_invoice_line dataframe features in list given as parameter. All elements from list are checked to be into dataframe columns. | def list_feature_drop(self):
list_to_drop = list()
list_not_in_df = list()
#-------------------------------------------------------------------------
# Columns are checked to be into df_invoice_line dataframe
#-------------------------------------------------------------------------
for col in self._list_feature_to_drop:
if col in self.df_invoice_line.columns:
list_to_drop.append(col)
else:
list_not_in_df.append(col)
if 0 == len(list_to_drop):
self.strprint("\n*** ERROR : no element in list belonging to dataframe!")
else:
if len(self._list_feature_to_drop) != len(list_to_drop):
self.strprint("\n*** WARNING : followings features do not belong to \
dataframe : {}".format(list_not_in_df))
else:
pass
list_col_keep \
= [col for col in self.df_invoice_line.columns \
if col not in list_to_drop]
s
self.df_invoice_line = self.df_invoice_line[list_col_keep]
return | [
"def drop_dfcol(self, drop_list):\n self.data = self.df\n for lbl in drop_list:\n self.data = self.data.drop(lbl, axis=1)\n self.n_features = np.shape(self.data)[1]",
"def drop(self,df, column_list):\n df.drop(columns = column_list, inplace = True)\n return df",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process df_invoice_line.Description with NLTK package. | def feature_description_nlp(self):
#-------------------------------------------------------------------------
# Returned dataframe is aggregated with weights from self.vectorizer
#-------------------------------------------------------------------------
list_no_words=['SET','PACK']
self.df_invoice_line, vectorizer, matrix_weights \
= p5_util.nlp_process(self.df_invoice_line,'Description'\
, vectorizer=self.vectorizer, list_no_words=list_no_words)
#-------------------------------------------------------------------------
# Each vectorized column 'x' is renamed w_nlp_i
#-------------------------------------------------------------------------
dict_matching_name = dict()
for col in self.df_invoice_line.columns:
if str(col).isdigit() is True:
new_col_name = "w_nlp_"+str(col)
dict_matching_name[col] = new_col_name
self.df_invoice_line.rename(columns=dict_matching_name,inplace=True)
#-------------------------------------------------------------------------
# Description is droped from columns
#-------------------------------------------------------------------------
del(self.df_invoice_line['Description']) | [
"def process_text(self, text, language):",
"def data_transform_nlp(self):\n df_invoice_line = None\n \n is_build_step = False\n\n if self._vectorizer_nlp is None:\n is_build_step = True\n \n list_no_words=['SET','PACK']\n\n df_invoice_line, csr_matrix_weights, self._v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Standardize quantitatives features. Standardizer is stored as object attribute. It will be copied into P5_SegmentClassifier object. | def feature_scale(self):
#-------------------------------------------------------------------------
# List of quantitative features to be standardized
#-------------------------------------------------------------------------
list_quant_feature = ['Quantity','UnitPrice']
self._list_quant_feature = list_quant_feature.copy()
#-------------------------------------------------------------------------
# Standardization is applied over quantitative features in list.
#-------------------------------------------------------------------------
X_std = self.std_scale.transform(self.df_invoice_line[self.list_quant_feature])
df_quant_std = pd.DataFrame(X_std, index=self.df_invoice_line.index)
#-------------------------------------------------------------------------
# Columns from standardized dataframe are renamed
#-------------------------------------------------------------------------
df_quant_std.rename(columns={0:'STD_Quantity',1:'STD_UnitPrice'}\
,inplace=True)
#-------------------------------------------------------------------------
# Standardized values dataframe is aggregated to df_invoice_line
#-------------------------------------------------------------------------
list_col_drop = ['Quantity','UnitPrice']
list_col_keep = \
[col for col in self.df_invoice_line.columns if col not in list_col_drop ]
self.df_invoice_line = self.df_invoice_line[list_col_keep]
self.df_invoice_line \
= pd.concat([self.df_invoice_line,df_quant_std], axis=1)
return | [
"def standardiser(self):\n # Select only numeric features first\n\n #self.X = self.data.loc[:, self.data.columns != self.target].values\n numeric_columns = []\n for col in self.X.columns:\n if self.X[col].dtype!='object':\n numeric_columns.append(col)\n s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns market segment ID related to a customer thanks to customer invoices lines given as parameter. Features transformations are applied on data included into invoice lines. Once done, a machine learning algorithm is invocated in order to predict customer market segment. | def get_customer_marketSegment(self, df_invoice_line_customer):
#-------------------------------------------------------------------------
# Building data model
#-------------------------------------------------------------------------
self.data_transform(df_invoice_line_customer)
#-------------------------------------------------------------------------
# Customer features are built thanks to transformers.
#-------------------------------------------------------------------------
self.df_customers_features_build()
#-------------------------------------------------------------------------
# Customer market segment is predicted
#-------------------------------------------------------------------------
X_test = self._df_customers.values
y_pred = self._classifier_model.predict(X_test)
segmentID = y_pred[0]
return segmentID | [
"def predict_segment(self, df_invoice_line=None):\n if df_invoice_line is not None:\n self.data_transform(df_invoice_line) \n self.df_customers_features_build() \n else:\n pass\n X_test = self._df_customers.values\n y_pred = self._classifier_model.predict(X_test)\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function creates an invoice compounding invoices lines from data given as parameters. Once done, this function computes market segment customer belongs to. If customerID is None, then a new customer identifier is created before order process to take place. | def order_process(self, customerID, list_stockCode, list_quantity\
, orderDate=None):
segmentID = -1
#-------------------------------------------------------------------------
# A new customer is created and inserted into data-set.
#-------------------------------------------------------------------------
if customerID is None:
customerID = int(self.createCustomerID())
else:
pass
#-------------------------------------------------------------------------
# A new dataframe with new invoice lines are created.
#-------------------------------------------------------------------------
df_invoice_line = self.create_customer_df_invoice_line(customerID\
, list_stockCode, list_quantity, orderDate)
#-------------------------------------------------------------------------
# Original dataframe is updated with customer invoices lines.
#-------------------------------------------------------------------------
print("order_process : shape before concat= "+str(self._df_invoice_original.shape))
self._df_invoice_original \
= pd.concat([self._df_invoice_original, df_invoice_line], axis=0)
print("order_process : shape after concat= "+str(self._df_invoice_original.shape))
#-------------------------------------------------------------------------
# All invoices lines (including new one) related to customer is retrieved
# from original dataframe.
#-------------------------------------------------------------------------
df_invoice_line_customer \
= self.get_customer_history_df_invoice_line(customerID)
#-------------------------------------------------------------------------
# When calling get_customer_marketSegment(), df_invoice_line_customer is
# concatened to the original dataframe.
#-------------------------------------------------------------------------
segmentID = self.get_customer_marketSegment(df_invoice_line_customer)
return segmentID, customerID | [
"def create_customer_df_invoice_line(self, customerID, list_stockCode\\\n , list_quantity, invoiceDate):\n \n dict_invoice = dict()\n\n dict_invoice['Quantity'] = list_quantity\n dict_invoice['StockCode'] = list_stockCode\n\n #--------------------------------------------------------------... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the segment identifier a customers is predicted to belongs to. | def predict_segment(self, df_invoice_line=None):
if df_invoice_line is not None:
self.data_transform(df_invoice_line)
self.df_customers_features_build()
else:
pass
X_test = self._df_customers.values
y_pred = self._classifier_model.predict(X_test)
return y_pred[0] | [
"def get_customer_marketSegment(self, df_invoice_line_customer):\n #-------------------------------------------------------------------------\n # Building data model \n #-------------------------------------------------------------------------\n self.data_transform(df_invoice_line_customer)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns list of stock codes from list of items descriptions. | def getStockCodeList(self, list_description=None):
list_stockCode = list()
df = self._df_invoice_original
if list_description is None:
list_stockCode = list(df.StockCode.unique())
else :
for description in list_description:
stockCode = df[df.Description==description].StockCode.unique()[0]
list_stockCode.append(stockCode)
return list_stockCode | [
"def getDescriptionList(self, list_stockCode=None):\n df = self._df_invoice_original\n\n list_description = list()\n if list_stockCode is None :\n list_description = list(df.Description.unique())\n else:\n for stockCode in list_stockCode:\n description = df[df.StockCod... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns list of imtes unit price from list of stock codes. | def getUnitPriceList(self, list_stockCode):
df = self._df_invoice_original
list_unitPrice = list()
for stockCode in list_stockCode:
unitPrice = df[df.StockCode==stockCode].UnitPrice.unique()[0]
list_unitPrice.append(unitPrice)
return list_unitPrice | [
"def get_price_list(self, item_list):\n price_list = []\n for item in item_list:\n price_list.append(Inventory.stock[item].price)\n return price_list",
"def getStockCodeList(self, list_description=None):\n list_stockCode = list()\n df = self._df_invoice_original\n \n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns list of items descriptions from list of stock codes. | def getDescriptionList(self, list_stockCode=None):
df = self._df_invoice_original
list_description = list()
if list_stockCode is None :
list_description = list(df.Description.unique())
else:
for stockCode in list_stockCode:
description = df[df.StockCode==stockCode].Description.unique()[0]
list_description.append(description)
return list_description | [
"def getStockCodeList(self, list_description=None):\n list_stockCode = list()\n df = self._df_invoice_original\n \n if list_description is None:\n list_stockCode = list(df.StockCode.unique())\n else :\n for description in list_description:\n stockCode = df[df.Desc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates new dataframe with invoices lines issued from given parameters. Once done, the new dataframe is aggregated with original one. | def create_customer_df_invoice_line(self, customerID, list_stockCode\
, list_quantity, invoiceDate):
dict_invoice = dict()
dict_invoice['Quantity'] = list_quantity
dict_invoice['StockCode'] = list_stockCode
#------------------------------------------------------------------------
# Build invoiceDate from local current time
#------------------------------------------------------------------------
if invoiceDate is None:
time_struct = time.localtime()
invoiceDate = str(time_struct.tm_year)+'-'+str(time_struct.tm_mon)\
+'-'+str(time_struct.tm_mday)
invoiceDate +=' '
invoiceDate +=str(time_struct.tm_hour)+':'+str(time_struct.tm_min)\
+':'+str(time_struct.tm_sec)
invoiceDate = pd.Timestamp(invoiceDate)
else:
pass
#------------------------------------------------------------------------
# Lists initialization
#------------------------------------------------------------------------
list_customerID = list()
list_invoiceNo = list()
list_invoiceDate = list()
list_invoice_line_index = list()
#------------------------------------------------------------------------
# Increase Invoice number
#------------------------------------------------------------------------
invoiceNo = max(self._df_invoice_original.InvoiceNo)
invoiceNo += 1
#------------------------------------------------------------------------
# Get latest invoice line index value
#------------------------------------------------------------------------
invoice_line_index = max(self._df_invoice_original.index)
#------------------------------------------------------------------------
# Build lists for CustomerID, InvoiceNo, InvoiceDate
# A list of incremented indexes is built for new rows.
#------------------------------------------------------------------------
for quantity in list_quantity:
list_customerID.append(customerID)
list_invoiceNo.append(invoiceNo)
list_invoiceDate.append(invoiceDate)
invoice_line_index += 1
list_invoice_line_index.append(invoice_line_index)
dict_invoice['CustomerID'] = list_customerID
dict_invoice['InvoiceNo'] = list_invoiceNo
dict_invoice['InvoiceDate'] = list_invoiceDate
#------------------------------------------------------------------------
# Get description list from list of stock codes.
#------------------------------------------------------------------------
list_description = self.getDescriptionList(list_stockCode)
dict_invoice['Description'] = list_description
#------------------------------------------------------------------------
# Get unit price list from list of stock codes.
#------------------------------------------------------------------------
list_unitPrice = self.getUnitPriceList(list_stockCode)
dict_invoice['UnitPrice'] = list_unitPrice
#------------------------------------------------------------------------
# Dataframe with new invoices lines is created.
#------------------------------------------------------------------------
df_invoice_line \
= pd.DataFrame(dict_invoice, columns=dict_invoice.keys()\
, index=list_invoice_line_index)
return df_invoice_line | [
"def merge_purchase_invoice(self):\r\n active_id = self.env['purchase.order'].browse(self.env['purchase.order']._context.get('active_ids'))\r\n journal_id = self.env['account.journal'].search([('type', '=', 'purchase')]) \r\n active_id_count = 0\r\n active_count = 0\r\n exist_vend... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a dataframe with all invoice lines from customerID given as parameter. | def get_customer_history_df_invoice_line(self, customerID):
df_invoice_line \
= self._df_invoice_original[self._df_invoice_original.CustomerID \
== customerID]
return df_invoice_line | [
"def create_customer_df_invoice_line(self, customerID, list_stockCode\\\n , list_quantity, invoiceDate):\n \n dict_invoice = dict()\n\n dict_invoice['Quantity'] = list_quantity\n dict_invoice['StockCode'] = list_stockCode\n\n #--------------------------------------------------------------... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of customers that have been excluded of data sampling used for building model. By default, 10 customers identifier is returned. If customerCount value is None, or <= 0, then list of all customers that have been excluded of data sampling is returned. | def get_listCustomer_out_sample(self, customerCount=10):
if customerCount is None :
listCustomer= list(self._df_invoice_line_out_sample.CustomerID.unique())
else:
if customerCount <= 0 :
listCustomer \
= list(self._df_invoice_line_out_sample.CustomerID.unique())
else:
listCustomer \
= list(self._df_invoice_line_out_sample.CustomerID.unique()[:customerCount])
return listCustomer | [
"def remove_exiting_customers(self):\n self.customers=[c for c in self.customers if c.is_active()]",
"def get_all_customer_ids():\n table = data_manager.get_table_from_file(\"sales/sales.csv\")\n return get_all_customer_ids_from_table(table)",
"def get_all_customers():\n data = user_obj.get_all_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns number of invoices from original dataset. | def get_invoice_count(self):
return self._df_invoice_original.InvoiceNo.unique().shape[0] | [
"def _compute_no_of_invoices(self):\n for record in self:\n record.invoice_count = len(record.invoice_ids)",
"def get_invl_count(self):\n return self._df_invoice_original.index.unique().shape[0]",
"def invoices(self):\n from invoice.models.inv import Invoice\n\n return Invoi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns number of customers from original dataset. | def get_customer_count(self):
return self._df_invoice_original.CustomerID.unique().shape[0] | [
"def get_total_customers(self, report_df):\n\n return len(report_df.loc[:, 'customer_id'].unique())",
"def bus_total_customers(self) -> int:\n return self.dss_obj.BUSI(4, 0)",
"def test_customer_count(self):\n\n # test that enpoint returns the correct count of products\n rv = self.ap... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns number of invoice lines (number of rows) from original dataset. | def get_invl_count(self):
return self._df_invoice_original.index.unique().shape[0] | [
"def get_invoice_count(self):\n return self._df_invoice_original.InvoiceNo.unique().shape[0]",
"def getNumRows(self) -> int:\n ...",
"def _compute_no_of_invoices(self):\n for record in self:\n record.invoice_count = len(record.invoice_ids)",
"def get_num_lines(new_crystal_text):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns JSON structure issued form dataframe content given as parameter . | def json_df_builder(self, df, marketID, RFM=None):
#-------------------------------------------------------------------------
# Extract from dataframe content to be returned
#-------------------------------------------------------------------------
str_customerID = str(df.CustomerID.unique()[0])
invoice_count = len(df.InvoiceNo.unique())
item_count = df.Quantity.sum()
invl_count = df.shape[0]
ser_incomes = df.UnitPrice * df.Quantity
incomes = ser_incomes.sum()
str_incomes = "{0:1.2F}".format(incomes)
mean_unit_price = incomes/item_count
str_mean_unit_price = "{0:1.2F}".format(mean_unit_price)
serInvoiceDate = df.InvoiceDate
str_old_date = serInvoiceDate.map(str).min()
str_new_date = serInvoiceDate.map(str).max()
#-------------------------------------------------------------------------
# Build JSON structure form content
#-------------------------------------------------------------------------
json_result = '{\n'
json_result += '\t "_results":[\n'
json_result += "{\n"
json_result += "\t\t"+" \"customerID\":"+str_customerID+"\n"
json_result += "\t\t"+",\"marketID\":"+str(marketID)+"\n"
json_result += "\t\t"+",\"invoice_count\":"+str(invoice_count)+"\n"
json_result += "\t\t"+",\"item_count\":"+str(item_count)+"\n"
json_result += "\t\t"+",\"invl_count\":"+str(invl_count)+"\n"
json_result += "\t\t"+",\"mean_unit_price\":"+str_mean_unit_price+"\n"
json_result += "\t\t"+",\"incomes\":"+str_incomes+"\n"
json_result += "\t\t"+",\"old_date\":"+str_old_date+"\n"
json_result += "\t\t"+",\"new_date\":"+str_new_date+"\n"
if RFM is not None:
json_result += "\t\t"+",\"RFM\":"+RFM+"\n"
else:
pass
json_result += "}\n"
json_result += '\n\t]\n}'
return json_result | [
"def toJSON(self, df) :\n ret = json.dumps(df, indent=4)\n return ret",
"def get_json(df):\n\t import json\n\t import datetime\n\t def convert_timestamp(item_date_object):\n\t if isinstance(item_date_object, (datetime.date, datetime.datetime)):\n\t return item_date_object.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function is used for validation process. It returns a list of stockCode items and a list of quantities for each item. | def get_order_lists(self, n_items, n_quantities):
arr_stock_code = self._df_invoice_original.StockCode.unique()
arr_stock_code = np.random.choice(arr_stock_code, n_items)
list_stockCode = list(arr_stock_code)
list_quantities = np.ones(arr_stock_code.shape[0])
list_quantities *=n_quantities
return list_stockCode, list_quantities | [
"def get_items(self):\n \n items = []\n\n params = self.request.query_params\n\n if 'items[]' in params:\n items = params.getlist('items[]', [])\n elif 'item' in params:\n items = [params.get('item', None)]\n\n if type(items) not in [list, tuple]:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sentence generator for an entire corpus directory. | def sentences_for_dir(path='./',separate=True,gzipped=True):
for filename in cowfiles(path):
for metadata, data in sentence_generator(filename,separate,gzipped):
yield metadata, data | [
"def gen_sentences_from_dir(path, ext=\"txt\"):\n for doc in gen_documents_from_dir(path, ext):\n for s in gen_sentences_from_string(doc):\n yield s",
"def load_data_sentences(dirname):\n sentence_list = []\n for fname in os.listdir(dirname):\n with open(os.path.join(dirname, fna... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build each tree in the 'forest' of trees. After each iteration, evaluate the tree and reweight the input sample such that incorrect events are weighted up and correct events are weighted down | def build(self):
# weights to apply to training samples, updated on each
# iteration of the boosting algo, normalised to 1
sigWeights = np.ones(self.nSig, dtype=float)
bkgWeights = np.ones(self.nBkg, dtype=float)
reweight = 1.0/(np.sum(sigWeights)+np.sum(bkgWeights))
sigWeights *= reweight
bkgWeights *= reweight
# Weight of each tree, strong classifers have higher weight
self.treeWeights = np.zeros(self.ntrees, dtype=float)
for i in xrange(self.ntrees):
# build new tree
newTree = Tree()
newTree.load(self.sigData,self.bkgData,weights=(sigWeights,bkgWeights))
newTree.build()
self.dTrees.append(newTree)
# evaluate trees
# keep track of each event
err = 0.0
sigWrong = np.zeros(self.nSig)
bkgWrong = np.zeros(self.nBkg)
for j in range(self.nSig):
if newTree.classify(np.array((self.sigData[j,])))<0:
sigWrong[i]=1
err+=sigWeights[j]
for j in range(self.nBkg):
if newTree.classify(np.array((self.bkgData[j,])))>0:
bkgWrong[i]=1
err+=bkgWeights[j]
alpha = self.beta*math.log((1.0-err)/err)
print err,alpha
corFactor = math.exp(-alpha)
wrongFactor = math.exp(alpha)
if (err<1e-20 or err >= 0.5):
print "SOEMTHING WRONG!!"
self.treeWeights[i] = alpha
# reweight training samples
for j in range(self.nSig):
if sigWrong[j]:
sigWeights[j]*=wrongFactor
else :
sigWeights[j]*=corFactor
for j in range(self.nBkg):
if bkgWrong[j]:
bkgWeights[j]*=wrongFactor
else :
bkgWeights[j]*=corFactor
# normalise weights
reweight = 1.0/(np.sum(sigWeights)+np.sum(bkgWeights))
sigWeights *= reweight
bkgWeights *= reweight | [
"def grow_forest(forest, X, y, seeds, labels=None):\n # Convert data\n X, = check_arrays(X, dtype=DTYPE, sparse_format=\"dense\")\n # Make a list container for grown trees\n n_trees = forest.n_estimators\n trees = []\n # For each tree in the forest\n for i in range(n_trees):\n # Make a n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
classify a given event. Iterates over each tree in the forest and then returns the weighted average of the results | def classify(self, event):
results = np.zeros(self.ntrees, dtype=float)
for i,dt in enumerate(self.dTrees):
results[i] = self.treeWeights[i]*dt.classify(event)
return np.sum(results)*(1.0/np.sum(self.treeWeights)) | [
"def analyze_tree(dataset,my_tree,column_class=-1):\n #get the relevant starting variables\n labels = dataset[:,column_class]\n N, class_num = np.shape(dataset)\n datapred = np.zeros(N)\n #now loop and get the predictions\n for i in range(N):\n prediction = predict_tree(dataset[i,:], my_tre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Node frontiers generator using breadthfirst search. | def bfs_nodes_generator(graph, source, reverse=...):
... | [
"def breadthfirst(self):\n import os\n cwd = os.getcwd()\n os.chdir('/Users/raj/Documents/algorithms_in_python/linked_lists/')\n from linked_collections import LinkedQueue\n os.chdir(cwd) # change to cwd\n if not self.is_empty():\n lq = LinkedQueue()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Edges frontiers generator using breadthfirst search. | def bfs_edges_generator(graph, source, reverse=...):
... | [
"def bfs_nodes_generator(graph, source, reverse=...):\n ...",
"def breadthfirst(self):\n import os\n cwd = os.getcwd()\n os.chdir('/Users/raj/Documents/algorithms_in_python/linked_lists/')\n from linked_collections import LinkedQueue\n os.chdir(cwd) # change to cwd\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Node frontiers generator using topological traversal. | def topological_nodes_generator(graph, reverse=...):
... | [
"def bfs_nodes_generator(graph, source, reverse=...):\n ...",
"def _get_front_nodes(self):\n ret = []\n node = self.root.getprevious()\n while node is not None:\n ret.append(node)\n node = node.getprevious()\n return ret",
"def breadth_first_iterate(execution... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Edge frontiers generator using depthfirstsearch (DFS). Multiple source nodes can be specified to start the DFS traversal. One needs to make sure that each source node belongs to different connected component, so the frontiers can be easily merged. Otherwise, the behavior is undefined. | def dfs_edges_generator(graph, source, reverse=...):
... | [
"def bfs_nodes_generator(graph, source, reverse=...):\n ...",
"def breadth_first_search(self, source: int) -> list:\n # Time complexity: O(num_vertices + num_edges), aka O(V+E)\n \n # Note: This initialization is a must, since other methods may change defaults\n self.color = [Color.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find the feature to use for the next node split and also find where the plit should be in that feature This loops through the split options within a feature to find the best gini score, then it loops through each feature to compare optimal gini scores | def find_split(self, X, y):
choices = y.size
if choices <= 1:
return None, None
# find the number of each option in the current node.
options_parent = [np.sum(y == c) for c in range(self.num_outcomes)]
# find the gini of current node.
best_gini = 1.0 - sum((n / choices) ** 2 for n in options_parent)
best_idx, best_split = None, None
# loop through the features to get splits and options.
for idx in range(self.num_features):
splits, options = zip(*sorted(zip(X[:, idx], y)))
num_left = [0] * self.num_outcomes
num_right = options_parent.copy()
for i in range(1, choices):
c = options[i - 1]
num_left[c] += 1
num_right[c] -= 1
gini_left = 1.0 - sum(
(num_left[x] / i) ** 2 for x in range(self.num_outcomes)
)
gini_right = 1.0 - sum(
(num_right[x] / i) ** 2 for x in range(self.num_outcomes)
)
gini = (i * gini_left + (choices - i) * gini_right) / choices
if splits[i] == splits[i - 1]:
continue
if gini < best_gini:
best_gini = gini
best_idx = idx
best_split = (splits[i] + splits[i - 1]) / 2
return best_idx, best_split | [
"def find_best_split(data, feature_names, min_samples_leaf=5, random_subset=False, column_class=-1):\n N, f_n = np.shape(data)\n n = f_n - 1\n root_n = int(np.ceil(np.sqrt(n)))\n if (column_class == -1):\n column_class = f_n - 1\n if (random_subset == True):\n list_features = np.random.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A class without the key_fields annotation should raise a RuntimeError | def testNoKeyFields():
with pytest.raises(RuntimeError):
class AnnotatedNode(Node):
x: str
y: int
def __init__(self, x: str, y: int):
self.x = x
self.y = y
@property
def _display(self) -> str:
return self.x | [
"def test_key_init_inconsistent_fields(self):\n # Modify the class to add a bogus field name that is not in the DB\n TestMappings.index_fields.append('bad_field')\n tm = Keys(TestMappings)\n # Remove the field name again (or get horrible stuff in rest of tests)\n TestMappings.inde... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
creates randomized colors of shape size_x by size_y | def create_world(size_x = 100, size_y=100):
colors = np.random.randint(0,2,(size_x,size_y)).tolist()
for row in range(len(colors)):
for col in range(len(colors[row])):
if (colors[row][col]== 1):
colors[row][col] = 'R'
else:
colors[row][col] = 'G'
r = [[10.0 for i in range(size_y)] for i in range(size_x)]
g = [[10.0 for i in range(size_y)] for i in range(size_x)]
b = [[10.0 for i in range(size_y)] for i in range(size_x)]
RGB = []
for i in range(size_x):
for j in range(size_y):
if colors[i][j] == 'R':
r[i][j] = 255.0
else:
b[i][j] = 255.0
RGB.append(b[i][j])
RGB.append(r[i][j])
RGB.append(g[i][j])
RGB = np.array(RGB).reshape(size_x,size_y,3)
return RGB, colors | [
"def generate_random_colors(self):\n colors = [(random.randint(0, 200), random.randint(0, 200), random.randint(0, 255)) for _ in range(32)]\n grid = []\n for color in colors:\n grid.extend([color, color])\n grid[self.special_coord[0] + (self.special_coord[1] * 8)] = self.speci... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds a dihedral angle adjacent to the selected atoms that includes a new atom | def _find_dihedral(selected):
atom_name = lambda atom: atom.fullName()
atom_mass = lambda atom: atom.mass()
# Loop over possible nearest neighbors
for a2 in selected:
# Find the new atom
attached_to_a2 = sorted([a for a in a2.bondedTo() \
if a not in selected], key=atom_name)
for a1 in sorted(attached_to_a2, key=atom_mass, reverse=True):
# Find the third atom
attached_to_a3 = sorted([a for a in a2.bondedTo() \
if (a in selected) and (a!=a1)], key=atom_name)
for a3 in sorted(attached_to_a3, key=atom_mass, reverse=True):
# Find the last atom
attached_to_a4 = sorted([a for a in a3.bondedTo() \
if (a in selected) and (a!=a2)], key=atom_name)
for a4 in sorted(attached_to_a4, key=atom_mass, reverse=True):
return (a1, a2, a3, a4)
print 'Selected atoms:', selected
raise Exception('No new dihedral angle found!') | [
"def dihedral_calculator():\n\n\t# Prime with first 3 points\n\tp1 = Vector3((yield None))\n\tp2 = Vector3((yield None))\n\tp3 = Vector3((yield None))\n\n\t# Set up for first angle\n\tlastpoint = p3\n\tlastdisp = p3 - p2\n\tlastnormal = ((p2 - p1) @ lastdisp).normalize()\n\n\tangle = None\n\n\t# For each point star... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Conversion from (internal or extended) BondAngleTorsion to Cartesian coordinates | def Cartesian(self, BAT):
# Arrange BAT coordinates in convenient arrays
offset = 6 if len(BAT) == (3 * self.natoms) else 0
bonds = BAT[offset + 3::3]
angles = BAT[offset + 4::3]
phase_torsions = BAT[offset + 5::3]
torsions = [(phase_torsions[n] + phase_torsions[self._firstTorsionTInd[n]]) \
if self._firstTorsionTInd[n]!=n else phase_torsions[n] \
for n in range(self.ntorsions)]
p1 = np.array([0., 0., 0.])
p2 = np.array([0., 0., BAT[offset]])
p3 = np.array([BAT[offset+1]*np.sin(BAT[offset+2]), 0., \
BAT[offset]-BAT[offset+1]*np.cos(BAT[offset+2])])
# If appropriate, rotate and translate the first three atoms
if offset == 6:
# Rotate the third atom by the appropriate value
(phi, theta, omega) = BAT[3:6]
co = np.cos(omega)
so = np.sin(omega)
Romega = np.array([[co, -so, 0], [so, co, 0], [0, 0, 1]])
p3 = Romega.dot(p3)
# Rotate the second two atoms to point in the right direction
cp = np.cos(phi)
sp = np.sin(phi)
ct = np.cos(theta)
st = np.sin(theta)
Re = np.array([[cp * ct, -sp, cp * st], [ct * sp, cp, sp * st],
[-st, 0, ct]])
p2 = Re.dot(p2)
p3 = Re.dot(p3)
# Translate the first three atoms by the origin
origin = np.array(BAT[:3])
p1 += origin
p2 += origin
p3 += origin
XYZ = np.zeros((self.natoms, 3))
XYZ[self.rootInd[0]] = p1
XYZ[self.rootInd[1]] = p2
XYZ[self.rootInd[2]] = p3
for ((a1,a2,a3,a4), bond, angle, torsion) in \
zip(self._torsionIndL,bonds,angles,torsions):
sphere = Sphere(Vector(XYZ[a2]), bond)
cone = Cone(Vector(XYZ[a2]), Vector(XYZ[a3] - XYZ[a2]), angle)
plane123 = Plane(Vector(XYZ[a4]), Vector(XYZ[a3]), Vector(XYZ[a2]))
points = sphere.intersectWith(cone).intersectWith(plane123)
p = points[0] if (Plane(Vector(XYZ[a3]), Vector(
XYZ[a2]), points[0]).normal * plane123.normal) > 0 else points[1]
p = rotatePoint(Vector(p),
Line(Vector(XYZ[a2]), Vector(XYZ[a2] - XYZ[a3])),
torsion)
XYZ[a1] = p.array
return XYZ
for ((a1,a2,a3,a4), bond, angle, torsion) in \
zip(self._torsionIndL,bonds,angles,torsions):
p2 = XYZ[a2]
p3 = XYZ[a3]
p4 = XYZ[a4]
# circle = sphere.intersectWith(cone)
n23 = normalize(p3 - p2)
# points = circle.intersectWith(plane123)
# plane.intersectWith(Plane(circle.center, circle.normal)) is a line
# line_direction = cross(normalize(cross(p4-p3,n23)),n23)
# Rotate the point about the p2-p3 axis by the torsion angle
v21 = (bond * np.cos(angle)) * n23 - (bond * np.sin(angle)) * cross(
normalize(cross(p4 - p3, n23)), n23)
s = np.sin(torsion)
c = np.cos(torsion)
XYZ[a1] = p2 - cross(n23, v21) * s + np.sum(
n23 * v21) * n23 * (1.0 - c) + v21 * c | [
"def cartesian2polar(cartesian):\n cartesian = np.array(cartesian).squeeze()\n x, y = cartesian\n r = np.linalg.norm([x, y])\n azimuth = np.arctan2(y, x)\n return np.array([r, azimuth])",
"def to_cartesian(self):\n w = 1.73205 # sqrt(3)\n h = 2\n dx = 0.5 * w if self.y % 2 == ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Opens the molecule in VMD | def showMolecule(self, colorBy=None, label=False, dcdFN=None):
# Write PDB file
# To set Occupancy, change atom.occupancy
# To set Beta, change atom.temperature_factor
import os.path
pdbFN = os.path.join(MMTK.Database.molecule_types.directory,
'showMolecule.pdb')
outF = MMTK.PDB.PDBOutputFile(pdbFN)
outF.write(self.molecule)
outF.close()
# Write VMD script
script = 'set ligand [mol new ' + pdbFN + ']\n'
if colorBy is not None:
script += 'mol modcolor 0 $ligand ' + colorBy + '\n'
script += 'mol modstyle 0 0 CPK 1.000000 0.300000 10.000000 10.000000\n'
if label:
script += """
proc label_atoms { molid seltext } {
set sel [atomselect $molid $seltext]
set atomlist [$sel list]
foreach {atom} $atomlist {
set atomlabel [format "%d/%d" $molid $atom]
label add Atoms $atomlabel
}
$sel delete
}
label_atoms 0 all
"""
if dcdFN is not None:
script += 'animate delete all $ligand\n'
script += 'mol addfile ' + dcdFN + ' type dcd waitfor all\n'
scriptF = open('showMolecule.vmd', 'w')
scriptF.write(script)
scriptF.close()
# Find and run vmd
import AlGDock
vmdCommand = AlGDock.findPath(AlGDock.search_paths['vmd'])
import subprocess
subprocess.call([vmdCommand, '-e', 'showMolecule.vmd'])
# Remove files
os.remove(pdbFN)
os.remove('showMolecule.vmd') | [
"def open_mdd(self):\n import webbrowser\n\n mdd, *_ = self.simulation_dir.files(\"*.mdd\")\n\n webbrowser.open(mdd.abspath())",
"def viewNMDinVMD(filename):\n\n vmd = pathVMD()\n if vmd:\n os.system('{0} -e {1}'.format(vmd, abspath(filename)))",
"def _vmd_script_molecule(mole,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test read and write ints. | def test_message_int():
result = True
message = msg.Message()
for i in range(num_it):
message.appendInt(i)
if message.length != msg.HEADER_SIZE + (i+1)*msg.intStruct.size:
print("Size is ", message.length, " but should be ", msg.HEADER_SIZE + (i+1)*msg.intStruct.size)
print("Error : message.appendInt")
result = False
message.resetCursor()
for i in range(num_it):
r = message.readInt()
if r != i:
print(r, " vs ", i)
print("Error : message.read/appendInt")
result = False
return result | [
"def testSimpleReadWrite(self):\n write_data = self.GetRandomIntegers(2048)\n read_data = []\n # Writer writes some data.\n asserts.assertTrue(\n self._queue1_writer.write(write_data, 2048), \"Write queue failed.\")\n # Check reader reads them back correctly.\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handles a leave game request. Deletes the user from the game. | def leave_game(players_cursor, states_cursor, user, room_id):
leave_query = '''DELETE FROM players_table WHERE user = ? AND room_id = ?'''
players_cursor.execute(leave_query, (user, room_id))
FRAMES.append(display_game(players_cursor, states_cursor, user, room_id)) | [
"def leave(msg: telebot.types.Message):\n if utils.in_menu(msg.from_user):\n bot.reply_to(\n msg,\n 'This command outside of game is useless.'\n )\n return\n\n game, user, opponent = utils.get_game_user_opponent(msg.from_user)\n if not game or not user:\n #... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Select Relationships associated with specified fact_id. | def select_by_fact_id(cls, fact_id):
return db.session.query(cls).filter_by(fact_id=fact_id).all() | [
"def read_relationships(person_id):\n try:\n conn = sqlite3.connect(settings.database_name)\n conn.row_factory = sqlite3.Row\n c = conn.cursor()\n c.execute(\"PRAGMA foreign_keys = ON\")\n c.execute(relationship_query, (person_id,)) # note a tuple is needed as a parameter valu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Select Relationship with specified subject, object and relationship type. | def select_by_foreign_keys(cls, subject_id=None, object_id=None, relationship_type_id=None):
filter_clause = sa.and_(
sa.and_(cls.subject_id == subject_id, cls.object_id == object_id),
cls.relationship_type_id == relationship_type_id)
return db.session.query(cls).filter(filter_clause).first() | [
"def select_by_values(cls, relationship_type_name=None, relationship_number=None,\n subject_name=None, object_name=None):\n query = db.session.query(cls).\\\n join(RelationshipType).\\\n filter(RelationshipType.relationship_type_name==relationship_type_name)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Select Relationships with specified relationship_type, count, subject, and object. | def select_by_values(cls, relationship_type_name=None, relationship_number=None,
subject_name=None, object_name=None):
query = db.session.query(cls).\
join(RelationshipType).\
filter(RelationshipType.relationship_type_name==relationship_type_name)
if relationship_number:
query = query.filter(Relationship.count==relationship_number)
if subject_name:
subject_concept = sa_orm.aliased(Concept)
query = query.\
join(subject_concept, Relationship.subject_id==subject_concept.concept_id).\
filter(subject_concept.concept_name==subject_name)
if object_name:
object_concept = sa_orm.aliased(Concept)
query = query.\
join(object_concept, Relationship.object_id==object_concept.concept_id).\
filter(object_concept.concept_name==object_name)
return query.all() | [
"def select_by_foreign_keys(cls, subject_id=None, object_id=None, relationship_type_id=None):\n filter_clause = sa.and_(\n sa.and_(cls.subject_id == subject_id, cls.object_id == object_id),\n cls.relationship_type_id == relationship_type_id)\n return db.session.query(cls).filter(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate requests decorator with Cerberus | def validate_request_cerberus(schema):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
body_json = request.get_json()
current_app.logger.info(body_json)
v = Validator(schema, require_all=True)
v.allow_unknown = True # TODO: allow request params other then the ones defined on the schema level
if not v.validate(body_json):
valid_params_list = ', '.join(schema.keys())
return response_fail(f"You must call with all request params: {valid_params_list}")
return func(*args, **kwargs)
return wrapper
return decorator | [
"def validate_request(self, func):\n @wraps(func)\n def decorated_view(*args, **kwargs):\n if current_app.TESTING:\n return func(*args, **kwargs)\n url = request.base_url\n vars = request.values\n signature = request.header.get('X-Twilio-Signa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plots the graph. If the nodes have a position, the nodes will be placed there. Otherwise, they will be placed in a random but elegant manner. | def plot_graph(self) -> None: | [
"def plot_graph(self):\r\n x = []\r\n y = []\r\n\r\n for n in self.graph.get_all_v().values():\r\n if(n.get_pos() != None):\r\n x.append(n.get_pos().get_x())\r\n y.append(n.get_pos().get_y())\r\n else:\r\n x_random = random.rand... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Formats comparison as a strings | def format_comparison(objs):
def formatter(comp):
if not isinstance(comp, tuple):
return str(comp)
output = []
return "\n".join([comp.type] + [" "+errmessage for errmessage in output])
results = map(formatter,objs)
return "\n".join(results)
#obj1,obj2 = comp
### Sections
#for i,s1,s2 in diffs:
# if s1 and s2:
# output.append(f"Section {i} does not match:")
# result = compare_sections(s1,s2)
# output.extend(almethods.linepadder(result))
# else:
# if s1:
# output.append(f"Door 2 missing Section {i}")
# else:
# output.append(f"Door 1 missing Section {i}") | [
"def generate_comparison_output_string(comparisons: List[Dict[str, Any]]) -> str:\n result_dict = generate_comparison_dict(comparisons)\n result_string = json.dumps(result_dict, sort_keys=True, indent=4)\n return result_string",
"def format_condition(self, key, val1, val2):\n if val1 is not None a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Catches a difference when one or both of the objects are None (since it is handled the same across methods) | def none_comparison(func):
@functools.wraps(func)
def inner(obj1,obj2):
if obj1 is not None and obj2 is not None:
return func(obj1, obj2)
if obj1 is None and obj2 is None:
return []
if obj1 is not None and obj2 is None:
return Difference(f"Second {obj1.__class__.__name__} is None",(obj1,None))
return Difference(f"First {obj2.__class__.__name__} is None",(None,obj2))
return inner | [
"def ifnone(a: Any, b: Any) -> Any:\n return b if a is None else a",
"def _check_none(self) -> PossibleResult[T]:\n if self.constructor == type(None):\n if not self.obj is None:\n raise DeserializeError(\n type(None), self.obj, self.new_depth, self.key\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compares Attributes between 2 objects via getattr, returning the attribute values as a tuple if they do not match | def attr_comparison(obj1,obj2,attrs):
return [Difference(f"{obj1.__class__.__name__}.{attr}",(result1,result2)) for attr in attrs if (result1 := getattr(obj1,attr)) != (result2 := getattr(obj2,attr))] | [
"def attrs_to_tuple(obj):\n return tuple(getattr(obj, a) for a in attrs)",
"def CheckAttribs(a, b, attrs, assertEquals):\n # For Stop objects (and maybe others in the future) Validate converts some\n # attributes from string to native type\n a.Validate()\n b.Validate()\n for k in attrs:\n assertEqu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a list of tuples comparised of (subcomparison method, attr name for comparison), returns any Difference tuple retunred by each method using the given attr of obj1 and obj2 as arguments (if that method is not None) | def sub_comparison(obj1,obj2,translate):
return [Difference(f"{obj1.__class__.__name__} > {meth.__name__}",result) for (meth,attr) in translate if (result := meth(getattr(obj1,attr),getattr(obj2,attr))) is not None] | [
"def attr_comparison(obj1,obj2,attrs):\n return [Difference(f\"{obj1.__class__.__name__}.{attr}\",(result1,result2)) for attr in attrs if (result1 := getattr(obj1,attr)) != (result2 := getattr(obj2,attr))]",
"def sortByMethodCall(objList, tag):\n # replaces sortByName and sortByQualName\n \n ll = [(getattr(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Postmortem, using a custom debug function if passed | def post_mortem(*args, debug_fn: Optional[Callable] = None, **kwargs) -> None:
if debug_fn is None:
import pdb
debug_fn = pdb.post_mortem
debug_fn() | [
"def debugger_step_over():",
"def debug():",
"def debugTestRunner(post_mortem=None):\n if post_mortem is None:\n post_mortem = pdb.post_mortem\n class DebugTestResult(unittest.TextTestResult):\n def addError(self, test, err):\n # called before tearDown()\n traceback.pri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Simple forward step with crossentropy loss. | def _cross_entropy_forward_step(batch, model):
timers = get_timers()
# Get the batch.
timers('batch-generator', log_level=2).start()
try:
batch_ = next(batch)
except BaseException:
batch_ = batch
tokens, types, labels, attention_mask = process_batch(batch_)
timers('batch-generator').stop()
# Forward model.
output_tensor = model(tokens, attention_mask, tokentype_ids=types)
return output_tensor, partial(cross_entropy_loss_func, labels) | [
"def forward_train(self, *args, **kwargs):\n pass",
"def forward(self, X, training=False):\n pass",
"def forward_pass(self, x, targets=None):\n self.x = x\n self.targets = targets\n \n # Input layer\n out = self.layers[0].forward_pass(x)\n \n # Forward...\n for layer in sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build a looped dataloader with infinite size. | def _build_infinite_size_dataloader(dataloader):
iterator = dataloader.__iter__()
while True:
try:
yield iterator.__next__()
except StopIteration:
iterator = dataloader.__iter__() | [
"def create_reader_op(self, feed_list):\n reader = fluid.io.DataLoader.from_generator(feed_list=feed_list, \n capacity=256, iterable=True, use_double_buffer=True)\n\n return reader",
"def data_gen_infinite(self, batch_sz):\n g = self.data_gen_finite(batch_sz)\n whil... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Construct solver from Caffe solver prototxt file. | def from_caffe_solver_protoxt(cls, caffe_solver_prototxt_file: Path):
solver_param = caffe_pb2.SolverParameter()
with open(caffe_solver_prototxt_file, 'rt') as f:
pb2.text_format.Merge(f.read(), solver_param)
dictionary = {'lr_policy': solver_param.lr_policy,
'base_lr': solver_param.base_lr,
'gamma': solver_param.gamma,
'momentum': solver_param.momentum,
'max_iter': solver_param.max_iter,
'stepsize': solver_param.stepsize,
'stepvalues': solver_param.stepvalue,
'weight_decay': solver_param.weight_decay,
'iter_size': solver_param.iter_size,
'from_prototxt': caffe_solver_prototxt_file}
return cls(**dictionary) | [
"def from_file(self, file_path):\n clauses = []\n varnum = 0\n with open(file_path, 'r') as file:\n for line in file:\n if line.startswith(\"c\"):\n continue\n if line.startswith(\"p\"):\n tmp = line.split()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Refreshes the Job's details by querying the workspace. | def refresh(self):
self.details = self.workspace.get_job(self.id).details | [
"def refresh(self): # noqa\n data = self.connection.hgetall(self.key)\n if not data:\n raise NoSuchJobError('No such job: {0}'.format(self.key))\n self.restore(data)",
"def _reload(self):\n pr = Project(path=self._job_project_path)\n self._job = pr.load(self._job_nam... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a unique id for a new job. | def create_job_id() -> str:
return str(uuid.uuid1()) | [
"def assign_job_id(self):\n num_string = str(randint(0, 10000)).zfill(5)\n job_id = self.jobname + str(num_string) + datetime.today().strftime(\"%Y%m%d\")\n return job_id",
"def _generate_job_id():\n # CAIP job id can contains only numbers, letters and underscores.\n unique_tag = str(uu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Applies post processing to all the outputs in the provided run results. This is a convenience function to avoid the need for manual iteration over the run_results dictionary. | def postprocess(run_results, postprocess_func):
G_LOGGER.start(f"Applying post-processing to outputs: {postprocess_func.__name__}")
for _, iteration_results in run_results:
for index, iter_res in enumerate(iteration_results):
iteration_results[index] = postprocess_func(iter_res)
G_LOGGER.finish("Finished applying post-processing")
return run_results | [
"def postprocess(self, results):\n return results",
"def process_results(self, results):\n\t\traise NotImplementedError()",
"def postprocess_result(self):\n pass",
"def process(self, results):\n raise NotImplementedError",
"def postprocess_model_results(results, model_data, timings):\n l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Turns Freshbooks tickets from the past x days into Toggl projects. | def sync(self, no_of_days=1):
zd = Zendesk()
tg = Toggl()
try:
self.print("Syncing...")
self.print_divider(30)
tickets = zd.get_tickets(no_of_days)
for ticket in tickets:
project_title = self.format_title(ticket.id, ticket.subject)
if ticket.organization:
client_id = tg.get_client_id(name=ticket.organization.name)
if not client_id:
new_client = tg.create_client(ticket.organization.name)
client_id = new_client['id']
else:
client_id = False
self.print("Ticket '%s' has no associated organization!" % (project_title))
all_projects = tg.get_projects()
if not self.already_created(ticket.id, all_projects):
self.print("Creating project '%s'..." % (project_title))
result = tg.create_project(project_title, client_id, is_private=False)
self.print("Toggl response:")
self.log(result, silent=False)
else:
self.print("There is already a Toggl project for Zendesk ticket #%s!" % ticket.id)
pass
# TODO: edit Toggl project
# tg.edit_project(project_id, name=ticket.subject)
self.print_divider(30)
self.print("Done!")
except:
self.log(traceback.format_exc(), silent=False) | [
"def get_project_tickets(\n jira: Jira,\n project: str,\n insert_blank_tickets: bool = True,\n verbose: bool = True,\n) -> List[JiraTicket]:\n # Offsets for the API\n init = 0\n size = 100\n\n # Store all the API tickets to sort through later. Keys for this are\n # ticket number. Values a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Starts interactive time tracking session. Updates Freshbooks based on Toggl entries. | def time_tracking(self):
fb = FreshBooks()
tg = Toggl()
self.print_splash()
self.print("Tip: You can always enter 'skip' when you want to skip a time entry.", format='warn')
days = self.get_interactive_days() # number of days to go back
self.print("OK, I'll run you through the Toggl time entries of the past %i day(s)." % (days))
timestamp = self.get_timestamp(days) # unix timestamp including tz
time_entries = tg.get_time_entries(timestamp)
if len(time_entries) == 0:
self.print("No Toggl entries in this time span!", 'warn')
return False
time_entries = self.merge_toggl_time_entries(time_entries) # merge Toggl entries
fb_projects = fb.get_projects()
# Loop through merged Toggl time entries:
for entry in time_entries:
# Get and convert all necessary info:
client_id = tg.get_client_id(project_id=entry.get('pid'))
client_name = tg.get_client_name(client_id)
project = tg.get_project(entry.get('pid'))
duration = int(entry['duration']) / 60 / 60 # convert duration to hours
duration = round(duration * 4 ) / 4 # round hours to nearest .25
description = self.format_description(project['name'], entry['description'])
date = str(parser.parse(entry['start']).date())
# Print info in a nice way:
self.print_divider(30)
self.print("Description: " + description)
self.print("Date: " + date)
self.print("Hours spent: " + str(duration))
# Skip if Toggl entry is already booked:
if entry.get('tags') and tg.BOOKED_TAG in entry['tags']:
self.print("Skipping this entry because it is already in Freshbooks.", 'cross')
# Skip if duration is below 0.25:
elif duration < 0.25:
self.print("Skipping this entry because there are less than 0.25 hours spent.", 'cross')
# If billable, add to Freshbooks:
elif entry['billable']:
# Get FreshBooks project name through interactive search:
try:
self.print("Project: \U0001F50D ")
fb_project_name = self.interactive_search(fb_projects.keys(), client_name)
# Handle KeyboardInterrupt
except KeyboardInterrupt:
answer = input("\nKeyboardInterrupt! Skip current entry or quit time tracking? (S/q) ")
if answer.lower() == 's' or answer == '':
self.clear_lines(1)
self.print("Skipping this entry.", 'cross')
continue
else:
self.clear_lines(1)
self.print("Ok, stopping time tracking.", 'cross')
sys.exit()
# If user requests so, skip this entry:
self.clear_lines(1)
if not fb_project_name:
self.print("Skipping this entry.", 'cross')
continue
# Otherwise, add entry to FreshBooks and tag Toggl entry/entries:
self.print("Project: " + fb_project_name)
project_id = fb.get_project_id(fb_project_name)
fb.add_entry(project_id, duration, description, date)
tg.tag_projects(entry['merged_ids'], tg.BOOKED_TAG)
# If not billable, skip entry:
else:
self.print("Skipping this entry because it is not billable.", 'cross')
self.print_divider(30)
answer = input("All done! Open FreshBooks in browser to verify? (Y/n) ")
if answer.lower() == 'y' or answer == '':
webbrowser.open('https://%s.freshbooks.com/timesheet' % fb.fb_creds['subdomain']) | [
"def setTrackStartTime() :\n s.startTrack()",
"def start():\n start_tracking()",
"def main():\n\n # Step 0:\n # Print lovley greetings.\n print(\"\"\"\n ------\n > Welcome to Værmelder!\n > Store your room climate into your OneDrive!\n ------\"\"\")\n\n # Step 1.\n # Get access ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Starts interactive search, allows user to make a selection. Accepts array of strings and optional (user) query. Returns string chosen by user. | def interactive_search(self, choices, query=None):
if query:
match = self.get_interactive_match(choices, query)
if match:
self.print("Matched query to '%s'." % (match))
answer = input("Is that correct? (Y/n) ")
self.clear_lines(1)
if answer.lower() == 'y' or answer == '':
self.clear_lines(1)
return match
else:
self.clear_lines(1)
return self.interactive_search(choices)
else:
return None
else:
query = input("Please type a query: ")
self.clear_lines(1)
return self.interactive_search(choices, query) | [
"def launch_search(self):\n \n # gets the active selections from pymol\n active_selections = cmd.get_names('selections', 1)\n if len(active_selections) == 0:\n cmd.get_wizard().set_status('no selection')\n else:\n\n selection = active_selections[0]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns string that best matches query out of a list of choices. Prompts user if unsure about best match. | def get_interactive_match(self, choices, query):
if query in self.SKIP_KEYWORDS:
return None
results = process.extract(query, choices, limit=10) # fuzzy string matching
best_match = results[0]
second_best_match = results[1]
if best_match[1] == second_best_match[1] or best_match[1] < 50: # if inconclusive or low score
self.print("Couldn't find a conclusive match for '%s'. Best matches:" % (query))
i = 0
for result in results:
i += 1
print(" [%i] %s" % (i, result[0]))
answer = input("Choose one or specify a less ambiguous query: ")
self.clear_lines(2 + len(results))
if answer.isdigit() and int(answer) <= len(results):
return results[int(answer) - 1][0]
else:
return self.get_interactive_match(choices, answer)
else:
return best_match[0] | [
"def interactive_search(self, choices, query=None):\n if query:\n match = self.get_interactive_match(choices, query)\n if match:\n self.print(\"Matched query to '%s'.\" % (match))\n answer = input(\"Is that correct? (Y/n) \")\n self.clear_lin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Asks an user how many days to go back. Returns int. | def get_interactive_days(self):
answer = input("Press return to get entries of past day or input number of days to go back in time: ")
if answer == '':
days = 1
else:
try:
days = int(answer)
except:
print("You didn't enter a number, assuming 1 day.")
days = 1
return days | [
"def guessDown(self):\n self.guesses = self.guesses - 1",
"def days_back(i):\n yesterday = (datetime.now() - timedelta(i))\n return yesterday.strftime('%Y-%m-%d')",
"def remaining_days(requested_on: datetime.datetime, slo_limit: int) -> int:\n # Positive: There are days remaining.\n # Zer... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Hacky way to check if this function already made a Toggl project based on a Zendesk ticket ID. | def already_created(self, ticket_id, toggl_projects):
project_prepends = [p['name'].split()[0][1:] for p in toggl_projects]
if str(ticket_id) in project_prepends:
return True
return False | [
"async def check_if_is_ticket(ctx):\n channel : TextChannel = ctx.channel\n return 'ticket-' in channel.name",
"def has_project(cls, win_id):\r\n\r\n project = cls.get_project(win_id)\r\n return True if project is not None else False",
"def project_exists(response, project):\n if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Formats id and subject into a suitable (Freshbooks) title. | def format_title(self, ticket_id, subject):
# TODO: strip block tags?
title = "#%i %s" % (ticket_id, subject)
return title.strip() | [
"def get_subject_name(id):\n if id < 10:\n return 'sub-00{}'.format(id)\n elif id < 100:\n return 'sub-0{}'.format(id)\n else:\n return 'sub-{}'.format(id)",
"def BuildSubjectTitle(self):\n return u\"hunt %s\" % self.args.subject_urn.Basename()",
"def get_title_by_id(id):\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Formats Toggl project name and description into (Freshbooks) description. | def format_description(self, project_name, description):
description = description if description else ''
return "%s %s" % (project_name, '- ' + description) | [
"def parse_project_file(self, project_file):\n project_name = None\n lines = []\n with open(project_file, \"rt\") as f:\n for line in f:\n # Finding the project name\n if \"Short Project Name\" in line:\n project_name = line.split(\":\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Merges toggle time entries with same project name. Sums duration if billable. | def merge_toggl_time_entries(self, time_entries):
tg = Toggl()
d = {}
for entry in time_entries:
if entry.get('billable'):
if entry.get('tags') and tg.BOOKED_TAG in entry['tags']:
status = 'booked'
else:
status = 'not-booked'
date = parser.parse(entry['start']).date()
if not entry.get('pid'):
self.log("Couldn't find associated project for entry: %s" % (str(entry)))
continue
unique_id = str(entry['pid']) + str(date) + status
if not entry.get('description'):
entry['description'] = ""
if d.get(unique_id):
d[unique_id]['duration'] += entry['duration']
d[unique_id]['merged_ids'].append(entry['id'])
if d[unique_id].get('description'):
if entry['description'].strip() not in d[unique_id]['description']:
d[unique_id]['description'] += ' / ' + entry['description']
else:
d[unique_id]['description'] = entry['description']
else:
entry['merged_ids'] = [entry['id']]
d[unique_id] = entry
return d.values() | [
"def work_timing_merge(self):\n work = self.work_timing()\n work[-2].merge(work[-1])\n work.pop()\n self.set_work_timing(work)",
"def _task_data(self):\n output = {\n 'all': [],\n 'open': [],\n 'open_hours': 0,\n 'done': [],\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |