content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
# -*- coding: utf-8 -*- """ Profile: http://hl7.org/fhir/StructureDefinition/Claim Release: R4 Version: 4.0.1 Build ID: 9346c8cc45 Last updated: 2019-11-01T09:29:23.356+11:00 """ from pydantic.validators import bytes_validator # noqa: F401 from .. import fhirtypes # noqa: F401 from .. import claim def test_claim_1(base_settings): """No. 1 tests collection for Claim. Test File: claim-example-institutional-rich.json """ filename = ( base_settings["unittest_data_dir"] / "claim-example-institutional-rich.json" ) inst = claim.Claim.parse_file( filename, content_type="application/json", encoding="utf-8" ) assert "Claim" == inst.resource_type impl_claim_1(inst) # testing reverse by generating data from itself and create again. data = inst.dict() assert "Claim" == data["resourceType"] inst2 = claim.Claim(**data) impl_claim_1(inst2) def test_claim_2(base_settings): """No. 2 tests collection for Claim. Test File: claim-example-professional.json """ filename = base_settings["unittest_data_dir"] / "claim-example-professional.json" inst = claim.Claim.parse_file( filename, content_type="application/json", encoding="utf-8" ) assert "Claim" == inst.resource_type impl_claim_2(inst) # testing reverse by generating data from itself and create again. data = inst.dict() assert "Claim" == data["resourceType"] inst2 = claim.Claim(**data) impl_claim_2(inst2) def test_claim_3(base_settings): """No. 3 tests collection for Claim. Test File: claim-example.json """ filename = base_settings["unittest_data_dir"] / "claim-example.json" inst = claim.Claim.parse_file( filename, content_type="application/json", encoding="utf-8" ) assert "Claim" == inst.resource_type impl_claim_3(inst) # testing reverse by generating data from itself and create again. data = inst.dict() assert "Claim" == data["resourceType"] inst2 = claim.Claim(**data) impl_claim_3(inst2) def test_claim_4(base_settings): """No. 4 tests collection for Claim. Test File: claim-example-vision.json """ filename = base_settings["unittest_data_dir"] / "claim-example-vision.json" inst = claim.Claim.parse_file( filename, content_type="application/json", encoding="utf-8" ) assert "Claim" == inst.resource_type impl_claim_4(inst) # testing reverse by generating data from itself and create again. data = inst.dict() assert "Claim" == data["resourceType"] inst2 = claim.Claim(**data) impl_claim_4(inst2) def test_claim_5(base_settings): """No. 5 tests collection for Claim. Test File: claim-example-vision-glasses-3tier.json """ filename = ( base_settings["unittest_data_dir"] / "claim-example-vision-glasses-3tier.json" ) inst = claim.Claim.parse_file( filename, content_type="application/json", encoding="utf-8" ) assert "Claim" == inst.resource_type impl_claim_5(inst) # testing reverse by generating data from itself and create again. data = inst.dict() assert "Claim" == data["resourceType"] inst2 = claim.Claim(**data) impl_claim_5(inst2) def test_claim_6(base_settings): """No. 6 tests collection for Claim. Test File: claim-example-institutional.json """ filename = base_settings["unittest_data_dir"] / "claim-example-institutional.json" inst = claim.Claim.parse_file( filename, content_type="application/json", encoding="utf-8" ) assert "Claim" == inst.resource_type impl_claim_6(inst) # testing reverse by generating data from itself and create again. data = inst.dict() assert "Claim" == data["resourceType"] inst2 = claim.Claim(**data) impl_claim_6(inst2) def test_claim_7(base_settings): """No. 7 tests collection for Claim. Test File: claim-example-oral-contained.json """ filename = base_settings["unittest_data_dir"] / "claim-example-oral-contained.json" inst = claim.Claim.parse_file( filename, content_type="application/json", encoding="utf-8" ) assert "Claim" == inst.resource_type impl_claim_7(inst) # testing reverse by generating data from itself and create again. data = inst.dict() assert "Claim" == data["resourceType"] inst2 = claim.Claim(**data) impl_claim_7(inst2) def test_claim_8(base_settings): """No. 8 tests collection for Claim. Test File: claim-example-pharmacy-medication.json """ filename = ( base_settings["unittest_data_dir"] / "claim-example-pharmacy-medication.json" ) inst = claim.Claim.parse_file( filename, content_type="application/json", encoding="utf-8" ) assert "Claim" == inst.resource_type impl_claim_8(inst) # testing reverse by generating data from itself and create again. data = inst.dict() assert "Claim" == data["resourceType"] inst2 = claim.Claim(**data) impl_claim_8(inst2) def test_claim_9(base_settings): """No. 9 tests collection for Claim. Test File: claim-example-oral-orthoplan.json """ filename = base_settings["unittest_data_dir"] / "claim-example-oral-orthoplan.json" inst = claim.Claim.parse_file( filename, content_type="application/json", encoding="utf-8" ) assert "Claim" == inst.resource_type impl_claim_9(inst) # testing reverse by generating data from itself and create again. data = inst.dict() assert "Claim" == data["resourceType"] inst2 = claim.Claim(**data) impl_claim_9(inst2) def test_claim_10(base_settings): """No. 10 tests collection for Claim. Test File: claim-example-cms1500-medical.json """ filename = base_settings["unittest_data_dir"] / "claim-example-cms1500-medical.json" inst = claim.Claim.parse_file( filename, content_type="application/json", encoding="utf-8" ) assert "Claim" == inst.resource_type impl_claim_10(inst) # testing reverse by generating data from itself and create again. data = inst.dict() assert "Claim" == data["resourceType"] inst2 = claim.Claim(**data) impl_claim_10(inst2)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 37046, 25, 2638, 1378, 18519, 22, 13, 2398, 14, 69, 71, 343, 14, 1273, 5620, 36621, 14, 44819, 198, 26362, 25, 371, 19, 198, 14815, 25, 604, 13, 15, 13, ...
2.707719
2,306
import argparse import os.path import sys sys.path.append( os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))) import pymia.deeplearning.logging as log import tensorflow as tf import pc.configuration.config as cfg import pc.data.handler as hdlr import pc.data.split as split import pc.model.point_cnn as net import pc.utilities.filesystem as fs import pc.utilities.seeding as seed import pc.utilities.training as train if __name__ == '__main__': """The program's entry point. Parse the arguments and run the program. """ parser = argparse.ArgumentParser(description='Deep learning for shape learning on point clouds') parser.add_argument( '--config_file', type=str, default='./bin/config.json', help='Path to the configuration file.' ) args = parser.parse_args() main(args.config_file)
[ 11748, 1822, 29572, 198, 11748, 28686, 13, 6978, 198, 11748, 25064, 198, 198, 17597, 13, 6978, 13, 33295, 7, 198, 220, 220, 220, 28686, 13, 6978, 13, 397, 2777, 776, 7, 418, 13, 6978, 13, 22179, 7, 418, 13, 6978, 13, 15908, 3672, ...
2.786164
318
from nipype.interfaces.utility import Function Topup_scan_params = Function(function=topup_scan_params, input_names=['pe_direction', 'te', 'epi_factor'], output_names=['fn']) Apply_scan_params = Function(function=apply_scan_params, input_names=['pe_direction', 'te', 'epi_factor', 'nr_trs'], output_names=['fn'])
[ 6738, 299, 541, 2981, 13, 3849, 32186, 13, 315, 879, 1330, 15553, 628, 198, 198, 9126, 929, 62, 35836, 62, 37266, 796, 15553, 7, 8818, 28, 4852, 929, 62, 35836, 62, 37266, 11, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220,...
1.760148
271
import os import pickle from deployConfig import workDir import sys env_fp = f"{workDir}/env.pickle" if not os.path.exists(env_fp): env = {} with open(env_fp, "wb") as fh: pickle.dump(env, fh) # add_to_env("LD_LIBRARY_PATH", "/usr/local/lib/eopenssl11/") # add_to_env("LD_LIBRARY_PATH", f"{project_root}/Builds/Python-3.10.0/") # add_to_env("PATH", f"{project_root}/Builds/Python-3.10.0/bin") # add_to_env("PATH", f"{project_root}/Builds/postgresql-14.0/bin")
[ 11748, 28686, 198, 11748, 2298, 293, 198, 6738, 6061, 16934, 1330, 670, 35277, 198, 11748, 25064, 198, 24330, 62, 46428, 796, 277, 1, 90, 1818, 35277, 92, 14, 24330, 13, 27729, 293, 1, 628, 628, 198, 361, 407, 28686, 13, 6978, 13, 1...
2.146552
232
""" from: http://adventofcode.com/2017/day/6 --- Day 6: Memory Reallocation --- A debugger program here is having an issue: it is trying to repair a memory reallocation routine, but it keeps getting stuck in an infinite loop. In this area, there are sixteen memory banks; each memory bank can hold any number of blocks. The goal of the reallocation routine is to balance the blocks between the memory banks. The reallocation routine operates in cycles. In each cycle, it finds the memory bank with the most blocks (ties won by the lowest-numbered memory bank) and redistributes those blocks among the banks. To do this, it removes all of the blocks from the selected bank, then moves to the next (by index) memory bank and inserts one of the blocks. It continues doing this until it runs out of blocks; if it reaches the last memory bank, it wraps around to the first one. The debugger would like to know how many redistributions can be done before a blocks-in-banks configuration is produced that has been seen before. For example, imagine a scenario with only four memory banks: The banks start with 0, 2, 7, and 0 blocks. The third bank has the most blocks, so it is chosen for redistribution. Starting with the next bank (the fourth bank) and then continuing to the first bank, the second bank, and so on, the 7 blocks are spread out over the memory banks. The fourth, first, and second banks get two blocks each, and the third bank gets one back. The final result looks like this: 2 4 1 2. Next, the second bank is chosen because it contains the most blocks (four). Because there are four memory banks, each gets one block. The result is: 3 1 2 3. Now, there is a tie between the first and fourth memory banks, both of which have three blocks. The first bank wins the tie, and its three blocks are distributed evenly over the other three banks, leaving it with none: 0 2 3 4. The fourth bank is chosen, and its four blocks are distributed such that each of the four banks receives one: 1 3 4 1. The third bank is chosen, and the same thing happens: 2 4 1 2. At this point, we've reached a state we've seen before: 2 4 1 2 was already seen. The infinite loop is detected after the fifth block redistribution cycle, and so the answer in this example is 5. Given the initial block counts in your puzzle input, how many redistribution cycles must be completed before a configuration is produced that has been seen before? """ def main(): """Solve the problem!""" with open('input.txt') as input_file: data = input_file.read() banks = [int(x) for x in data.split()] print(banks) if __name__ == "__main__": main()
[ 37811, 198, 6738, 25, 2638, 1378, 324, 1151, 1659, 8189, 13, 785, 14, 5539, 14, 820, 14, 21, 198, 198, 6329, 3596, 718, 25, 14059, 797, 439, 5040, 11420, 198, 32, 49518, 1430, 994, 318, 1719, 281, 2071, 25, 340, 318, 2111, 284, 91...
3.895434
679
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Unittests for the GDAl tools. This file is part of the REDRESS algorithm M. Lamare, M. Dumont, G. Picard (IGE, CEN). """ import pytest from geojson import Polygon, Feature, FeatureCollection, dump from redress.geospatial.gdal_ops import (build_poly_from_coords, build_poly_from_geojson, geom_contains)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 3118, 715, 3558, 329, 262, 27044, 2348, 4899, 13, 198, 198, 1212, 2393, 318, 636, 286, 262, 23848, 49, 759...
2.07109
211
from output.models.ms_data.regex.letterlike_symbols_xsd.letterlike_symbols import Doc __all__ = [ "Doc", ]
[ 6738, 5072, 13, 27530, 13, 907, 62, 7890, 13, 260, 25636, 13, 9291, 2339, 62, 1837, 2022, 10220, 62, 87, 21282, 13, 9291, 2339, 62, 1837, 2022, 10220, 1330, 14432, 198, 198, 834, 439, 834, 796, 685, 198, 220, 220, 220, 366, 23579, ...
2.382979
47
"""test.py Python3 Test script that demonstrates the passing of an initialized python structure to C and retrieving the structure back. """ import testMod from ctypes import * TESTSTRUCT._fields_ = [ ("name", c_char_p), ("next", POINTER(TESTSTRUCT), #We can use a structure pointer for a linked list. ("next2", c_void_p) #We can use void pointers for structures as well! ] struct1 = TESTSTRUCT(c_char_p("Hello!".encode()), None, None) struct2 = TESTSTRUCT(c_char_p("Goodbye!".encode()), None, None) struct22 = TESTSTRUCT(c_char_p("My Love!".encode()), None, None) struct1.next = pointer(struct2) #Must cast lp to void p before assigning it or it will complain... struct1.next2 = cast(pointer(struct22), c_void_p) outbytes = testMod.py_returnMe(struct1) #Must cast outbytes back into pointer for a struct and retrieve contents. struct3 = cast(outbytes, POINTER(TESTSTRUCT)).contents #Next is already a pointer so all we need are just the contents. nextStruct = struct3.next.contents #Next2 is a void p so we need to cast it back to TESTSTRUCT pointer and get #the contents. next2Struct = cast(struct3.next2, POINTER(TESTSTRUCT)).contents print ("Result: {}, {}, {}".format(struct3.name, nextStrut.name, next2Struct.name)
[ 37811, 9288, 13, 9078, 198, 37906, 18, 198, 14402, 4226, 326, 15687, 262, 6427, 286, 281, 198, 17532, 21015, 4645, 284, 327, 290, 50122, 198, 1169, 4645, 736, 13, 198, 37811, 198, 11748, 1332, 5841, 198, 6738, 269, 19199, 1330, 1635, ...
3.036232
414
from __future__ import print_function import os import csv import graphviz import numpy as np import plotly.graph_objs as go import plotly import plotly.plotly as py import matplotlib.pyplot as plt import matplotlib.pylab as pylab import copy import warnings import matplotlib as mpl from plotly.offline import download_plotlyjs, plot, iplot mpl.use('TkAgg') plotly.tools.set_credentials_file(username=os.environ['PLOTLY_USERNAME'], api_key=os.environ['PLOTLY_API_KEY']) def plot_stats(statistics, ylog=False, view=False, filename='avg_fitness.svg'): """ Plots the population's average and best fitness. """ if plt is None: warnings.warn( "This display is not available due to a missing optional dependency (matplotlib)") return generation = range(len(statistics.most_fit_genomes)) best_fitness = [c.fitness for c in statistics.most_fit_genomes] avg_fitness = np.array(statistics.get_fitness_mean()) stdev_fitness = np.array(statistics.get_fitness_stdev()) median_fitness = np.array(statistics.get_fitness_median()) plt.figure(figsize=(12, 9)) ax = plt.subplot(111) ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) ax.get_xaxis().tick_bottom() ax.get_yaxis().tick_left() plt.plot(generation, avg_fitness, 'b-', label="average") plt.plot(generation, avg_fitness - stdev_fitness, 'g-.', label="-1 sd") plt.plot(generation, avg_fitness + stdev_fitness, 'g-.', label="+1 sd") plt.plot(generation, best_fitness, 'r-', label="best") plt.plot(generation, median_fitness, 'y-', label="median") plt.title("Population's average and best fitness") plt.xlabel("Generations") plt.ylabel("Fitness") plt.grid() plt.legend(loc="best") if ylog: plt.gca().set_yscale('symlog') plt.savefig(filename) if view: plt.show() plt.close() def plot_spikes(spikes, view=False, filename=None, title=None): """ Plots the trains for a single spiking neuron. """ t_values = [t for t, I, v, u, f in spikes] v_values = [v for t, I, v, u, f in spikes] u_values = [u for t, I, v, u, f in spikes] I_values = [I for t, I, v, u, f in spikes] f_values = [f for t, I, v, u, f in spikes] fig = plt.figure() plt.subplot(4, 1, 1) plt.ylabel("Potential (mv)") plt.xlabel("Time (in ms)") plt.grid() plt.plot(t_values, v_values, "g-") if title is None: plt.title("Izhikevich's spiking neuron model") else: plt.title("Izhikevich's spiking neuron model ({0!s})".format(title)) plt.subplot(4, 1, 2) plt.ylabel("Fired") plt.xlabel("Time (in ms)") plt.grid() plt.plot(t_values, f_values, "r-") plt.subplot(4, 1, 3) plt.ylabel("Recovery (u)") plt.xlabel("Time (in ms)") plt.grid() plt.plot(t_values, u_values, "r-") plt.subplot(4, 1, 4) plt.ylabel("Current (I)") plt.xlabel("Time (in ms)") plt.grid() plt.plot(t_values, I_values, "r-o") if filename is not None: plt.savefig(filename) if view: plt.show() plt.close() fig = None plt.close() return fig def plot_species(statistics, view=False, filename='speciation.svg'): """ Visualizes speciation throughout evolution. """ if plt is None: warnings.warn( "This display is not available due to a missing optional dependency (matplotlib)") return species_sizes = statistics.get_species_sizes() num_generations = len(species_sizes) curves = np.array(species_sizes).T plt.figure(figsize=(12, 9)) _, ax = plt.subplots() ax.stackplot(range(num_generations), *curves) plt.title("Speciation") plt.ylabel("Size per Species") plt.xlabel("Generations") plt.savefig(filename) if view: plt.show() plt.close() def draw_net(config, genome, view=False, filename=None, node_names=None, show_disabled=True, prune_unused=False, node_colors=None, fmt='svg'): """ Receives a genome and draws a neural network with arbitrary topology. """ # Attributes for network nodes. if graphviz is None: warnings.warn( "This display is not available due to a missing optional dependency (graphviz)") return if node_names is None: node_names = {} assert type(node_names) is dict if node_colors is None: node_colors = {} assert type(node_colors) is dict node_attrs = { 'shape': 'circle', 'fontsize': '9', 'height': '0.2', 'width': '0.2'} dot = graphviz.Digraph(format=fmt, node_attr=node_attrs) inputs = set() for k in config.genome_config.input_keys: inputs.add(k) name = node_names.get(k, str(k)) input_attrs = {'style': 'filled', 'shape': 'box'} input_attrs['fillcolor'] = node_colors.get(k, 'lightgray') dot.node(name, _attributes=input_attrs) outputs = set() for k in config.genome_config.output_keys: outputs.add(k) name = node_names.get(k, str(k)) node_attrs = {'style': 'filled'} node_attrs['fillcolor'] = node_colors.get(k, 'lightblue') dot.node(name, _attributes=node_attrs) if prune_unused: connections = set() for cg in genome.connections.values(): if cg.enabled or show_disabled: connections.add((cg.in_node_id, cg.out_node_id)) used_nodes = copy.copy(outputs) pending = copy.copy(outputs) while pending: new_pending = set() for a, b in connections: if b in pending and a not in used_nodes: new_pending.add(a) used_nodes.add(a) pending = new_pending else: used_nodes = set(genome.nodes.keys()) for n in used_nodes: if n in inputs or n in outputs: continue attrs = {'style': 'filled', 'fillcolor': node_colors.get(n, 'white')} dot.node(str(n), _attributes=attrs) for cg in genome.connections.values(): if cg.enabled or show_disabled: # if cg.input not in used_nodes or cg.output not in used_nodes: # continue input, output = cg.key a = node_names.get(input, str(input)) b = node_names.get(output, str(output)) style = 'solid' if cg.enabled else 'dotted' color = 'green' if cg.weight > 0 else 'red' width = str(0.1 + abs(cg.weight / 5.0)) dot.edge(a, b, _attributes={ 'style': style, 'color': color, 'penwidth': width}) dot.render(filename, view=view) return dot def plot_single_run_scatter(scatter, dt, title): """Plots a single run with MAX, AVG, MEDIAN, All individuals""" l = [] y = [] N = len(scatter.gen.unique()) c = ['hsl('+str(h)+',50%'+',50%)' for h in np.linspace(0, 360, N)] for i in range(int(N)): subset = scatter.loc[scatter['gen'] == i] trace0 = go.Scatter( x=subset.loc[:, 'gen'], y=subset.loc[:, 'fitness'], mode='markers', marker=dict(size=7, line=dict(width=1), color=c[i], opacity=0.5 ), name='gen {}'.format(i), text=subset.loc[:, 'genome'] ) l.append(trace0) trace0 = go.Scatter( x=dt.loc[:, 'gen'], y=dt.loc[:, 'max'], mode='lines', name='Max', line=dict( color="rgb(204, 51, 51)", dash="solid", shape="spline", smoothing=1.0, width=2 ), ) trace1 = go.Scatter( x=dt.loc[:, 'gen'], y=dt.loc[:, 'median'], mode='lines', name='Median', line=dict( color="rgb(173, 181, 97)", shape="spline", dash="solid", smoothing=1.0, width=2 ) ) trace2 = go.Scatter( x=dt.loc[:, 'gen'], y=dt.loc[:, 'avg'], mode='lines', name='Average', line=dict( color="rgb(62, 173, 212)", shape="spline", dash="solid", smoothing=1.0, width=2 ) ) data = [trace0, trace1, trace2] layout = go.Layout( title='Fitness of Population Individuals - {}'.format(title), hovermode='closest', xaxis=dict( title='Generations', ticklen=5, zeroline=False, gridwidth=2, ), yaxis=dict( title='Fitness', ticklen=5, gridwidth=1, ), showlegend=False ) fig = go.Figure(data=data+l, layout=layout) return py.iplot(fig, filename='single-run-scater-line-plot', layout=layout) def plot_runs(dt, title, offline=True): """Plots the Max/Average/Median""" trace0 = go.Scatter( x=dt.index, y=dt.loc[:, 'max'], mode='lines', name='Max', line=dict( color="rgb(204, 51, 51)", dash="solid", shape="spline", smoothing=0.0, width=2 ), ) trace1 = go.Scatter( x=dt.index, y=dt.loc[:, 'median'], mode='lines', name='Median', line=dict( color="rgb(173, 181, 97)", shape="spline", dash="solid", smoothing=0.0, width=2 ) ) trace2 = go.Scatter( x=dt.index, y=dt.loc[:, 'avg'], mode='lines', name='Average', line=dict( color="rgb(62, 173, 212)", shape="spline", dash="solid", smoothing=0.0, width=2 ) ) layout = go.Layout( showlegend=True, hovermode='closest', title=title, xaxis=dict( autorange=False, range=[0, 20], showspikes=False, title="Generations", ticklen=5, gridwidth=1, ), yaxis=dict( autorange=True, title="Fitness", ticklen=5, gridwidth=1, ), ) data = [trace0, trace1, trace2] fig = go.Figure(data, layout=layout) return py.iplot(fig, filename=title) l = [] y = [] N = len(scatter.gen.unique()) c = ['hsl('+str(h)+',50%'+',50%)' for h in np.linspace(0, 360, N)] for i in range(int(N)): subset = scatter.loc[scatter['gen'] == i] trace0 = go.Scatter( x=subset.loc[:, 'gen'], y=subset.loc[:, 'fitness'], mode='markers', marker=dict(size=7, line=dict(width=1), color=c[i], opacity=0.5 ), name='gen {}'.format(i), text=subset.loc[:, 'genome'] ) l.append(trace0) trace0 = go.Scatter( x=dt.loc[:, 'gen'], y=dt.loc[:, 'max'], mode='lines', name='Max', line=dict( color="rgb(204, 51, 51)", dash="solid", shape="spline", smoothing=0.0, width=2 ), ) trace1 = go.Scatter( x=dt.loc[:, 'gen'], y=dt.loc[:, 'median'], mode='lines', name='Median', line=dict( color="rgb(173, 181, 97)", shape="spline", dash="solid", smoothing=0.0, width=2 ) ) trace2 = go.Scatter( x=dt.loc[:, 'gen'], y=dt.loc[:, 'avg'], mode='lines', name='Average', line=dict( color="rgb(62, 173, 212)", shape="spline", dash="solid", smoothing=0.0, width=2 ) ) data = [trace0, trace1, trace2] layout = go.Layout( title='Fitness of Population Individuals - {}'.format(title), hovermode='closest', xaxis=dict( title='Generations', ticklen=5, zeroline=False, gridwidth=2, ), yaxis=dict( title='Fitness', ticklen=5, gridwidth=1, ), showlegend=False ) fig = go.Figure(data=data+l, layout=layout) return py.iplot(fig, filename='fitness-average-n-runs', layout=layout) def plot_scatter(dt, title): """Plots a Scatter plot of each individual in the population""" l = [] y = [] N = len(dt.gen.unique()) c = ['hsl('+str(h)+',50%'+',50%)' for h in np.linspace(0, 360, N)] for i in range(int(N)): subset = dt.loc[dt['gen'] == i] trace0 = go.Scatter( x=subset.loc[:, 'gen'], y=subset.loc[:, 'fitness'], mode='markers', marker=dict(size=14, line=dict(width=1), color=c[i], opacity=0.3 ), name='gen {}'.format(i), text=subset.loc[:, 'genome'], ) l.append(trace0) layout = go.Layout( title='Fitness of Population Individuals - {}'.format(title), hovermode='closest', xaxis=dict( title='Generations', ticklen=5, zeroline=False, gridwidth=2, ), yaxis=dict( title='Fitness', ticklen=5, gridwidth=1, ), showlegend=False ) fig = go.Figure(data=l, layout=layout) return py.iplot(fig, filename='population-scatter')
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 28686, 198, 11748, 269, 21370, 198, 11748, 4823, 85, 528, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 7110, 306, 13, 34960, 62, 672, 8457, 355, 467, 198, 11748, 7110, ...
1.911457
7,262
# -*- coding: utf-8 -*- """ --------------------------------------------- File Name: Desciption: Author: fanzhiwei date: 2019/9/5 9:58 --------------------------------------------- Change Activity: 2019/9/5 9:58 --------------------------------------------- """ import numpy as np import math import matplotlib.pyplot as plt from scipy import ndimage from PIL import Image LongRangeScanRaw = plt.imread("./1.tif") ShortRangeScanRaw = plt.imread("./2.tif") ShortRangeScanMean = ndimage.median_filter(ShortRangeScanRaw, 10) LongRangeScanMean = ndimage.median_filter(LongRangeScanRaw, 10) SizeLong = math.sqrt(LongRangeScanRaw.size) SizeShort = math.sqrt(ShortRangeScanRaw.size) if __name__ == "__main__": Longimage = Image.fromarray(ToBinary(LongRangeScanMean)) Shortimage = Image.fromarray(ToBinary(ShortRangeScanMean)) Longimage.save("new_1.bmp") Shortimage.save("new_2.bmp")
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 3880, 32501, 198, 220, 220, 220, 9220, 6530, 25, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 198, 220, 220, 220, 2935, 979, 1159, 25, 220, 220, 220...
2.622283
368
from django.utils.text import slugify from django_extensions.db.fields import AutoSlugField from django.db import models from datetime import datetime # Create your models here.
[ 6738, 42625, 14208, 13, 26791, 13, 5239, 1330, 31065, 1958, 198, 6738, 42625, 14208, 62, 2302, 5736, 13, 9945, 13, 25747, 1330, 11160, 11122, 1018, 15878, 628, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 4818, 8079, 1330, ...
3.54902
51
from brl_gym.estimators.learnable_bf.learnable_bf import LearnableBF #from brl_gym.estimators.learnable_bf.bf_dataset import BayesFilterDataset
[ 6738, 865, 75, 62, 1360, 76, 13, 395, 320, 2024, 13, 35720, 540, 62, 19881, 13, 35720, 540, 62, 19881, 1330, 14365, 540, 29499, 198, 2, 6738, 865, 75, 62, 1360, 76, 13, 395, 320, 2024, 13, 35720, 540, 62, 19881, 13, 19881, 62, 1...
2.636364
55
import os import argparse import logging import numpy as np import torch as th from torch.utils.data import DataLoader from torchvision import transforms import ttools from ttools.modules.image_operators import crop_like import rendernet.dataset as dset import rendernet.modules.preprocessors as pre import rendernet.modules.models as models import rendernet.interfaces as interfaces import rendernet.callbacks as cb import rendernet.viz as viz from sbmc.utils import make_variable import skimage.io as skio log = logging.getLogger("rendernet") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--checkpoint", required=True) parser.add_argument("--data", required=True) parser.add_argument("--output", required=True) args = parser.parse_args() ttools.set_logger(True) main(args)
[ 11748, 28686, 198, 11748, 1822, 29572, 198, 11748, 18931, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 355, 294, 198, 6738, 28034, 13, 26791, 13, 7890, 1330, 6060, 17401, 198, 6738, 28034, 10178, 1330, 31408, 198, 198, 1174...
3.314741
251
from django.db import models # Create your models here. from shortener.models import CondenseURL
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 198, 2, 13610, 534, 4981, 994, 13, 198, 6738, 1790, 877, 13, 27530, 1330, 9724, 1072, 21886 ]
3.88
25
if __name__ == "__main__": from pathlib import Path clean_pycache(Path(__file__).parents[2])
[ 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 422, 3108, 8019, 1330, 10644, 628, 220, 220, 220, 3424, 62, 9078, 23870, 7, 15235, 7, 834, 7753, 834, 737, 23743, 58, 17, 12962, 198 ]
2.536585
41
from dataclasses import dataclass from typing import List from orbsim_language.orbsim_ast.expression_node import ExpressionNode
[ 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 198, 6738, 19720, 1330, 7343, 198, 6738, 37403, 320, 62, 16129, 13, 273, 1443, 320, 62, 459, 13, 38011, 62, 17440, 1330, 41986, 19667 ]
3.96875
32
import sys import numpy as np import pandas as pd if __name__ == '__main__': argv = sys.argv if len(argv) < 7: print('USAGE: %s <in1_name> <in1_suffix> <in2_name> <in2_suffix> <out_name> <add_keys>'%argv[0]) sys.exit(-1) in1_name = argv[1] in1_suffix = argv[2] in2_name = argv[3] in2_suffix = argv[4] out_name = argv[5] add_keys = int(argv[6]) in1 = pd.read_csv(in1_name) in2 = pd.read_csv(in2_name) if add_keys: df_add_keys(in1) df_add_keys(in2) merged = df_merge(in1, in1_suffix, in2, in2_suffix) merged.to_csv(out_name)
[ 11748, 25064, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1822, 85, 796, 25064, 13, 853, 85, 198, 220, 220, 2...
1.811765
340
from sys import stdout
[ 6738, 25064, 1330, 14367, 448, 628 ]
4
6
import argparse import csv import os parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', help="Input path of the missing urls CSV file") parser.add_argument('-o', '--output', help="Output directory where the new CSV files will be stored") parser.add_argument('-q', '--quiet', action='store_true', help="Do not print the list of missing files") args = parser.parse_args() with open(args.input) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') missing_urls_output = os.path.join(args.output, 'silknow-missing-urls.csv') missing_files_output = os.path.join(args.output, 'silknow-missing-files.csv') with open(missing_urls_output, mode='w') as missing_url: missing_url_writer = csv.writer(missing_url, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) with open(missing_files_output, mode='w') as missing_file: missing_file_writer = csv.writer(missing_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) header = next(csv_reader) missing_file_writer.writerow(header); filepath_cache = [] for row in csv_reader: museum = row[3].split('/')[5] filename = os.path.basename(row[3]) filepath = os.path.normpath(os.path.join(museum, filename)) filepath_cache.append(filepath) if not os.path.exists(filepath): missing_file_writer.writerow(row) if not args.quiet: print(filepath + ' does not exist in files') for root, dirs, files in os.walk('./'): for file in files: if file.endswith('.jpg'): filepath = os.path.normpath(os.path.join(root, file)) if filepath not in filepath_cache: missing_url_writer.writerow([filepath]) if not args.quiet: print(filepath + ' does not exist in query result')
[ 11748, 1822, 29572, 198, 11748, 269, 21370, 198, 11748, 28686, 198, 198, 48610, 796, 1822, 29572, 13, 28100, 1713, 46677, 3419, 198, 48610, 13, 2860, 62, 49140, 10786, 12, 72, 3256, 705, 438, 15414, 3256, 1037, 2625, 20560, 3108, 286, 2...
2.486523
742
# -*- coding: utf-8 -*- """ Created on Tue Nov 21 11:20:06 2017 @author: NPB """ import cv2 import pickle
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 30030, 5267, 2310, 1367, 25, 1238, 25, 3312, 2177, 198, 198, 31, 9800, 25, 28498, 33, 198, 37811, 198, 198, 11748, 269, 85, 17, 198, 11748, 229...
2.291667
48
# @Created Date: 2019-12-08 06:46:49 pm # @Filename: api.py # @Email: 1730416009@stu.suda.edu.cn # @Author: ZeFeng Zhu # @Last Modified: 2020-02-16 10:54:32 am # @Copyright (c) 2020 MinghuiGroup, Soochow University from typing import Iterable, Iterator, Optional, Union, Generator, Dict, List from time import perf_counter from numpy import nan, array from pathlib import Path from unsync import unsync, Unfuture from copy import deepcopy from pdb_profiling.log import Abclog from pdb_profiling.utils import init_semaphore, init_folder_from_suffix, init_folder_from_suffixes, a_read_csv from pdb_profiling.fetcher.webfetch import UnsyncFetch from uuid import uuid4 from pdb_profiling.cif_gz_stream import iter_index from aiohttp import ClientSession from aiofiles import open as aiofiles_open from pdb_profiling.ensure import EnsureBase from tenacity import wait_random, stop_after_attempt ensure = EnsureBase() rt_kw = dict(wait=wait_random(max=20), stop=stop_after_attempt(6)) """QUERY_COLUMNS: List[str] = [ 'id', 'length', 'reviewed', 'comment(ALTERNATIVE%20PRODUCTS)', 'feature(ALTERNATIVE%20SEQUENCE)', 'genes', 'organism', 'protein%20names'] RESULT_COLUMNS: List[str] = [ 'Entry', 'Length', 'Status', 'Alternative products (isoforms)', 'Alternative sequence', 'Gene names', 'Organism', 'Protein names'] COLUMNS_DICT: Dict = dict(zip(QUERY_COLUMNS, RESULT_COLUMNS)) RESULT_NEW_COLUMN: List[str] = ['yourlist', 'isomap']""" BASE_URL: str = 'https://www.uniprot.org' """PARAMS: Dict = { # 'fil': 'organism%3A"Homo+sapiens+(Human)+[9606]"+AND+reviewed%3Ayes', # reviewed:yes+AND+organism:9606 'columns': None, 'query': None, 'from': None, 'to': 'ACC', 'format': 'tab'}""" """ class MapUniProtID(Abclog): ''' Implement UniProt Retrieve/ID Mapping API ''' def __init__(self, id_col: str, id_type: str, dfrm: Optional[DataFrame], ids: Optional[Iterable] = None, sites: Optional[Iterable] = None, genes: Optional[Iterable] = None, usecols: Optional[Iterable] = QUERY_COLUMNS, site_col: Optional[str] = None, gene_col: Optional[str] = None, logger: Optional[logging.Logger] = None, loggingPath: Optional[str] = None): self.init_logger(self.__class__.__name__, logger) if dfrm is not None: self.dfrm = dfrm.drop_duplicates().reset_index(drop=True) else: ''' the length of dataframe is based on: * the num of `ids` if there is more than one id * the num of `sites` if there is just one id with specified `sites` ''' if isinstance(ids, str): if sites is not None and not isinstance(sites, str): index_len = len(sites) else: index_len = 1 else: index_len = len(ids) self.dfrm = DataFrame(dict(zip( (col for col in (id_col, site_col, gene_col) if col is not None), (value for value in (ids, sites, genes) if value is not None))), index=list(range(index_len))) self.index = dfrm.index self.id_col = id_col self.id_type = id_type self.site_col = site_col self.gene_col = gene_col self.loggingPath = loggingPath if isinstance(usecols, str): PARAMS['columns'] = usecols usecols = usecols.split(',') elif isinstance(usecols, (Iterable, Iterator)): PARAMS['columns'] = ','.join(usecols) else: raise ValueError('Invalid usecols') self.usecols = usecols PARAMS['from'] = id_type if isinstance(loggingPath, (str, Path)): self.set_logging_fileHandler(loggingPath) @property def sites(self) -> Generator: if self.site_col is not None: for name, group in self.dfrm.groupby(by=self.id_col, sort=False): yield name, group[self.site_col] else: yield None @staticmethod def split_df(dfrm, colName, sep): '''Split DataFrame''' df = dfrm.copy() return df.drop([colName], axis=1).join(df[colName].str.split(sep, expand=True).stack().reset_index(level=1, drop=True).rename(colName)) def yieldTasks(self, lyst: Iterable, chunksize: int = 100, sep: str = ',') -> Generator: fileName = self.outputPath.stem for i in range(0, len(lyst), chunksize): cur_fileName = f'{fileName}+{i}' cur_params = deepcopy(PARAMS) cur_params['query'] = sep.join(lyst[i:i+chunksize]) # self.outputPath.suffix yield ('get', {'url': f'{BASE_URL}/uploadlists/', 'params': cur_params}, str(Path(self.outputPath.parent, cur_fileName+'.tsv'))) def retrieve(self, outputPath: Union[str, Path], finishedPath: Optional[str] = None, sep: str = '\t', chunksize: int = 100, concur_req: int = 20, rate: float = 1.5, ret_res: bool = True, semaphore = None): finish_id = list() self.outputPath = Path(outputPath) self.result_cols = [COLUMNS_DICT.get( i, i) for i in self.usecols] + RESULT_NEW_COLUMN if finishedPath is not None: try: target_col = RESULT_NEW_COLUMN[0] finish: Series = read_csv( finishedPath, sep=sep, usecols=[target_col], names=self.result_cols, skiprows=1, header=None)[target_col] except Exception as e: col_to_add = RESULT_NEW_COLUMN[1] self.logger.warning( f"{e}\nSomething wrong with finished raw file, probably without '{col_to_add}' column.") finish_df = read_csv( finishedPath, sep=sep, names=self.result_cols[:-1], skiprows=1, header=None) finish_df[col_to_add] = nan finish_df.to_csv(finishedPath, sep=sep, index=False) finish: Series = finish_df[target_col] for query_id in finish: if ',' in query_id: finish_id.extend(query_id.split(',')) else: finish_id.append(query_id) query_id: Series = self.dfrm[self.id_col] if finish_id: rest_id = list(set(query_id) - set(finish_id)) else: rest_id = query_id.unique() self.logger.info( f"Have finished {len(finish_id)} ids, {len(rest_id)} ids left.") res = UnsyncFetch.multi_tasks( tasks=self.yieldTasks(rest_id, chunksize), to_do_func=self.process, concur_req=concur_req, rate=rate, ret_res=ret_res, semaphore=semaphore) return res def getCanonicalInfo(self, dfrm: DataFrame): ''' Will Change the dfrm * Add new column (canonical_isoform) * Change the content of column (UniProt) ''' # Get info from Alt Product file if self.altProPath is None: dfrm['canonical_isoform'] = nan return dfrm else: usecols = ["IsoId", "Sequence", "Entry", "UniProt"] altPro_df = read_csv(self.altProPath, sep="\t", usecols=usecols) altPro_df = altPro_df[altPro_df["Sequence"] == "Displayed"].reset_index(drop=True) altPro_df.rename( columns={"IsoId": "canonical_isoform"}, inplace=True) # Modify dfrm dfrm = merge( dfrm, altPro_df[["canonical_isoform", "Entry"]], how="left") return dfrm def getGeneStatus(self, handled_df: DataFrame, colName: str = 'GENE_status'): ''' Will Change the dfrm, add Gene Status * Add new column (GENE) # if id_col != gene_col * Add new column (GENE_status) **About GENE_status** * ``False`` : First element of Gene names is not correspond with refSeq's GENE (e.g) * others(corresponding GENE) ''' self.gene_status_col = colName if self.id_type != 'GENENAME': if self.gene_col is None: handled_df[colName] = True return None gene_map = self.dfrm[[self.id_col, self.gene_col]].drop_duplicates() gene_map = gene_map.groupby(self.id_col)[self.gene_col].apply( lambda x: array(x) if len(x) > 1 else list(x)[0]) handled_df['GENE'] = handled_df.apply( lambda z: gene_map[z['yourlist']], axis=1) handled_df[colName] = handled_df.apply(lambda x: x['GENE'] == x['Gene names'].split( ' ')[0] if not isinstance(x['Gene names'], float) else False, axis=1) handled_df['GENE'] = handled_df['GENE'].apply( lambda x: ','.join(x) if not isinstance(x, str) else x) else: handled_df[colName] = handled_df.apply(lambda x: x['yourlist'] == x['Gene names'].split( ' ')[0] if not isinstance(x['Gene names'], float) else False, axis=1) def label_mapping_status(self, dfrm: DataFrame, colName: str = 'Mapping_status'): self.mapping_status_col = colName gene_status_col = self.gene_status_col dfrm[colName] = 'No' dfrm[gene_status_col] = dfrm[gene_status_col].apply( lambda x: x.any() if isinstance(x, Iterable) else x) if self.id_col == 'GENENAME': pass_df = dfrm[ (dfrm[gene_status_col] == True) & (dfrm['Status'] == 'reviewed') & (dfrm['unp_map_tage'] != 'Untrusted & No Isoform')] else: pass_df = dfrm[ (dfrm['Status'] == 'reviewed') & (dfrm['unp_map_tage'] != 'Untrusted & No Isoform')] pass_index = pass_df.index dfrm.loc[pass_index, colName] = 'Yes' # Deal with 'one to many' situation multipleCounter = Counter(dfrm.loc[pass_index, 'yourlist']) err_li = [i for i, j in multipleCounter.items() if j > 1] err_index = pass_df[pass_df['yourlist'].isin(err_li)].index dfrm.loc[err_index, colName] = 'Error' @unsync async def process(self, path: Union[str, Path, Unfuture], sep: str = '\t'): self.logger.debug("Start to handle id mapping result") if not isinstance(path, (Path, str)): path = await path # .result() if not Path(path).stat().st_size: return None self.altSeqPath, self.altProPath = ExtractIsoAlt.main(path=path) try: df = read_csv( path, sep='\t', names=self.result_cols, skiprows=1, header=None) except ValueError: df = read_csv( path, sep='\t', names=self.result_cols[:-1], skiprows=1, header=None) # Add New Column: canonical_isoform df = self.getCanonicalInfo(df) # Add New Column: unp_map_tage df['unp_map_tage'] = nan # Classification df_with_no_isomap = df[df['isomap'].isnull()] # Class A df_with_isomap = df[df['isomap'].notnull()] # Class B # ---------------------------------------------------------------------- # In Class A # ---------------------------------------------------------------------- if len(df_with_no_isomap) > 0: df_wni_split = self.split_df(df_with_no_isomap, 'yourlist', ',') df_wni_split.drop(columns=['isomap'], inplace=True) # [yourlist <-> UniProt] df_wni_split['UniProt'] = df_wni_split['Entry'] df_wni_split['unp_map_tage'] = 'Trusted & No Isoform' # Find out special cases 1 df_wni_split_warn = df_wni_split[df_wni_split['Alternative products (isoforms)'].notnull( )].index df_wni_split.loc[df_wni_split_warn, 'unp_map_tage'] = 'Untrusted & No Isoform' # 'Entry', 'Gene names', 'Status', 'Alternative products (isoforms)', 'Organism', 'yourlist', 'UniProt' # ---------------------------------------------------------------------- # In Class B # ---------------------------------------------------------------------- if len(df_with_isomap) > 0: wi_yourlist_count = df_with_isomap.apply( lambda x: x['yourlist'].count(','), axis=1) wi_isomap_count = df_with_isomap.apply( lambda x: x['isomap'].count(','), axis=1) # In subClass 1 df_wi_eq = df_with_isomap.loc[wi_yourlist_count[wi_yourlist_count == wi_isomap_count].index] if len(df_wi_eq) > 0: df_wi_eq_split = self.split_df( df_wi_eq.drop(columns=['yourlist']), 'isomap', ',') df_wi_eq_split[['yourlist', 'UniProt']] = df_wi_eq_split['isomap'].str.split( ' -> ', expand=True) # [yourlist <-> UniProt] df_wi_eq_split.drop(columns=['isomap'], inplace=True) df_wi_eq_split['unp_map_tage'] = 'Trusted & Isoform' # # 'Entry', 'Gene names', 'Status', 'Alternative products (isoforms)', 'Organism', 'yourlist', 'UniProt' # In subClass 2 df_wi_ne = df_with_isomap.loc[wi_yourlist_count[wi_yourlist_count != wi_isomap_count].index] if len(df_wi_ne) > 0: df_wi_ne_split = self.split_df(df_wi_ne, 'isomap', ',') df_wi_ne_split.rename( columns={'yourlist': 'checkinglist'}, inplace=True) df_wi_ne_split[['yourlist', 'UniProt']] = df_wi_ne_split['isomap'].str.split( ' -> ', expand=True) df_wi_ne_split.drop(columns=['isomap'], inplace=True) df_wi_ne_split['unp_map_tage'] = 'Trusted & Isoform & Contain Warnings' # 'Entry', 'Gene names', 'Status', 'Alternative products (isoforms)', 'Organism', 'yourlist', 'UniProt', 'checkinglist' # Find out special cases 2 usecols = Index(set(df_wi_ne_split.columns) - {'yourlist', 'UniProt'}) df_wi_ne_warn = self.split_df( df_wi_ne_split[usecols].drop_duplicates(), 'checkinglist', ',') df_wi_ne_warn = df_wi_ne_warn[~df_wi_ne_warn['checkinglist'].isin( df_wi_ne_split['yourlist'])].rename(columns={'checkinglist': 'yourlist'}) df_wi_ne_warn['UniProt'] = df_wi_ne_warn['Entry'] # sequence conflict df_wi_ne_warn['unp_map_tage'] = 'Untrusted & No Isoform' df_wi_ne_split.drop(columns=['checkinglist'], inplace=True) # Concat Dfrm variables = ["df_wni_split", "df_wi_eq_split", "df_wi_ne_split", "df_wi_ne_warn"] lvs = locals() varLyst = [lvs[variable] for variable in variables if variable in lvs] final_df = concat(varLyst, sort=False).reset_index(drop=True) cano_index = final_df[final_df["canonical_isoform"].notnull()].index if len(cano_index) > 0: final_df.loc[cano_index, "UniProt"] = final_df.loc[cano_index, ].apply( lambda x: x["Entry"] if x["UniProt"] in x["canonical_isoform"] else x["UniProt"], axis=1) # Add Gene Status self.getGeneStatus(final_df) # Label Mapping Status self.label_mapping_status(final_df) pathOb = Path(path) edPath = str(Path(pathOb.parent, f'{pathOb.stem}_ed.tsv')) # {pathOb.suffix} final_df.to_csv(edPath, sep=sep, index=False) self.logger.debug(f"Handled id mapping result saved in {edPath}") return edPath """ def task_unit(self, unp:str): cur_fileName = f'{unp}.{self.suffix}' return ('get', {'url': f'{BASE_URL}/uniprot/{cur_fileName}', 'params': self.params}, self.get_cur_folder()/cur_fileName) def single_retrieve(self, identifier: str, rate: float = 1.5): return UnsyncFetch.single_task( task=self.task_unit(identifier), semaphore=self.web_semaphore, rate=rate) def stream_retrieve_txt(self, identifier, name_suffix='VAR_SEQ', **kwargs): assert self.suffix == 'txt' return self.txt_writer(handle=self.txt_reader(f'{BASE_URL}/uniprot/{identifier}.{self.suffix}'), path=self.get_cur_folder()/f'{identifier}+{name_suffix}.{self.suffix}', **kwargs)
[ 2, 2488, 41972, 7536, 25, 13130, 12, 1065, 12, 2919, 9130, 25, 3510, 25, 2920, 9114, 198, 2, 2488, 35063, 25, 40391, 13, 9078, 198, 2, 2488, 15333, 25, 220, 1596, 21288, 1433, 28694, 31, 301, 84, 13, 82, 15339, 13, 15532, 13, 3152...
1.983362
8,595
''' Function and classes representing statistical tools. ''' __author__ = ['Miguel Ramos Pernas'] __email__ = ['miguel.ramos.pernas@cern.ch'] from hep_spt.stats.core import chi2_one_dof, one_sigma from hep_spt.core import decorate, taking_ndarray from hep_spt import PACKAGE_PATH import numpy as np import os from scipy.stats import poisson from scipy.optimize import fsolve import warnings __all__ = ['calc_poisson_fu', 'calc_poisson_llu', 'gauss_unc', 'poisson_fu', 'poisson_llu', 'sw2_unc' ] # Number after which the poisson uncertainty is considered to # be the same as that of a gaussian with "std = sqrt(lambda)". __poisson_to_gauss__ = 200 def _access_db(name): ''' Access a database table under 'data/'. :param name: name of the file holding the data. :type name: str :returns: Array holding the data. :rtype: numpy.ndarray ''' ifile = os.path.join(PACKAGE_PATH, 'data', name) table = np.loadtxt(ifile) return table def gauss_unc(s, cl=one_sigma): ''' Calculate the gaussian uncertainty for a given confidence level. :param s: standard deviation of the gaussian. :type s: float or numpy.ndarray(float) :param cl: confidence level. :type cl: float :returns: Gaussian uncertainty. :rtype: float or numpy.ndarray(float) .. seealso:: :func:`poisson_fu`, :func:`poisson_llu`, :func:`sw2_unc` ''' n = np.sqrt(chi2_one_dof.ppf(cl)) return n*s def poisson_fu(m): ''' Return the poisson frequentist uncertainty at one standard deviation of confidence level. :param m: measured value(s). :type m: int or numpy.ndarray(int) :returns: Lower and upper frequentist uncertainties. :rtype: numpy.ndarray(float, float) .. seealso:: :func:`gauss_unc`, :func:`poisson_llu`, :func:`sw2_unc` ''' return _poisson_unc_from_db(m, 'poisson_fu.dat') def poisson_llu(m): ''' Return the poisson uncertainty at one standard deviation of confidence level. The lower and upper uncertainties are defined by those two points with a variation of one in the value of the negative logarithm of the likelihood multiplied by two: .. math:: \\sigma_\\text{low} = n_\\text{obs} - \\lambda_\\text{low} .. math:: \\alpha - 2\\log P(n_\\text{obs}|\\lambda_\\text{low}) = 1 .. math:: \\sigma_\\text{up} = \\lambda_\\text{up} - n_\\text{obs} .. math:: \\alpha - 2\\log P(n_\\text{obs}|\\lambda_\\text{up}) = 1 where :math:`\\alpha = 2\\log P(n_\\text{obs}|n_\\text{obs})`. :param m: measured value(s). :type m: int or numpy.ndarray(int) :returns: Lower and upper frequentist uncertainties. :rtype: numpy.ndarray(float, float) .. seealso:: :func:`gauss_unc`, :func:`poisson_fu`, :func:`sw2_unc` ''' return _poisson_unc_from_db(m, 'poisson_llu.dat') def _poisson_unc_from_db(m, database): ''' Used in functions to calculate poissonian uncertainties, which are partially stored on databases. If "m" is above the maximum number stored in the database, the gaussian approximation is taken instead. :param m: measured value(s). :type m: int or numpy.ndarray(int) :param database: name of the database. :type database: str :returns: Lower and upper frequentist uncertainties. :rtype: (float, float) or numpy.ndarray(float, float) :raises TypeError: if the input is a (has) non-integer value(s). :raises ValueError: if the input value(s) is(are) not positive. ''' m = np.array(m) if not np.issubdtype(m.dtype, np.integer): raise TypeError('Calling function with a non-integer value') if np.any(m < 0): raise ValueError('Values must be positive') scalar_input = False if m.ndim == 0: m = m[None] scalar_input = True no_app = (m < __poisson_to_gauss__) if np.count_nonzero(no_app) == 0: # We can use the gaussian approximation in all out = np.array(2*[np.sqrt(m)]).T else: # Non-approximated uncertainties table = _access_db(database) out = np.zeros((len(m), 2), dtype=np.float64) out[no_app] = table[m[no_app]] mk_app = np.logical_not(no_app) if mk_app.any(): # Use the gaussian approximation for the rest out[mk_app] = np.array(2*[np.sqrt(m[mk_app])]).T if scalar_input: return np.squeeze(out) return out def _process_poisson_unc(m, lw, up): ''' Calculate the uncertainties and display an error if they have been incorrectly calculated. :param m: mean value. :type m: float :param lw: lower bound. :type lw: float :param up: upper bound. :type up: float :returns: Lower and upper uncertainties. :type: numpy.ndarray(float, float) ''' s_lw = m - lw s_up = up - m if any(s < 0 for s in (s_lw, s_up)): warnings.warn('Poisson uncertainties have been ' 'incorrectly calculated') # numpy.vectorize needs to know the exact type of the output return float(s_lw), float(s_up) def sw2_unc(arr, bins=20, range=None, weights=None): ''' Calculate the errors using the sum of squares of weights. The uncertainty is calculated as follows: .. math:: \\sigma_i = \\sqrt{\\sum_{j = 0}^{n - 1} \\omega_{i,j}^2} where *i* refers to the i-th bin and :math:`j \\in [0, n)` refers to each entry in that bin with weight :math:`\\omega_{i,j}`. If "weights" is None, then this coincides with the square root of the number of entries in each bin. :param arr: input array of data to process. :param bins: see :func:`numpy.histogram`. :type bins: int, sequence of scalars or str :param range: range to process in the input array. :type range: None or tuple(float, float) :param weights: possible weights for the histogram. :type weights: None or numpy.ndarray(value-type) :returns: Symmetric uncertainty. :rtype: numpy.ndarray .. seealso:: :func:`gauss_unc`, :func:`poisson_fu`, :func:`poisson_llu` ''' if weights is not None: values = np.histogram(arr, bins, range, weights=weights*weights)[0] else: values = np.histogram(arr, bins, range)[0] return np.sqrt(values) if __name__ == '__main__': ''' Generate the tables to store the pre-calculated values of some uncertainties. ''' m = np.arange(__poisson_to_gauss__) print('Creating databases:') for func in (calc_poisson_fu, calc_poisson_llu): ucts = np.array(func(m, one_sigma)).T name = func.__name__.replace('calc_', r'') + '.dat' fpath = os.path.join('data', name) print('- {}'.format(fpath)) np.savetxt(fpath, ucts)
[ 7061, 6, 198, 22203, 290, 6097, 10200, 13905, 4899, 13, 198, 7061, 6, 198, 198, 834, 9800, 834, 796, 37250, 44, 328, 2731, 36692, 350, 1142, 292, 20520, 198, 834, 12888, 834, 796, 37250, 76, 328, 2731, 13, 859, 418, 13, 525, 24716, ...
2.439459
2,808
import tornado import logging import httplib try: import simplejson as json except ImportError: import json from octopus.core.framework.wsappframework import WSAppFramework, MainLoopApplication from octopus.core.framework.webservice import MappingSet from octopus.core.communication.http import Http400 from octopus.core.tools import Workload __all__ = ['WSAppFramework', 'MainLoopApplication'] __all__ += ['Controller', 'ControllerError', 'ResourceNotFoundErro', 'BaseResource'] logger = logging.getLogger('main.dispatcher.webservice')
[ 11748, 33718, 198, 11748, 18931, 198, 11748, 1841, 489, 571, 198, 28311, 25, 198, 220, 220, 220, 1330, 2829, 17752, 355, 33918, 198, 16341, 17267, 12331, 25, 198, 220, 220, 220, 1330, 33918, 198, 198, 6738, 19318, 25790, 13, 7295, 13, ...
3.363636
165
from provstore.document import Document from provstore.bundle_manager import BundleManager from provstore.bundle import Bundle
[ 6738, 899, 8095, 13, 22897, 1330, 16854, 198, 6738, 899, 8095, 13, 65, 31249, 62, 37153, 1330, 25282, 13511, 198, 6738, 899, 8095, 13, 65, 31249, 1330, 25282, 198 ]
4.37931
29
from __future__ import annotations import typing as tp from loguru import logger
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 11748, 19720, 355, 256, 79, 198, 198, 6738, 2604, 14717, 1330, 49706, 628 ]
4.15
20
# Login to https://developer.spotify.com/dashboard/, create an application and fill these out before use! client_id = "" client_secret = ""
[ 2, 23093, 284, 3740, 1378, 16244, 263, 13, 20485, 1958, 13, 785, 14, 42460, 3526, 47454, 2251, 281, 3586, 290, 6070, 777, 503, 878, 779, 0, 198, 16366, 62, 312, 796, 13538, 198, 16366, 62, 21078, 796, 13538 ]
3.657895
38
import cv2 import numpy as np import matplotlib.image as mpimg from pathlib import Path from model import * CAMERA_STEERING_CORRECTION = 0.2 def image_path(sample, camera="center"): """ Transform the sample path to the repository structure. Args: sample: a sample (row) of the data dataframe. Usually drawn of a batch by the generator camera: the camera to extract the path for Returns: the converted image path string """ return str(Path(f"./data/{sample[camera].split('data')[-1]}")) def crop_image(image, top=60, bot=25): """ Crop the upper and lower borders of the given image. Args: image: the image to crop top: the pixels to crop from the upper part bot: the pixels to crop from the bottom part Returns: the cropped image """ return image[top:-bot, :, :] def resize_image(image, shape=NVIDIA_SHAPE[0:2]): """ Resize the image to shape. Args: image: input image shape: (height, width) tuple, defaults to Nvidia input shape (66, 200) Returns: the resized image """ h, w = shape return cv2.resize(image, dsize=(w, h), interpolation=cv2.INTER_AREA) def rgb2yuv(rgb_image): """ Convert the RGB image to YUV space. """ return cv2.cvtColor(rgb_image, cv2.COLOR_RGB2YUV) def rgb2hsv(rgb_image): """ Convert the RGB image to HSV space. """ return cv2.cvtColor(rgb_image, cv2.COLOR_RGB2HSV) def hsv2rgb(hsv_image): """ Convert the HSV image to RGB space. """ return cv2.cvtColor(hsv_image, cv2.COLOR_HSV2RGB) def choose_camera(sample, camera='random', probs=None): """ Choose an image for a specific camera and eventually adjust the steering. The steering of the left and right cameras is adjusted according to the defined constant CAMERA_STEERING_CONSTANT Args: sample: a sample (row) of the data dataframe. Usually drawn of a batch by the generator camera: 'random', 'left', 'center' or 'right'. If 'random' choose the camera with the given probabilities. probs: the probabilities to choose the left, center or right cameras. If None, the probabilities are uniform. Returns: a (image, steering) tuple """ if camera == 'random': camera = np.random.choice(["left", "center", "right"], p=probs) image = mpimg.imread(image_path(sample, camera=camera)) steering = sample["steer"] if camera == "left": steering += CAMERA_STEERING_CORRECTION elif camera == "right": steering -= CAMERA_STEERING_CORRECTION return image, steering def flip(image, steering, prob=0.5): """ Flip the image and steering with the given probability. Args: image: the image to flip steering: the steering corresponding to the image prob: the flip probability Returns: the augmented image """ if np.random.random() < prob: image = cv2.flip(image, 1) steering *= -1 return image, steering def shadow(rgb_image, prob=0.5): """ Add a shadow to the rgb image with the given probability. The shadow is created by converting the RGB image into HSV space and modifying the value channel in a random range. The area in which the value is modified is defined by a convex hull created for 6 randomly chosen points in the lower half of the image. Args: rgb_image: the image to add the shadow to. Has to be in RGB space. prob: the probability to add the shadow Returns: the augmented image """ if np.random.random() < prob: width, height = rgb_image.shape[1], rgb_image.shape[0] # Get 6 random vertices in the lower half of the image x = np.random.randint(-0.1 * width, 1.1 * width, 6) y = np.random.randint(height * 0.5, 1.1 * height, 6) vertices = np.column_stack((x, y)).astype(np.int32) vertices = cv2.convexHull(vertices).squeeze() # Intilialize mask mask = np.zeros((height, width), dtype=np.int32) # Create the polygon mask cv2.fillPoly(mask, [vertices], 1) # Adjust value hsv = rgb2hsv(rgb_image) v = hsv[:, :, 2] hsv[:, :, 2] = np.where(mask, v * np.random.uniform(0.5, 0.8), v) rgb_image = hsv2rgb(hsv) return rgb_image def brightness(rgb_image, low=0.6, high=1.4, prob=0.5): """ Modify the brighntess of the rgb image with the given probability. The brightness is modified by converting the RGB image into HSV space and adusting the value channel in a random range between the low and high bounds. Args: rgb_image: the image to modify the brightness. Has to be in RGB space. low: lower value bound high: upper value bound prob: the probability to modify the brightness Returns: the augmented image """ if np.random.random() < prob: hsv = rgb2hsv(rgb_image) value = hsv[:, :, 2] hsv[:, :, 2] = np.clip(value * np.random.uniform(low, high), 0, 255) rgb_image = hsv2rgb(hsv) return rgb_image def shift(image, steering, shiftx=60, shifty=20, prob=0.5): """ Shift the image and adjust the steering with the given probability. The steering of the shifted image is adjusted depending on the amount of pixels shifted in the width direction. Args: image: the image to shift. steering: the corresponding steering. shiftx: the upper bound of pixels to shift in the width direction shifty: the upper bound of pixels to shift in the height direction prob: the probability to shift the image Returns: the augmented image """ if np.random.random() < prob: # The angle correction per pixel is derived from the angle correction # specified for the side cameras. It is estimated that the images of two # adjacent cameras are shifted by 80 pixels (at the bottom of the image) angle_correction_per_pixel = CAMERA_STEERING_CORRECTION / 80 # Draw translations in x and y directions from a uniform distribution tx = int(np.random.uniform(-shiftx, shiftx)) ty = int(np.random.uniform(-shifty, shifty)) # Transformation matrix mat = np.float32([[1, 0, tx], [0, 1, ty]]) # Transform image and correct steering angle height, width, _ = image.shape image = cv2.warpAffine(image, mat, (width, height), borderMode=cv2.BORDER_REPLICATE) steering += tx * angle_correction_per_pixel return image, steering def augment(sample, camera_probs=None, flip_prob=0.5, shadow_prob=0.5, bright_prob=0.5, shift_prob=0.5, ): """ Augment the sample with the given probabilities. Args: sample: a sample (row) of the data dataframe. Usually drawn of a batch by the generator camera_probs: the probabilities to draw left, center or right camera images flip_prob: probability for an image to be flipped shadow_prob: probability of shadow additon to the image bright_prob: probability to modify the brightness of the image shift_prob: probability for and image to be shifed """ image, steering = choose_camera(sample, probs=camera_probs) image, steering = flip(image, steering, prob=flip_prob) image = shadow(image, prob=shadow_prob) image = brightness(image, prob=bright_prob) image, steering = shift(image, steering, prob=shift_prob) return image, steering
[ 11748, 269, 85, 17, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 11748, 2603, 29487, 8019, 13, 9060, 355, 29034, 9600, 201, 198, 201, 198, 6738, 3108, 8019, 1330, 10644, 201, 198, 201, 198, 6738, 2746, 1330, 1635, 201, 198, 201,...
2.461996
3,197
import json import logging from typing import List import os import sys import numpy as np import torch from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer, BertTokenizer from vilbert.vilbert import BertConfig from utils.cli import get_parser from utils.dataset.common import pad_packed, load_json_data from utils.dataset.zero_shot_dataset import ZeroShotDataset from utils.dataset import PanoFeaturesReader from airbert import Airbert from train import get_model_input, get_mask_options logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO, stream=sys.stdout, ) logger = logging.getLogger(__name__) # ------------- # # batch parsing # # ------------- # if __name__ == "__main__": main()
[ 11748, 33918, 198, 11748, 18931, 198, 6738, 19720, 1330, 7343, 198, 11748, 28686, 198, 11748, 25064, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 6738, 28034, 13, 26791, 13, 7890, 1330, 6060, 17401, 198, 6738, 256, 80,...
2.821192
302
from modeledcommandparameter import * from pseudoregion import *
[ 6738, 29563, 21812, 17143, 2357, 1330, 1635, 198, 6738, 25038, 382, 70, 295, 1330, 1635, 198 ]
4.0625
16
import numpy as np import torch from torch.nn import functional as F from torch.utils.data import Dataset, DataLoader from torchvision import datasets, transforms from torchvision.utils import save_image from utils.fast_tensor_dataloader import FastTensorDataLoader
[ 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 6738, 28034, 13, 20471, 1330, 10345, 355, 376, 198, 6738, 28034, 13, 26791, 13, 7890, 1330, 16092, 292, 316, 11, 6060, 17401, 198, 6738, 28034, 10178, 1330, 40522, 11, 31408, 198, 6...
3.702703
74
from flask import ( Blueprint,session, flash, g, redirect, render_template, request, url_for ) from werkzeug.exceptions import abort from anonymail.auth import login_required from anonymail.db import get_db import datetime now = datetime.datetime.now() current_year = now.year bp = Blueprint('posts', __name__)
[ 6738, 42903, 1330, 357, 198, 220, 220, 220, 39932, 11, 29891, 11, 7644, 11, 308, 11, 18941, 11, 8543, 62, 28243, 11, 2581, 11, 19016, 62, 1640, 198, 8, 198, 6738, 266, 9587, 2736, 1018, 13, 1069, 11755, 1330, 15614, 198, 198, 6738, ...
3.22449
98
# from python-decouple import config from flask import Flask, request, jsonify from .obj_detector import object_detection # from flask_sqlalchemy import SQLAlchemy from dotenv import load_dotenv load_dotenv()
[ 2, 422, 21015, 12, 12501, 43846, 1330, 4566, 201, 198, 6738, 42903, 1330, 46947, 11, 2581, 11, 33918, 1958, 201, 198, 6738, 764, 26801, 62, 15255, 9250, 1330, 2134, 62, 15255, 3213, 201, 198, 2, 422, 42903, 62, 25410, 282, 26599, 1330...
3.220588
68
from .subroutine import subroutine from parameters.string_parameter import string_parameter as String from parameters.numeric_parameter import numeric_parameter as Numeric from parameters.array_parameter import array_parameter as Array from ast import literal_eval
[ 6738, 764, 7266, 81, 28399, 1330, 850, 81, 28399, 198, 6738, 10007, 13, 8841, 62, 17143, 2357, 1330, 4731, 62, 17143, 2357, 355, 10903, 198, 6738, 10007, 13, 77, 39223, 62, 17143, 2357, 1330, 35575, 62, 17143, 2357, 355, 399, 39223, 1...
4.092308
65
import requests import json from config import config from logbook import Logger, StreamHandler import sys StreamHandler(sys.stdout).push_application() log = Logger('auth')
[ 11748, 7007, 198, 11748, 33918, 198, 6738, 4566, 1330, 4566, 198, 6738, 2604, 2070, 1330, 5972, 1362, 11, 13860, 25060, 198, 11748, 25064, 198, 198, 12124, 25060, 7, 17597, 13, 19282, 448, 737, 14689, 62, 31438, 3419, 198, 6404, 796, 59...
3.804348
46
# Copyright (c) 2019 Bita Hasheminezhad # # Distributed under the Boost Software License, Version 1.0. (See accompanying # file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) # #942: `fold_left`, `fold_right` and `fmap` do not work with a lazy function import numpy as np from phylanx import Phylanx, PhylanxSession, execution_tree PhylanxSession.init(1) sum = Phylanx.lazy(sum_eager) result = test_map(np.array([[1, 2, 3]])) assert(np.all(result == [6])), result result = test_map(np.array([1, 2, 3])) assert(np.all(result == [1, 2, 3])), result
[ 2, 220, 15069, 357, 66, 8, 13130, 4722, 64, 7875, 258, 3810, 89, 18108, 198, 2, 198, 2, 220, 4307, 6169, 739, 262, 19835, 10442, 13789, 11, 10628, 352, 13, 15, 13, 357, 6214, 19249, 198, 2, 220, 2393, 38559, 24290, 62, 16, 62, 1...
2.607143
224
# Die Fibonacci-Folge ist die unendliche Folge natrlicher Zahlen, die (ursprnglich) mit zweimal der Zahl 1 beginnt # oder (hufig, in moderner Schreibweise) zustzlich mit einer fhrenden Zahl 0 versehen ist. # Im Anschluss ergibt jeweils die Summe zweier aufeinanderfolgender Zahlen die unmittelbar danach folgende Zahl: # 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 -> Hier fangen wir mit der 0 an zu zhlen. # 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 -> Hier fangen wir mit der 1 an zu zhlen.
[ 2, 6733, 41566, 261, 44456, 12, 37, 349, 469, 318, 83, 4656, 555, 437, 677, 258, 30938, 469, 34664, 81, 677, 372, 49063, 11925, 11, 4656, 357, 1834, 1050, 782, 33467, 8, 10255, 1976, 732, 4402, 4587, 1168, 15668, 352, 2221, 429, 198...
2.39196
199
import numpy as np import dnnlib.tflib as tflib from training import dataset tflib.init_tf()
[ 11748, 299, 32152, 355, 45941, 198, 11748, 288, 20471, 8019, 13, 83, 2704, 571, 355, 256, 2704, 571, 198, 6738, 3047, 1330, 27039, 628, 198, 83, 2704, 571, 13, 15003, 62, 27110, 3419, 628 ]
2.823529
34
from collections import namedtuple import pytest from rest_framework.authtoken.models import Token from tests.conftest import twilio_vcr from apostello import models StatusCode = namedtuple("StatusCode", "anon, user, staff")
[ 6738, 17268, 1330, 3706, 83, 29291, 198, 198, 11748, 12972, 9288, 198, 6738, 1334, 62, 30604, 13, 18439, 30001, 13, 27530, 1330, 29130, 198, 6738, 5254, 13, 1102, 701, 395, 1330, 665, 346, 952, 62, 85, 6098, 198, 198, 6738, 18584, 111...
3.538462
65
""" A *really* simple guestbook flask app. Data is stored in a SQLite database that looks something like the following: +------------+------------------+------------+ | Name | Email | signed_on | +============+==================+============+ | John Doe | jdoe@example.com | 2012-05-28 | +------------+------------------+------------+ | Jane Doe | jane@example.com | 2012-05-28 | +------------+------------------+------------+ This can be created with the following SQL (see bottom of this file): create table guestbook (name text, email text, signed_on date); Related Docs: * `sqlite3 <http://docs.python.org/library/sqlite3.html>`_ * `datetime <http://docs.python.org/library/datetime.html>`_ * `Flask <http://flask.pocoo.org/docs/>`_ """ from datetime import date from flask import Flask, redirect, request, url_for, render_template import sqlite3 app = Flask(__name__) # our Flask app DB_FILE = 'guestbook.db' # file for our Database def _select(): """ just pull all the results from the database """ connection = sqlite3.connect(DB_FILE) cursor = connection.cursor() cursor.execute("SELECT * FROM guestbook") return cursor.fetchall() def _insert(name, email): """ put a new entry in the database """ params = {'name':name, 'email':email, 'date':date.today()} connection = sqlite3.connect(DB_FILE) cursor = connection.cursor() cursor.execute("insert into guestbook (name, email, signed_on) VALUES (:name, :email, :date)", params) connection.commit() cursor.close() if __name__ == '__main__': # Make sure our database exists connection = sqlite3.connect(DB_FILE) cursor = connection.cursor() try: cursor.execute("select count(rowid) from guestbook") except sqlite3.OperationalError: cursor.execute("create table guestbook (name text, email text, signed_on date)") cursor.close() app.run(host='0.0.0.0', debug=True)
[ 37811, 198, 32, 1635, 27485, 9, 2829, 8319, 2070, 42903, 598, 13, 6060, 318, 8574, 287, 257, 16363, 578, 6831, 326, 198, 5460, 82, 1223, 588, 262, 1708, 25, 198, 198, 10, 10541, 10, 1783, 44785, 10541, 10, 220, 198, 91, 6530, 220, ...
2.845934
701
import sqlite3 import base64 import requests import json import hashlib import logging from lingvodoc.queue.client import QueueClient #def change_dict_status(session, converting_status_url, status, task_id, progress): # def change_dict_status(task_id, progress): # #session.put(converting_status_url, json={'status': status}) # QueueClient.update_progress(task_id, progress) if __name__ == "__main__": log = logging.getLogger(__name__) log.setLevel(logging.DEBUG) logging.basicConfig(format='%(asctime)s\t%(levelname)s\t[%(name)s]\t%(message)s') log.debug("!!!!!!!!!! YOU SHOULD NOT SEE IT !!!!!!!!") convert_one(filename="/home/student/dicts-current/nenets_kaninski.sqlite", login="Test", password_hash="$2a$12$zBMnhV9oUfKehlHJCHnsPuGM98Wwq/g9hlWWNqg8ZGDuLNyUSfxza", language_client_id=1, language_object_id=1, dictionary_client_id=None, dictionary_object_id=None, perspective_client_id=None, perspective_object_id=None, server_url="http://lingvodoc.ispras.ru/")
[ 11748, 44161, 578, 18, 198, 11748, 2779, 2414, 198, 11748, 7007, 198, 11748, 33918, 198, 11748, 12234, 8019, 198, 11748, 18931, 198, 198, 6738, 18459, 85, 375, 420, 13, 36560, 13, 16366, 1330, 4670, 518, 11792, 628, 628, 628, 198, 198, ...
2.35141
461
""" Tests the code. """ from torch.utils.data import DataLoader from models import MODELS from pipeline import argument_parser from pipeline.datasets import DATASETS, get_dataset from run import main def test_datasets(): """ Tests all the datasets defined in pipeline.datasets.DATASETS. """ for ds_name in DATASETS: train_set, test_set, _ = get_dataset(ds_name, seed=42) for set_ in (train_set, test_set): dl = DataLoader(list(zip(*set_)), batch_size=5) for data, missing_data, mask in dl: assert len(data) == 5, f"The {ds_name} dataset has less than 5 samples." assert data.shape[1] > 1, f"The {ds_name} dataset has none or one column only." print("data:", data, "missing_data:", missing_data, "mask:", mask, sep="\n") break def test_general(capsys): """ Tests most of the code by checking it produces the expected result. """ main(argument_parser.get_args(["--metric_steps", "50", "--datasets", "Boston", "--seeds", "0", "1"])) captured = capsys.readouterr() with open("tests/current_output.txt", "w") as f: assert f.write(captured.out) with open("tests/gold_output.txt", "r") as f: assert captured.out == f.read() def test_models(): """ Tests all the models (only checks if these run). """ for model in MODELS: main(argument_parser.get_args(["--model", model, "--metric_steps", "0", "1", "5", "--datasets", "Boston", "--seeds", "0"]))
[ 37811, 30307, 262, 2438, 13, 37227, 198, 198, 6738, 28034, 13, 26791, 13, 7890, 1330, 6060, 17401, 198, 198, 6738, 4981, 1330, 19164, 37142, 198, 6738, 11523, 1330, 4578, 62, 48610, 198, 6738, 11523, 13, 19608, 292, 1039, 1330, 360, 140...
2.395672
647
# -*- coding: utf-8 -*- import numpy as np import random import os import sys import torch from src.agent import ( EpsilonGreedyAgent, MaxAgent, RandomAgent, RandomCreateBVAgent, ProbabilityAgent, QAgent, QAndUtilityAgent, MultiEpsilonGreedyAgent, MultiMaxAgent, MultiProbabilityAgent, MultiQAgent, MultiQAndUtilityAgent, )
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 4738, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 28034, 198, 198, 6738, 12351, 13, 25781, 1330, 357, 198, 220, 220, ...
2.470588
153
def func(x, y, z): """ :param x: <caret> :param y: :param z: :return: """
[ 4299, 25439, 7, 87, 11, 331, 11, 1976, 2599, 198, 220, 220, 220, 37227, 220, 198, 220, 220, 220, 1058, 17143, 2124, 25, 1279, 6651, 83, 29, 198, 220, 220, 220, 1058, 17143, 331, 25, 220, 198, 220, 220, 220, 1058, 17143, 1976, 25, ...
1.741379
58
from hashlib import sha3_256 import magic from enums import Dep, MangoType MIME_MTYPE = { 'text/plain': MangoType.text, 'audio/flac': MangoType.audio_flac, 'audio/wav': MangoType.audio_wav, 'image/png': MangoType.picture_png, 'image/jpeg': MangoType.picture_jpg, 'video/x-matroska': MangoType.video_mkv, 'video/mp4': MangoType.video_mp4 } TYPE_ALLOWED = { Dep.d51: (MangoType.audio_flac, ), Dep.d59: (MangoType.audio_flac, ), Dep.d60: (MangoType.picture_png, ), Dep.d71: (MangoType.audio_flac, ), Dep.d72: (MangoType.text, ), Dep.d73: (MangoType.video_mkv, MangoType.video_mp4) } EXTS = { MangoType.audio_flac: 'flac', MangoType.picture_png: 'png', MangoType.text: 'txt', MangoType.video_mkv: 'mkv', MangoType.video_mp4: 'mp4' }
[ 6738, 12234, 8019, 1330, 427, 64, 18, 62, 11645, 198, 198, 11748, 5536, 198, 198, 6738, 551, 5700, 1330, 2129, 11, 337, 14208, 6030, 198, 198, 44, 12789, 62, 44, 25216, 796, 1391, 198, 220, 220, 220, 705, 5239, 14, 25638, 10354, 337...
2.098446
386
#!/usr/bin/env python3 # MIT License # # Copyright (c) 2020 FABRIC Testbed # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # Author Komal Thareja (kthare10@renci.org) """ Main Entry Point """ import os import signal import connexion import prometheus_client import waitress from flask import jsonify from fabric_cm.credmgr.swagger_server import encoder from fabric_cm.credmgr.config import CONFIG_OBJ from fabric_cm.credmgr.logging import LOG def main(): """ Main Entry Point """ log = LOG try: app = connexion.App(__name__, specification_dir='swagger/') app.app.json_encoder = encoder.JSONEncoder app.add_api('swagger.yaml', arguments={'title': 'Fabric Credential Manager API'}, pythonic_params=True) port = CONFIG_OBJ.get_rest_port() # prometheus server prometheus_port = CONFIG_OBJ.get_prometheus_port() prometheus_client.start_http_server(prometheus_port) # Start up the server to expose the metrics. waitress.serve(app, port=port) except Exception as ex: log.error("Exception occurred while starting Flask app") log.error(ex) raise ex if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 17168, 13789, 198, 2, 198, 2, 15069, 357, 66, 8, 12131, 376, 6242, 41132, 6208, 3077, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, ...
2.955497
764
# Generated by Django 3.1.2 on 2022-02-27 17:59 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import versatileimagefield.fields
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 17, 319, 33160, 12, 2999, 12, 1983, 1596, 25, 3270, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14...
3.237288
59
#!/usr/bin/python # -*- coding: utf-8 -*- # python version 2.7 # Cemal Melih Tanis (C) ############################################################################### import os import shutil import datetime from pytz import timezone from uuid import uuid4 from definitions import * import fetchers import calculations from calculations import calcnames, calccommands, paramnames, paramdefs, paramopts, calcids, calcdescs,paramhelps, calcnames_en import maskers import parsers import sources from data import * import readers import calcfuncs import matplotlib, sys import numpy as np if sysargv['gui']: matplotlib.use('TkAgg') from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import Tkinter, Tkconstants, tkFileDialog, tkMessageBox, tkSimpleDialog, tkFont import Tkinter as tk import ttk import matplotlib.dates as mdate import PIL from PIL import Image,ImageDraw, ImageFont if sysargv['gui']: from PIL import ImageTk if os.path.sep == '/': from PIL import _tkinter_finder import mahotas from copy import deepcopy import subprocess from auxdata import auxlist, auxnamelist import auxdata import comparators import webbrowser import h5py import textwrap import gc if sysargv['gui']: import FileDialog if not sysargv['gui']: Tkinter = None import noTk as Tkinter import noTk as tk import noTk as tkMessageBox import noTk as tkSimpleDialog import noTk as webbrowser import noTk as tkFont if __name__ == "__main__": app = monimet_gui(None) app.title('FMIPROT ' + sysargv['version']) if os.path.sep != "/": app.iconbitmap(os.path.join(ResourcesDir,'monimet.ico')) app.mainloop()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 201, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 2, 21015, 2196, 362, 13, 22, 201, 198, 2, 327, 368, 282, 5616, 4449, 11818, 271, 357, 34, 8, 201, 198, 29113, ...
2.761513
608
import sys import subprocess if __name__ == "__main__": main()
[ 11748, 25064, 198, 11748, 850, 14681, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1388, 3419, 198 ]
2.72
25
################################################# #****************LINEAR MODELS******************# ################################################# CLASSIF_LOGISTIC_REGRESSION = {"C":{"range": (1., 100.), "type": 1}, "tol":{"range": (0.0001,0.9999), "type": 1}} CLASSIF_PERCEPTRON = {"tol":{"range": (0.0001,0.9999), "type": 1}, "alpha":{"range": (0.0001,0.9999), "type": 1}} REG_LASSO = {"tol":{"range": (0.0001,0.9999), "type": 1}, "alpha":{"range": (1., 100.), "type": 1}} REG_RIDGE = {"tol":{"range": (0.0001,0.9999), "type": 1}, "alpha":{"range": (1., 100.), "type": 1}} ################################################ #*****************SVM MODELS*******************# ################################################ CLASSIF_SVC = {"C":{"range": (1.,100.), "type": 1}, "alpha":{"range": (0.0001,0.9999), "type": 1}} REG_SVR = {"C":{"range": (1.,100.), "type": 1}, "alpha":{"range": (0.0001,0.9999), "type": 1}} ################################################## #******************KNN MODELS********************# ################################################## CLASSIF_KNEIGHBORSCLASSIFIER = {"n_neighbors":{"range": (2,11), "type": 0}, "p":{"range": (1, 3), "type": 0}} REG_KNEIGHBORSREGRESSOR = {"n_neighbors":{"range": (2,11), "type": 0}, "p":{"range": (1, 3), "type": 0}} ################################################## #******************MLP MODELS********************# ################################################## CLASSIF_MLPCLASSIFIER = {"tol":{"range": (0.0001,0.9999), "type": 1}, "alpha":{"range": (0.0001, 0.999), "type": 1}} REG_MLPREGRESSOR = {"tol":{"range": (0.0001,0.9999), "type": 1}, "alpha":{"range": (0.0001, 0.999), "type": 1}} ################################################## #*************Random Forest MODELS***************# ################################################## CLASSIF_RANDOMFORESTCLASSIFIER = {"n_estimators":{"range": (100,250), "type": 0}, "max_depth":{"range": (4, 20), "type": 0}, "min_samples_split":{"range": (2,25), "type": 0}} REG_RANDOMFORESTREGRESSOR = {"n_estimators":{"range": (100,250), "type": 0}, "max_depth":{"range": (4, 20), "type": 0}, "min_samples_split":{"range": (2,25), "type": 0}} ################################################## #*************Decision trees MODELS**************# ################################################## CLASSIF_DECISIONTREECLASSIFIER = {"min_weight_fraction_leaf":{"range": (0,20), "type": 0}, "max_depth":{"range": (4, 20), "type": 0}, "min_samples_split":{"range": (2,25), "type": 0}} REG_DECISIONTREEREGRESSOR = {"min_weight_fraction_leaf":{"range": (0,20), "type": 0}, "max_depth":{"range": (4, 20), "type": 0}, "min_samples_split":{"range": (2,25), "type": 0}}
[ 29113, 14468, 2, 198, 2, 8412, 24027, 1503, 19164, 37142, 8412, 1174, 2, 198, 29113, 14468, 2, 198, 198, 31631, 5064, 62, 25294, 8808, 2149, 62, 2200, 10761, 47621, 796, 19779, 34, 8351, 9521, 1298, 357, 16, 1539, 1802, 12179, 366, 49...
2.302966
1,416
# -*- coding: utf-8 -*- from datetime import timedelta import logging from delorean import Delorean import tornado.web from gryphon.dashboards.handlers.admin_base import AdminBaseHandler from gryphon.lib.exchange import exchange_factory from gryphon.lib.models.order import Order from gryphon.lib.models.exchange import Exchange as ExchangeData from gryphon.lib.models.exchange import Balance from gryphon.lib.models.transaction import Transaction from gryphon.lib.money import Money logger = logging.getLogger(__name__) BANK_ACCOUNT_HIGHLIGHT_THRESHOLD = 30000
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 4818, 8079, 1330, 28805, 12514, 198, 11748, 18931, 198, 198, 6738, 1619, 29456, 1330, 4216, 29456, 198, 11748, 33718, 13, 12384, 198, 198, 6738, 308, 563, 746, 261, ...
3.092391
184
import yfinance as yf import numpy as np import pandas as pd if __name__ == "__main__": stock = StockSetup('SPY', 3) print(stock.data.tail()) print(stock.data.isna().sum())
[ 11748, 331, 69, 14149, 355, 331, 69, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 4283, 796, 10500, 40786, 10786,...
2.527027
74
from collections import OrderedDict from .base import ApiBase import logging logger = logging.getLogger(__name__)
[ 6738, 17268, 1330, 14230, 1068, 35, 713, 198, 198, 6738, 764, 8692, 1330, 5949, 72, 14881, 198, 11748, 18931, 198, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 7, 834, 3672, 834, 8, 628 ]
3.342857
35
import graphene from schema.queries import Query from schema.mutations import Mutations schema = graphene.Schema(query=Query, mutation=Mutations)
[ 11748, 42463, 198, 6738, 32815, 13, 421, 10640, 1330, 43301, 198, 6738, 32815, 13, 21973, 602, 1330, 13859, 602, 198, 198, 15952, 2611, 796, 42463, 13, 27054, 2611, 7, 22766, 28, 20746, 11, 15148, 28, 44, 32855, 8, 198 ]
3.769231
39
""" This module contains a number of other commands that can be run via the cli. All classes in this submodule which inherit the baseclass `airbox.commands.base.Command` are automatically included in the possible commands to execute via the commandline. The commands can be called using their `name` property. """ from logging import getLogger from .backup import BackupCommand from .backup_sync import BackupSyncCommand from .basic_plot import BasicPlotCommand from .create_mounts import CreateMountsCommand from .install import InstallCommand from .print_fstab import PrintFstabCommand from .run_schedule import RunScheduleCommand from .spectronus_subset import SpectronusSubsetCommand from .subset import SubsetCommand logger = getLogger(__name__) # Commands are registered below _commands = [ BackupCommand(), BackupSyncCommand(), BasicPlotCommand(), CreateMountsCommand(), InstallCommand(), PrintFstabCommand(), RunScheduleCommand(), SpectronusSubsetCommand(), SubsetCommand() ] def find_commands(): """ Finds all the Commands in this package :return: List of Classes within """ # TODO: Make this actually do that. For now commands are manually registered pass def initialise_commands(parser): """ Initialise the parser with the commandline arguments for each parser :param parser: :return: """ find_commands() for c in _commands: p = parser.add_parser(c.name, help=c.help) c.initialise_parser(p) def run_command(cmd_name): """ Attempts to run a command :param config: Configuration data """ for c in _commands: if cmd_name == c.name: return c.run()
[ 37811, 198, 1212, 8265, 4909, 257, 1271, 286, 584, 9729, 326, 460, 307, 1057, 2884, 262, 537, 72, 13, 198, 198, 3237, 6097, 287, 428, 850, 21412, 543, 16955, 262, 2779, 4871, 4600, 958, 3524, 13, 9503, 1746, 13, 8692, 13, 21575, 63,...
3.109091
550
#!/usr/bin/python # Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import waveguide from wvtest import wvtest if __name__ == '__main__': wvtest.wvtest_main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 15069, 1853, 3012, 3457, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428...
3.58209
201
import re from ava.common.check import _ValueCheck, _TimingCheck from ava.common.exception import InvalidFormatException # metadata name = __name__ description = "checks for shell injection"
[ 11748, 302, 198, 6738, 1196, 64, 13, 11321, 13, 9122, 1330, 4808, 11395, 9787, 11, 4808, 14967, 278, 9787, 198, 6738, 1196, 64, 13, 11321, 13, 1069, 4516, 1330, 17665, 26227, 16922, 628, 198, 2, 20150, 198, 3672, 796, 11593, 3672, 834...
3.679245
53
import os import xml.etree.ElementTree as ET import numpy as np import scipy.sparse import scipy.io as sio import cPickle import subprocess import uuid if __name__ == '__main__': #Save_Name = './dataset/8.train_val' ImageSets = ['../LOC/LOC_Split/trecvid_val_8.txt', '../LOC/LOC_Split/trecvid_train_8.txt'] ImageSets = ['../LOC/LOC_Split/trecvid_train_Animal_Music.txt', '../LOC/LOC_Split/trecvid_val_Animal_Music.txt'] ImageSets = ['../LOC/LOC_Split/trecvid_5_manual_train.txt'] ImageSets = ['../LOC/LOC_Split/trecvid_train_8.txt', '../LOC/LOC_Split/trecvid_val_8.txt', '../LOC/LOC_Split/trecvid_train_Animal_Music.txt', '../LOC/LOC_Split/trecvid_val_Animal_Music.txt'] num_cls = 10 Save_Name = '../dataset/{}.train_val'.format(num_cls) _wind_to_ind, _class_to_ind = Get_Class_Ind(num_cls) for ImageSet in ImageSets: if not os.path.isfile(ImageSet): print 'File({}) does not exist'.format(ImageSet) sys.exit(1) else: print 'Open File : {} '.format(ImageSet) print 'Save into : {} '.format(Save_Name) out_file = open(Save_Name, 'w') ids = 0 count_cls = np.zeros((num_cls+1), dtype=np.int32) assert count_cls.shape[0]-1 == len(_class_to_ind) for ImageSet in ImageSets: file = open(ImageSet, 'r') while True: line = file.readline() if line == '': break line = line.strip('\n') xml_path = '../LOC/BBOX/{}.xml'.format(line) rec = load_annotation(xml_path, _wind_to_ind) out_file.write('# {}\n'.format(ids)) ids = ids + 1 out_file.write('{}.JPEG\n'.format(line)) boxes = rec['boxes'] gt_classes = rec['gt_classes'] assert boxes.shape[0] == gt_classes.shape[0] out_file.write('{}\n'.format(boxes.shape[0])) for j in range(boxes.shape[0]): out_file.write('{} {} {} {} {} 0\n'.format(int(gt_classes[j]),int(boxes[j,0]),int(boxes[j,1]),int(boxes[j,2]),int(boxes[j,3]))) count_cls[ int(gt_classes[j]) ] = count_cls[ int(gt_classes[j]) ] + 1 if ids % 2000 == 0: print 'print {} image with recs into {}'.format(ids, Save_Name) file.close() for i in range(count_cls.shape[0]): print ('%2d th : %4d' % (i, count_cls[i])) i = i + 1 out_file.close()
[ 11748, 28686, 198, 11748, 35555, 13, 316, 631, 13, 20180, 27660, 355, 12152, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 629, 541, 88, 13, 82, 29572, 198, 11748, 629, 541, 88, 13, 952, 355, 264, 952, 198, 11748, 269, 31686, 293, ...
2.013104
1,221
import argparse import logging import os import sys import numpy as np from tqdm import tqdm import time import torch import torch.nn as nn from torch import optim from torch.utils.tensorboard import SummaryWriter from torch.utils.data import DataLoader from models.unet import UNet from models.nested_unet import NestedUNet from datasets.promise12 import Promise12 from datasets.chaos import Chaos from dice_loss import DiceBCELoss, dice_coeff from eval import eval_net torch.manual_seed(2020) if __name__ == '__main__': args = get_args() args.save = 'logs_train/{}-{}-{}'.format(args.model, args.dataset, time.strftime("%Y%m%d-%H%M%S")) if not os.path.exists(args.save): os.makedirs(args.save) log_format = '%(asctime)s %(message)s' logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format, datefmt='%m/%d %I:%M:%S %p') fh = logging.FileHandler(os.path.join(args.save, 'log.txt')) fh.setFormatter(logging.Formatter(log_format)) logging.getLogger().addHandler(fh) logging.info(f''' Model: {args.model} Dataset: {args.dataset} Total Epochs: {args.epochs} Batch size: {args.batch_size} Learning rate: {args.lr} Weight decay: {args.weight_decay} Device: GPU{args.gpu} Log name: {args.save} ''') torch.cuda.set_device(args.gpu) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # choose a model if args.model == 'unet': net = UNet() elif args.model == 'nestedunet': net = NestedUNet() net.to(device=device) # choose a dataset if args.dataset == 'promise12': dir_data = '../data/promise12' trainset = Promise12(dir_data, mode='train') valset = Promise12(dir_data, mode='val') elif args.dataset == 'chaos': dir_data = '../data/chaos' trainset = Chaos(dir_data, mode='train') valset = Chaos(dir_data, mode='val') try: train_net(net=net, trainset=trainset, valset=valset, epochs=args.epochs, batch_size=args.batch_size, lr=args.lr, weight_decay=args.weight_decay, device=device, log_save_path=args.save) except KeyboardInterrupt: try: sys.exit(0) except SystemExit: os._exit(0)
[ 11748, 1822, 29572, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 11748, 640, 198, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, ...
2.058007
1,224
from booking.constants import myConstant
[ 6738, 25452, 13, 9979, 1187, 1330, 616, 3103, 18797, 198 ]
4.1
10
import urllib import xml.etree.ElementTree as ET address = raw_input('Enter location: ') url = address print 'Retrieving', url uh = urllib.urlopen(url) data = uh.read() print 'Retrieved',len(data),'characters' tree = ET.fromstring(data) sumcount=count=0 counts = tree.findall('.//count') for i in counts: count+=1 sumcount+= int(i.text) print 'Count: '+str(count) print 'Sum: '+str(sumcount)
[ 11748, 2956, 297, 571, 198, 11748, 35555, 13, 316, 631, 13, 20180, 27660, 355, 12152, 628, 628, 198, 21975, 796, 8246, 62, 15414, 10786, 17469, 4067, 25, 705, 8, 628, 198, 6371, 796, 2209, 198, 4798, 705, 9781, 37418, 3256, 19016, 198...
2.584906
159
from flask import Flask from flask.ext.tweepy import Tweepy app = Flask(__name__) app.config.setdefault('TWEEPY_CONSUMER_KEY', 'sve32G2LtUhvgyj64J0aaEPNk') app.config.setdefault('TWEEPY_CONSUMER_SECRET', '0z4NmfjET4BrLiOGsspTkVKxzDK1Qv6Yb2oiHpZC9Vi0T9cY2X') app.config.setdefault('TWEEPY_ACCESS_TOKEN_KEY', '1425531373-dvjiA55ApSFEnTAWPzzZAZLRoGDo3OTTtt4ER1W') app.config.setdefault('TWEEPY_ACCESS_TOKEN_SECRET', '357nVGYtynDtDBmqAZw2vxeXE3F8GbqBSqWInwStDluDX') tweepy = Tweepy(app)
[ 6738, 42903, 1330, 46947, 198, 6738, 42903, 13, 2302, 13, 83, 732, 538, 88, 1330, 24205, 538, 88, 198, 198, 1324, 796, 46947, 7, 834, 3672, 834, 8, 198, 1324, 13, 11250, 13, 2617, 12286, 10786, 34551, 35238, 56, 62, 10943, 50, 5883,...
1.944
250
from __future__ import absolute_import from .__main__ import main from .sftp import * from .sync import * __version__ = '0.6'
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 6738, 764, 834, 12417, 834, 1330, 1388, 198, 6738, 764, 82, 701, 79, 1330, 1635, 198, 6738, 764, 27261, 1330, 1635, 198, 198, 834, 9641, 834, 796, 705, 15, 13, 21, 6, 198 ]
2.976744
43
"""Simple predictor using random forest """ import pandas as pd import numpy as np import math from sklearn.ensemble import RandomForestRegressor from sklearn.ensemble import RandomForestClassifier from sklearn import preprocessing from sklearn.metrics import mean_absolute_error from sklearn.metrics import f1_score from sklearn.model_selection import cross_val_score from sklearn import metrics from core.predictor.predictor import Predictor from common.sql_handler import SqlHandler from common.metric import ccc_score import config from global_values import * from common.log_handler import get_logger logger = get_logger()
[ 37811, 26437, 41568, 1262, 4738, 8222, 198, 37811, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 10688, 198, 6738, 1341, 35720, 13, 1072, 11306, 1330, 14534, 34605, 8081, 44292, 198, 6738, 1341...
3.721893
169
def showSpeed(func, r, *args): '''Usage: showSpeed(function, runs) You can also pass arguments into <function> like so: showSpeed(function, runs, <other>, <args>, <here> ...) showSpeed() prints the average execution time of <function> over <runs> runs ''' import os, sys, gc from time import perf_counter as pf garbage = gc.isenabled() gc.disable() start = pf() with noPrint(): for _ in range(r): func(*args) end = pf() if garbage: gc.enable() print(f'{formatted((end-start)/r)}') def getSpeed(func, r, *args): '''Usage: getSpeed(function, runs) You can also pass arguments into <function> like so: getSpeed(function, runs, <other>, <args>, <here> ...) getSpeed() returns the average execution time of <function> over <runs> runs, as a float ''' import os, sys, gc from time import perf_counter as pf garbage = gc.isenabled() gc.disable() start = pf() with noPrint(): for _ in range(r): func(*args) end = pf() if garbage: gc.enable() return (end-start)/r
[ 4299, 905, 22785, 7, 20786, 11, 374, 11, 1635, 22046, 2599, 198, 220, 220, 220, 705, 7061, 28350, 25, 905, 22785, 7, 8818, 11, 4539, 8, 198, 220, 220, 220, 921, 460, 635, 1208, 7159, 656, 1279, 8818, 29, 588, 523, 25, 198, 220, ...
2.431965
463
#!/usr/bin/env python u""" polygonize.py Yara Mohajerani (Last update 09/2020) Read output predictions and convert to shapefile lines """ import os import sys import rasterio import numpy as np import getopt import shapefile from skimage.measure import find_contours from shapely.geometry import Polygon,LineString,Point #-- main function #-- run main program if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 84, 37811, 198, 35428, 14520, 1096, 13, 9078, 198, 56, 3301, 9719, 1228, 263, 3216, 357, 5956, 4296, 7769, 14, 42334, 8, 198, 198, 5569, 5072, 16277, 290, 10385, 284, 5485, 7753, 3951,...
3.174603
126
import numpy as np import pytest from autofit.graphical import ( EPMeanField, LaplaceOptimiser, EPOptimiser, Factor, ) from autofit.messages import FixedMessage, NormalMessage np.random.seed(1) prior_std = 10. error_std = 1. a = np.array([[-1.3], [0.7]]) b = np.array([-0.5]) n_obs = 100 n_features, n_dims = a.shape x = 5 * np.random.randn(n_obs, n_features) y = x.dot(a) + b + np.random.randn(n_obs, n_dims) def check_model_approx(mean_field, a_, b_, z_, x_, y_): X = np.c_[x, np.ones(len(x))] XTX = X.T.dot(X) + np.eye(3) * (error_std / prior_std)**2 cov = np.linalg.inv(XTX) * error_std**2 cov_a = cov[:2, :] cov_b = cov[2, :] # Analytic results mean_a = cov_a.dot(X.T.dot(y)) mean_b = cov_b.dot(X.T.dot(y)) a_std = cov_a.diagonal()[:, None] ** 0.5 b_std = cov_b[[-1]] ** 0.5 assert mean_field[a_].mean == pytest.approx(mean_a, rel=1e-2) assert mean_field[b_].mean == pytest.approx(mean_b, rel=1e-2) assert mean_field[a_].sigma == pytest.approx(a_std, rel=0.5) assert mean_field[b_].sigma == pytest.approx(b_std, rel=0.5)
[ 11748, 299, 32152, 355, 45941, 198, 11748, 12972, 9288, 198, 198, 6738, 1960, 1659, 270, 13, 34960, 605, 1330, 357, 198, 220, 220, 220, 14724, 5308, 272, 15878, 11, 198, 220, 220, 220, 4689, 5372, 27871, 320, 5847, 11, 198, 220, 220, ...
2.007181
557
import math from torch import nn import torch import torch.nn.functional as F import linear_cpu as linear
[ 11748, 10688, 198, 6738, 28034, 1330, 299, 77, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 11748, 14174, 62, 36166, 355, 14174, 628, 198 ]
3.724138
29
""" Files API """ import boto3 import os import io from datetime import datetime, timedelta import json import time from s3_helpers import write_s3_json, read_s3_json, delete_s3_key from api_helpers import json_serial from search_files import crawl_available_files, update_pdf_fields from dynamo_helpers import add_file_to_process_keys, add_file_group_keys, get_iso_date_as_string, add_image_group_keys, add_media_group_keys, add_media_keys, add_image_keys from dynamo_save_functions import save_file_system_record from add_files_to_json_object import change_file_extensions_to_tif from pipelineutilities.dynamo_query_functions import get_all_file_to_process_records_by_storage_system
[ 37811, 13283, 7824, 37227, 198, 11748, 275, 2069, 18, 198, 11748, 28686, 198, 11748, 33245, 198, 6738, 4818, 8079, 1330, 4818, 8079, 11, 28805, 12514, 198, 11748, 33918, 198, 11748, 640, 198, 6738, 264, 18, 62, 16794, 364, 1330, 3551, 6...
3.09009
222
# coding: utf-8 """ """ import flask import flask_login import json from flask_babel import _ from . import frontend from .. import logic from ..logic.object_permissions import Permissions from ..logic.security_tokens import verify_token from ..logic.languages import get_languages, get_language, get_language_by_lang_code from ..models.languages import Language from .projects_forms import CreateProjectForm, EditProjectForm, LeaveProjectForm, InviteUserToProjectForm, InviteGroupToProjectForm, AddSubprojectForm, RemoveSubprojectForm, DeleteProjectForm, RemoveProjectMemberForm, RemoveProjectGroupForm, ObjectLinkForm from .permission_forms import PermissionsForm from .utils import check_current_user_is_not_readonly from ..logic.utils import get_translated_text
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 37811, 198, 198, 37811, 198, 198, 11748, 42903, 198, 11748, 42903, 62, 38235, 198, 11748, 33918, 198, 6738, 42903, 62, 65, 9608, 1330, 4808, 198, 198, 6738, 764, 1330, 2166, 437, 198, 6738, 11485, ...
3.621495
214
#!/usr/bin/env python3 import codecs import os import re from setuptools import setup with open('README.md', 'r') as f: readme = f.read() here = os.path.abspath(os.path.dirname(__file__)) _title = 'caaalle' _description = 'caaalle' _author = 'Carl Larsson' _author_email = 'example@gmail.com' _license = 'Apache 2.0' _url = 'https://github.com/caalle/caaalle' setup( name=_title, description=_description, long_description=readme, long_description_content_type='text/markdown', version=find_version("caaalle", "__init__.py"), author=_author, author_email=_author_email, url=_url, packages=['caaalle'], include_package_data=True, python_requires=">=3.5.*", install_requires=[], license=_license, zip_safe=False, classifiers=[ 'Intended Audience :: Developers', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.5' ], keywords='caaalle' )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 40481, 82, 198, 11748, 28686, 198, 11748, 302, 198, 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 4480, 1280, 10786, 15675, 11682, 13, 9132, 3256, 705, 81, 11537, 355, ...
2.457275
433
#!/usr/bin/env python # -*- coding: utf-8 -*- # # ----------------------------------------------------------------------------- # Copyright (c) 2016 The Regents of the University of California # # This file is part of kevlar (http://github.com/dib-lab/kevlar) and is # licensed under the MIT license: see LICENSE. # ----------------------------------------------------------------------------- import filecmp import glob import json import pytest import re from tempfile import NamedTemporaryFile, mkdtemp import screed from shutil import rmtree import sys import kevlar from kevlar.tests import data_file, data_glob from khmer import Counttable def test_novel_two_cases(capsys): cases = kevlar.tests.data_glob('trio1/case6*.fq') controls = kevlar.tests.data_glob('trio1/ctrl[5,6].fq') with NamedTemporaryFile(suffix='.ct') as case1ct, \ NamedTemporaryFile(suffix='.ct') as case2ct, \ NamedTemporaryFile(suffix='.ct') as ctrl1ct, \ NamedTemporaryFile(suffix='.ct') as ctrl2ct: counttables = [case1ct, case2ct, ctrl1ct, ctrl2ct] seqfiles = cases + controls for ct, seqfile in zip(counttables, seqfiles): arglist = ['count', '--ksize', '19', '--memory', '1e7', ct.name, seqfile] print(arglist) args = kevlar.cli.parser().parse_args(arglist) kevlar.count.main(args) arglist = ['novel', '--ksize', '19', '--memory', '1e7', '--ctrl-max', '1', '--case-min', '7', '--case', cases[0], '--case', cases[1], '--case-counts', case1ct.name, case2ct.name, '--control-counts', ctrl1ct.name, ctrl2ct.name] args = kevlar.cli.parser().parse_args(arglist) kevlar.novel.main(args) out, err = capsys.readouterr() assert out.strip() != '' for line in out.split('\n'): if not line.endswith('#') or line.startswith('#mateseq'): continue abundmatch = re.search(r'(\d+) (\d+) (\d+) (\d+)#$', line) assert abundmatch, line case1 = int(abundmatch.group(1)) case2 = int(abundmatch.group(2)) ctl1 = int(abundmatch.group(3)) ctl2 = int(abundmatch.group(4)) assert case1 >= 7 and case2 >= 7 assert ctl1 <= 1 and ctl2 <= 1
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 16529, 32501, 198, 2, 15069, 357, 66, 8, 1584, 383, 3310, 658, 286, 262, 2059, 286, 3442, 198, 2, 198, ...
2.261331
1,037
get_magic_triangle(5)
[ 201, 198, 201, 198, 1136, 62, 32707, 62, 28461, 9248, 7, 20, 8, 201, 198 ]
1.8
15
# -*- coding: utf-8 -*- import os import telebot import time import random import threading from emoji import emojize from telebot import types from pymongo import MongoClient import traceback token = os.environ['TELEGRAM_TOKEN'] bot = telebot.TeleBot(token) #client=MongoClient(os.environ['database']) #db=client. #users=db.users print('7777') bot.polling(none_stop=True,timeout=600)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 28686, 198, 11748, 5735, 13645, 198, 11748, 640, 198, 11748, 4738, 198, 11748, 4704, 278, 198, 6738, 44805, 1330, 795, 13210, 1096, 198, 6738, 5735, 13645, 1330, 38...
2.383784
185
from .api import MojangApi from .dispatcher import Dispatch from .exceptions import ( ApiException, ResourceNotFound, InternalServerException, UserNotFound, ) __version__ = "0.0.1a" __license__ = "MIT" __author__ = "capslock321"
[ 6738, 764, 15042, 1330, 40120, 648, 32, 14415, 201, 198, 6738, 764, 6381, 8071, 2044, 1330, 35934, 201, 198, 6738, 764, 1069, 11755, 1330, 357, 201, 198, 220, 220, 220, 5949, 72, 16922, 11, 201, 198, 220, 220, 220, 20857, 3673, 21077,...
2.471698
106
from loguru import logger from channels.db import database_sync_to_async from schema.base import query from .models import Player from .schemata import PlayerConnection
[ 6738, 2604, 14717, 1330, 49706, 198, 198, 6738, 9619, 13, 9945, 1330, 6831, 62, 27261, 62, 1462, 62, 292, 13361, 198, 198, 6738, 32815, 13, 8692, 1330, 12405, 198, 198, 6738, 764, 27530, 1330, 7853, 198, 6738, 764, 1416, 4411, 1045, 1...
3.844444
45
import asyncio import logging import random import time from abc import ABC from typing import Literal, Optional import aiohttp import discord from redbot.core import Config, bank, checks, commands from redbot.core.utils.chat_formatting import box from redbot.core.utils.menus import DEFAULT_CONTROLS, menu from tabulate import tabulate from .core import SimHelper from .functions import WEATHER from .simset import SimsetMixin from .stats import StatsMixin from .teamset import TeamsetMixin # THANKS TO https://code.sololearn.com/ci42wd5h0UQX/#py FOR THE SIMULATION AND FIXATOR/AIKATERNA/STEVY FOR THE PILLOW HELP/LEVELER
[ 11748, 30351, 952, 198, 11748, 18931, 198, 11748, 4738, 198, 11748, 640, 198, 6738, 450, 66, 1330, 9738, 198, 6738, 19720, 1330, 25659, 1691, 11, 32233, 198, 198, 11748, 257, 952, 4023, 198, 11748, 36446, 198, 6738, 2266, 13645, 13, 729...
3.270833
192
""" Deep Learning """ import pandas as pd from keras.models import Sequential from keras.layers import Dense from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix from sklearn.preprocessing import LabelEncoder, OneHotEncoder from sklearn.preprocessing import StandardScaler from sklearn.compose import make_column_transformer import os path = os.path.abspath(os.getcwd()) + r"/0_dataset/" dataset = pd.read_csv(path + "Credit2.csv", sep=";") dataset #separao dos variveis, ignoro primeira pois no tem valor semntico X = dataset.iloc[:,1:10].values y = dataset.iloc[:, 10].values #temos um arry e no mais um data frame X #label encoder coluna checking_status #atribui valores de zero a 3 labelencoder = LabelEncoder() X[:,0] = labelencoder.fit_transform(X[:,0]) X #one hot encoder coluna credit_history #deve adicionar 5 colunas onehotencoder = make_column_transformer((OneHotEncoder(categories='auto', sparse=False), [1]), remainder="passthrough") X = onehotencoder.fit_transform(X) X #Excluimos a varivel para evitar a dummy variable trap X = X:,1: X #Laber encoder com a classe labelencoder_Y = LabelEncoder() y = labelencoder_Y.fit_transform(y) y #separao em treino e teste X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) print(len(X_train),len(X_test),len(y_train),len(y_test)) #Feature Scalling, Padronizao z-score sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) X_test classifier = Sequential() classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 12)) classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu')) classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid')) classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) classifier.fit(X_train, y_train, batch_size = 10, epochs = 100) y_pred = classifier.predict(X_test) y_pred = (y_pred > 0.5) y_pred #matriz de confuso cm = confusion_matrix(y_test, y_pred) cm
[ 37811, 198, 29744, 18252, 198, 37811, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 41927, 292, 13, 27530, 1330, 24604, 1843, 198, 6738, 41927, 292, 13, 75, 6962, 1330, 360, 1072, 198, 6738, 1341, 35720, 13, 19849, 62, 49283, ...
2.742188
768
import re # import all settings-modules here, so we can only import this module to get them all from python_settings.settings_activatable import * from python_settings.settings_child_placeholder import * from python_settings.settings_choice import * from python_settings.settings_comment import * from python_settings.settings_conditional import * from python_settings.settings_container import * from python_settings.settings_dict_entry import * from python_settings.settings_empty_line import * from python_settings.settings_list_entry import * # this holds a complete settings.py by parsing its config-dict and storing the rest of the file in prefix and postfix
[ 11748, 302, 198, 198, 2, 1330, 477, 6460, 12, 18170, 994, 11, 523, 356, 460, 691, 1330, 428, 8265, 284, 651, 606, 477, 198, 6738, 21015, 62, 33692, 13, 33692, 62, 15791, 21156, 1330, 1635, 198, 6738, 21015, 62, 33692, 13, 33692, 62,...
4.123457
162
# -*- coding: utf-8 -*- import timeit from functools import wraps from titan.manages.global_manager import GlobalManager
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 640, 270, 198, 6738, 1257, 310, 10141, 1330, 27521, 198, 6738, 48047, 13, 805, 1095, 13, 20541, 62, 37153, 1330, 8060, 13511, 628 ]
3.210526
38
# Copyright (c) 2014 Eventbrite, Inc. All rights reserved. # See "LICENSE" file for license. import re open_r_str = r'\<\?cs\s*([a-zA-Z]+)([:]|\s)' close_r_str = r'\<\?cs\s*/([a-zA-Z]+)\s*\?\>' open_r = re.compile(open_r_str) close_r = re.compile(close_r_str)
[ 2, 15069, 357, 66, 8, 1946, 8558, 1671, 578, 11, 3457, 13, 1439, 2489, 10395, 13, 198, 2, 4091, 366, 43, 2149, 24290, 1, 2393, 329, 5964, 13, 198, 198, 11748, 302, 198, 198, 9654, 62, 81, 62, 2536, 796, 374, 6, 49778, 59, 30, ...
2.031008
129
# -*- coding: utf-8 -*- # Copyright 2019 Subteno IT # License MIT License import requests import xmltodict import string import random import io
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 13130, 3834, 1452, 78, 7283, 198, 2, 13789, 17168, 13789, 198, 198, 11748, 7007, 198, 11748, 2124, 76, 2528, 375, 713, 198, 11748, 4731, 198, 11748, 4738, 198,...
3.12766
47
import bpy from bpy.types import Panel from bpy.props import * import math default_surface_names = [ ("bcc", "bcc", "", 1), ("schwarzp", "schwarzp", "", 2), ("schwarzd", "schwarzd", "", 3), ("gyroid", "gyroid", "", 4), ("double-p", "double-p", "", 5), ("double-d", "double-d", "", 6), ("double-gyroid", "double-gyroid", "", 7), ("lidinoid", "lidinoid", "", 8), ("schoen_iwp", "schoen_iwp", "", 9), ("neovius", "neovius", "", 10), ("tubular_g_ab", "tubular_g_ab", "", 11), ("tubular_g_c", "tubular_g_c", "", 12) ] default_direction = [ ("X", "X", "", 0), ("Y", "Y", "", 1), ("Z", "Z", "", 2), ("All", "All", "", 3) ]
[ 11748, 275, 9078, 198, 6738, 275, 9078, 13, 19199, 1330, 18810, 198, 6738, 275, 9078, 13, 1676, 862, 1330, 1635, 198, 11748, 10688, 198, 198, 12286, 62, 42029, 62, 14933, 796, 685, 198, 220, 220, 220, 5855, 65, 535, 1600, 366, 65, 5...
2.032836
335
import argparse import torch from torch.nn import Softplus from pina import PINN, Plotter from pina.model import FeedForward from problems.burgers import Burgers1D if __name__ == "__main__": parser = argparse.ArgumentParser(description="Run PINA") group = parser.add_mutually_exclusive_group(required=True) group.add_argument("-s", "-save", action="store_true") group.add_argument("-l", "-load", action="store_true") parser.add_argument("id_run", help="number of run", type=int) parser.add_argument("features", help="extra features", type=int) args = parser.parse_args() feat = [myFeature(0)] if args.features else [] burgers_problem = Burgers1D() model = FeedForward( layers=[30, 20, 10, 5], output_variables=burgers_problem.output_variables, input_variables=burgers_problem.input_variables, func=Softplus, extra_features=feat, ) pinn = PINN( burgers_problem, model, lr=0.006, error_norm='mse', regularizer=0, lr_accelerate=None) if args.s: pinn.span_pts(2000, 'latin', ['D']) pinn.span_pts(150, 'random', ['gamma1', 'gamma2', 't0']) pinn.train(5000, 100) pinn.save_state('pina.burger.{}.{}'.format(args.id_run, args.features)) else: pinn.load_state('pina.burger.{}.{}'.format(args.id_run, args.features)) plotter = Plotter() plotter.plot(pinn)
[ 11748, 1822, 29572, 198, 11748, 28034, 198, 6738, 28034, 13, 20471, 1330, 8297, 9541, 198, 198, 6738, 279, 1437, 1330, 34279, 45, 11, 28114, 353, 198, 6738, 279, 1437, 13, 19849, 1330, 18272, 39746, 198, 6738, 2761, 13, 7423, 364, 1330,...
2.316879
628
""" In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1. Two nodes of a binary tree are cousins if they have the same depth, but have different parents. We are given the root of a binary tree with unique values, and the values xand yof two different nodes in the tree. Returntrueif and only if the nodes corresponding to the values x and y are cousins. Example 1: Input: root = [1,2,3,4], x = 4, y = 3 Output: false Example 2: Input: root = [1,2,3,null,4,null,5], x = 5, y = 4 Output: true Example 3: Input: root = [1,2,3,null,4], x = 2, y = 3 Output: false Constraints: The number of nodes in the tree will be between 2 and 100. Each node has a unique integer value from 1 to 100. """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right
[ 37811, 198, 198, 818, 257, 13934, 5509, 11, 262, 6808, 10139, 318, 379, 6795, 657, 11, 290, 1751, 286, 1123, 6795, 479, 10139, 389, 379, 6795, 479, 10, 16, 13, 198, 7571, 13760, 286, 257, 13934, 5509, 389, 28706, 611, 484, 423, 262,...
2.895706
326
from .configuration_entry import ConfigurationEntry from utility_ai.traits.utility_score_trait import UtilityScoreTrait
[ 6738, 764, 11250, 3924, 62, 13000, 1330, 28373, 30150, 198, 6738, 10361, 62, 1872, 13, 9535, 896, 13, 315, 879, 62, 26675, 62, 9535, 270, 1330, 34030, 26595, 51, 12907, 628 ]
3.903226
31
from collections import namedtuple Style = namedtuple('Style', 'name fg bg') default_pal = { Style('inv-black', 'black', 'light gray'), Style('green-bold', 'dark green,bold', ''), Style('red-bold', 'dark red,bold', ''), Style('blue-bold', 'dark blue,bold', ''), Style('yellow-bold', 'yellow,bold', ''), Style('magenta-bold', 'dark magenta,bold', ''), Style('cyan-bold', 'dark cyan,bold', ''), Style('green', 'dark green', ''), Style('red', 'dark red', ''), Style('blue', 'dark blue', ''), Style('cyan', 'dark cyan', ''), Style('magenta', 'dark magenta', ''), Style('yellow', 'yellow', ''), } INV_BLACK = 'inv-black' RED_BOLD = 'red-bold' GREEN_BOLD = 'green-bold' BLUE_BOLD = 'blue-bold' MAGENTA_BOLD = 'magenta-bold' CYAN_BOLD = 'cyan-bold' YELLOW_BOLD = 'yellow-bold' BLUE = 'blue' GREEN = 'green' RED = 'red' MAGENTA = 'magenta' CYAN = 'cyan' YELLOW = 'yellow'
[ 6738, 17268, 1330, 3706, 83, 29291, 198, 198, 21466, 796, 3706, 83, 29291, 10786, 21466, 3256, 705, 3672, 277, 70, 275, 70, 11537, 198, 198, 12286, 62, 18596, 796, 1391, 198, 220, 220, 220, 17738, 10786, 16340, 12, 13424, 3256, 220, 2...
1.939341
577
#!/usr/bin/env python3 import tensorflow as tf x=tf.Variable(0.5) y = x*x sess = tf.Session() sess.run(tf.global_variables_initializer()) print("x =",sess.run(x)) print("y =",sess.run(y))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 198, 87, 28, 27110, 13, 43015, 7, 15, 13, 20, 8, 198, 88, 796, 2124, 9, 87, 198, 82, 408, 796, 48700, 13, 36044, 3419, 198, 82, 408...
2.223529
85
import os import random import cv2 import numpy as np from gen_textures import add_noise, texture, blank_image from nist_tools.extract_nist_text import BaseMain, parse_args, display if __name__ == '__main__': random.seed(123) args = parse_args() CombineMain().main(args) print('done')
[ 11748, 28686, 198, 11748, 4738, 198, 198, 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 2429, 62, 5239, 942, 1330, 751, 62, 3919, 786, 11, 11743, 11, 9178, 62, 9060, 198, 6738, 299, 396, 62, 31391, 13, 2302...
2.756757
111
# this function looks for either the encounter date or the patient's date of birth # so that we can avoid duplicate encounters. import time #this will select element in div with relement div.
[ 2, 428, 2163, 3073, 329, 2035, 262, 8791, 3128, 393, 262, 5827, 338, 3128, 286, 4082, 220, 198, 2, 523, 326, 356, 460, 3368, 23418, 16925, 13, 220, 198, 11748, 640, 628, 198, 2, 5661, 481, 2922, 5002, 287, 2659, 351, 302, 1732, 26...
2.797619
84
from flask import g from flask_restplus import Resource, marshal from app import db from app.api.namespaces.token_namespace import token_ns, token from app.api.security.authentication import basic_auth, token_auth
[ 6738, 42903, 1330, 308, 198, 6738, 42903, 62, 2118, 9541, 1330, 20857, 11, 22397, 282, 198, 198, 6738, 598, 1330, 20613, 198, 6738, 598, 13, 15042, 13, 14933, 43076, 13, 30001, 62, 14933, 10223, 1330, 11241, 62, 5907, 11, 11241, 198, ...
3.661017
59
# -*- coding: utf-8 -*- # low --> Starting index, high --> Ending index test = Solution() print test.quickSort([10, 80, 30, 90, 40, 50, 70], 0, 6)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 1877, 220, 14610, 17962, 6376, 11, 220, 1029, 220, 14610, 43626, 6376, 198, 198, 9288, 796, 28186, 3419, 198, 4798, 1332, 13, 24209, 42758, 26933, 940, 11, 4019, 11, ...
2.586207
58
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Multi arch dockerized build tool. """ __author__ = 'Pedro Larroy' __version__ = '0.1' import os import sys import subprocess import logging import argparse from subprocess import check_call import glob import re def get_arches(): """Get a list of architectures given our dockerfiles""" dockerfiles = glob.glob("Dockerfile.build.*") dockerfiles = list(filter(lambda x: x[-1] != '~', dockerfiles)) arches = list(map(lambda x: re.sub(r"Dockerfile.build.(.*)", r"\1", x), dockerfiles)) arches.sort() return arches def build(arch): """Build the given architecture in the container""" assert arch in get_arches(), "No such architecture {0}, Dockerfile.build.{0} not found".format(arch) logging.info("Building for target platform {0}".format(arch)) check_call(["docker", "build", "-f", get_dockerfile(arch), "-t", get_docker_tag(arch), "."]) def collect_artifacts(arch): """Collects the artifacts built inside the docker container to the local fs""" logging.info("Collect artifacts from build in {0}".format(artifact_path(arch))) mkdir_p("build/{}".format(arch)) # Mount artifact_path on /$arch inside the container and copy the build output so we can access # locally from the host fs check_call(["docker","run", "-v", "{}:/{}".format(artifact_path(arch), arch), get_docker_tag(arch), "bash", "-c", "cp -r /work/build/* /{}".format(arch)]) if __name__ == '__main__': sys.exit(main())
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 49962, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 198, 2, 393, 517, 18920, 5964, 11704, ...
3.080263
760
import json if __name__ == '__main__': test_norun()
[ 11748, 33918, 201, 198, 201, 198, 201, 198, 201, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 201, 198, 220, 220, 220, 1332, 62, 13099, 403, 3419, 201, 198 ]
2.03125
32
# -*- coding: utf-8 -*- """ # @file name : module_containers.py # @author : tingsongyu # @date : 2019-09-20 10:08:00 # @brief : Sequential, ModuleList, ModuleDict """ import torch import torchvision import torch.nn as nn from collections import OrderedDict # ============================ Sequential # net = LeNetSequential(classes=2) # net = LeNetSequentialOrderDict(classes=2) # # fake_img = torch.randn((4, 3, 32, 32), dtype=torch.float32) # # output = net(fake_img) # # print(net) # print(output) # ============================ ModuleList # net = ModuleList() # # print(net) # # fake_data = torch.ones((10, 10)) # # output = net(fake_data) # # print(output) # ============================ ModuleDict net = ModuleDict() fake_img = torch.randn((4, 10, 32, 32)) output = net(fake_img, 'conv', 'relu') print(output) # 4 AlexNet alexnet = torchvision.models.AlexNet()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 2, 2488, 7753, 1438, 220, 1058, 8265, 62, 3642, 50221, 13, 9078, 198, 2, 2488, 9800, 220, 220, 220, 220, 1058, 256, 654, 506, 24767, 198, 2, 2488, 4475, ...
2.631884
345
import pytest import shutil as sh import pandas as pd from pathlib import Path from glob import glob import libs.dirs as dirs from libs.iteration_manager import SampleImages from libs.utils import copy_files, replace_symbols
[ 11748, 12972, 9288, 198, 11748, 4423, 346, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 355, 427, 198, 11748, 19798, 292, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 355, 279, 67,...
2.05298
151
data={ "":" ", "":" ", "":" ", "":" SHOW TIME!", "":" ", "":" \n ", "":" ", "":"! \n ", "":" ", "":" ", "":" ", }
[ 7890, 34758, 198, 220, 220, 220, 366, 2404, 220, 220, 33172, 198, 220, 220, 220, 366, 2404, 220, 220, 33172, 198, 220, 220, 220, 366, 2404, 220, 220, 33172, 198, 220, 220, 220, 366, 2404, 220, 220, 37041, 20460, 40754, 198, 220, 220...
1.621622
111
BASE_URL = 'https://api.themoviedb.org/3'
[ 33, 11159, 62, 21886, 796, 705, 5450, 1378, 15042, 13, 18855, 709, 798, 65, 13, 2398, 14, 18, 6, 198 ]
2.1
20
speed(0) penup() setposition(-100, 0) pendown() for i in range (6): pendown() make_square(i) penup() forward(35)
[ 12287, 7, 15, 8, 201, 198, 201, 198, 3617, 929, 3419, 201, 198, 2617, 9150, 32590, 3064, 11, 657, 8, 201, 198, 37038, 593, 3419, 201, 198, 1640, 1312, 287, 2837, 357, 21, 2599, 201, 198, 220, 220, 220, 44017, 593, 3419, 201, 198, ...
1.944444
72
""" Module for reading data from 'linearX.csv' and 'linearY.csv' """ import numpy as np def loadData (x_file="ass1_data/linearX.csv", y_file="ass1_data/linearY.csv"): """ Loads the X, Y matrices. Splits into training, validation and test sets """ X = np.genfromtxt(x_file) Y = np.genfromtxt(y_file) Z = [X, Y] Z = np.c_[X.reshape(len(X), -1), Y.reshape(len(Y), -1)] np.random.shuffle(Z) # Partition the data into three sets size = len(Z) training_size = int(0.8 * size) validation_size = int(0.1 * size) test_size = int(0.1 * size) training_Z = Z[0:training_size] validation_Z = Z[training_size:training_size+validation_size] test_Z = Z[training_size+validation_size:] return (Z[:,0], Z[:,1])
[ 37811, 198, 26796, 329, 3555, 1366, 422, 705, 29127, 55, 13, 40664, 6, 290, 705, 29127, 56, 13, 40664, 6, 198, 37811, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 4299, 3440, 6601, 357, 87, 62, 7753, 2625, 562, 16, 62, 7890, ...
2.294643
336
from django import forms from .models import Experiment
[ 6738, 42625, 14208, 1330, 5107, 198, 198, 6738, 764, 27530, 1330, 29544, 628 ]
4.461538
13