signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
@button.command('<STR_LIT>')<EOL>@click.option('<STR_LIT>', prompt="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>@click.option('<STR_LIT>', prompt="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>@click.option('<STR_LIT>', prompt="<STR_LIT>", default="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>@click.option('<STR_LIT>', prompt="<STR_LIT>", default="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>@click.option('<STR_LIT>', prompt="<STR_LIT>", default="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>@click.option('<STR_LIT>', prompt="<STR_LIT>", default="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>def write_config(ip, mac, single, double, long, touch): | click.echo("<STR_LIT>" % ip)<EOL>data = {<EOL>'<STR_LIT>': single,<EOL>'<STR_LIT>': double,<EOL>'<STR_LIT>': long,<EOL>'<STR_LIT>': touch,<EOL>}<EOL>request = requests.post(<EOL>'<STR_LIT>'.format(ip, URI, mac), data=data, timeout=TIMEOUT)<EOL>if request.status_code == <NUM_LIT:200>:<EOL><INDENT>click.echo("<STR_LIT>" % mac)<EOL><DEDENT> | Write the current configuration of a myStrom button. | f15248:m4 |
@button.command('<STR_LIT>')<EOL>@click.option('<STR_LIT>', prompt="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>@click.option('<STR_LIT>', prompt="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>@click.option('<STR_LIT>', prompt="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>@click.option('<STR_LIT>', prompt="<STR_LIT>",<EOL>default="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>@click.option('<STR_LIT>', prompt="<STR_LIT>", default="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>def write_ha_config(ip, mac, hass, port, id): | click.echo("<STR_LIT>" % ip)<EOL>action = "<STR_LIT>"<EOL>data = {<EOL>'<STR_LIT>': action.format('<STR_LIT>', hass, port, id),<EOL>'<STR_LIT>': action.format('<STR_LIT>', hass, port, id),<EOL>'<STR_LIT>': action.format('<STR_LIT>', hass, port, id),<EOL>'<STR_LIT>': action.format('<STR_LIT>', hass, port, id),<EOL>}<EOL>request = requests.post(<EOL>'<STR_LIT>'.format(ip, URI, mac), data=data, timeout=TIMEOUT)<EOL>if request.status_code == <NUM_LIT:200>:<EOL><INDENT>click.echo("<STR_LIT>" % ip)<EOL>click.echo("<STR_LIT>"<EOL>"<STR_LIT>" % id)<EOL><DEDENT> | Write the configuration for Home Assistant to a myStrom button. | f15248:m5 |
@button.command('<STR_LIT>')<EOL>@click.option('<STR_LIT>', prompt="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>@click.option('<STR_LIT>', prompt="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>def reset_config(ip, mac): | click.echo("<STR_LIT>" % ip)<EOL>data = {<EOL>'<STR_LIT>': "<STR_LIT>",<EOL>'<STR_LIT>': "<STR_LIT>",<EOL>'<STR_LIT>': "<STR_LIT>",<EOL>'<STR_LIT>': "<STR_LIT>",<EOL>}<EOL>request = requests.post(<EOL>'<STR_LIT>'.format(ip, URI, mac), data=data, timeout=TIMEOUT)<EOL>if request.status_code == <NUM_LIT:200>:<EOL><INDENT>click.echo("<STR_LIT>" % mac)<EOL><DEDENT> | Reset the current configuration of a myStrom WiFi Button. | f15248:m6 |
@main.group('<STR_LIT>')<EOL>def bulb(): | Get and set details of a myStrom bulb. | f15248:m7 | |
@bulb.command('<STR_LIT>')<EOL>@click.option('<STR_LIT>', prompt="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>@click.option('<STR_LIT>', prompt="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>def on(ip, mac): | bulb = MyStromBulb(ip, mac)<EOL>bulb.set_color_hex('<STR_LIT>')<EOL> | Switch the bulb on. | f15248:m8 |
@bulb.command('<STR_LIT>')<EOL>@click.option('<STR_LIT>', prompt="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>@click.option('<STR_LIT>', prompt="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>@click.option('<STR_LIT>', prompt="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>@click.option('<STR_LIT>', prompt="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>@click.option('<STR_LIT>', prompt="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>def color(ip, mac, hue, saturation, value): | bulb = MyStromBulb(ip, mac)<EOL>bulb.set_color_hsv(hue, saturation, value)<EOL> | Switch the bulb on with the given color. | f15248:m9 |
@bulb.command('<STR_LIT>')<EOL>@click.option('<STR_LIT>', prompt="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>@click.option('<STR_LIT>', prompt="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>def off(ip, mac): | bulb = MyStromBulb(ip, mac)<EOL>bulb.set_off()<EOL> | Switch the bulb off. | f15248:m10 |
def __init__(self, host): | self.resource = '<STR_LIT>'.format(host)<EOL>self.timeout = <NUM_LIT:5><EOL>self.data = None<EOL>self.state = None<EOL>self.consumption = <NUM_LIT:0><EOL>self.temperature = <NUM_LIT:0><EOL> | Initialize the switch. | f15249:c0:m0 |
def set_relay_on(self): | if not self.get_relay_state():<EOL><INDENT>try:<EOL><INDENT>request = requests.get(<EOL>'<STR_LIT>'.format(self.resource), params={'<STR_LIT:state>': '<STR_LIT:1>'},<EOL>timeout=self.timeout)<EOL>if request.status_code == <NUM_LIT:200>:<EOL><INDENT>self.data['<STR_LIT>'] = True<EOL><DEDENT><DEDENT>except requests.exceptions.ConnectionError:<EOL><INDENT>raise exceptions.MyStromConnectionError()<EOL><DEDENT><DEDENT> | Turn the relay on. | f15249:c0:m1 |
def set_relay_off(self): | if self.get_relay_state():<EOL><INDENT>try:<EOL><INDENT>request = requests.get(<EOL>'<STR_LIT>'.format(self.resource), params={'<STR_LIT:state>': '<STR_LIT:0>'},<EOL>timeout=self.timeout)<EOL>if request.status_code == <NUM_LIT:200>:<EOL><INDENT>self.data['<STR_LIT>'] = False<EOL><DEDENT><DEDENT>except requests.exceptions.ConnectionError:<EOL><INDENT>raise exceptions.MyStromConnectionError()<EOL><DEDENT><DEDENT> | Turn the relay off. | f15249:c0:m2 |
def get_status(self): | try:<EOL><INDENT>request = requests.get(<EOL>'<STR_LIT>'.format(self.resource), timeout=self.timeout)<EOL>self.data = request.json()<EOL>return self.data<EOL><DEDENT>except (requests.exceptions.ConnectionError, ValueError):<EOL><INDENT>raise exceptions.MyStromConnectionError()<EOL><DEDENT> | Get the details from the switch. | f15249:c0:m3 |
def get_relay_state(self): | self.get_status()<EOL>try:<EOL><INDENT>self.state = self.data['<STR_LIT>']<EOL><DEDENT>except TypeError:<EOL><INDENT>self.state = False<EOL><DEDENT>return bool(self.state)<EOL> | Get the relay state. | f15249:c0:m4 |
def get_consumption(self): | self.get_status()<EOL>try:<EOL><INDENT>self.consumption = self.data['<STR_LIT>']<EOL><DEDENT>except TypeError:<EOL><INDENT>self.consumption = <NUM_LIT:0><EOL><DEDENT>return self.consumption<EOL> | Get current power consumption in mWh. | f15249:c0:m5 |
def get_temperature(self): | try:<EOL><INDENT>request = requests.get(<EOL>'<STR_LIT>'.format(self.resource), timeout=self.timeout, allow_redirects=False)<EOL>self.temperature = request.json()['<STR_LIT>']<EOL>return self.temperature<EOL><DEDENT>except requests.exceptions.ConnectionError:<EOL><INDENT>raise exceptions.MyStromConnectionError()<EOL><DEDENT>except ValueError:<EOL><INDENT>raise exceptions.MyStromNotVersionTwoSwitch()<EOL><DEDENT> | Get current temperature in celsius. | f15249:c0:m6 |
def ctmc(data, numstates, transintv=<NUM_LIT:1.0>, toltime=<NUM_LIT>, debug=False): | <EOL>if debug:<EOL><INDENT>datacheck(data, numstates, toltime)<EOL><DEDENT>transcount, statetime = aggregateevents(data, numstates)<EOL>if debug:<EOL><INDENT>errorcheck(transcount, statetime, toltime)<EOL><DEDENT>genmat = generatormatrix(transcount, statetime)<EOL>transmat = scipy.linalg.expm(genmat * transintv)<EOL>return transmat, genmat, transcount, statetime<EOL> | Continous Time Markov Chain
Parameters
----------
data : list of lists
A python list of N examples (e.g. rating histories of N companies,
the event data of N basketball games, etc.). The i-th example
consist of one list with M_i encoded state labels and M_i the
durations or time periods the state lasted since the recording
started.
numstates : int
number of unique states
transintv : float
The time interval
toltime : float
(If debug=True) Will throw an exception if the aggregated state
duration or aggregated time periods of any state is smaller
than toltime.
debug : bool
(Default: False) If True run the ctmc.datacheck function.
Enable this flag if you to check if your 'data' variable
has been processed correctly.
Returns
-------
transmat : ndarray
The estimated transition/stochastic matrix.
genmat : ndarray
The estimated generator matrix
transcount : ndarray
statetime : ndarray
Errors:
-------
- ctmc assumes a clean data object and does not
autocorrect any errors as result of it
The main error sources are
- transitions counting (e.g. two consequtive states
has not been aggregated, only one distinct state
reported) and
- a state is modeled ore required that does not occur
in the dataset (e.g. you a certain scale in mind
and just assume it's in the data) or resp. involved
in any transition (e.g. an example with just one
state)
You can enable error checking and exceptions by setting
debug=True. You should do this for the first run on a
smaller dataset.
Example:
--------
Use `datacheck` to check during preprocessing the
dataset
data = ...
ctmc.datacheck(data, numstates, toltime)
Disable checks in `ctmc`
transmat, genmat, transcount, statetime = ctmc.ctmc(
data, numstates, toltime, checks=False)
Check aftwards if there has been an error
ctmc.errorcheck(transcount, statetime, toltime) | f15254:m0 |
def fit(self, X, y=None): | self.transmat, self.genmat, self.transcount, self.statetime = ctmc(<EOL>X, self.numstates, self.transintv, self.toltime, self.debug)<EOL>return self<EOL> | Calls the ctmc.ctmc function
Parameters
----------
X : list of lists
(see ctmc function 'data')
y
not used, present for API consistence purpose. | f15258:c0:m1 |
def predict(self, X, steps=<NUM_LIT:1>): | return simulate(X, self.transmat, steps)<EOL> | Parameters
----------
X : ndarray
vector with state variables at t
Returns
-------
C : ndarray
vector with state variables at t+1 | f15258:c0:m2 |
def simulate(s0, transmat, steps=<NUM_LIT:1>): | <EOL>if steps == <NUM_LIT:1>:<EOL><INDENT>return np.dot(s0, transmat)<EOL><DEDENT>out = np.zeros(shape=(steps + <NUM_LIT:1>, len(s0)), order='<STR_LIT:C>')<EOL>out[<NUM_LIT:0>, :] = s0<EOL>for i in range(<NUM_LIT:1>, steps + <NUM_LIT:1>):<EOL><INDENT>out[i, :] = np.dot(out[i - <NUM_LIT:1>, :], transmat)<EOL><DEDENT>return out<EOL> | Simulate the next state
Parameters
----------
s0 : ndarray
Vector with state variables at t=0
transmat : ndarray
The estimated transition/stochastic matrix.
steps : int
(Default: 1) The number of steps to simulate model outputs ahead.
If steps>1 the a Mult-Step Simulation is triggered.
Returns
-------
out : ndarray
(steps=1) Vector with simulated state variables ().
(steps>1) Matrix with out[:,step] columns (Fortran order) from a
Multi-Step Simulation. The first column is the initial state
vector out[:,0]=s0 for algorithmic reasons. | f15261:m0 |
def setUp(self): | raise NotImplementedError<EOL> | Start a (local) wes-service server to make requests against. | f15265:c0:m1 |
def tearDown(self): | os.kill(self.wes_server_process.pid, signal.SIGTERM)<EOL>while get_server_pids():<EOL><INDENT>for pid in get_server_pids():<EOL><INDENT>try:<EOL><INDENT>os.kill(int(pid), signal.SIGKILL)<EOL>time.sleep(<NUM_LIT:3>)<EOL><DEDENT>except OSError as e:<EOL><INDENT>print(e)<EOL><DEDENT><DEDENT><DEDENT>unittest.TestCase.tearDown(self)<EOL> | Kill the wes-service server. | f15265:c0:m2 |
def run_md5sum(self, wf_input, json_input, workflow_attachment=None): | response = self.client.run(wf_input, json_input, workflow_attachment)<EOL>assert '<STR_LIT>' in response, str(response.json())<EOL>output_dir = os.path.abspath(os.path.join('<STR_LIT>', response['<STR_LIT>'], '<STR_LIT>'))<EOL>return os.path.join(output_dir, '<STR_LIT>'), response['<STR_LIT>']<EOL> | Pass a local md5sum cwl to the wes-service server, and return the path of the output file that was created. | f15265:c0:m9 |
def wait_for_finish(self, run_id, seconds=<NUM_LIT>): | wait_counter = <NUM_LIT:0><EOL>r = self.client.get_run_status(run_id)<EOL>while r["<STR_LIT:state>"] in ("<STR_LIT>", "<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>time.sleep(<NUM_LIT:1>)<EOL>wait_counter += <NUM_LIT:1><EOL>if wait_counter > seconds:<EOL><INDENT>return None<EOL><DEDENT>r = self.client.get_run_status(run_id)<EOL><DEDENT>return r["<STR_LIT:state>"]<EOL> | Return True if a file exists within a certain amount of time. | f15265:c0:m10 |
def check_for_file(self, filepath, seconds=<NUM_LIT>): | wait_counter = <NUM_LIT:0><EOL>while not os.path.exists(filepath):<EOL><INDENT>time.sleep(<NUM_LIT:1>)<EOL>wait_counter += <NUM_LIT:1><EOL>if wait_counter > seconds:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL> | Return True if a file exists within a certain amount of time. | f15265:c0:m12 |
def setUp(self): | if os.path.exists('<STR_LIT>'):<EOL><INDENT>shutil.rmtree('<STR_LIT>')<EOL><DEDENT>self.wes_server_process = subprocess.Popen(<EOL>['<STR_LIT>', os.path.abspath('<STR_LIT>'),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'])<EOL>time.sleep(<NUM_LIT:5>)<EOL> | Start a (local) wes-service server to make requests against.
Use cwltool as the wes-service server 'backend'. | f15265:c1:m0 |
def setUp(self): | self.wes_server_process = subprocess.Popen('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(os.path.abspath('<STR_LIT>')),<EOL>shell=True)<EOL>time.sleep(<NUM_LIT:5>)<EOL> | Start a (local) wes-service server to make requests against.
Use toil as the wes-service server 'backend'. | f15265:c2:m0 |
def setUp(self): | if os.path.exists('<STR_LIT>'):<EOL><INDENT>shutil.rmtree('<STR_LIT>')<EOL><DEDENT>self.wes_server_process = subprocess.Popen(<EOL>['<STR_LIT>', os.path.abspath('<STR_LIT>'),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'])<EOL>self.client.auth = {"<STR_LIT>": "<STR_LIT>" + os.environ["<STR_LIT>"]}<EOL>time.sleep(<NUM_LIT:5>)<EOL> | Start a (local) wes-service server to make requests against.
Use arvados-cwl-runner as the wes-service server 'backend'.
Requires ARVADOS_API_HOST and ARVADOS_API_TOKEN to be set in the environment. | f15265:c3:m0 |
def two_seven_compatible(filePath): | try:<EOL><INDENT>check_call(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', filePath], stderr=DEVNULL)<EOL><DEDENT>except CalledProcessError:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>return True<EOL> | Determines if a python file is 2.7 compatible by seeing if it compiles in a subprocess | f15267:m0 |
def get_version(extension, workflow_file): | if extension == '<STR_LIT>' and two_seven_compatible(workflow_file):<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>elif extension == '<STR_LIT>':<EOL><INDENT>return yaml.load(open(workflow_file))['<STR_LIT>']<EOL><DEDENT>else: <EOL><INDENT>try:<EOL><INDENT>return [l.lstrip('<STR_LIT:version>') for l in workflow_file.splitlines() if '<STR_LIT:version>' in l.split('<STR_LIT:U+0020>')][<NUM_LIT:0>]<EOL><DEDENT>except IndexError:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT><DEDENT> | Determines the version of a .py, .wdl, or .cwl file. | f15267:m1 |
def wf_info(workflow_path): | supported_formats = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>file_type = workflow_path.lower().split('<STR_LIT:.>')[-<NUM_LIT:1>] <EOL>workflow_path = workflow_path if '<STR_LIT::>' in workflow_path else '<STR_LIT>' + workflow_path<EOL>if file_type in supported_formats:<EOL><INDENT>if workflow_path.startswith('<STR_LIT>'):<EOL><INDENT>version = get_version(file_type, workflow_path[<NUM_LIT:7>:])<EOL><DEDENT>elif workflow_path.startswith('<STR_LIT>') or workflow_path.startswith('<STR_LIT>'):<EOL><INDENT>html = urlopen(workflow_path).read()<EOL>local_loc = os.path.join(os.getcwd(), '<STR_LIT>' + file_type)<EOL>with open(local_loc, '<STR_LIT:w>') as f:<EOL><INDENT>f.write(html.decode())<EOL><DEDENT>version = wf_info('<STR_LIT>' + local_loc)[<NUM_LIT:0>] <EOL>os.remove(local_loc) <EOL><DEDENT>else:<EOL><INDENT>raise NotImplementedError('<STR_LIT>'.format(workflow_path))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>'.format(file_type, '<STR_LIT>'))<EOL><DEDENT>return version, file_type.upper()<EOL> | Returns the version of the file and the file extension.
Assumes that the file path is to the file directly ie, ends with a valid file extension.Supports checking local
files as well as files at http:// and https:// locations. Files at these remote locations are recreated locally to
enable our approach to version checking, then removed after version is extracted. | f15267:m2 |
def modify_jsonyaml_paths(jsonyaml_file): | loader = schema_salad.ref_resolver.Loader({<EOL>"<STR_LIT:location>": {"<STR_LIT>": "<STR_LIT>"},<EOL>"<STR_LIT:path>": {"<STR_LIT>": "<STR_LIT>"}<EOL>})<EOL>input_dict, _ = loader.resolve_ref(jsonyaml_file, checklinks=False)<EOL>basedir = os.path.dirname(jsonyaml_file)<EOL>def fixpaths(d):<EOL><INDENT>"""<STR_LIT>"""<EOL>if isinstance(d, dict):<EOL><INDENT>if "<STR_LIT:path>" in d:<EOL><INDENT>if "<STR_LIT::>" not in d["<STR_LIT:path>"]:<EOL><INDENT>local_path = os.path.normpath(os.path.join(os.getcwd(), basedir, d["<STR_LIT:path>"]))<EOL>d["<STR_LIT:location>"] = pathname2url(local_path)<EOL><DEDENT>else:<EOL><INDENT>d["<STR_LIT:location>"] = d["<STR_LIT:path>"]<EOL><DEDENT>del d["<STR_LIT:path>"]<EOL><DEDENT><DEDENT><DEDENT>visit(input_dict, fixpaths)<EOL>return json.dumps(input_dict)<EOL> | Changes relative paths in a json/yaml file to be relative
to where the json/yaml file is located.
:param jsonyaml_file: Path to a json/yaml file. | f15267:m3 |
def build_wes_request(workflow_file, json_path, attachments=None): | workflow_file = "<STR_LIT>" + workflow_file if "<STR_LIT::>" not in workflow_file else workflow_file<EOL>wfbase = None<EOL>if json_path.startswith("<STR_LIT>"):<EOL><INDENT>wfbase = os.path.dirname(json_path[<NUM_LIT:7>:])<EOL>json_path = json_path[<NUM_LIT:7>:]<EOL>with open(json_path) as f:<EOL><INDENT>wf_params = json.dumps(json.load(f))<EOL><DEDENT><DEDENT>elif json_path.startswith("<STR_LIT:http>"):<EOL><INDENT>wf_params = modify_jsonyaml_paths(json_path)<EOL><DEDENT>else:<EOL><INDENT>wf_params = json_path<EOL><DEDENT>wf_version, wf_type = wf_info(workflow_file)<EOL>parts = [("<STR_LIT>", wf_params),<EOL>("<STR_LIT>", wf_type),<EOL>("<STR_LIT>", wf_version)]<EOL>if workflow_file.startswith("<STR_LIT>"):<EOL><INDENT>if wfbase is None:<EOL><INDENT>wfbase = os.path.dirname(workflow_file[<NUM_LIT:7>:])<EOL><DEDENT>parts.append(("<STR_LIT>", (os.path.basename(workflow_file[<NUM_LIT:7>:]), open(workflow_file[<NUM_LIT:7>:], "<STR_LIT:rb>"))))<EOL>parts.append(("<STR_LIT>", os.path.basename(workflow_file[<NUM_LIT:7>:])))<EOL><DEDENT>else:<EOL><INDENT>parts.append(("<STR_LIT>", workflow_file))<EOL><DEDENT>if wfbase is None:<EOL><INDENT>wfbase = os.getcwd()<EOL><DEDENT>if attachments:<EOL><INDENT>for attachment in attachments:<EOL><INDENT>if attachment.startswith("<STR_LIT>"):<EOL><INDENT>attachment = attachment[<NUM_LIT:7>:]<EOL>attach_f = open(attachment, "<STR_LIT:rb>")<EOL>relpath = os.path.relpath(attachment, wfbase)<EOL><DEDENT>elif attachment.startswith("<STR_LIT:http>"):<EOL><INDENT>attach_f = urlopen(attachment)<EOL>relpath = os.path.basename(attach_f)<EOL><DEDENT>parts.append(("<STR_LIT>", (relpath, attach_f)))<EOL><DEDENT><DEDENT>return parts<EOL> | :param str workflow_file: Path to cwl/wdl file. Can be http/https/file.
:param json_path: Path to accompanying json file.
:param attachments: Any other files needing to be uploaded to the server.
:return: A list of tuples formatted to be sent in a post to the wes-server (Swagger API). | f15267:m4 |
def get_service_info(self): | postresult = requests.get("<STR_LIT>" % (self.proto, self.host),<EOL>headers=self.auth)<EOL>return wes_reponse(postresult)<EOL> | Get information about Workflow Execution Service. May
include information related (but not limited to) the
workflow descriptor formats, versions supported, the
WES API versions supported, and information about general
the service availability.
:param str auth: String to send in the auth header.
:param proto: Schema where the server resides (http, https)
:param host: Port where the post request will be sent and the wes server listens at (default 8080)
:return: The body of the get result as a dictionary. | f15267:c0:m1 |
def list_runs(self): | postresult = requests.get("<STR_LIT>" % (self.proto, self.host),<EOL>headers=self.auth)<EOL>return wes_reponse(postresult)<EOL> | List the workflows, this endpoint will list the workflows
in order of oldest to newest. There is no guarantee of
live updates as the user traverses the pages, the behavior
should be decided (and documented) by each implementation.
:param str auth: String to send in the auth header.
:param proto: Schema where the server resides (http, https)
:param host: Port where the post request will be sent and the wes server listens at (default 8080)
:return: The body of the get result as a dictionary. | f15267:c0:m2 |
def run(self, wf, jsonyaml, attachments): | attachments = list(expand_globs(attachments))<EOL>parts = build_wes_request(wf, jsonyaml, attachments)<EOL>postresult = requests.post("<STR_LIT>" % (self.proto, self.host),<EOL>files=parts,<EOL>headers=self.auth)<EOL>return wes_reponse(postresult)<EOL> | Composes and sends a post request that signals the wes server to run a workflow.
:param str workflow_file: A local/http/https path to a cwl/wdl/python workflow file.
:param str jsonyaml: A local path to a json or yaml file.
:param list attachments: A list of local paths to files that will be uploaded to the server.
:param str auth: String to send in the auth header.
:param proto: Schema where the server resides (http, https)
:param host: Port where the post request will be sent and the wes server listens at (default 8080)
:return: The body of the post result as a dictionary. | f15267:c0:m3 |
def cancel(self, run_id): | postresult = requests.post("<STR_LIT>" % (self.proto, self.host, run_id),<EOL>headers=self.auth)<EOL>return wes_reponse(postresult)<EOL> | Cancel a running workflow.
:param run_id: String (typically a uuid) identifying the run.
:param str auth: String to send in the auth header.
:param proto: Schema where the server resides (http, https)
:param host: Port where the post request will be sent and the wes server listens at (default 8080)
:return: The body of the delete result as a dictionary. | f15267:c0:m4 |
def get_run_log(self, run_id): | postresult = requests.get("<STR_LIT>" % (self.proto, self.host, run_id),<EOL>headers=self.auth)<EOL>return wes_reponse(postresult)<EOL> | Get detailed info about a running workflow.
:param run_id: String (typically a uuid) identifying the run.
:param str auth: String to send in the auth header.
:param proto: Schema where the server resides (http, https)
:param host: Port where the post request will be sent and the wes server listens at (default 8080)
:return: The body of the get result as a dictionary. | f15267:c0:m5 |
def get_run_status(self, run_id): | postresult = requests.get("<STR_LIT>" % (self.proto, self.host, run_id),<EOL>headers=self.auth)<EOL>return wes_reponse(postresult)<EOL> | Get quick status info about a running workflow.
:param run_id: String (typically a uuid) identifying the run.
:param str auth: String to send in the auth header.
:param proto: Schema where the server resides (http, https)
:param host: Port where the post request will be sent and the wes server listens at (default 8080)
:return: The body of the get result as a dictionary. | f15267:c0:m6 |
def visit(d, op): | op(d)<EOL>if isinstance(d, list):<EOL><INDENT>for i in d:<EOL><INDENT>visit(i, op)<EOL><DEDENT><DEDENT>elif isinstance(d, dict):<EOL><INDENT>for i in itervalues(d):<EOL><INDENT>visit(i, op)<EOL><DEDENT><DEDENT> | Recursively call op(d) for all list subelements and dictionary 'values' that d may have. | f15269:m0 |
def __init__(self, opts): | self.pairs = []<EOL>for o in opts if opts else []:<EOL><INDENT>k, v = o.split("<STR_LIT:=>", <NUM_LIT:1>)<EOL>self.pairs.append((k, v))<EOL><DEDENT> | Parse and store options as a list of tuples. | f15269:c0:m0 |
def getopt(self, p, default=None): | for k, v in self.pairs:<EOL><INDENT>if k == p:<EOL><INDENT>return v<EOL><DEDENT><DEDENT>return default<EOL> | Returns the first option value stored that matches p or default. | f15269:c0:m1 |
def getoptlist(self, p): | optlist = []<EOL>for k, v in self.pairs:<EOL><INDENT>if k == p:<EOL><INDENT>optlist.append(v)<EOL><DEDENT><DEDENT>return optlist<EOL> | Returns all option values stored that match p as a list. | f15269:c0:m2 |
def __init__(self, run_id): | super(ToilWorkflow, self).__init__()<EOL>self.run_id = run_id<EOL>self.workdir = os.path.join(os.getcwd(), '<STR_LIT>', self.run_id)<EOL>self.outdir = os.path.join(self.workdir, '<STR_LIT>')<EOL>if not os.path.exists(self.outdir):<EOL><INDENT>os.makedirs(self.outdir)<EOL><DEDENT>self.outfile = os.path.join(self.workdir, '<STR_LIT>')<EOL>self.errfile = os.path.join(self.workdir, '<STR_LIT>')<EOL>self.starttime = os.path.join(self.workdir, '<STR_LIT>')<EOL>self.endtime = os.path.join(self.workdir, '<STR_LIT>')<EOL>self.pidfile = os.path.join(self.workdir, '<STR_LIT>')<EOL>self.statcompletefile = os.path.join(self.workdir, '<STR_LIT>')<EOL>self.staterrorfile = os.path.join(self.workdir, '<STR_LIT>')<EOL>self.cmdfile = os.path.join(self.workdir, '<STR_LIT>')<EOL>self.jobstorefile = os.path.join(self.workdir, '<STR_LIT>')<EOL>self.request_json = os.path.join(self.workdir, '<STR_LIT>')<EOL>self.input_json = os.path.join(self.workdir, "<STR_LIT>")<EOL>self.jobstore_default = '<STR_LIT>' + os.path.join(self.workdir, '<STR_LIT>')<EOL>self.jobstore = None<EOL> | Represents a toil workflow.
:param str run_id: A uuid string. Used to name the folder that contains
all of the files containing this particular workflow instance's information. | f15270:c0:m0 |
def write_workflow(self, request, opts, cwd, wftype='<STR_LIT>'): | workflow_url = request.get("<STR_LIT>")<EOL>if workflow_url.startswith('<STR_LIT>'):<EOL><INDENT>os.link(workflow_url[<NUM_LIT:7>:], os.path.join(cwd, "<STR_LIT>" + wftype))<EOL>workflow_url = os.path.join(cwd, "<STR_LIT>" + wftype)<EOL><DEDENT>os.link(self.input_json, os.path.join(cwd, "<STR_LIT>"))<EOL>self.input_json = os.path.join(cwd, "<STR_LIT>")<EOL>extra_options = self.sort_toil_options(opts.getoptlist("<STR_LIT>"))<EOL>if wftype == '<STR_LIT>':<EOL><INDENT>command_args = ['<STR_LIT>'] + extra_options + [workflow_url, self.input_json]<EOL><DEDENT>elif wftype == '<STR_LIT>':<EOL><INDENT>command_args = ['<STR_LIT>'] + extra_options + [workflow_url, self.input_json]<EOL><DEDENT>elif wftype == '<STR_LIT>':<EOL><INDENT>command_args = ['<STR_LIT>'] + extra_options + [workflow_url]<EOL><DEDENT>else:<EOL><INDENT>raise RuntimeError('<STR_LIT>' + str(wftype))<EOL><DEDENT>return command_args<EOL> | Writes a cwl, wdl, or python file as appropriate from the request dictionary. | f15270:c0:m2 |
def call_cmd(self, cmd, cwd): | with open(self.cmdfile, '<STR_LIT:w>') as f:<EOL><INDENT>f.write(str(cmd))<EOL><DEDENT>stdout = open(self.outfile, '<STR_LIT:w>')<EOL>stderr = open(self.errfile, '<STR_LIT:w>')<EOL>logging.info('<STR_LIT>' + '<STR_LIT:U+0020>'.join(cmd))<EOL>process = subprocess.Popen(cmd,<EOL>stdout=stdout,<EOL>stderr=stderr,<EOL>close_fds=True,<EOL>cwd=cwd)<EOL>stdout.close()<EOL>stderr.close()<EOL>return process.pid<EOL> | Calls a command with Popen.
Writes stdout, stderr, and the command to separate files.
:param cmd: A string or array of strings.
:param tempdir:
:return: The pid of the command. | f15270:c0:m4 |
def run(self, request, tempdir, opts): | wftype = request['<STR_LIT>'].lower().strip()<EOL>version = request['<STR_LIT>']<EOL>if version != '<STR_LIT>' and wftype == '<STR_LIT>':<EOL><INDENT>raise RuntimeError('<STR_LIT>'<EOL>'<STR_LIT>' + str(version))<EOL><DEDENT>if version != '<STR_LIT>' and wftype == '<STR_LIT>':<EOL><INDENT>raise RuntimeError('<STR_LIT>'<EOL>'<STR_LIT>' + str(version))<EOL><DEDENT>logging.info('<STR_LIT>' + str(self.run_id))<EOL>with open(self.starttime, '<STR_LIT:w>') as f:<EOL><INDENT>f.write(str(time.time()))<EOL><DEDENT>with open(self.request_json, '<STR_LIT:w>') as f:<EOL><INDENT>json.dump(request, f)<EOL><DEDENT>with open(self.input_json, "<STR_LIT:w>") as inputtemp:<EOL><INDENT>json.dump(request["<STR_LIT>"], inputtemp)<EOL><DEDENT>command_args = self.write_workflow(request, opts, tempdir, wftype=wftype)<EOL>pid = self.call_cmd(command_args, tempdir)<EOL>with open(self.endtime, '<STR_LIT:w>') as f:<EOL><INDENT>f.write(str(time.time()))<EOL><DEDENT>with open(self.pidfile, '<STR_LIT:w>') as f:<EOL><INDENT>f.write(str(pid))<EOL><DEDENT>return self.getstatus()<EOL> | Constructs a command to run a cwl/json from requests and opts,
runs it, and deposits the outputs in outdir.
Runner:
opts.getopt("runner", default="cwl-runner")
CWL (url):
request["workflow_url"] == a url to a cwl file
or
request["workflow_attachment"] == input cwl text (written to a file and a url constructed for that file)
JSON File:
request["workflow_params"] == input json text (to be written to a file)
:param dict request: A dictionary containing the cwl/json information.
:param str tempdir: Folder where input files have been staged and the cwd to run at.
:param wes_service.util.WESBackend opts: contains the user's arguments;
specifically the runner and runner options
:return: {"run_id": self.run_id, "state": state} | f15270:c0:m8 |
def getstate(self): | <EOL>if not os.path.exists(self.jobstorefile):<EOL><INDENT>logging.info('<STR_LIT>' + self.run_id + '<STR_LIT>')<EOL>return "<STR_LIT>", -<NUM_LIT:1><EOL><DEDENT>if os.path.exists(self.statcompletefile):<EOL><INDENT>logging.info('<STR_LIT>' + self.run_id + '<STR_LIT>')<EOL>return "<STR_LIT>", <NUM_LIT:0><EOL><DEDENT>if os.path.exists(self.staterrorfile):<EOL><INDENT>logging.info('<STR_LIT>' + self.run_id + '<STR_LIT>')<EOL>return "<STR_LIT>", <NUM_LIT:255><EOL><DEDENT>if not os.path.exists(self.errfile):<EOL><INDENT>logging.info('<STR_LIT>' + self.run_id + '<STR_LIT>')<EOL>return "<STR_LIT>", -<NUM_LIT:1><EOL><DEDENT>completed = False<EOL>with open(self.errfile, '<STR_LIT:r>') as f:<EOL><INDENT>for line in f:<EOL><INDENT>if '<STR_LIT>' in line:<EOL><INDENT>logging.info('<STR_LIT>' + self.run_id + '<STR_LIT>')<EOL>open(self.staterrorfile, '<STR_LIT:a>').close()<EOL>return "<STR_LIT>", <NUM_LIT:255><EOL><DEDENT>if '<STR_LIT>' in line:<EOL><INDENT>completed = True<EOL><DEDENT><DEDENT><DEDENT>if completed:<EOL><INDENT>logging.info('<STR_LIT>' + self.run_id + '<STR_LIT>')<EOL>open(self.statcompletefile, '<STR_LIT:a>').close()<EOL>return "<STR_LIT>", <NUM_LIT:0><EOL><DEDENT>logging.info('<STR_LIT>' + self.run_id + '<STR_LIT>')<EOL>return "<STR_LIT>", -<NUM_LIT:1><EOL> | Returns QUEUED, -1
INITIALIZING, -1
RUNNING, -1
COMPLETE, 0
or
EXECUTOR_ERROR, 255 | f15270:c0:m9 |
def run(self, request, tempdir, opts): | with open(os.path.join(self.workdir, "<STR_LIT>"), "<STR_LIT:w>") as f:<EOL><INDENT>json.dump(request, f)<EOL><DEDENT>with open(os.path.join(self.workdir, "<STR_LIT>"), "<STR_LIT:w>") as inputtemp:<EOL><INDENT>json.dump(request["<STR_LIT>"], inputtemp)<EOL><DEDENT>workflow_url = request.get("<STR_LIT>") <EOL>output = open(os.path.join(self.workdir, "<STR_LIT>"), "<STR_LIT:w>")<EOL>stderr = open(os.path.join(self.workdir, "<STR_LIT>"), "<STR_LIT:w>")<EOL>runner = opts.getopt("<STR_LIT>", default="<STR_LIT>")<EOL>extra = opts.getoptlist("<STR_LIT>")<EOL>for e in extra:<EOL><INDENT>if e.startswith('<STR_LIT>'):<EOL><INDENT>extra.remove(e)<EOL><DEDENT><DEDENT>extra.append('<STR_LIT>' + self.outdir)<EOL>if workflow_url.startswith('<STR_LIT>'):<EOL><INDENT>os.symlink(workflow_url[<NUM_LIT:7>:], os.path.join(tempdir, "<STR_LIT>"))<EOL>workflow_url = os.path.join(tempdir, "<STR_LIT>")<EOL><DEDENT>os.symlink(inputtemp.name, os.path.join(tempdir, "<STR_LIT>"))<EOL>jsonpath = os.path.join(tempdir, "<STR_LIT>")<EOL>command_args = [runner] + extra + [workflow_url, jsonpath]<EOL>proc = subprocess.Popen(command_args,<EOL>stdout=output,<EOL>stderr=stderr,<EOL>close_fds=True,<EOL>cwd=tempdir)<EOL>output.close()<EOL>stderr.close()<EOL>with open(os.path.join(self.workdir, "<STR_LIT>"), "<STR_LIT:w>") as pid:<EOL><INDENT>pid.write(str(proc.pid))<EOL><DEDENT>return self.getstatus()<EOL> | Constructs a command to run a cwl/json from requests and opts,
runs it, and deposits the outputs in outdir.
Runner:
opts.getopt("runner", default="cwl-runner")
CWL (url):
request["workflow_url"] == a url to a cwl file
or
request["workflow_attachment"] == input cwl text (written to a file and a url constructed for that file)
JSON File:
request["workflow_params"] == input json text (to be written to a file)
:param dict request: A dictionary containing the cwl/json information.
:param wes_service.util.WESBackend opts: contains the user's arguments;
specifically the runner and runner options
:return: {"run_id": self.run_id, "state": state} | f15271:c0:m1 |
def getstate(self): | state = "<STR_LIT>"<EOL>exit_code = -<NUM_LIT:1><EOL>exitcode_file = os.path.join(self.workdir, "<STR_LIT>")<EOL>pid_file = os.path.join(self.workdir, "<STR_LIT>")<EOL>if os.path.exists(exitcode_file):<EOL><INDENT>with open(exitcode_file) as f:<EOL><INDENT>exit_code = int(f.read())<EOL><DEDENT><DEDENT>elif os.path.exists(pid_file):<EOL><INDENT>with open(pid_file, "<STR_LIT:r>") as pid:<EOL><INDENT>pid = int(pid.read())<EOL><DEDENT>try:<EOL><INDENT>(_pid, exit_status) = os.waitpid(pid, os.WNOHANG)<EOL>if _pid != <NUM_LIT:0>:<EOL><INDENT>exit_code = exit_status >> <NUM_LIT:8><EOL>with open(exitcode_file, "<STR_LIT:w>") as f:<EOL><INDENT>f.write(str(exit_code))<EOL><DEDENT>os.unlink(pid_file)<EOL><DEDENT><DEDENT>except OSError:<EOL><INDENT>os.unlink(pid_file)<EOL>exit_code = <NUM_LIT:255><EOL><DEDENT><DEDENT>if exit_code == <NUM_LIT:0>:<EOL><INDENT>state = "<STR_LIT>"<EOL><DEDENT>elif exit_code != -<NUM_LIT:1>:<EOL><INDENT>state = "<STR_LIT>"<EOL><DEDENT>return state, exit_code<EOL> | Returns RUNNING, -1
COMPLETE, 0
or
EXECUTOR_ERROR, 255 | f15271:c0:m2 |
def catch_exceptions(orig_func): | @functools.wraps(orig_func)<EOL>def catch_exceptions_wrapper(self, *args, **kwargs):<EOL><INDENT>try:<EOL><INDENT>return orig_func(self, *args, **kwargs)<EOL><DEDENT>except arvados.errors.ApiError as e:<EOL><INDENT>logging.exception("<STR_LIT>")<EOL>return {"<STR_LIT>": e._get_reason(), "<STR_LIT>": e.resp.status}, int(e.resp.status)<EOL><DEDENT>except subprocess.CalledProcessError as e:<EOL><INDENT>return {"<STR_LIT>": str(e), "<STR_LIT>": <NUM_LIT>}, <NUM_LIT><EOL><DEDENT>except MissingAuthorization:<EOL><INDENT>return {"<STR_LIT>": "<STR_LIT>", "<STR_LIT>": <NUM_LIT>}, <NUM_LIT><EOL><DEDENT>except ValueError as e:<EOL><INDENT>return {"<STR_LIT>": str(e), "<STR_LIT>": <NUM_LIT>}, <NUM_LIT><EOL><DEDENT>except Exception as e:<EOL><INDENT>return {"<STR_LIT>": str(e), "<STR_LIT>": <NUM_LIT>}, <NUM_LIT><EOL><DEDENT><DEDENT>return catch_exceptions_wrapper<EOL> | Catch uncaught exceptions and turn them into http errors | f15273:m1 |
def requires_authentication(func): | def _auth(self, *args, **kwargs):<EOL><INDENT>if not self._authenticated:<EOL><INDENT>raise NotAuthenticatedException('<STR_LIT>'<EOL>.format(func.__name__)<EOL>+ '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>return func(self, *args, **kwargs)<EOL><DEDENT><DEDENT>return _auth<EOL> | Function decorator that throws an exception if the user
is not authenticated, and executes the function normally
if the user is authenticated. | f15278:c5:m0 |
def __init__(self, username, password,<EOL>scraper='<STR_LIT>'): | self._authenticated = True<EOL>self.username = username<EOL>self._tg_ticket, self._service_ticket = _get_ticket(username, password)<EOL>self._session = _tsquare_login(self._service_ticket)<EOL>try:<EOL><INDENT>self._html_iface = parsers.REGISTERED_METHODS[scraper]()<EOL><DEDENT>except KeyError:<EOL><INDENT>self._html_iface = parsers.REGISTERED_METHODS['<STR_LIT:default>']()<EOL><DEDENT> | Initialize a TSquareAPI object.
Logs in to TSquare with username and password.
@param username - The username to log in with
@param password - The password to log in with. Not stored.
@returns A TSquareUser object that represents the user that
was logged in.
@throws TSquareAuthException - If something goes wrong during the
authentication process (i.e. credentials are bad) | f15278:c5:m1 |
@requires_authentication<EOL><INDENT>def get_user_info(self):<DEDENT> | response = self._session.get(BASE_URL_TSQUARE + '<STR_LIT>')<EOL>response.raise_for_status() <EOL>user_data = response.json()<EOL>del user_data['<STR_LIT:password>'] <EOL>return TSquareUser(**user_data)<EOL> | Returns a TSquareUser object representing the currently logged in user.
Throws a NotAuthenticatedException if the user is not authenticated. | f15278:c5:m3 |
@requires_authentication<EOL><INDENT>def get_site_by_id(self, id):<DEDENT> | response = self._session.get(BASE_URL_TSQUARE + '<STR_LIT>'.format(id))<EOL>response.raise_for_status()<EOL>site_data = response.json()<EOL>return TSquareSite(**site_data)<EOL> | Looks up a site by ID and returns a TSquareSite representing that
object, or throws an exception if no such site is found.
@param id - The entityID of the site to look up
@returns A TSquareSite object | f15278:c5:m4 |
@requires_authentication<EOL><INDENT>def get_sites(self, filter_func=lambda x: True):<DEDENT> | response = self._session.get(BASE_URL_TSQUARE + '<STR_LIT>')<EOL>response.raise_for_status() <EOL>site_list = response.json()['<STR_LIT>']<EOL>if not site_list:<EOL><INDENT>self._authenticated = False<EOL>raise SessionExpiredException('<STR_LIT>')<EOL><DEDENT>result_list = []<EOL>for site in site_list:<EOL><INDENT>t_site = TSquareSite(**site)<EOL>if not hasattr(t_site, "<STR_LIT>"):<EOL><INDENT>t_site.props = {}<EOL><DEDENT>if not '<STR_LIT>' in t_site.props:<EOL><INDENT>t_site.props['<STR_LIT>'] = None<EOL><DEDENT>if not '<STR_LIT>' in t_site.props:<EOL><INDENT>t_site.props['<STR_LIT>'] = None<EOL><DEDENT>if not '<STR_LIT>' in t_site.props:<EOL><INDENT>t_site.props['<STR_LIT>'] = None<EOL><DEDENT>if filter_func(t_site):<EOL><INDENT>result_list.append(t_site)<EOL><DEDENT><DEDENT>return result_list<EOL> | Returns a list of TSquareSite objects that represent the sites available
to a user.
@param filter_func - A function taking in a Site object as a parameter
that returns a True or False, depending on whether
or not that site should be returned by this
function. Filter_func should be used to create
filters on the list of sites (i.e. user's
preferences on what sites to display by default).
If not specified, no filter is applied.
@returns - A list of TSquareSite objects encapsulating t-square's JSON
response. | f15278:c5:m5 |
@requires_authentication<EOL><INDENT>def get_announcements(self, site=None, num=<NUM_LIT:10>, age=<NUM_LIT:20>):<DEDENT> | url = BASE_URL_TSQUARE + '<STR_LIT>'<EOL>if site:<EOL><INDENT>url += '<STR_LIT>'.format(site.id, num, age)<EOL><DEDENT>else:<EOL><INDENT>url += '<STR_LIT>'.format(num, age)<EOL><DEDENT>request = self._session.get(url)<EOL>request.raise_for_status()<EOL>announcement_list = request.json()['<STR_LIT>']<EOL>return [TSquareAnnouncement(**x) for x in announcement_list]<EOL> | Gets announcements from a site if site is not None, or from every
site otherwise. Returns a list of TSquareAnnouncement objects.
@param site_obj (TSquareSite) If non-None, gets only the announcements
from that site. If none, get anouncements
from all sites.
@param num - The number of announcements to fetch. Default is 10.
@param age - 'How far back' to go to retreive announcements. Default
is 20, which means that only announcements that are
less than 20 days old will be returned, even if there
less than 'num' of them.
@returns - A list of TSquareAnnouncement objects. The length will be
at most num, and it may be less than num depending on
the number of announcements whose age is less than age. | f15278:c5:m6 |
@requires_authentication<EOL><INDENT>def get_tools(self, site):<DEDENT> | <EOL>url = site.entityURL.replace('<STR_LIT>', '<STR_LIT>')<EOL>response = self._session.get(url)<EOL>response.raise_for_status()<EOL>tools_dict_list = self._html_iface.get_tools(response.text)<EOL>return [TSquareTool(**x) for x in tools_dict_list]<EOL> | Gets all tools associated with a site.
@param site (TSquareSite) - The site to search for tools
@returns A list of dictionaries representing Tsquare tools. | f15278:c5:m7 |
@requires_authentication<EOL><INDENT>def get_assignments(self, site):<DEDENT> | tools = self.get_tools(site)<EOL>assignment_tool_filter = [x.href for x in tools if x.name == '<STR_LIT>']<EOL>if not assignment_tool_filter:<EOL><INDENT>return []<EOL><DEDENT>assignment_tool_url = assignment_tool_filter[<NUM_LIT:0>].href<EOL>response = self._session.get(assignment_tool_url)<EOL>response.raise_for_status()<EOL>iframes = self._html_iface.get_iframes(response.text)<EOL>iframe_url = '<STR_LIT>'<EOL>for frame in iframes:<EOL><INDENT>if frame['<STR_LIT:title>'] == '<STR_LIT>':<EOL><INDENT>iframe_url = frame['<STR_LIT:src>']<EOL><DEDENT><DEDENT>if iframe_url == '<STR_LIT>':<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>response = self._session.get(iframe_url)<EOL>response.raise_for_status()<EOL>assignment_dict_list = self._html_iface.get_assignments(response.text)<EOL>return [TSquareAssignment(**x) for x in assignment_dict_list]<EOL> | Gets a list of assignments associated with a site (class). Returns
a list of TSquareAssignment objects.
@param site (TSquareSite) - The site to use with the assignment query
@returns - A list of TSquareSite objects. May be an empty list if
the site has defined no assignments. | f15278:c5:m8 |
@requires_authentication<EOL><INDENT>def get_grades(self, site):<DEDENT> | tools = self.get_tools(site)<EOL>grade_tool_filter = [x.href for x in tools if x.name == '<STR_LIT>']<EOL>if not grade_tool_filter:<EOL><INDENT>return []<EOL><DEDENT>response = self._session.get(grade_tool_filter[<NUM_LIT:0>])<EOL>response.raise_for_status()<EOL>iframes = self._html_iface.get_iframes(response.text)<EOL>iframe_url = '<STR_LIT>'<EOL>for frame in iframes:<EOL><INDENT>if frame['<STR_LIT:title>'] == '<STR_LIT>':<EOL><INDENT>iframe_url = frame['<STR_LIT:src>']<EOL><DEDENT><DEDENT>if iframe_url == '<STR_LIT>':<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>response = self._session.get(iframe_url)<EOL>response.raise_for_status()<EOL>grade_dict_list = self._html_iface.get_grades(response.text)<EOL>return grade_dict_list<EOL> | Gets a list of grades associated with a site. The return type is a dictionary
whose keys are assignment categories, similar to how the page is laid out
in TSquare. | f15278:c5:m9 |
@requires_authentication<EOL><INDENT>def get_syllabus(self, site):<DEDENT> | tools = self.get_tools(site)<EOL>syllabus_filter = [x.href for x in tools if x.name == '<STR_LIT>']<EOL>if not syllabus_filter:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>response = self._session.get(syllabus_filter[<NUM_LIT:0>])<EOL>response.raise_for_status()<EOL>iframes = self._html_iface.get_iframes(response.text)<EOL>iframe_url = '<STR_LIT>'<EOL>for frame in iframes:<EOL><INDENT>if frame['<STR_LIT:title>'] == '<STR_LIT>':<EOL><INDENT>iframe_url = frame['<STR_LIT:src>']<EOL><DEDENT><DEDENT>if iframe_url == '<STR_LIT>':<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>response = self._session.get(iframe_url)<EOL>response.raise_for_status()<EOL>syllabus_html = self._html_iface.get_syllabus(response.text)<EOL>return syllabus_html<EOL> | Gets the syllabus for a course. The syllabus may or may not
contain HTML, depending on the site. TSquare does not enforce
whether or not pages are allowed to have HTML, so it is impossible
to tell. | f15278:c5:m10 |
def __init__(self, **kwargs): | for key in kwargs:<EOL><INDENT>setattr(self, key, kwargs[key])<EOL><DEDENT>def list_attrs(self):<EOL><INDENT>return list(self.__dict__.keys())<EOL><DEDENT> | Encapsulates the raw JSON dictionary that represents a user in TSquare.
Converts a dictionary to attributes of an object for ease of use.
This constructor should never be called directly; instead, it is
called by get_user_info. | f15278:c6:m0 |
def __init__(self, **kwargs): | for key in kwargs:<EOL><INDENT>setattr(self, key, kwargs[key])<EOL><DEDENT> | Encapsulates the raw JSON dictionary that represents a site in TSquare.
Converts a dictionary to attributes of an object for ease of use.
This constructor should never be called directly; instead, it is called
by get_sites. | f15278:c7:m0 |
def __init__(self, **kwargs): | for key in kwargs:<EOL><INDENT>setattr(self, key, kwargs[key])<EOL><DEDENT> | Encapsulates the raw JSON dictionary that represents an announcement
in TSquare.
Converts a dictionary to attributes of an object for ease of use.
This constructor should never be called directly; instead, it is called
by get_announcements. | f15278:c8:m0 |
def __init__(self, **kwargs): | for key in kwargs:<EOL><INDENT>setattr(self, key, kwargs[key])<EOL><DEDENT> | Encapsulates the raw JSON dictionary that represents a tool in TSquare.
A tool is any third party application that TSquare uses to provide a
service. In this case, assignments, grades, and resources are the most
common tools in use. | f15278:c9:m0 |
def __init__(self, **kwargs): | for key in kwargs:<EOL><INDENT>setattr(self, key, kwargs[key])<EOL><DEDENT> | Encapsulates the dictionary that this module builds by scraping the
Assignments page. An assignment is anything that can be turned
in according to TSquare. | f15278:c10:m0 |
def choices(self, cl): | <EOL>def _choice_item(is_selected, query_string, title):<EOL><INDENT>return {<EOL>'<STR_LIT>': is_selected,<EOL>'<STR_LIT>': query_string,<EOL>'<STR_LIT>': force_text(title),<EOL>}<EOL><DEDENT>yield _choice_item(<EOL>self.lookup_val is None,<EOL>cl.get_query_string({}, [self.lookup_kwarg]),<EOL>_('<STR_LIT>'))<EOL>container = (self.field.choices<EOL>if isinstance(self.field, ChoicesField) else<EOL>self.field.flatchoices)<EOL>for lookup, title in container:<EOL><INDENT>yield _choice_item(<EOL>smart_text(lookup) == self.lookup_val,<EOL>cl.get_query_string({self.lookup_kwarg: lookup}),<EOL>title)<EOL><DEDENT> | Take choices from field's 'choices' attribute for 'ChoicesField' and
use 'flatchoices' as usual for other fields. | f15280:c0:m0 |
def to_python(self, value): | value = '<STR_LIT>' if value in validators.EMPTY_VALUES else smart_text(value)<EOL>if value == self.empty_value or value in validators.EMPTY_VALUES:<EOL><INDENT>return self.empty_value<EOL><DEDENT>try:<EOL><INDENT>value = self.coerce(value)<EOL><DEDENT>except (ValueError, TypeError, ValidationError):<EOL><INDENT>self._on_invalid_value(value)<EOL><DEDENT>return value<EOL> | Validates that the value is in self.choices and can be coerced to the
right type. | f15281:c0:m2 |
def validate(self, value): | super(ChoicesField, self).validate(value)<EOL>if value and not self.valid_value(value):<EOL><INDENT>self._on_invalid_value(value)<EOL><DEDENT> | Validates that the input is in self.choices. | f15281:c0:m3 |
def valid_value(self, value): | if isinstance(value, Constant):<EOL><INDENT>value = value.name<EOL><DEDENT>text_value = force_text(value)<EOL>for option_value, option_label, option_title in self.choices:<EOL><INDENT>if value == option_value or text_value == force_text(option_value):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL> | Check if the provided value is a valid choice. | f15281:c0:m4 |
def clean(self, value, model_instance): | <EOL>value = self.to_python(value).name<EOL>self.validate(value, model_instance)<EOL>self.run_validators(value)<EOL>return value<EOL> | Convert the value's type and run validation. Validation errors
from to_python and validate are propagated. The correct value is
returned if no error is raised. | f15283:c0:m6 |
def _get_choices(self): | if not self._choices:<EOL><INDENT>self._choices = tuple(<EOL>(x.name, getattr(x, '<STR_LIT>', x.name) or x.name)<EOL>for x in self.choices_class.constants()<EOL>)<EOL><DEDENT>return self._choices<EOL> | Redefine standard method. | f15283:c0:m7 |
def _get_flatchoices(self): | return [<EOL>(self.to_python(choice), value) for choice, value in self._choices<EOL>]<EOL> | Redefine standard method.
Return constants themselves instead of their names for right rendering
in admin's 'change_list' view, if field is present in 'list_display'
attribute of model's admin. | f15283:c0:m8 |
def formfield(self, form_class=None, choices_form_class=None, **kwargs): | defaults = {<EOL>'<STR_LIT>': not self.blank,<EOL>'<STR_LIT:label>': capfirst(self.verbose_name),<EOL>'<STR_LIT>': self.help_text,<EOL>}<EOL>if self.has_default():<EOL><INDENT>if callable(self.default):<EOL><INDENT>defaults['<STR_LIT>'] = self.default<EOL>defaults['<STR_LIT>'] = True<EOL><DEDENT>else:<EOL><INDENT>defaults['<STR_LIT>'] = self.get_default()<EOL><DEDENT><DEDENT>include_blank = (self.blank<EOL>or not (self.has_default()<EOL>or '<STR_LIT>' in kwargs))<EOL>choices = [BLANK_CHOICE_DASH, ] if include_blank else []<EOL>choices.extend([<EOL>(<EOL>x.name,<EOL>getattr(x, '<STR_LIT>', x.name) or x.name,<EOL>getattr(x, '<STR_LIT>', None) or None<EOL>)<EOL>for x in self.choices_class.constants()<EOL>])<EOL>defaults['<STR_LIT>'] = choices<EOL>defaults['<STR_LIT>'] = self.to_python<EOL>if self.null:<EOL><INDENT>defaults['<STR_LIT>'] = None<EOL><DEDENT>for k in list(kwargs):<EOL><INDENT>if k not in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT:label>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>del kwargs[k]<EOL><DEDENT><DEDENT>defaults.update(kwargs)<EOL>form_class = choices_form_class or ChoicesFormField<EOL>return form_class(**defaults)<EOL> | Returns a django.forms.Field instance for this database Field. | f15283:c0:m9 |
def south_field_triple(self): | from south.modelsinspector import introspector<EOL>field_class = '<STR_LIT>'<EOL>args, kwargs = introspector(self)<EOL>return (field_class, args, kwargs)<EOL> | Returns a suitable description of this field for South. | f15283:c0:m10 |
def read(*paths): | with open(os.path.join(*paths), '<STR_LIT:r>') as f:<EOL><INDENT>return f.read()<EOL><DEDENT> | Build a file path from *paths* and return the contents. | f15287:m0 |
def blockgen(bytes, block_size=<NUM_LIT:16>): | for i in range(<NUM_LIT:0>, len(bytes), block_size):<EOL><INDENT>block = bytes[i:i + block_size]<EOL>block_len = len(block)<EOL>if block_len > <NUM_LIT:0>:<EOL><INDENT>yield block<EOL><DEDENT>if block_len < block_size:<EOL><INDENT>break<EOL><DEDENT><DEDENT> | a block generator for pprp | f15289:m4 |
def get_access_list( self, email, uid ): | path = '<STR_LIT>'<EOL>userRef = {<EOL>'<STR_LIT>': uid,<EOL>'<STR_LIT:email>': email,<EOL>'<STR_LIT>': int(time.time())<EOL>}<EOL>serialized = json.dumps(userRef)<EOL>user_ref = utinypass.crypto.aesencrypt(self.private_key, serialized)<EOL>data = {<EOL>'<STR_LIT>': self.app_id,<EOL>'<STR_LIT>': user_ref, <EOL>}<EOL>r = requests.get( self.base_url + path, data=data )<EOL>if r.status_code != <NUM_LIT:200>:<EOL><INDENT>raise ValueError( path + "<STR_LIT::>" + r.reason )<EOL><DEDENT>access_struct = json.loads( r.content )<EOL>return access_struct<EOL> | Takes and email and matching uid, builds a uref and fetches an access structure that looks like:
{
"count": 1,
"code": 0,
"ts": 1428522205,
"limit": 100,
"offset": 0,
"total": 1,
"data": [
{
"granted": true,
"resource": {
"aid": "J8MY0Bu8Xs",
"rid": "RESOURCE_MONTHLY",
"image_url": "/images2/default/file-document.png",
"name": "Month",
"description": ""
},
"user": {
"first_name": "WackoJacko",
"last_name": "AndDot",
"email": "dotswill@echo.net",
"api_token": "CDEADBEEFcafebabe0x1337KxYzCiuIHaX0Ri3GH"
},
"access_id": "1VShIZzLeIod"
}
]
} | f15290:c0:m2 |
def grant_user_access( self, uid, rid, expire_datetime = None, send_email=False ): | path = "<STR_LIT>"<EOL>if expire_datetime:<EOL><INDENT>expires_seconds = calendar.timegm(expires_datetime.timetuple())<EOL><DEDENT>else:<EOL><INDENT>expires_seconds = calendar.timegm(datetime.datetime.now().timetuple()) + (<NUM_LIT>*<NUM_LIT>*<NUM_LIT>)<EOL><DEDENT>data = {<EOL>'<STR_LIT>': self.api_token, <EOL>'<STR_LIT>': self.app_id,<EOL>'<STR_LIT>': rid,<EOL>'<STR_LIT>': uid,<EOL>'<STR_LIT>': expires_seconds,<EOL>'<STR_LIT>': send_email,<EOL>}<EOL>r = requests.get( self.base_url + path, data=data )<EOL>if r.status_code != <NUM_LIT:200>:<EOL><INDENT>raise ValueError( path + "<STR_LIT::>" + r.reason ) <EOL><DEDENT> | Takes a user id and resource id and records a grant of access to that reseource for the user.
If no expire_date is set, we'll default to 24 hours.
If send_email is set to True, Tinypass will send an email related to the grant.
No return value, raises ValueError. | f15290:c0:m3 |
def revoke_user_access( self, access_id ): | path = "<STR_LIT>"<EOL>data = {<EOL>'<STR_LIT>': self.api_token, <EOL>'<STR_LIT>': access_id,<EOL>}<EOL>r = requests.get( self.base_url + path, data=data )<EOL>if r.status_code != <NUM_LIT:200>:<EOL><INDENT>raise ValueError( path + "<STR_LIT::>" + r.reason )<EOL><DEDENT> | Takes an access_id, probably obtained from the get_access_list structure, and revokes that access.
No return value, but may raise ValueError. | f15290:c0:m4 |
def get_user( self, uid, disabled=False ): | path = "<STR_LIT>"<EOL>data = {<EOL>'<STR_LIT>': self.api_token,<EOL>'<STR_LIT>': self.app_id,<EOL>'<STR_LIT>': uid,<EOL>'<STR_LIT>': disabled,<EOL>}<EOL>r = requests.get( self.base_url + path, data=data )<EOL>if r.status_code == <NUM_LIT:2>:<EOL><INDENT>raise ValueError( path + "<STR_LIT::>" + r.reason ) <EOL><DEDENT>if r.status_code == <NUM_LIT>:<EOL><INDENT>return None <EOL><DEDENT>res = json.loads( r.content )<EOL>if '<STR_LIT:code>' in res:<EOL><INDENT>if res['<STR_LIT:code>'] != <NUM_LIT:0>:<EOL><INDENT>if res['<STR_LIT:code>'] == <NUM_LIT:2>:<EOL><INDENT>raise ValueError( path + "<STR_LIT::>" + res['<STR_LIT:message>'] ) <EOL><DEDENT>print(res)<EOL>return None<EOL><DEDENT><DEDENT>return res['<STR_LIT:user>']<EOL> | given a uid, returns
{
first_name (string): User's first name,
image1 (string): User's profile image,
email (string): User's email address,
create_date (string): The creation date,
last_name (string): User's last name,
uid (string): User's UID
}
You can pass disabled=True if you'd like to get the user even if the user has been disabled. | f15290:c0:m7 |
def setUpModule(): | logging.disable(logging.CRITICAL)<EOL> | The module specific setUp method | f15292:m0 |
def tearDownModule(): | logging.disable(logging.NOTSET)<EOL> | The module specific tearDown method | f15292:m1 |
def setUp(self): | self._data = os.path.normpath(os.path.join(os.path.dirname(__file__), '<STR_LIT:..>', '<STR_LIT:data>'))<EOL>self.assertTrue(os.path.isdir(self._data), '<STR_LIT>'.format(self._data))<EOL>self._output = os.path.normpath(os.path.join(self._data, '<STR_LIT>'))<EOL>self.assertFalse(os.path.exists(self._output), '<STR_LIT>'.format(self._output))<EOL>self._package = os.path.normpath(os.path.join(self._data, '<STR_LIT>'))<EOL>self.assertTrue(os.path.isdir(self._package), '<STR_LIT>'.format(self._package))<EOL>rootdir = os.path.dirname(self._package)<EOL>if rootdir not in sys.path:<EOL><INDENT>sys.path.append(rootdir)<EOL><DEDENT> | The class specific setUp method | f15292:c0:m0 |
def tearDown(self): | <EOL>rootdir = os.path.dirname(self._package)<EOL>if rootdir in sys.path:<EOL><INDENT>sys.path.remove(rootdir)<EOL><DEDENT>if os.path.exists(self._output):<EOL><INDENT>shutil.rmtree(self._output)<EOL><DEDENT> | The class specific tearDown method | f15292:c0:m1 |
def setUpModule(): | logging.disable(logging.CRITICAL)<EOL>datadir = os.path.join(os.path.dirname(__file__), '<STR_LIT:..>', '<STR_LIT:data>')<EOL>if datadir not in sys.path:<EOL><INDENT>sys.path.append(datadir)<EOL><DEDENT>import vsgendemo<EOL>demodistribution = pkg_resources.Distribution(os.path.dirname(__main__.__file__), project_name='<STR_LIT>', version="<STR_LIT>")<EOL>try:<EOL><INDENT>demodistribution._ep_map<EOL><DEDENT>except AttributeError:<EOL><INDENT>demodistribution._ep_map = {}<EOL><DEDENT>demodistribution._ep_map.update({<EOL>'<STR_LIT>': {'<STR_LIT>': pkg_resources.EntryPoint('<STR_LIT>', '<STR_LIT>', attrs=('<STR_LIT>',), dist=demodistribution)},<EOL>'<STR_LIT>': {'<STR_LIT>': pkg_resources.EntryPoint('<STR_LIT>', '<STR_LIT>', attrs=('<STR_LIT>',), dist=demodistribution)}<EOL>})<EOL>pkg_resources.working_set.add(demodistribution, '<STR_LIT>')<EOL>suite_classes = {ep.name: ep.load() for ep in pkg_resources.iter_entry_points('<STR_LIT>')}<EOL>assert '<STR_LIT>' in suite_classes, '<STR_LIT>'<EOL>assert suite_classes['<STR_LIT>'] == vsgendemo.suite.VSGDemoSuite, '<STR_LIT>'<EOL>project_classes = {ep.name: ep.load() for ep in pkg_resources.iter_entry_points('<STR_LIT>')}<EOL>assert '<STR_LIT>' in project_classes, '<STR_LIT>'<EOL>assert project_classes['<STR_LIT>'] == vsgendemo.projects.VSGAutoDemoProject, '<STR_LIT>'<EOL> | The module specific setUp method | f15293:m0 |
def tearDownModule(): | logging.disable(logging.NOTSET)<EOL> | The module specific tearDown method | f15293:m1 |
def setUp(self): | self._root = os.path.dirname(__main__.__file__)<EOL>self._data = os.path.normpath(os.path.join(os.path.dirname(__file__), '<STR_LIT:..>', '<STR_LIT:data>'))<EOL>self.assertTrue(os.path.isdir(self._data), '<STR_LIT>'.format(self._data))<EOL>self._output = os.path.normpath(os.path.join(self._data, '<STR_LIT>'))<EOL>self.assertFalse(os.path.exists(self._output), '<STR_LIT>'.format(self._output))<EOL>self._file = os.path.normpath(os.path.join(self._data, '<STR_LIT>', '<STR_LIT>'))<EOL>self.assertTrue(os.path.isfile(self._file), '<STR_LIT>'.format(self._file))<EOL> | The class specific setUp method | f15293:c0:m0 |
def tearDown(self): | if os.path.exists(self._output):<EOL><INDENT>shutil.rmtree(self._output)<EOL><DEDENT> | The class specific tearDown method | f15293:c0:m1 |
def setUp(self): | self._root = os.path.dirname(__main__.__file__)<EOL>self._name = '<STR_LIT>'<EOL>self._solution = os.path.normpath(os.path.join(self._root, self._name + '<STR_LIT>'))<EOL>self.assertFalse(os.path.exists(self._solution), '<STR_LIT>'.format(self._solution))<EOL>self._project = os.path.normpath(os.path.join(self._root, self._name + '<STR_LIT>'))<EOL>self.assertFalse(os.path.exists(self._project), '<STR_LIT>'.format(self._project))<EOL> | The class specific setUp method | f15293:c1:m0 |
def tearDown(self): | <EOL>if os.path.exists(self._solution):<EOL><INDENT>os.remove(self._solution)<EOL><DEDENT>if os.path.exists(self._project):<EOL><INDENT>os.remove(self._project)<EOL><DEDENT> | The class specific tearDown method | f15293:c1:m1 |
def main(argv=[]): | import argparse<EOL>import unittest<EOL>parser = argparse.ArgumentParser(description='<STR_LIT>', formatter_class=argparse.ArgumentDefaultsHelpFormatter)<EOL>parser.add_argument('<STR_LIT>', '<STR_LIT>', help='<STR_LIT>', action='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', '<STR_LIT>', help='<STR_LIT>', default='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', '<STR_LIT>', help='<STR_LIT>', default=os.path.dirname(os.path.realpath(__file__)))<EOL>args = parser.parse_args(argv[<NUM_LIT:1>:])<EOL>loader = unittest.TestLoader()<EOL>if args.testname:<EOL><INDENT>testsuite = loader.loadTestsFromNames(args.testname)<EOL><DEDENT>else:<EOL><INDENT>testsuite = loader.discover(args.testpath, args.testpattern)<EOL><DEDENT>runner = unittest.TextTestRunner(verbosity=<NUM_LIT:2>)<EOL>result = runner.run(testsuite)<EOL>return <NUM_LIT:0> if not result.failures and not result.errors else <NUM_LIT:1><EOL> | Test main script | f15294:m0 |
def __init__(self, **kwargs): | super(VSGDemoMockRegisterable, self).__init__()<EOL>self.BaseInterpreter = uuid.uuid1()<EOL>self.Version = "<STR_LIT>"<EOL> | Constructor.
:param kwargs: List of arbitrary keyworded arguments to be processed as instance variable data | f15295:c1:m0 |
def register(self): | pass<EOL> | Registers the environment into the windows registry.
:note: We're explictly writing the environment to the registry to facilitate sharing. See `How to share pyproj across team with custom environments <https://pytools.codeplex.com/workitem/2765>`_ for motivation. | f15295:c1:m1 |
def __init__(self, name, rootpath, **kwargs): | super(VSGDemoBaseProject, self).__init__(**kwargs)<EOL>self.Name = name<EOL>self.FileName = os.path.join(VSGDemoSettings.ProjectRoot, '<STR_LIT>'.format(name.lower()))<EOL>self.ProjectHome = rootpath<EOL>self.SearchPath = [rootpath]<EOL>self.WorkingDirectory = rootpath<EOL>self.OutputPath = rootpath<EOL>self.RootNamespace = '<STR_LIT>'<EOL>self.PythonInterpreters = [VSGDemoMockRegisterable()]<EOL>self.PythonInterpreterArgs = ['<STR_LIT>']<EOL>self.IsWindowsApplication = True<EOL>self.CompileInFilter = ['<STR_LIT>', '<STR_LIT>']<EOL>self.ContentInFilter = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL> | Constructor.
:param kwargs: List of arbitrary keyworded arguments to be processed as instance variable data | f15295:c2:m0 |
def initialize(self): | pass<EOL> | Initializes the VSGSolution by overriding the default values with instance specific values. | f15295:c2:m1 |
def write(self): | filters = {<EOL>'<STR_LIT>': lambda x: ('<STR_LIT>' % x).upper(),<EOL>'<STR_LIT>': lambda x: os.path.relpath(x, self.ProjectHome),<EOL>'<STR_LIT>': lambda x: os.path.relpath(x, self.FileName)<EOL>}<EOL>context = {<EOL>'<STR_LIT>': self,<EOL>}<EOL>return self.render(self.__jinja_template__, self.FileName, context, filters)<EOL> | Creates a simple PTVS project file. | f15295:c2:m2 |
def register(self): | <EOL>for i in set(self.PythonInterpreters):<EOL><INDENT>i.register()<EOL><DEDENT> | Registers the project's python environments. | f15295:c2:m3 |
def main(argv=[]): | from vsgen import VSGWriteCommand, VSGRegisterCommand, VSGLogger<EOL>from vsgendemo.solutions import VSGDemoSolution<EOL>from vsgendemo.settings import VSGDemoSettings<EOL>pylogger = VSGLogger()<EOL>solutions = [VSGDemoSolution(VSVersion=VSGDemoSettings.VSVersion)]<EOL>with VSGWriteCommand('<STR_LIT>', solutions) as command:<EOL><INDENT>command.execute()<EOL><DEDENT>projects = set(sorted((p for s in solutions for p in s.Projects), key=lambda x: x.Name))<EOL>with VSGWriteCommand('<STR_LIT>', projects) as command:<EOL><INDENT>command.execute()<EOL><DEDENT>interpretters = set(i for p in projects for i in p.PythonInterpreters)<EOL>with VSGRegisterCommand('<STR_LIT>', interpretters) as command:<EOL><INDENT>command.execute()<EOL><DEDENT>return <NUM_LIT:0><EOL> | The entry point of the script.
It will generate the Python Tools for Visual Studio IDE Solutions and Project as per configured. | f15296:m0 |
def __init__(self, **kwargs): | super(VSGDemoSolution, self).__init__(**kwargs)<EOL>self.Name = '<STR_LIT>'<EOL>self.FileName = os.path.join(VSGDemoSettings.SolutionRoot, '<STR_LIT>'.format(self.Name.lower()))<EOL>self.Projects.append(VSGCoreProject(VSVersion=self.VSVersion))<EOL>self.Projects.append(VSGDemoProject(VSVersion=self.VSVersion))<EOL> | Constructor. | f15297:c0:m0 |
def __init__(self, **kwargs): | <EOL>config = VSGConfigParser()<EOL>if self.__template__ not in config.read([self.__template__]):<EOL><INDENT>raise ValueError('<STR_LIT>' % __template__)<EOL><DEDENT>for s in config.sections():<EOL><INDENT>for o in config.options(s):<EOL><INDENT>override = kwargs.pop(o, None)<EOL>if override:<EOL><INDENT>config.set(s, o, override)<EOL><DEDENT><DEDENT><DEDENT>super(VSGDemoSuite, self).__init__(config)<EOL> | Constructor.
:param kwargs: List of arbitrary keyworded arguments to be processed as instance variable data. | f15298:c0:m0 |
@classmethod<EOL><INDENT>def make_parser(cls, **kwargs):<DEDENT> | <EOL>parser = argparse.ArgumentParser(**kwargs)<EOL>parser.add_argument('<STR_LIT>', metavar='<STR_LIT>', type=DirectoryType(), help='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', help='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', metavar='<STR_LIT>', help='<STR_LIT>')<EOL>return parser<EOL> | Creates a :class:`~argparse.ArgumentParser` instances to work with :class:`~vsgen.project.VSGProject` classes.
:param kwargs: List of additional keyworded arguments to be passed into the :class:`~argparse.ArgumentParser`.
:return: A :class:`~argparse.ArgumentParser` instance. | f15298:c0:m1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.