body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1
value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
50b19f277869654b2618286dea7c22f98c92f034cf83878f64deeb53271710b7 | def _generate_jwt_token(self):
"\n Generates a JSON Web Token that stores this user's ID and has an expiry\n date set to 60 days into the future.\n "
dt = (datetime.now() + timedelta(days=60))
token = jwt.encode({'id': self.pk, 'exp': int(dt.strftime('%s'))}, str(self.jwt_secret), algor... | Generates a JSON Web Token that stores this user's ID and has an expiry
date set to 60 days into the future. | authentication/models.py | _generate_jwt_token | RetroFlow/retro-flow | 0 | python | def _generate_jwt_token(self):
"\n Generates a JSON Web Token that stores this user's ID and has an expiry\n date set to 60 days into the future.\n "
dt = (datetime.now() + timedelta(days=60))
token = jwt.encode({'id': self.pk, 'exp': int(dt.strftime('%s'))}, str(self.jwt_secret), algor... | def _generate_jwt_token(self):
"\n Generates a JSON Web Token that stores this user's ID and has an expiry\n date set to 60 days into the future.\n "
dt = (datetime.now() + timedelta(days=60))
token = jwt.encode({'id': self.pk, 'exp': int(dt.strftime('%s'))}, str(self.jwt_secret), algor... |
69e68ced87833cc832061fb25d1acebdef8e7f39230f612304e48b73edfda8f2 | def logout(self):
'\n Generated new jwt secret. After this previous JWT token will be invalid\n '
self.jwt_secret = uuid.uuid4()
self.save() | Generated new jwt secret. After this previous JWT token will be invalid | authentication/models.py | logout | RetroFlow/retro-flow | 0 | python | def logout(self):
'\n \n '
self.jwt_secret = uuid.uuid4()
self.save() | def logout(self):
'\n \n '
self.jwt_secret = uuid.uuid4()
self.save()<|docstring|>Generated new jwt secret. After this previous JWT token will be invalid<|endoftext|> |
b7cbce54eb5c69e103475f627c2648b472ef6e8852106d5ec696b8f55a8923d2 | def hookes_hamiltonian_from_graph_fn(graph: jraph.GraphsTuple) -> jraph.GraphsTuple:
'Computes Hamiltonian of a Hooke\'s potential system represented in a graph.\n\n While this function hardcodes the Hamiltonian for a Hooke\'s potential, a\n learned Hamiltonian Graph Network (https://arxiv.org/abs/1909.12790) cou... | Computes Hamiltonian of a Hooke's potential system represented in a graph.
While this function hardcodes the Hamiltonian for a Hooke's potential, a
learned Hamiltonian Graph Network (https://arxiv.org/abs/1909.12790) could
be implemented by replacing the hardcoded formulas by learnable MLPs that
take as inputs all of ... | jraph/examples/hamiltonian_graph_network.py | hookes_hamiltonian_from_graph_fn | vishalbelsare/jraph | 871 | python | def hookes_hamiltonian_from_graph_fn(graph: jraph.GraphsTuple) -> jraph.GraphsTuple:
'Computes Hamiltonian of a Hooke\'s potential system represented in a graph.\n\n While this function hardcodes the Hamiltonian for a Hooke\'s potential, a\n learned Hamiltonian Graph Network (https://arxiv.org/abs/1909.12790) cou... | def hookes_hamiltonian_from_graph_fn(graph: jraph.GraphsTuple) -> jraph.GraphsTuple:
'Computes Hamiltonian of a Hooke\'s potential system represented in a graph.\n\n While this function hardcodes the Hamiltonian for a Hooke\'s potential, a\n learned Hamiltonian Graph Network (https://arxiv.org/abs/1909.12790) cou... |
1084a075198c1f112a05e286e792f6d611213625c2c832c66c3ec6ca7c8f08f2 | def build_hookes_particle_state_graph(num_particles: int) -> jraph.GraphsTuple:
"Generates a graph representing a Hooke's system in a random state."
mass = np.random.uniform(0, 5, [num_particles])
velocity = get_random_uniform_norm2d_vectors(0, 0.1, num_particles)
position = get_random_uniform_norm2d_ve... | Generates a graph representing a Hooke's system in a random state. | jraph/examples/hamiltonian_graph_network.py | build_hookes_particle_state_graph | vishalbelsare/jraph | 871 | python | def build_hookes_particle_state_graph(num_particles: int) -> jraph.GraphsTuple:
mass = np.random.uniform(0, 5, [num_particles])
velocity = get_random_uniform_norm2d_vectors(0, 0.1, num_particles)
position = get_random_uniform_norm2d_vectors(0, 1, num_particles)
momentum = (velocity * np.expand_dims... | def build_hookes_particle_state_graph(num_particles: int) -> jraph.GraphsTuple:
mass = np.random.uniform(0, 5, [num_particles])
velocity = get_random_uniform_norm2d_vectors(0, 0.1, num_particles)
position = get_random_uniform_norm2d_vectors(0, 1, num_particles)
momentum = (velocity * np.expand_dims... |
1717e473fa5978d0b0a4f3bd2e01c174d6735e7334862482776743c747706256 | def get_random_uniform_norm2d_vectors(min_norm: float, max_norm: float, num_particles: int) -> np.ndarray:
'Returns 2-d vectors with random norms.'
norm = np.random.uniform(min_norm, max_norm, [num_particles, 1])
angle = np.random.uniform(0, (2 * np.pi), [num_particles])
return (norm * np.stack([np.cos(... | Returns 2-d vectors with random norms. | jraph/examples/hamiltonian_graph_network.py | get_random_uniform_norm2d_vectors | vishalbelsare/jraph | 871 | python | def get_random_uniform_norm2d_vectors(min_norm: float, max_norm: float, num_particles: int) -> np.ndarray:
norm = np.random.uniform(min_norm, max_norm, [num_particles, 1])
angle = np.random.uniform(0, (2 * np.pi), [num_particles])
return (norm * np.stack([np.cos(angle), np.sin(angle)], axis=(- 1))) | def get_random_uniform_norm2d_vectors(min_norm: float, max_norm: float, num_particles: int) -> np.ndarray:
norm = np.random.uniform(min_norm, max_norm, [num_particles, 1])
angle = np.random.uniform(0, (2 * np.pi), [num_particles])
return (norm * np.stack([np.cos(angle), np.sin(angle)], axis=(- 1)))<|do... |
6fb83c89f5ae297630be30e59f5948dc38f3ccffd633960b3e8954e5e10ed7a8 | def get_fully_connected_senders_and_receivers(num_particles: int, self_edges: bool=False) -> Tuple[(np.ndarray, np.ndarray)]:
'Returns senders and receivers for fully connected particles.'
particle_indices = np.arange(num_particles)
(senders, receivers) = np.meshgrid(particle_indices, particle_indices)
... | Returns senders and receivers for fully connected particles. | jraph/examples/hamiltonian_graph_network.py | get_fully_connected_senders_and_receivers | vishalbelsare/jraph | 871 | python | def get_fully_connected_senders_and_receivers(num_particles: int, self_edges: bool=False) -> Tuple[(np.ndarray, np.ndarray)]:
particle_indices = np.arange(num_particles)
(senders, receivers) = np.meshgrid(particle_indices, particle_indices)
(senders, receivers) = (senders.flatten(), receivers.flatten()... | def get_fully_connected_senders_and_receivers(num_particles: int, self_edges: bool=False) -> Tuple[(np.ndarray, np.ndarray)]:
particle_indices = np.arange(num_particles)
(senders, receivers) = np.meshgrid(particle_indices, particle_indices)
(senders, receivers) = (senders.flatten(), receivers.flatten()... |
a33fd6d6df4f9da5c827b0dcdaf8af4859860420cb29092c7ea1bda1361b2085 | def set_system_state(static_graph: jraph.GraphsTuple, position: np.ndarray, momentum: np.ndarray) -> jraph.GraphsTuple:
'Sets the non-static parameters of the graph (momentum, position).'
nodes = static_graph.nodes.copy(position=position, momentum=momentum)
return static_graph._replace(nodes=nodes) | Sets the non-static parameters of the graph (momentum, position). | jraph/examples/hamiltonian_graph_network.py | set_system_state | vishalbelsare/jraph | 871 | python | def set_system_state(static_graph: jraph.GraphsTuple, position: np.ndarray, momentum: np.ndarray) -> jraph.GraphsTuple:
nodes = static_graph.nodes.copy(position=position, momentum=momentum)
return static_graph._replace(nodes=nodes) | def set_system_state(static_graph: jraph.GraphsTuple, position: np.ndarray, momentum: np.ndarray) -> jraph.GraphsTuple:
nodes = static_graph.nodes.copy(position=position, momentum=momentum)
return static_graph._replace(nodes=nodes)<|docstring|>Sets the non-static parameters of the graph (momentum, position... |
b376d61b3d02d6fe2e47eee3107c111168a5de04d4fa6a3b309292e2e05e01aa | def get_static_graph(graph: jraph.GraphsTuple) -> jraph.GraphsTuple:
'Returns the graph with the static parts of a system only.'
nodes = dict(graph.nodes)
del nodes['position'], nodes['momentum']
return graph._replace(nodes=frozendict(nodes)) | Returns the graph with the static parts of a system only. | jraph/examples/hamiltonian_graph_network.py | get_static_graph | vishalbelsare/jraph | 871 | python | def get_static_graph(graph: jraph.GraphsTuple) -> jraph.GraphsTuple:
nodes = dict(graph.nodes)
del nodes['position'], nodes['momentum']
return graph._replace(nodes=frozendict(nodes)) | def get_static_graph(graph: jraph.GraphsTuple) -> jraph.GraphsTuple:
nodes = dict(graph.nodes)
del nodes['position'], nodes['momentum']
return graph._replace(nodes=frozendict(nodes))<|docstring|>Returns the graph with the static parts of a system only.<|endoftext|> |
fa7739aba719b5cfff1c45454d6125c54094e39044b622e8280543808c00420f | def get_hamiltonian_from_state_fn(static_graph: jraph.GraphsTuple, hamiltonian_from_graph_fn: Callable[([jraph.GraphsTuple], jraph.GraphsTuple)]) -> Callable[([np.ndarray, np.ndarray], float)]:
'Returns fn such that fn(position, momentum) -> scalar Hamiltonian.\n\n Args:\n static_graph: `GraphsTuple` containi... | Returns fn such that fn(position, momentum) -> scalar Hamiltonian.
Args:
static_graph: `GraphsTuple` containing per-particle static parameters and
connectivity, such as a full graph of the state can be build by calling
`set_system_state(static_graph, position, momentum)`.
hamiltonian_from_graph_f... | jraph/examples/hamiltonian_graph_network.py | get_hamiltonian_from_state_fn | vishalbelsare/jraph | 871 | python | def get_hamiltonian_from_state_fn(static_graph: jraph.GraphsTuple, hamiltonian_from_graph_fn: Callable[([jraph.GraphsTuple], jraph.GraphsTuple)]) -> Callable[([np.ndarray, np.ndarray], float)]:
'Returns fn such that fn(position, momentum) -> scalar Hamiltonian.\n\n Args:\n static_graph: `GraphsTuple` containi... | def get_hamiltonian_from_state_fn(static_graph: jraph.GraphsTuple, hamiltonian_from_graph_fn: Callable[([jraph.GraphsTuple], jraph.GraphsTuple)]) -> Callable[([np.ndarray, np.ndarray], float)]:
'Returns fn such that fn(position, momentum) -> scalar Hamiltonian.\n\n Args:\n static_graph: `GraphsTuple` containi... |
db7638ac84972fd11adf97964c57b1f78d6ddd90adf72f3182de0e5ef91420ee | def get_state_derivatives_from_hamiltonian_fn(hamiltonian_from_state_fn: Callable[([np.ndarray, np.ndarray], float)]) -> Callable[([np.ndarray, np.ndarray], Tuple[(np.ndarray, np.ndarray)])]:
'Returns fn(position, momentum, ...) -> (dposition_dt, dmomentum_dt).\n\n Args:\n hamiltonian_from_state_fn: Function ... | Returns fn(position, momentum, ...) -> (dposition_dt, dmomentum_dt).
Args:
hamiltonian_from_state_fn: Function that given a state
(position, momentum) returns the scalar Hamiltonian.
Returns:
Function that given a state (position, momentum) returns the time
derivatives of the state (dposition_dt,... | jraph/examples/hamiltonian_graph_network.py | get_state_derivatives_from_hamiltonian_fn | vishalbelsare/jraph | 871 | python | def get_state_derivatives_from_hamiltonian_fn(hamiltonian_from_state_fn: Callable[([np.ndarray, np.ndarray], float)]) -> Callable[([np.ndarray, np.ndarray], Tuple[(np.ndarray, np.ndarray)])]:
'Returns fn(position, momentum, ...) -> (dposition_dt, dmomentum_dt).\n\n Args:\n hamiltonian_from_state_fn: Function ... | def get_state_derivatives_from_hamiltonian_fn(hamiltonian_from_state_fn: Callable[([np.ndarray, np.ndarray], float)]) -> Callable[([np.ndarray, np.ndarray], Tuple[(np.ndarray, np.ndarray)])]:
'Returns fn(position, momentum, ...) -> (dposition_dt, dmomentum_dt).\n\n Args:\n hamiltonian_from_state_fn: Function ... |
c34f1c2dac7d50c6e677424910e010db06ad70b969ba213fafe1936692fb69ea | def abstract_integrator(position: np.ndarray, momentum: np.ndarray, time_step: float, state_derivatives_fn: StateDerivativesFnType) -> Tuple[(np.ndarray, np.ndarray)]:
'Signature of an abstract integrator.\n\n An integrator is a function, that given the the current state, a time step,\n and a `state_derivatives_f... | Signature of an abstract integrator.
An integrator is a function, that given the the current state, a time step,
and a `state_derivatives_fn` returns the next state.
Args:
position: array with the position at time t.
momentum: array with the momentum at time t.
time_step: integration step size.
state_... | jraph/examples/hamiltonian_graph_network.py | abstract_integrator | vishalbelsare/jraph | 871 | python | def abstract_integrator(position: np.ndarray, momentum: np.ndarray, time_step: float, state_derivatives_fn: StateDerivativesFnType) -> Tuple[(np.ndarray, np.ndarray)]:
'Signature of an abstract integrator.\n\n An integrator is a function, that given the the current state, a time step,\n and a `state_derivatives_f... | def abstract_integrator(position: np.ndarray, momentum: np.ndarray, time_step: float, state_derivatives_fn: StateDerivativesFnType) -> Tuple[(np.ndarray, np.ndarray)]:
'Signature of an abstract integrator.\n\n An integrator is a function, that given the the current state, a time step,\n and a `state_derivatives_f... |
fdeda24a684a3e7c5cea4ed3088c43101c3655547acac705a236a7b985f9854a | def euler_integrator(position: np.ndarray, momentum: np.ndarray, time_step: float, state_derivatives_fn: StateDerivativesFnType) -> Tuple[(np.ndarray, np.ndarray)]:
'Implementation of an Euler integrator (see `abstract_integrator`).'
(dposition_dt, dmomentum_dt) = state_derivatives_fn(position, momentum)
ne... | Implementation of an Euler integrator (see `abstract_integrator`). | jraph/examples/hamiltonian_graph_network.py | euler_integrator | vishalbelsare/jraph | 871 | python | def euler_integrator(position: np.ndarray, momentum: np.ndarray, time_step: float, state_derivatives_fn: StateDerivativesFnType) -> Tuple[(np.ndarray, np.ndarray)]:
(dposition_dt, dmomentum_dt) = state_derivatives_fn(position, momentum)
next_position = (position + (dposition_dt * time_step))
next_momen... | def euler_integrator(position: np.ndarray, momentum: np.ndarray, time_step: float, state_derivatives_fn: StateDerivativesFnType) -> Tuple[(np.ndarray, np.ndarray)]:
(dposition_dt, dmomentum_dt) = state_derivatives_fn(position, momentum)
next_position = (position + (dposition_dt * time_step))
next_momen... |
fc075d0fda2c994fe2664eeed7b62af0cdb890981d8a23a41855ade3b769467e | def verlet_integrator(position: np.ndarray, momentum: np.ndarray, time_step: float, state_derivatives_fn: StateDerivativesFnType) -> Tuple[(np.ndarray, np.ndarray)]:
'Implementation of Verlet integrator (see `abstract_integrator`).'
(_, dmomentum_dt) = state_derivatives_fn(position, momentum)
aux_momentum =... | Implementation of Verlet integrator (see `abstract_integrator`). | jraph/examples/hamiltonian_graph_network.py | verlet_integrator | vishalbelsare/jraph | 871 | python | def verlet_integrator(position: np.ndarray, momentum: np.ndarray, time_step: float, state_derivatives_fn: StateDerivativesFnType) -> Tuple[(np.ndarray, np.ndarray)]:
(_, dmomentum_dt) = state_derivatives_fn(position, momentum)
aux_momentum = (momentum + ((dmomentum_dt * time_step) / 2))
(dposition_dt, ... | def verlet_integrator(position: np.ndarray, momentum: np.ndarray, time_step: float, state_derivatives_fn: StateDerivativesFnType) -> Tuple[(np.ndarray, np.ndarray)]:
(_, dmomentum_dt) = state_derivatives_fn(position, momentum)
aux_momentum = (momentum + ((dmomentum_dt * time_step) / 2))
(dposition_dt, ... |
1277cbff094bad51a1093e7a7e8fd138131fb1837e1db6171aa88cefdbf761a4 | def single_integration_step(graph: jraph.GraphsTuple, time_step: float, integrator_fn: IntegratorType, hamiltonian_from_graph_fn: Callable[([jraph.GraphsTuple], jraph.GraphsTuple)]) -> Tuple[(float, jraph.GraphsTuple)]:
'Updates a graph state integrating by a single step.\n\n Args:\n graph: `GraphsTuple` repres... | Updates a graph state integrating by a single step.
Args:
graph: `GraphsTuple` representing a system state at time t.
time_step: size of the timestep to integrate for.
integrator_fn: Integrator to use. A function fn such that
fn(position_t, momentum_t, time_step, state_derivatives_fn) ->
(position_... | jraph/examples/hamiltonian_graph_network.py | single_integration_step | vishalbelsare/jraph | 871 | python | def single_integration_step(graph: jraph.GraphsTuple, time_step: float, integrator_fn: IntegratorType, hamiltonian_from_graph_fn: Callable[([jraph.GraphsTuple], jraph.GraphsTuple)]) -> Tuple[(float, jraph.GraphsTuple)]:
'Updates a graph state integrating by a single step.\n\n Args:\n graph: `GraphsTuple` repres... | def single_integration_step(graph: jraph.GraphsTuple, time_step: float, integrator_fn: IntegratorType, hamiltonian_from_graph_fn: Callable[([jraph.GraphsTuple], jraph.GraphsTuple)]) -> Tuple[(float, jraph.GraphsTuple)]:
'Updates a graph state integrating by a single step.\n\n Args:\n graph: `GraphsTuple` repres... |
b8894beffc35c007af012dc7b18ee12f3d124d0cca860d59c0fc8198ee6ac32d | def Preprocess_Path_One(train_data, target_variable, ml_usecase=None, test_data=None, categorical_features=[], numerical_features=[], time_features=[], features_todrop=[], display_types=True, imputation_type='simple', numeric_imputation_strategy='mean', categorical_imputation_strategy='not_available', imputation_classi... | Follwoing preprocess steps are taken:
- 1) Auto infer data types
- 2) Impute (simple or with surrogate columns)
- 3) Ordinal Encoder
- 4) Drop categorical variables that have zero variance or near zero variance
- 5) Club categorical variables levels togather as a new level (other_infrequent) that are rare / ... | pycaret/internal/preprocess.py | Preprocess_Path_One | pakallis/pycaret | 1 | python | def Preprocess_Path_One(train_data, target_variable, ml_usecase=None, test_data=None, categorical_features=[], numerical_features=[], time_features=[], features_todrop=[], display_types=True, imputation_type='simple', numeric_imputation_strategy='mean', categorical_imputation_strategy='not_available', imputation_classi... | def Preprocess_Path_One(train_data, target_variable, ml_usecase=None, test_data=None, categorical_features=[], numerical_features=[], time_features=[], features_todrop=[], display_types=True, imputation_type='simple', numeric_imputation_strategy='mean', categorical_imputation_strategy='not_available', imputation_classi... |
7f0beecd423beafd2b39b7d70bca04db8d01820fcd29880fadfd9f0cd94c17a7 | def Preprocess_Path_Two(train_data, ml_usecase=None, test_data=None, categorical_features=[], numerical_features=[], time_features=[], features_todrop=[], display_types=False, imputation_type='simple', numeric_imputation_strategy='mean', categorical_imputation_strategy='not_available', imputation_classifier=None, imput... | Follwoing preprocess steps are taken:
- THIS IS BUILt FOR UNSUPERVISED LEARNING
- 1) Auto infer data types
- 2) Impute (simple or with surrogate columns)
- 3) Ordinal Encoder
- 4) Drop categorical variables that have zero variance or near zero variance
- 5) Club categorical variables levels togather as a n... | pycaret/internal/preprocess.py | Preprocess_Path_Two | pakallis/pycaret | 1 | python | def Preprocess_Path_Two(train_data, ml_usecase=None, test_data=None, categorical_features=[], numerical_features=[], time_features=[], features_todrop=[], display_types=False, imputation_type='simple', numeric_imputation_strategy='mean', categorical_imputation_strategy='not_available', imputation_classifier=None, imput... | def Preprocess_Path_Two(train_data, ml_usecase=None, test_data=None, categorical_features=[], numerical_features=[], time_features=[], features_todrop=[], display_types=False, imputation_type='simple', numeric_imputation_strategy='mean', categorical_imputation_strategy='not_available', imputation_classifier=None, imput... |
afc138781b1d72b4ecad28851211841d44edace5976e684b4362a875e2160cca | def __init__(self, target, ml_usecase, categorical_features=[], numerical_features=[], time_features=[], features_todrop=[], id_columns=[], display_types=True):
"\n User to define the target (y) variable\n args:\n target: string, name of the target variable\n ml_usecase: string , 'regresson' o... | User to define the target (y) variable
args:
target: string, name of the target variable
ml_usecase: string , 'regresson' or 'classification . For now, only supports two class classification
- this is useful in case target variable is an object / string . it will replace the strings with integers
cat... | pycaret/internal/preprocess.py | __init__ | pakallis/pycaret | 1 | python | def __init__(self, target, ml_usecase, categorical_features=[], numerical_features=[], time_features=[], features_todrop=[], id_columns=[], display_types=True):
"\n User to define the target (y) variable\n args:\n target: string, name of the target variable\n ml_usecase: string , 'regresson' o... | def __init__(self, target, ml_usecase, categorical_features=[], numerical_features=[], time_features=[], features_todrop=[], id_columns=[], display_types=True):
"\n User to define the target (y) variable\n args:\n target: string, name of the target variable\n ml_usecase: string , 'regresson' o... |
44c214cddc3af4fe47f1939784cc7e1f588388c9d506c5649e1503cf3c0872fe | def fit(self, dataset, y=None):
'\n Args: \n data: accepts a pandas data frame\n Returns:\n Panda Data Frame\n '
data = dataset.copy()
data.columns = [str(i) for i in data.columns]
data.drop(columns=self.features_todrop, errors='ignore', inplace=True)
data.replace([np.inf, (- np.i... | Args:
data: accepts a pandas data frame
Returns:
Panda Data Frame | pycaret/internal/preprocess.py | fit | pakallis/pycaret | 1 | python | def fit(self, dataset, y=None):
'\n Args: \n data: accepts a pandas data frame\n Returns:\n Panda Data Frame\n '
data = dataset.copy()
data.columns = [str(i) for i in data.columns]
data.drop(columns=self.features_todrop, errors='ignore', inplace=True)
data.replace([np.inf, (- np.i... | def fit(self, dataset, y=None):
'\n Args: \n data: accepts a pandas data frame\n Returns:\n Panda Data Frame\n '
data = dataset.copy()
data.columns = [str(i) for i in data.columns]
data.drop(columns=self.features_todrop, errors='ignore', inplace=True)
data.replace([np.inf, (- np.i... |
8f4bf8341aa4409f6c59d5a1d849d96b2a051d1e224a99c0b760fd8983be972a | def transform(self, dataset, y=None):
'\n Args: \n data: accepts a pandas data frame\n Returns:\n Panda Data Frame\n '
data = dataset.copy()
data.columns = [str(i) for i in data.columns]
data.drop(columns=self.features_todrop, errors='ignore', inplace=True)
data = data[sel... | Args:
data: accepts a pandas data frame
Returns:
Panda Data Frame | pycaret/internal/preprocess.py | transform | pakallis/pycaret | 1 | python | def transform(self, dataset, y=None):
'\n Args: \n data: accepts a pandas data frame\n Returns:\n Panda Data Frame\n '
data = dataset.copy()
data.columns = [str(i) for i in data.columns]
data.drop(columns=self.features_todrop, errors='ignore', inplace=True)
data = data[sel... | def transform(self, dataset, y=None):
'\n Args: \n data: accepts a pandas data frame\n Returns:\n Panda Data Frame\n '
data = dataset.copy()
data.columns = [str(i) for i in data.columns]
data.drop(columns=self.features_todrop, errors='ignore', inplace=True)
data = data[sel... |
41b7eaf00ed22e98df6380f9c67ff2667a4036e13197b3dc8d4f4d2d460eacbd | def fit(self, data, y=None):
'\n Args:\n data = takes preprocessed data frame\n Returns:\n None\n '
self.data1 = data
corr = pd.DataFrame(np.corrcoef(self.data1.T))
corr.columns = self.data1.columns
corr.index = self.data1.columns
self.corr_matrix = abs(cor... | Args:
data = takes preprocessed data frame
Returns:
None | pycaret/internal/preprocess.py | fit | pakallis/pycaret | 1 | python | def fit(self, data, y=None):
'\n Args:\n data = takes preprocessed data frame\n Returns:\n None\n '
self.data1 = data
corr = pd.DataFrame(np.corrcoef(self.data1.T))
corr.columns = self.data1.columns
corr.index = self.data1.columns
self.corr_matrix = abs(cor... | def fit(self, data, y=None):
'\n Args:\n data = takes preprocessed data frame\n Returns:\n None\n '
self.data1 = data
corr = pd.DataFrame(np.corrcoef(self.data1.T))
corr.columns = self.data1.columns
corr.index = self.data1.columns
self.corr_matrix = abs(cor... |
440fe1e61d30146289fdd15f6241b353b5952c08e74e4f96952ef1c6f01492be | def transform(self, dataset, y=None):
'\n Args:f\n data = takes preprocessed data frame\n Returns:\n data frame\n '
data = dataset
data = data.drop(self.to_drop, axis=1)
data.drop(self.to_drop_taret_correlation, axis=1, inplace=True, errors='ignore')
return dat... | Args:f
data = takes preprocessed data frame
Returns:
data frame | pycaret/internal/preprocess.py | transform | pakallis/pycaret | 1 | python | def transform(self, dataset, y=None):
'\n Args:f\n data = takes preprocessed data frame\n Returns:\n data frame\n '
data = dataset
data = data.drop(self.to_drop, axis=1)
data.drop(self.to_drop_taret_correlation, axis=1, inplace=True, errors='ignore')
return dat... | def transform(self, dataset, y=None):
'\n Args:f\n data = takes preprocessed data frame\n Returns:\n data frame\n '
data = dataset
data = data.drop(self.to_drop, axis=1)
data.drop(self.to_drop_taret_correlation, axis=1, inplace=True, errors='ignore')
return dat... |
e1de8af371cbe4cb162544e14c4c472a6fd6f1e3b81f00b2dfb3ee8c10cbf1be | def fit_transform(self, data, y=None):
'\n Args:\n data = takes preprocessed data frame\n Returns:\n data frame\n '
self.fit(data)
return self.transform(data) | Args:
data = takes preprocessed data frame
Returns:
data frame | pycaret/internal/preprocess.py | fit_transform | pakallis/pycaret | 1 | python | def fit_transform(self, data, y=None):
'\n Args:\n data = takes preprocessed data frame\n Returns:\n data frame\n '
self.fit(data)
return self.transform(data) | def fit_transform(self, data, y=None):
'\n Args:\n data = takes preprocessed data frame\n Returns:\n data frame\n '
self.fit(data)
return self.transform(data)<|docstring|>Args:
data = takes preprocessed data frame
Returns:
data frame<|endoftext|> |
11e1c73683bc5ffb145db2943c36f0299aac2eee030c34e8cbfa60a2e7167ac5 | def _cleanup(self):
'Does a couple of cleanup tasks to ensure consistent data for later\n processing.'
if self.todolist.exists():
try:
with open(self.todolist, encoding='utf-8') as f:
saved_todo = iter(f)
int(next(saved_todo).strip())
fo... | Does a couple of cleanup tasks to ensure consistent data for later
processing. | src/bandersnatch/mirror.py | _cleanup | mosquito/bandersnatch | 0 | python | def _cleanup(self):
'Does a couple of cleanup tasks to ensure consistent data for later\n processing.'
if self.todolist.exists():
try:
with open(self.todolist, encoding='utf-8') as f:
saved_todo = iter(f)
int(next(saved_todo).strip())
fo... | def _cleanup(self):
'Does a couple of cleanup tasks to ensure consistent data for later\n processing.'
if self.todolist.exists():
try:
with open(self.todolist, encoding='utf-8') as f:
saved_todo = iter(f)
int(next(saved_todo).strip())
fo... |
648e12b2ea3edbf570a0b81248db0570c2874f7971df0ba817a3c50e99e3645c | def _filter_packages(self):
'\n Run the package filtering plugins and remove any packages from the\n packages_to_sync that match any filters.\n - Logging of action will be done within the check_match methods\n '
global LOG_PLUGINS
filter_plugins = filter_project_plugins()
if ... | Run the package filtering plugins and remove any packages from the
packages_to_sync that match any filters.
- Logging of action will be done within the check_match methods | src/bandersnatch/mirror.py | _filter_packages | mosquito/bandersnatch | 0 | python | def _filter_packages(self):
'\n Run the package filtering plugins and remove any packages from the\n packages_to_sync that match any filters.\n - Logging of action will be done within the check_match methods\n '
global LOG_PLUGINS
filter_plugins = filter_project_plugins()
if ... | def _filter_packages(self):
'\n Run the package filtering plugins and remove any packages from the\n packages_to_sync that match any filters.\n - Logging of action will be done within the check_match methods\n '
global LOG_PLUGINS
filter_plugins = filter_project_plugins()
if ... |
902e39b40feeade804c90e52812948198883b6f8f557be4cbee591fcd77b90b0 | async def determine_packages_to_sync(self):
'\n Update the self.packages_to_sync to contain packages that need to be\n synced.\n '
self.target_serial = self.synced_serial
self.packages_to_sync = {}
logger.info(f'Current mirror serial: {self.synced_serial}')
if self.todolist.exis... | Update the self.packages_to_sync to contain packages that need to be
synced. | src/bandersnatch/mirror.py | determine_packages_to_sync | mosquito/bandersnatch | 0 | python | async def determine_packages_to_sync(self):
'\n Update the self.packages_to_sync to contain packages that need to be\n synced.\n '
self.target_serial = self.synced_serial
self.packages_to_sync = {}
logger.info(f'Current mirror serial: {self.synced_serial}')
if self.todolist.exis... | async def determine_packages_to_sync(self):
'\n Update the self.packages_to_sync to contain packages that need to be\n synced.\n '
self.target_serial = self.synced_serial
self.packages_to_sync = {}
logger.info(f'Current mirror serial: {self.synced_serial}')
if self.todolist.exis... |
c8997103d377ed385355cb77554db47e2a4df952a468c70a25c2101e0471cfb1 | def get_simple_dirs(self, simple_dir: Path) -> List[Path]:
'Return a list of simple index directories that should be searched\n for package indexes when compiling the main index page.'
if self.hash_index:
subdirs = [(simple_dir / x) for x in simple_dir.iterdir() if x.is_dir()]
else:
s... | Return a list of simple index directories that should be searched
for package indexes when compiling the main index page. | src/bandersnatch/mirror.py | get_simple_dirs | mosquito/bandersnatch | 0 | python | def get_simple_dirs(self, simple_dir: Path) -> List[Path]:
'Return a list of simple index directories that should be searched\n for package indexes when compiling the main index page.'
if self.hash_index:
subdirs = [(simple_dir / x) for x in simple_dir.iterdir() if x.is_dir()]
else:
s... | def get_simple_dirs(self, simple_dir: Path) -> List[Path]:
'Return a list of simple index directories that should be searched\n for package indexes when compiling the main index page.'
if self.hash_index:
subdirs = [(simple_dir / x) for x in simple_dir.iterdir() if x.is_dir()]
else:
s... |
40f7c334c0ff455600376fa663b77b5629c133f05cacf335bf872a7bbc78a4eb | def find_package_indexes_in_dir(self, simple_dir):
'Given a directory that contains simple packages indexes, return\n a sorted list of normalized package names. This presumes every\n directory within is a simple package index directory.'
packages = sorted({canonicalize_name(x) for x in os.listdir... | Given a directory that contains simple packages indexes, return
a sorted list of normalized package names. This presumes every
directory within is a simple package index directory. | src/bandersnatch/mirror.py | find_package_indexes_in_dir | mosquito/bandersnatch | 0 | python | def find_package_indexes_in_dir(self, simple_dir):
'Given a directory that contains simple packages indexes, return\n a sorted list of normalized package names. This presumes every\n directory within is a simple package index directory.'
packages = sorted({canonicalize_name(x) for x in os.listdir... | def find_package_indexes_in_dir(self, simple_dir):
'Given a directory that contains simple packages indexes, return\n a sorted list of normalized package names. This presumes every\n directory within is a simple package index directory.'
packages = sorted({canonicalize_name(x) for x in os.listdir... |
574177f7b9f382cb6deff57790cb19c85590d82022360f71904408921a52aa9f | def create_dataset(project_id, display_name):
'Create a dataset.'
from google.cloud import automl
client = automl.AutoMlClient()
project_location = f'projects/{project_id}/locations/us-central1'
metadata = automl.TextClassificationDatasetMetadata(classification_type=automl.ClassificationType.MULTICL... | Create a dataset. | samples/snippets/language_text_classification_create_dataset.py | create_dataset | renovate-bot/python-automl | 68 | python | def create_dataset(project_id, display_name):
from google.cloud import automl
client = automl.AutoMlClient()
project_location = f'projects/{project_id}/locations/us-central1'
metadata = automl.TextClassificationDatasetMetadata(classification_type=automl.ClassificationType.MULTICLASS)
dataset = ... | def create_dataset(project_id, display_name):
from google.cloud import automl
client = automl.AutoMlClient()
project_location = f'projects/{project_id}/locations/us-central1'
metadata = automl.TextClassificationDatasetMetadata(classification_type=automl.ClassificationType.MULTICLASS)
dataset = ... |
509d246ae65ba362ef7442d77ecfffba9a294d957f3f15ae7dba32528fa2e870 | def __init__(self, parser_actions, options):
'Initialize.'
self.parser_actions = parser_actions
self.options = options | Initialize. | buildscripts/resmokelib/powercycle/__init__.py | __init__ | benety/mongo | 0 | python | def __init__(self, parser_actions, options):
self.parser_actions = parser_actions
self.options = options | def __init__(self, parser_actions, options):
self.parser_actions = parser_actions
self.options = options<|docstring|>Initialize.<|endoftext|> |
84e2d34edd7ae6ad851e7be265412f9e712363cbac9283559ae3df5a9ec75a44 | def execute(self):
'Execute powercycle test.'
return {self.RUN: self._exec_powercycle_main, self.HOST_SETUP: self._exec_powercycle_host_setup, self.SAVE_DIAG: self._exec_powercycle_save_diagnostics, self.REMOTE_HANG_ANALYZER: self._exec_powercycle_hang_analyzer}[self.options.run_option]() | Execute powercycle test. | buildscripts/resmokelib/powercycle/__init__.py | execute | benety/mongo | 0 | python | def execute(self):
return {self.RUN: self._exec_powercycle_main, self.HOST_SETUP: self._exec_powercycle_host_setup, self.SAVE_DIAG: self._exec_powercycle_save_diagnostics, self.REMOTE_HANG_ANALYZER: self._exec_powercycle_hang_analyzer}[self.options.run_option]() | def execute(self):
return {self.RUN: self._exec_powercycle_main, self.HOST_SETUP: self._exec_powercycle_host_setup, self.SAVE_DIAG: self._exec_powercycle_save_diagnostics, self.REMOTE_HANG_ANALYZER: self._exec_powercycle_hang_analyzer}[self.options.run_option]()<|docstring|>Execute powercycle test.<|endoftext|... |
78afe1ef901c0703287bf7f5d5d301aea933b39b1dad5f6d7e82eedc1fd3c28b | def __init__(self):
'Initialize.'
self.parser_actions = None | Initialize. | buildscripts/resmokelib/powercycle/__init__.py | __init__ | benety/mongo | 0 | python | def __init__(self):
self.parser_actions = None | def __init__(self):
self.parser_actions = None<|docstring|>Initialize.<|endoftext|> |
c92c69fe01ad099247e651f83baaed8f9022233303ac4530a58797031588bc74 | @staticmethod
def _add_powercycle_commands(parent_parser):
'Add sub-subcommands for powercycle.'
sub_parsers = parent_parser.add_subparsers()
setup_parser = sub_parsers.add_parser('setup-host', help='Step 1. Set up the host for powercycle')
setup_parser.set_defaults(run_option=Powercycle.HOST_SETUP)
... | Add sub-subcommands for powercycle. | buildscripts/resmokelib/powercycle/__init__.py | _add_powercycle_commands | benety/mongo | 0 | python | @staticmethod
def _add_powercycle_commands(parent_parser):
sub_parsers = parent_parser.add_subparsers()
setup_parser = sub_parsers.add_parser('setup-host', help='Step 1. Set up the host for powercycle')
setup_parser.set_defaults(run_option=Powercycle.HOST_SETUP)
run_parser = sub_parsers.add_parser(... | @staticmethod
def _add_powercycle_commands(parent_parser):
sub_parsers = parent_parser.add_subparsers()
setup_parser = sub_parsers.add_parser('setup-host', help='Step 1. Set up the host for powercycle')
setup_parser.set_defaults(run_option=Powercycle.HOST_SETUP)
run_parser = sub_parsers.add_parser(... |
e9351ae5cdd0bee44cbcdcbabd5c7da691a321e82705c470917215811e6908dc | def add_subcommand(self, subparsers):
'Create and add the parser for the subcommand.'
intermediate_parser = subparsers.add_parser(SUBCOMMAND, help=__doc__, usage='\nMongoDB Powercycle Tests. To run a powercycle test locally, use the following steps:\n\n1. Spin up an Evergreen spawnhost or virtual workstation th... | Create and add the parser for the subcommand. | buildscripts/resmokelib/powercycle/__init__.py | add_subcommand | benety/mongo | 0 | python | def add_subcommand(self, subparsers):
intermediate_parser = subparsers.add_parser(SUBCOMMAND, help=__doc__, usage='\nMongoDB Powercycle Tests. To run a powercycle test locally, use the following steps:\n\n1. Spin up an Evergreen spawnhost or virtual workstation that supports running\n Powercycle, e.g. by cre... | def add_subcommand(self, subparsers):
intermediate_parser = subparsers.add_parser(SUBCOMMAND, help=__doc__, usage='\nMongoDB Powercycle Tests. To run a powercycle test locally, use the following steps:\n\n1. Spin up an Evergreen spawnhost or virtual workstation that supports running\n Powercycle, e.g. by cre... |
a68f079b205104f8c038e464edf9be3e41e433ad0ea9dcf7bbe6655ad4281aa4 | def parse(self, subcommand, parser, parsed_args, **kwargs):
'Parse command-line options.'
if (subcommand == SUBCOMMAND):
return Powercycle(self.parser_actions, parsed_args)
return None | Parse command-line options. | buildscripts/resmokelib/powercycle/__init__.py | parse | benety/mongo | 0 | python | def parse(self, subcommand, parser, parsed_args, **kwargs):
if (subcommand == SUBCOMMAND):
return Powercycle(self.parser_actions, parsed_args)
return None | def parse(self, subcommand, parser, parsed_args, **kwargs):
if (subcommand == SUBCOMMAND):
return Powercycle(self.parser_actions, parsed_args)
return None<|docstring|>Parse command-line options.<|endoftext|> |
7b96d791577d699cedee44830b24566ae22af6432f039c190bf7aec20f667d2f | def generate_move_random(board: np.ndarray, player: BoardPiece, saved_state: Optional[SavedState]) -> Tuple[(PlayerAction, Optional[SavedState])]:
'\n Choose a valid, non-full column randomly and return it as `action`\n\n Arguments:\n board: ndarray representation of the board\n player: whether agent pl... | Choose a valid, non-full column randomly and return it as `action`
Arguments:
board: ndarray representation of the board
player: whether agent plays with X (Player1) or O (Player2)
saved_state: computation that it could reuse for future moves
Return:
Tuple[PlayerAction, SavedState]: returns the column, where the ... | agents/agents_random/random.py | generate_move_random | ConnectFourPythonProjekt/Connect4 | 0 | python | def generate_move_random(board: np.ndarray, player: BoardPiece, saved_state: Optional[SavedState]) -> Tuple[(PlayerAction, Optional[SavedState])]:
'\n Choose a valid, non-full column randomly and return it as `action`\n\n Arguments:\n board: ndarray representation of the board\n player: whether agent pl... | def generate_move_random(board: np.ndarray, player: BoardPiece, saved_state: Optional[SavedState]) -> Tuple[(PlayerAction, Optional[SavedState])]:
'\n Choose a valid, non-full column randomly and return it as `action`\n\n Arguments:\n board: ndarray representation of the board\n player: whether agent pl... |
b754c969ca2cba243ee6176edef8cad650dcfafb2627fac9299b8b9f67100d68 | def getCoordsFromFile(self, filename):
'breaks the tree file down into a list of coordinates\n '
pixels = [[], [], []]
with open(filename) as coordFile:
for line in coordFile.readlines():
line = line.replace('\n', '').replace(']', '').replace('[', '')
coords = line.spl... | breaks the tree file down into a list of coordinates | neopixel.py | getCoordsFromFile | NathanMalta/xmastree2020 | 2 | python | def getCoordsFromFile(self, filename):
'\n '
pixels = [[], [], []]
with open(filename) as coordFile:
for line in coordFile.readlines():
line = line.replace('\n', ).replace(']', ).replace('[', )
coords = line.split(', ')
pixels[0].append(int(coords[0]))
... | def getCoordsFromFile(self, filename):
'\n '
pixels = [[], [], []]
with open(filename) as coordFile:
for line in coordFile.readlines():
line = line.replace('\n', ).replace(']', ).replace('[', )
coords = line.split(', ')
pixels[0].append(int(coords[0]))
... |
df618d858e0bb45f89bd7a40dceedad009a5574881c7942554f3649870e19a99 | def __setitem__(self, pixelNum, color):
'enables the syntax neopixel[pixelNum] = color\n '
self.pixelColors[pixelNum] = [((2 * color[1]) / 255.0), ((2 * color[0]) / 255.0), ((2 * color[2]) / 255)] | enables the syntax neopixel[pixelNum] = color | neopixel.py | __setitem__ | NathanMalta/xmastree2020 | 2 | python | def __setitem__(self, pixelNum, color):
'\n '
self.pixelColors[pixelNum] = [((2 * color[1]) / 255.0), ((2 * color[0]) / 255.0), ((2 * color[2]) / 255)] | def __setitem__(self, pixelNum, color):
'\n '
self.pixelColors[pixelNum] = [((2 * color[1]) / 255.0), ((2 * color[0]) / 255.0), ((2 * color[2]) / 255)]<|docstring|>enables the syntax neopixel[pixelNum] = color<|endoftext|> |
c23c7ef612609835eb514354493361cdf58815b766cf04f6f5abeae5201303dc | def show(self):
'updates the tree animation when neopixel.show() is called\n '
self.scatter.remove()
self.scatter = self.ax.scatter(self.pixelLocations[0], self.pixelLocations[1], self.pixelLocations[2], c=self.pixelColors)
plt.draw()
plt.pause(0.02)
self.ax.cla()
self.ax.set_xlim((- ... | updates the tree animation when neopixel.show() is called | neopixel.py | show | NathanMalta/xmastree2020 | 2 | python | def show(self):
'\n '
self.scatter.remove()
self.scatter = self.ax.scatter(self.pixelLocations[0], self.pixelLocations[1], self.pixelLocations[2], c=self.pixelColors)
plt.draw()
plt.pause(0.02)
self.ax.cla()
self.ax.set_xlim((- 460), 460)
self.ax.set_ylim((- 460), 460)
self.ax... | def show(self):
'\n '
self.scatter.remove()
self.scatter = self.ax.scatter(self.pixelLocations[0], self.pixelLocations[1], self.pixelLocations[2], c=self.pixelColors)
plt.draw()
plt.pause(0.02)
self.ax.cla()
self.ax.set_xlim((- 460), 460)
self.ax.set_ylim((- 460), 460)
self.ax... |
8dd50859b58a00b90e130f61da97f4f9a29e25d0c045fd38f1de67e2c3aa3a85 | def ca_generate():
'\n test_ca_geneerate uses ca_cert_generate to generate ca certificate \n in cert_dir directory\n '
SSLFactory.ca_cert_generate('/tmp/test/')
file_list = subprocess.run('ls -la /tmp/test/', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
files = file_list.stdout.d... | test_ca_geneerate uses ca_cert_generate to generate ca certificate
in cert_dir directory | Jumpscale/sal/ssl/tests/test_ssl.py | ca_generate | threefoldtech/JumpscaleX | 2 | python | def ca_generate():
'\n test_ca_geneerate uses ca_cert_generate to generate ca certificate \n in cert_dir directory\n '
SSLFactory.ca_cert_generate('/tmp/test/')
file_list = subprocess.run('ls -la /tmp/test/', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
files = file_list.stdout.d... | def ca_generate():
'\n test_ca_geneerate uses ca_cert_generate to generate ca certificate \n in cert_dir directory\n '
SSLFactory.ca_cert_generate('/tmp/test/')
file_list = subprocess.run('ls -la /tmp/test/', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
files = file_list.stdout.d... |
d31b51e4320da8f1c154994310018bf7a9e67133bc9cba7c0dbaadc6f4d650e4 | def verify():
'\n It reads the pathes of certificate and key files of an X509 certificate\n and verify if certificate matches private key\n '
output = SSLFactory.verify('/tmp/test/ca.crt', '/tmp/test/ca.key')
assert (output is True) | It reads the pathes of certificate and key files of an X509 certificate
and verify if certificate matches private key | Jumpscale/sal/ssl/tests/test_ssl.py | verify | threefoldtech/JumpscaleX | 2 | python | def verify():
'\n It reads the pathes of certificate and key files of an X509 certificate\n and verify if certificate matches private key\n '
output = SSLFactory.verify('/tmp/test/ca.crt', '/tmp/test/ca.key')
assert (output is True) | def verify():
'\n It reads the pathes of certificate and key files of an X509 certificate\n and verify if certificate matches private key\n '
output = SSLFactory.verify('/tmp/test/ca.crt', '/tmp/test/ca.key')
assert (output is True)<|docstring|>It reads the pathes of certificate and key files of an... |
cd96c06f8bd036d90e2d0cf89949fb45fb34720f69c4d18d93e100aa53588e65 | def certificate_signing_request_create():
'\n Creating CSR (Certificate Signing Request)\n this CSR normally passed to the CA (Certificate Authority) to create a signed certificate\n '
output = SSLFactory.certificate_signing_request_create('test')
assert ('BEGIN PRIVATE KEY' in str(output))
ass... | Creating CSR (Certificate Signing Request)
this CSR normally passed to the CA (Certificate Authority) to create a signed certificate | Jumpscale/sal/ssl/tests/test_ssl.py | certificate_signing_request_create | threefoldtech/JumpscaleX | 2 | python | def certificate_signing_request_create():
'\n Creating CSR (Certificate Signing Request)\n this CSR normally passed to the CA (Certificate Authority) to create a signed certificate\n '
output = SSLFactory.certificate_signing_request_create('test')
assert ('BEGIN PRIVATE KEY' in str(output))
ass... | def certificate_signing_request_create():
'\n Creating CSR (Certificate Signing Request)\n this CSR normally passed to the CA (Certificate Authority) to create a signed certificate\n '
output = SSLFactory.certificate_signing_request_create('test')
assert ('BEGIN PRIVATE KEY' in str(output))
ass... |
5acc9ec4733ff76f90cb6851085aacddc997a64698ce8e439ac7eb966411047e | def test_main(self=None):
' to run:\n kosmos \'j.sal.ssl._test(name="ssl")\'\n\n '
ca_generate()
verify()
certificate_signing_request_create() | to run:
kosmos 'j.sal.ssl._test(name="ssl")' | Jumpscale/sal/ssl/tests/test_ssl.py | test_main | threefoldtech/JumpscaleX | 2 | python | def test_main(self=None):
' to run:\n kosmos \'j.sal.ssl._test(name="ssl")\'\n\n '
ca_generate()
verify()
certificate_signing_request_create() | def test_main(self=None):
' to run:\n kosmos \'j.sal.ssl._test(name="ssl")\'\n\n '
ca_generate()
verify()
certificate_signing_request_create()<|docstring|>to run:
kosmos 'j.sal.ssl._test(name="ssl")'<|endoftext|> |
38e818f51ece112301f7dffff6b4f45b9481faaa8f12a13d054f78ba21c6c48f | def __init__(self, *args, **kwargs):
'Initializer for CircuitBreakerHelper.'
retries = (kwargs.get('maximum_failures', None) or CIRCUIT_BREAKER_RETRY)
timeout = (kwargs.get('timeout') or CIRCUIT_BREAKER_TIMEOUT)
self.circuit_breaker = CircuitBreaker(maximum_failures=retries, reset_timeout_seconds=timeou... | Initializer for CircuitBreakerHelper. | asyncio_requests/helpers/internal/circuit_breaker_helper.py | __init__ | gofynd/asyncio-requests | 1 | python | def __init__(self, *args, **kwargs):
retries = (kwargs.get('maximum_failures', None) or CIRCUIT_BREAKER_RETRY)
timeout = (kwargs.get('timeout') or CIRCUIT_BREAKER_TIMEOUT)
self.circuit_breaker = CircuitBreaker(maximum_failures=retries, reset_timeout_seconds=timeout)
retry_policy = kwargs.get('retry... | def __init__(self, *args, **kwargs):
retries = (kwargs.get('maximum_failures', None) or CIRCUIT_BREAKER_RETRY)
timeout = (kwargs.get('timeout') or CIRCUIT_BREAKER_TIMEOUT)
self.circuit_breaker = CircuitBreaker(maximum_failures=retries, reset_timeout_seconds=timeout)
retry_policy = kwargs.get('retry... |
fc871fca4de3327f8ddc005f47b00d2c95e81efb648dbd50bee1721c73465cff | @staticmethod
async def get_retry_policy(name: Optional[str], **kwargs: Any) -> Optional[RetryPolicy]:
'Get retry policy.'
allowed_retries = kwargs['allowed_retries']
retriable_exceptions: List[Callable] = kwargs.get('retriable_exceptions', None)
abortable_exceptions: List[Callable] = kwargs.get('aborta... | Get retry policy. | asyncio_requests/helpers/internal/circuit_breaker_helper.py | get_retry_policy | gofynd/asyncio-requests | 1 | python | @staticmethod
async def get_retry_policy(name: Optional[str], **kwargs: Any) -> Optional[RetryPolicy]:
allowed_retries = kwargs['allowed_retries']
retriable_exceptions: List[Callable] = kwargs.get('retriable_exceptions', None)
abortable_exceptions: List[Callable] = kwargs.get('abortable_exceptions', No... | @staticmethod
async def get_retry_policy(name: Optional[str], **kwargs: Any) -> Optional[RetryPolicy]:
allowed_retries = kwargs['allowed_retries']
retriable_exceptions: List[Callable] = kwargs.get('retriable_exceptions', None)
abortable_exceptions: List[Callable] = kwargs.get('abortable_exceptions', No... |
762722ff036130c36e8b85b7214e7dc96b00f4dc47af71240c96675c21a41c53 | def lookup_genes(alignment_group):
'Looks up Genes.\n\n\tReturns list of dictionaries with keys:\n\t\t* gene\n\t\t* num_variants\n\t'
materialized_view_manager = MeltedVariantMaterializedViewManager(alignment_group.reference_genome)
materialized_view_manager.create_if_not_exists_or_invalid()
select_clau... | Looks up Genes.
Returns list of dictionaries with keys:
* gene
* num_variants | genome_designer/variants/gene_query.py | lookup_genes | churchlab/millstone | 45 | python | def lookup_genes(alignment_group):
'Looks up Genes.\n\n\tReturns list of dictionaries with keys:\n\t\t* gene\n\t\t* num_variants\n\t'
materialized_view_manager = MeltedVariantMaterializedViewManager(alignment_group.reference_genome)
materialized_view_manager.create_if_not_exists_or_invalid()
select_clau... | def lookup_genes(alignment_group):
'Looks up Genes.\n\n\tReturns list of dictionaries with keys:\n\t\t* gene\n\t\t* num_variants\n\t'
materialized_view_manager = MeltedVariantMaterializedViewManager(alignment_group.reference_genome)
materialized_view_manager.create_if_not_exists_or_invalid()
select_clau... |
0e290f342a2e0c34f39b855e700c3d7811f006c5e86436f88bb0056f61cca50d | def usage(output: io.IOBase) -> None:
'Display the command line usage help screen.'
with open('etc/usage.md') as f:
for line in f.readlines():
output.write(line)
f.close() | Display the command line usage help screen. | app.py | usage | jasonhanks/k8v | 1 | python | def usage(output: io.IOBase) -> None:
with open('etc/usage.md') as f:
for line in f.readlines():
output.write(line)
f.close() | def usage(output: io.IOBase) -> None:
with open('etc/usage.md') as f:
for line in f.readlines():
output.write(line)
f.close()<|docstring|>Display the command line usage help screen.<|endoftext|> |
25145fe409619c3829f269e4265bef6d1612a00103e4ce9f4827c77cd85e2040 | def main(argv: list) -> None:
'Main execution to setup the Viewer.'
viewer: k8v.viewer.Viewer = k8v.viewer.Viewer()
try:
(opts, args) = getopt.getopt(argv, 'ARtvhc:e:f:i:n:o:r:s:', ['all-related', 'all-resources', 'colors', 'all-namespaces', 'exclude', 'file', 'help', 'include', 'namespace', 'output... | Main execution to setup the Viewer. | app.py | main | jasonhanks/k8v | 1 | python | def main(argv: list) -> None:
viewer: k8v.viewer.Viewer = k8v.viewer.Viewer()
try:
(opts, args) = getopt.getopt(argv, 'ARtvhc:e:f:i:n:o:r:s:', ['all-related', 'all-resources', 'colors', 'all-namespaces', 'exclude', 'file', 'help', 'include', 'namespace', 'output', 'resource', 'selector', 'verbose']... | def main(argv: list) -> None:
viewer: k8v.viewer.Viewer = k8v.viewer.Viewer()
try:
(opts, args) = getopt.getopt(argv, 'ARtvhc:e:f:i:n:o:r:s:', ['all-related', 'all-resources', 'colors', 'all-namespaces', 'exclude', 'file', 'help', 'include', 'namespace', 'output', 'resource', 'selector', 'verbose']... |
b404e90f9346f6e67a84a1e5f0e7a2b1f7bab33c158ef1b44032b336433b0db4 | def split_cfold(nsamples, k=5, seed=None):
'\n Function that returns indices for splitting data into random folds.\n\n Parameters\n ----------\n nsamples: int\n the number of samples in the dataset\n k: int, optional\n the number of folds\n seed: int, optional\n random seed to... | Function that returns indices for splitting data into random folds.
Parameters
----------
nsamples: int
the number of samples in the dataset
k: int, optional
the number of folds
seed: int, optional
random seed to provide to numpy
Returns
-------
cvinds: list
list of arrays of length k, each with appro... | uncoverml/validate.py | split_cfold | GeoscienceAustralia/uncoverml | 34 | python | def split_cfold(nsamples, k=5, seed=None):
'\n Function that returns indices for splitting data into random folds.\n\n Parameters\n ----------\n nsamples: int\n the number of samples in the dataset\n k: int, optional\n the number of folds\n seed: int, optional\n random seed to... | def split_cfold(nsamples, k=5, seed=None):
'\n Function that returns indices for splitting data into random folds.\n\n Parameters\n ----------\n nsamples: int\n the number of samples in the dataset\n k: int, optional\n the number of folds\n seed: int, optional\n random seed to... |
db0ccf619586c658f75e4c291b599c7dd9ac5fc63d6c2d70dd356c9065d7ba09 | def classification_validation_scores(ys, eys, pys):
' Calculates the validation scores for a regression prediction\n Given the test and training data, as well as the outputs from every model,\n this function calculates all of the applicable metrics in the following\n list, and returns a dictionary with the... | Calculates the validation scores for a regression prediction
Given the test and training data, as well as the outputs from every model,
this function calculates all of the applicable metrics in the following
list, and returns a dictionary with the following (possible) keys:
+ accuracy
+ log_loss
+ f1
Param... | uncoverml/validate.py | classification_validation_scores | GeoscienceAustralia/uncoverml | 34 | python | def classification_validation_scores(ys, eys, pys):
' Calculates the validation scores for a regression prediction\n Given the test and training data, as well as the outputs from every model,\n this function calculates all of the applicable metrics in the following\n list, and returns a dictionary with the... | def classification_validation_scores(ys, eys, pys):
' Calculates the validation scores for a regression prediction\n Given the test and training data, as well as the outputs from every model,\n this function calculates all of the applicable metrics in the following\n list, and returns a dictionary with the... |
3b37be65846c86c4c7790e427851994fdf956738ef50a65083cd06be5bf422c1 | def regression_validation_scores(y, ey, n_covariates, model):
' Calculates the validation scores for a regression prediction\n Given the test and training data, as well as the outputs from every model,\n this function calculates all of the applicable metrics in the following\n list, and returns a dictionar... | Calculates the validation scores for a regression prediction
Given the test and training data, as well as the outputs from every model,
this function calculates all of the applicable metrics in the following
list, and returns a dictionary with the following (possible) keys:
+ r2_score
+ expvar
+ smse
+ ... | uncoverml/validate.py | regression_validation_scores | GeoscienceAustralia/uncoverml | 34 | python | def regression_validation_scores(y, ey, n_covariates, model):
' Calculates the validation scores for a regression prediction\n Given the test and training data, as well as the outputs from every model,\n this function calculates all of the applicable metrics in the following\n list, and returns a dictionar... | def regression_validation_scores(y, ey, n_covariates, model):
' Calculates the validation scores for a regression prediction\n Given the test and training data, as well as the outputs from every model,\n this function calculates all of the applicable metrics in the following\n list, and returns a dictionar... |
fbba7927533f2a8cfed7f89b30e64acc2106afb75d4026a5cf16deccd2d4ceb2 | def local_rank_features(image_chunk_sets, transform_sets, targets, config):
' Ranks the importance of the features based on their performance.\n This function trains and cross-validates a model with each individual\n feature removed and then measures the performance of the model with that\n feature removed... | Ranks the importance of the features based on their performance.
This function trains and cross-validates a model with each individual
feature removed and then measures the performance of the model with that
feature removed. The most important feature is the one which; when removed,
causes the greatest degradation in t... | uncoverml/validate.py | local_rank_features | GeoscienceAustralia/uncoverml | 34 | python | def local_rank_features(image_chunk_sets, transform_sets, targets, config):
' Ranks the importance of the features based on their performance.\n This function trains and cross-validates a model with each individual\n feature removed and then measures the performance of the model with that\n feature removed... | def local_rank_features(image_chunk_sets, transform_sets, targets, config):
' Ranks the importance of the features based on their performance.\n This function trains and cross-validates a model with each individual\n feature removed and then measures the performance of the model with that\n feature removed... |
4c082bb9b68d98bf4f4e5151c4d2fa86789c1dd6a229559e721c76e5f771d6d7 | def local_crossval(x_all, targets_all, config):
' Performs K-fold cross validation to test the applicability of a model.\n Given a set of inputs and outputs, this function will evaluate the\n effectiveness of a model at predicting the targets, by splitting all of\n the known data. A model is trained on a s... | Performs K-fold cross validation to test the applicability of a model.
Given a set of inputs and outputs, this function will evaluate the
effectiveness of a model at predicting the targets, by splitting all of
the known data. A model is trained on a subset of the total data, and then
this model is used to predict all o... | uncoverml/validate.py | local_crossval | GeoscienceAustralia/uncoverml | 34 | python | def local_crossval(x_all, targets_all, config):
' Performs K-fold cross validation to test the applicability of a model.\n Given a set of inputs and outputs, this function will evaluate the\n effectiveness of a model at predicting the targets, by splitting all of\n the known data. A model is trained on a s... | def local_crossval(x_all, targets_all, config):
' Performs K-fold cross validation to test the applicability of a model.\n Given a set of inputs and outputs, this function will evaluate the\n effectiveness of a model at predicting the targets, by splitting all of\n the known data. A model is trained on a s... |
ef8788194e1466d93c1f3a77fd746cd886780eec25fb6265920b51dc2bb99d1e | def export_crossval(self, config):
"\n Exports a CSV file containing real target values and their\n corresponding predicted value generated as part of \n cross-validation. \n\n Also populates the 'prediction' column of the 'rawcovariates'\n CSV file. \n\n If enabled, the re... | Exports a CSV file containing real target values and their
corresponding predicted value generated as part of
cross-validation.
Also populates the 'prediction' column of the 'rawcovariates'
CSV file.
If enabled, the real vs predicted values will be plotted.
Parameters
----------
config: Config
Uncover-ml conf... | uncoverml/validate.py | export_crossval | GeoscienceAustralia/uncoverml | 34 | python | def export_crossval(self, config):
"\n Exports a CSV file containing real target values and their\n corresponding predicted value generated as part of \n cross-validation. \n\n Also populates the 'prediction' column of the 'rawcovariates'\n CSV file. \n\n If enabled, the re... | def export_crossval(self, config):
"\n Exports a CSV file containing real target values and their\n corresponding predicted value generated as part of \n cross-validation. \n\n Also populates the 'prediction' column of the 'rawcovariates'\n CSV file. \n\n If enabled, the re... |
49f9e454db80c532f1bd13e35a43b00ee27c5f98b5e300421e6ace223eac6266 | def parse_ascii(M):
'\n Parse an ASCII art grid into subplots commands.\n\n :param M: A list of strings, each string representing a row.\n :returns: A dict containing the width and height of the grid, and a description of the grid as a list of subplots. Each subplot is a tuple of ... | Parse an ASCII art grid into subplots commands.
:param M: A list of strings, each string representing a row.
:returns: A dict containing the width and height of the grid, and a description of the grid as a list of subplots. Each subplot is a tuple of ``((y_position, x_position), sym... | replot/grid/parser.py | parse_ascii | Phyks/replot | 0 | python | def parse_ascii(M):
'\n Parse an ASCII art grid into subplots commands.\n\n :param M: A list of strings, each string representing a row.\n :returns: A dict containing the width and height of the grid, and a description of the grid as a list of subplots. Each subplot is a tuple of ... | def parse_ascii(M):
'\n Parse an ASCII art grid into subplots commands.\n\n :param M: A list of strings, each string representing a row.\n :returns: A dict containing the width and height of the grid, and a description of the grid as a list of subplots. Each subplot is a tuple of ... |
aa3885113da5aac903c3bc602625a5024376ffb6e845fecef83bf91ec80eaa53 | def _check_rect(n_x, n_y, dx, dy, symbol, M):
'\n Check that for a rectangle defined by two of its sides, every element within it is the same.\n\n .. note:: This method is called once the main script has reached the limits of a rectangle.\n\n :param n_x: Starting position of the rec... | Check that for a rectangle defined by two of its sides, every element within it is the same.
.. note:: This method is called once the main script has reached the limits of a rectangle.
:param n_x: Starting position of the rectangle (top left corner abscissa).
:param n_y: Starting position of t... | replot/grid/parser.py | _check_rect | Phyks/replot | 0 | python | def _check_rect(n_x, n_y, dx, dy, symbol, M):
'\n Check that for a rectangle defined by two of its sides, every element within it is the same.\n\n .. note:: This method is called once the main script has reached the limits of a rectangle.\n\n :param n_x: Starting position of the rec... | def _check_rect(n_x, n_y, dx, dy, symbol, M):
'\n Check that for a rectangle defined by two of its sides, every element within it is the same.\n\n .. note:: This method is called once the main script has reached the limits of a rectangle.\n\n :param n_x: Starting position of the rec... |
3012eb2b25489f35c22b4173ef72b0d079cfd11f4026fc19b2afe6129d7244d5 | def _set_as_done(n_x, n_y, dx, dy, elements_done):
'\n Mark some elements as having been processed, to keep track of them.\n\n :param n_x: Starting position of the rectangle (top left corner abscissa).\n :param n_y: Starting position of the rectangle (top left corner ordonate).\n :param dx: Width of the... | Mark some elements as having been processed, to keep track of them.
:param n_x: Starting position of the rectangle (top left corner abscissa).
:param n_y: Starting position of the rectangle (top left corner ordonate).
:param dx: Width of the rectangle.
:param dy: Height of the rectangle.
:param elements_done: A matrix... | replot/grid/parser.py | _set_as_done | Phyks/replot | 0 | python | def _set_as_done(n_x, n_y, dx, dy, elements_done):
'\n Mark some elements as having been processed, to keep track of them.\n\n :param n_x: Starting position of the rectangle (top left corner abscissa).\n :param n_y: Starting position of the rectangle (top left corner ordonate).\n :param dx: Width of the... | def _set_as_done(n_x, n_y, dx, dy, elements_done):
'\n Mark some elements as having been processed, to keep track of them.\n\n :param n_x: Starting position of the rectangle (top left corner abscissa).\n :param n_y: Starting position of the rectangle (top left corner ordonate).\n :param dx: Width of the... |
fc807bf1d0a61c4834bd1a97a86ce8b59f4aaa85f7e524a313bf36d2e74d54de | def json_serial(obj):
'JSON serializer for objects not serializable by default json code'
if isinstance(obj, (datetime, date)):
return obj.isoformat()
if isinstance(obj, (np.int_, np.intc, np.intp, np.int8, np.int16, np.int32, np.int64, np.uint8)):
return int(obj)
if isinstance(obj, (np.... | JSON serializer for objects not serializable by default json code | pyfan/amto/json/json.py | json_serial | FanWangEcon/pyfan | 1 | python | def json_serial(obj):
if isinstance(obj, (datetime, date)):
return obj.isoformat()
if isinstance(obj, (np.int_, np.intc, np.intp, np.int8, np.int16, np.int32, np.int64, np.uint8)):
return int(obj)
if isinstance(obj, (np.float_, np.float32)):
return float(obj)
if isinstance(o... | def json_serial(obj):
if isinstance(obj, (datetime, date)):
return obj.isoformat()
if isinstance(obj, (np.int_, np.intc, np.intp, np.int8, np.int16, np.int32, np.int64, np.uint8)):
return int(obj)
if isinstance(obj, (np.float_, np.float32)):
return float(obj)
if isinstance(o... |
9ebb483881be585747bf6ff1a352e3dbed2df5aab64dfb03435cbc6e200978e5 | def plot_tsp(p, x_coord, W, W_val, W_target, title='default'):
'\n Helper function to plot TSP tours.\n \n Args:\n p: Matplotlib figure/subplot\n x_coord: Coordinates of nodes\n W: Edge adjacency matrix\n W_val: Edge values (distance) matrix\n W_target: One-hot matrix wit... | Helper function to plot TSP tours.
Args:
p: Matplotlib figure/subplot
x_coord: Coordinates of nodes
W: Edge adjacency matrix
W_val: Edge values (distance) matrix
W_target: One-hot matrix with 1s on groundtruth/predicted edges
title: Title of figure/subplot
Returns:
p: Updated figure/subplo... | utils/plot_utils.py | plot_tsp | ianmalcolm/graph-convnet-tsp | 196 | python | def plot_tsp(p, x_coord, W, W_val, W_target, title='default'):
'\n Helper function to plot TSP tours.\n \n Args:\n p: Matplotlib figure/subplot\n x_coord: Coordinates of nodes\n W: Edge adjacency matrix\n W_val: Edge values (distance) matrix\n W_target: One-hot matrix wit... | def plot_tsp(p, x_coord, W, W_val, W_target, title='default'):
'\n Helper function to plot TSP tours.\n \n Args:\n p: Matplotlib figure/subplot\n x_coord: Coordinates of nodes\n W: Edge adjacency matrix\n W_val: Edge values (distance) matrix\n W_target: One-hot matrix wit... |
4876c81ec1a1123ea2b4efd4ce9fa64aa0b5a8130450ac31c567d61a9f24bf8a | def plot_tsp_heatmap(p, x_coord, W_val, W_pred, title='default'):
'\n Helper function to plot predicted TSP tours with edge strength denoting confidence of prediction.\n \n Args:\n p: Matplotlib figure/subplot\n x_coord: Coordinates of nodes\n W_val: Edge values (distance) matrix\n ... | Helper function to plot predicted TSP tours with edge strength denoting confidence of prediction.
Args:
p: Matplotlib figure/subplot
x_coord: Coordinates of nodes
W_val: Edge values (distance) matrix
W_pred: Edge predictions matrix
title: Title of figure/subplot
Returns:
p: Updated figure/subp... | utils/plot_utils.py | plot_tsp_heatmap | ianmalcolm/graph-convnet-tsp | 196 | python | def plot_tsp_heatmap(p, x_coord, W_val, W_pred, title='default'):
'\n Helper function to plot predicted TSP tours with edge strength denoting confidence of prediction.\n \n Args:\n p: Matplotlib figure/subplot\n x_coord: Coordinates of nodes\n W_val: Edge values (distance) matrix\n ... | def plot_tsp_heatmap(p, x_coord, W_val, W_pred, title='default'):
'\n Helper function to plot predicted TSP tours with edge strength denoting confidence of prediction.\n \n Args:\n p: Matplotlib figure/subplot\n x_coord: Coordinates of nodes\n W_val: Edge values (distance) matrix\n ... |
a9d5053182b121e8186f796779396d179357b378c72787b2a147498d2df726dd | def plot_predictions(x_nodes_coord, x_edges, x_edges_values, y_edges, y_pred_edges, num_plots=3):
'\n Plots groundtruth TSP tour vs. predicted tours (without beamsearch).\n \n Args:\n x_nodes_coord: Input node coordinates (batch_size, num_nodes, node_dim)\n x_edges: Input edge adjacency matri... | Plots groundtruth TSP tour vs. predicted tours (without beamsearch).
Args:
x_nodes_coord: Input node coordinates (batch_size, num_nodes, node_dim)
x_edges: Input edge adjacency matrix (batch_size, num_nodes, num_nodes)
x_edges_values: Input edge distance matrix (batch_size, num_nodes, num_nodes)
y_edge... | utils/plot_utils.py | plot_predictions | ianmalcolm/graph-convnet-tsp | 196 | python | def plot_predictions(x_nodes_coord, x_edges, x_edges_values, y_edges, y_pred_edges, num_plots=3):
'\n Plots groundtruth TSP tour vs. predicted tours (without beamsearch).\n \n Args:\n x_nodes_coord: Input node coordinates (batch_size, num_nodes, node_dim)\n x_edges: Input edge adjacency matri... | def plot_predictions(x_nodes_coord, x_edges, x_edges_values, y_edges, y_pred_edges, num_plots=3):
'\n Plots groundtruth TSP tour vs. predicted tours (without beamsearch).\n \n Args:\n x_nodes_coord: Input node coordinates (batch_size, num_nodes, node_dim)\n x_edges: Input edge adjacency matri... |
6e036a2eb83aa763cb8bcf77309226964cd70a631511bf59389bee45e3f4ca24 | def plot_predictions_beamsearch(x_nodes_coord, x_edges, x_edges_values, y_edges, y_pred_edges, bs_nodes, num_plots=3):
'\n Plots groundtruth TSP tour vs. predicted tours (with beamsearch).\n \n Args:\n x_nodes_coord: Input node coordinates (batch_size, num_nodes, node_dim)\n x_edges: Input ed... | Plots groundtruth TSP tour vs. predicted tours (with beamsearch).
Args:
x_nodes_coord: Input node coordinates (batch_size, num_nodes, node_dim)
x_edges: Input edge adjacency matrix (batch_size, num_nodes, num_nodes)
x_edges_values: Input edge distance matrix (batch_size, num_nodes, num_nodes)
y_edges: ... | utils/plot_utils.py | plot_predictions_beamsearch | ianmalcolm/graph-convnet-tsp | 196 | python | def plot_predictions_beamsearch(x_nodes_coord, x_edges, x_edges_values, y_edges, y_pred_edges, bs_nodes, num_plots=3):
'\n Plots groundtruth TSP tour vs. predicted tours (with beamsearch).\n \n Args:\n x_nodes_coord: Input node coordinates (batch_size, num_nodes, node_dim)\n x_edges: Input ed... | def plot_predictions_beamsearch(x_nodes_coord, x_edges, x_edges_values, y_edges, y_pred_edges, bs_nodes, num_plots=3):
'\n Plots groundtruth TSP tour vs. predicted tours (with beamsearch).\n \n Args:\n x_nodes_coord: Input node coordinates (batch_size, num_nodes, node_dim)\n x_edges: Input ed... |
3f31d42051e8be118d61111d2357cc01505abed8ab86fadd0ac25cb599d269da | def _edges_to_node_pairs(W):
'Helper function to convert edge matrix into pairs of adjacent nodes.\n '
pairs = []
for r in range(len(W)):
for c in range(len(W)):
if (W[r][c] == 1):
pairs.append((r, c))
return pairs | Helper function to convert edge matrix into pairs of adjacent nodes. | utils/plot_utils.py | _edges_to_node_pairs | ianmalcolm/graph-convnet-tsp | 196 | python | def _edges_to_node_pairs(W):
'\n '
pairs = []
for r in range(len(W)):
for c in range(len(W)):
if (W[r][c] == 1):
pairs.append((r, c))
return pairs | def _edges_to_node_pairs(W):
'\n '
pairs = []
for r in range(len(W)):
for c in range(len(W)):
if (W[r][c] == 1):
pairs.append((r, c))
return pairs<|docstring|>Helper function to convert edge matrix into pairs of adjacent nodes.<|endoftext|> |
b990a4d264324ec7414a4937c32d863f5985e7f1dbdf33fd1b4c0daf645df9eb | def _edges_to_node_pairs(W):
'Helper function to convert edge matrix into pairs of adjacent nodes.\n '
pairs = []
edge_preds = []
for r in range(len(W)):
for c in range(len(W)):
if (W[r][c] > 0.25):
pairs.append((r, c))
edge_preds.append(W[r][c]... | Helper function to convert edge matrix into pairs of adjacent nodes. | utils/plot_utils.py | _edges_to_node_pairs | ianmalcolm/graph-convnet-tsp | 196 | python | def _edges_to_node_pairs(W):
'\n '
pairs = []
edge_preds = []
for r in range(len(W)):
for c in range(len(W)):
if (W[r][c] > 0.25):
pairs.append((r, c))
edge_preds.append(W[r][c])
return (pairs, edge_preds) | def _edges_to_node_pairs(W):
'\n '
pairs = []
edge_preds = []
for r in range(len(W)):
for c in range(len(W)):
if (W[r][c] > 0.25):
pairs.append((r, c))
edge_preds.append(W[r][c])
return (pairs, edge_preds)<|docstring|>Helper function to conv... |
4eabbb3a4e0de8036d87b56f434e31fb1df927af4ab6072529da374f30444df0 | def create_mini_batches(inputs, targets, data, batch_size, shuffle=False):
' Create an mini-batch like iterator for the given inputs / target / data. Shamelessly copied from https://stackoverflow.com/questions/38157972/how-to-implement-mini-batch-gradient-descent-in-python\n \n Parameters\n ----------\n ... | Create an mini-batch like iterator for the given inputs / target / data. Shamelessly copied from https://stackoverflow.com/questions/38157972/how-to-implement-mini-batch-gradient-descent-in-python
Parameters
----------
inputs : array-like vector or matrix
The inputs to be iterated in mini batches
targets : array-... | PyPruning/NCPruningClassifier.py | create_mini_batches | sbuschjaeger/PyPruning | 7 | python | def create_mini_batches(inputs, targets, data, batch_size, shuffle=False):
' Create an mini-batch like iterator for the given inputs / target / data. Shamelessly copied from https://stackoverflow.com/questions/38157972/how-to-implement-mini-batch-gradient-descent-in-python\n \n Parameters\n ----------\n ... | def create_mini_batches(inputs, targets, data, batch_size, shuffle=False):
' Create an mini-batch like iterator for the given inputs / target / data. Shamelessly copied from https://stackoverflow.com/questions/38157972/how-to-implement-mini-batch-gradient-descent-in-python\n \n Parameters\n ----------\n ... |
270fe21b13e5c305bd3c4bad8521ff3aff85fe7d12669529bfb8ad051f6e2825 | def to_prob_simplex(x):
' Projects the given vector to the probability simplex so that :math:`\\sum_{i=1}^k x_i = 1, x_i \\in [0,1]`. \n\n Reference\n Weiran Wang and Miguel A. Carreira-Perpinan (2013) Projection onto the probability simplex: An efficient algorithm with a simple proof, and an application.... | Projects the given vector to the probability simplex so that :math:`\sum_{i=1}^k x_i = 1, x_i \in [0,1]`.
Reference
Weiran Wang and Miguel A. Carreira-Perpinan (2013) Projection onto the probability simplex: An efficient algorithm with a simple proof, and an application. https://eng.ucmerced.edu/people/wwang5/pap... | PyPruning/NCPruningClassifier.py | to_prob_simplex | sbuschjaeger/PyPruning | 7 | python | def to_prob_simplex(x):
' Projects the given vector to the probability simplex so that :math:`\\sum_{i=1}^k x_i = 1, x_i \\in [0,1]`. \n\n Reference\n Weiran Wang and Miguel A. Carreira-Perpinan (2013) Projection onto the probability simplex: An efficient algorithm with a simple proof, and an application.... | def to_prob_simplex(x):
' Projects the given vector to the probability simplex so that :math:`\\sum_{i=1}^k x_i = 1, x_i \\in [0,1]`. \n\n Reference\n Weiran Wang and Miguel A. Carreira-Perpinan (2013) Projection onto the probability simplex: An efficient algorithm with a simple proof, and an application.... |
7a379762fd6f483b0e8f2e39a1f8dd1e5ecca76403661e8cec63e2fe8fb086ff | def node_regularizer(est):
' Extract the number of nodes in the given tree \n\n Parameters\n ----------\n X : numpy matrix\n A (N, d) matrix with the datapoints used for pruning where N is the number of data points and d is the dimensionality\n \n Y : numpy array / list of ints\n A nump... | Extract the number of nodes in the given tree
Parameters
----------
X : numpy matrix
A (N, d) matrix with the datapoints used for pruning where N is the number of data points and d is the dimensionality
Y : numpy array / list of ints
A numpy array or list of N integers where each integer represents the class... | PyPruning/NCPruningClassifier.py | node_regularizer | sbuschjaeger/PyPruning | 7 | python | def node_regularizer(est):
' Extract the number of nodes in the given tree \n\n Parameters\n ----------\n X : numpy matrix\n A (N, d) matrix with the datapoints used for pruning where N is the number of data points and d is the dimensionality\n \n Y : numpy array / list of ints\n A nump... | def node_regularizer(est):
' Extract the number of nodes in the given tree \n\n Parameters\n ----------\n X : numpy matrix\n A (N, d) matrix with the datapoints used for pruning where N is the number of data points and d is the dimensionality\n \n Y : numpy array / list of ints\n A nump... |
94b5e5b93de8c058598a13ac6c95e8b0633493b23b9649da3e56c4bc837df924 | def avg_path_len_regularizer(est):
' Extract the number of nodes in the given tree \n\n Parameters\n ----------\n X : numpy matrix\n A (N, d) matrix with the datapoints used for pruning where N is the number of data points and d is the dimensionality\n \n Y : numpy array / list of ints\n ... | Extract the number of nodes in the given tree
Parameters
----------
X : numpy matrix
A (N, d) matrix with the datapoints used for pruning where N is the number of data points and d is the dimensionality
Y : numpy array / list of ints
A numpy array or list of N integers where each integer represents the class... | PyPruning/NCPruningClassifier.py | avg_path_len_regularizer | sbuschjaeger/PyPruning | 7 | python | def avg_path_len_regularizer(est):
' Extract the number of nodes in the given tree \n\n Parameters\n ----------\n X : numpy matrix\n A (N, d) matrix with the datapoints used for pruning where N is the number of data points and d is the dimensionality\n \n Y : numpy array / list of ints\n ... | def avg_path_len_regularizer(est):
' Extract the number of nodes in the given tree \n\n Parameters\n ----------\n X : numpy matrix\n A (N, d) matrix with the datapoints used for pruning where N is the number of data points and d is the dimensionality\n \n Y : numpy array / list of ints\n ... |
23f9e684ea0aca14bdbcce9053f6b1b05e6daf6ea3b11bc8e6b503bf4a5577af | def num_trees(self):
' Returns the number of nonzero weights '
return np.count_nonzero(self.weights_) | Returns the number of nonzero weights | PyPruning/NCPruningClassifier.py | num_trees | sbuschjaeger/PyPruning | 7 | python | def num_trees(self):
' '
return np.count_nonzero(self.weights_) | def num_trees(self):
' '
return np.count_nonzero(self.weights_)<|docstring|>Returns the number of nonzero weights<|endoftext|> |
e8c32d8bf2bd592faeb1448257b236c345563f15e51ff905cc309d7fc18043cc | def num_parameters(self):
' Returns the total number of decision nodes across all trees of the entire ensemble for all trees with nonzero weight. '
return sum([(est.tree_.node_count if (w != 0) else 0) for (w, est) in zip(self.weights_, self.estimators_)]) | Returns the total number of decision nodes across all trees of the entire ensemble for all trees with nonzero weight. | PyPruning/NCPruningClassifier.py | num_parameters | sbuschjaeger/PyPruning | 7 | python | def num_parameters(self):
' '
return sum([(est.tree_.node_count if (w != 0) else 0) for (w, est) in zip(self.weights_, self.estimators_)]) | def num_parameters(self):
' '
return sum([(est.tree_.node_count if (w != 0) else 0) for (w, est) in zip(self.weights_, self.estimators_)])<|docstring|>Returns the total number of decision nodes across all trees of the entire ensemble for all trees with nonzero weight.<|endoftext|> |
f4f5dbc77ef2f9b2ff98f8dd044d442fa6be6675afa1cc3f66ca0814a1799312 | def __init__(self, http_port: int=80, https_port: int=443, ct_name: str='proxy_stakkr', version: str='latest'):
'Set the right values to start the proxy.'
self.ports = {'http': http_port, 'https': https_port}
self.ct_name = ct_name
self.docker_client = docker.get_client()
self.version = version | Set the right values to start the proxy. | stakkr/proxy.py | __init__ | Lissandre/stakkr | 0 | python | def __init__(self, http_port: int=80, https_port: int=443, ct_name: str='proxy_stakkr', version: str='latest'):
self.ports = {'http': http_port, 'https': https_port}
self.ct_name = ct_name
self.docker_client = docker.get_client()
self.version = version | def __init__(self, http_port: int=80, https_port: int=443, ct_name: str='proxy_stakkr', version: str='latest'):
self.ports = {'http': http_port, 'https': https_port}
self.ct_name = ct_name
self.docker_client = docker.get_client()
self.version = version<|docstring|>Set the right values to start the ... |
5e2f6c321362ef55c146f49520bb1eb45714d20b8f35d489bded30c78793cf70 | def start(self, stakkr_network: str=None):
'Start stakkr proxy if stopped.'
if (docker.container_running(self.ct_name) is False):
print((click.style('[STARTING]', fg='green') + ' traefik'))
self._start_container()
if (stakkr_network is not None):
docker.add_container_to_network(self.... | Start stakkr proxy if stopped. | stakkr/proxy.py | start | Lissandre/stakkr | 0 | python | def start(self, stakkr_network: str=None):
if (docker.container_running(self.ct_name) is False):
print((click.style('[STARTING]', fg='green') + ' traefik'))
self._start_container()
if (stakkr_network is not None):
docker.add_container_to_network(self.ct_name, stakkr_network) | def start(self, stakkr_network: str=None):
if (docker.container_running(self.ct_name) is False):
print((click.style('[STARTING]', fg='green') + ' traefik'))
self._start_container()
if (stakkr_network is not None):
docker.add_container_to_network(self.ct_name, stakkr_network)<|docstr... |
96a5919989e02feda3ab30cdb3d5b69629a719b9e17e0d00db3e22eea75462e3 | def stop(self):
'Stop stakkr proxy.'
if (docker.container_running(self.ct_name) is False):
return
print((click.style('[STOPPING]', fg='green') + ' traefik'))
proxy_ct = self.docker_client.containers.get(self.ct_name)
proxy_ct.stop() | Stop stakkr proxy. | stakkr/proxy.py | stop | Lissandre/stakkr | 0 | python | def stop(self):
if (docker.container_running(self.ct_name) is False):
return
print((click.style('[STOPPING]', fg='green') + ' traefik'))
proxy_ct = self.docker_client.containers.get(self.ct_name)
proxy_ct.stop() | def stop(self):
if (docker.container_running(self.ct_name) is False):
return
print((click.style('[STOPPING]', fg='green') + ' traefik'))
proxy_ct = self.docker_client.containers.get(self.ct_name)
proxy_ct.stop()<|docstring|>Stop stakkr proxy.<|endoftext|> |
cdc38ff436bd00aeba51fca94a1bef5d60641759951ccc4d571b6f03cfa81c3c | def _start_container(self):
'Start proxy.'
proxy_conf_dir = get_dir('static/proxy')
try:
self.docker_client.images.pull('traefik:{}'.format(self.version))
self.docker_client.containers.run('traefik:{}'.format(self.version), remove=True, detach=True, hostname=self.ct_name, name=self.ct_name, ... | Start proxy. | stakkr/proxy.py | _start_container | Lissandre/stakkr | 0 | python | def _start_container(self):
proxy_conf_dir = get_dir('static/proxy')
try:
self.docker_client.images.pull('traefik:{}'.format(self.version))
self.docker_client.containers.run('traefik:{}'.format(self.version), remove=True, detach=True, hostname=self.ct_name, name=self.ct_name, volumes=['/var... | def _start_container(self):
proxy_conf_dir = get_dir('static/proxy')
try:
self.docker_client.images.pull('traefik:{}'.format(self.version))
self.docker_client.containers.run('traefik:{}'.format(self.version), remove=True, detach=True, hostname=self.ct_name, name=self.ct_name, volumes=['/var... |
a9aa8cb3bd3093ed95cf3a37d141242529ace793d2b40d56141df7a3e7dbaef8 | def dataset_constructor(config: ml_collections.ConfigDict) -> Tuple[(torch.utils.data.Dataset, torch.utils.data.Dataset, torch.utils.data.Dataset)]:
'\n Create datasets loaders for the chosen datasets\n :return: Tuple (training_set, validation_set, test_set)\n '
dataset = {'AddProblem': AdditionProblem... | Create datasets loaders for the chosen datasets
:return: Tuple (training_set, validation_set, test_set) | dataset.py | dataset_constructor | dwromero/ckconv | 74 | python | def dataset_constructor(config: ml_collections.ConfigDict) -> Tuple[(torch.utils.data.Dataset, torch.utils.data.Dataset, torch.utils.data.Dataset)]:
'\n Create datasets loaders for the chosen datasets\n :return: Tuple (training_set, validation_set, test_set)\n '
dataset = {'AddProblem': AdditionProblem... | def dataset_constructor(config: ml_collections.ConfigDict) -> Tuple[(torch.utils.data.Dataset, torch.utils.data.Dataset, torch.utils.data.Dataset)]:
'\n Create datasets loaders for the chosen datasets\n :return: Tuple (training_set, validation_set, test_set)\n '
dataset = {'AddProblem': AdditionProblem... |
a9bc60467bb246001ef4eea629742fc7cea92bd958344b445234e99edb2bf3de | def get_dataset(config: ml_collections.ConfigDict, num_workers: int=4, data_root='./data') -> Tuple[(dict, torch.utils.data.DataLoader)]:
'\n Create datasets loaders for the chosen datasets\n :return: Tuple ( dict(train_loader, val_loader) , test_loader)\n '
(training_set, validation_set, test_set) = d... | Create datasets loaders for the chosen datasets
:return: Tuple ( dict(train_loader, val_loader) , test_loader) | dataset.py | get_dataset | dwromero/ckconv | 74 | python | def get_dataset(config: ml_collections.ConfigDict, num_workers: int=4, data_root='./data') -> Tuple[(dict, torch.utils.data.DataLoader)]:
'\n Create datasets loaders for the chosen datasets\n :return: Tuple ( dict(train_loader, val_loader) , test_loader)\n '
(training_set, validation_set, test_set) = d... | def get_dataset(config: ml_collections.ConfigDict, num_workers: int=4, data_root='./data') -> Tuple[(dict, torch.utils.data.DataLoader)]:
'\n Create datasets loaders for the chosen datasets\n :return: Tuple ( dict(train_loader, val_loader) , test_loader)\n '
(training_set, validation_set, test_set) = d... |
24470377c989fdeb437b59f7e1093d0ba3627d1c3a3c95514d034ec99885af4f | def list(self, path, full=False, missing=False, max_depth=1, from_root=False):
'\n List files available from a remote repository for a local path\n\n :type path: str\n :param path: Local path\n\n :type missing: bool\n :param missing: Only list files missing from the local path\n\n... | List files available from a remote repository for a local path
:type path: str
:param path: Local path
:type missing: bool
:param missing: Only list files missing from the local path
:type full: bool
:param full: List full information for each file (size (in bytes), mtime, etc..)
:type max_depth: int
:param max_dep... | baricadr/file/__init__.py | list | mboudet/barique | 0 | python | def list(self, path, full=False, missing=False, max_depth=1, from_root=False):
'\n List files available from a remote repository for a local path\n\n :type path: str\n :param path: Local path\n\n :type missing: bool\n :param missing: Only list files missing from the local path\n\n... | def list(self, path, full=False, missing=False, max_depth=1, from_root=False):
'\n List files available from a remote repository for a local path\n\n :type path: str\n :param path: Local path\n\n :type missing: bool\n :param missing: Only list files missing from the local path\n\n... |
3f7decc75901e4a6eba15663186ef2a04fe4ee02c82f831e43e86501835c6b0c | def pull(self, path, email='', dry_run=False):
'\n Launch a pull task\n\n :type path: str\n :param path: Local path to a missing file or folder\n\n :type email: str\n :param email: User email adress for notification\n\n :type dry_run: bool\n :param dry_run: Do not ma... | Launch a pull task
:type path: str
:param path: Local path to a missing file or folder
:type email: str
:param email: User email adress for notification
:type dry_run: bool
:param dry_run: Do not make any pull, just list changes that would be made
:rtype: str
:return: Id associated to the pull task | baricadr/file/__init__.py | pull | mboudet/barique | 0 | python | def pull(self, path, email=, dry_run=False):
'\n Launch a pull task\n\n :type path: str\n :param path: Local path to a missing file or folder\n\n :type email: str\n :param email: User email adress for notification\n\n :type dry_run: bool\n :param dry_run: Do not make... | def pull(self, path, email=, dry_run=False):
'\n Launch a pull task\n\n :type path: str\n :param path: Local path to a missing file or folder\n\n :type email: str\n :param email: User email adress for notification\n\n :type dry_run: bool\n :param dry_run: Do not make... |
5f8056d7a7fc8c3a9245e201314cce22f29d01d639abfd3fbaa3faa0a5920bde | def freeze(self, path, force=False, dry_run=False, email=''):
'\n Launch a freeze task\n\n :type path: str\n :param path: Local path to a file or folder to freeze\n\n :type force: bool\n :param force: Force freezing, even if the freezing delay was not reached\n\n :type dry_... | Launch a freeze task
:type path: str
:param path: Local path to a file or folder to freeze
:type force: bool
:param force: Force freezing, even if the freezing delay was not reached
:type dry_run: bool
:param dry_run: Do not make any deletion, just list changes that would be made
:type email: str
:param email: User... | baricadr/file/__init__.py | freeze | mboudet/barique | 0 | python | def freeze(self, path, force=False, dry_run=False, email=):
'\n Launch a freeze task\n\n :type path: str\n :param path: Local path to a file or folder to freeze\n\n :type force: bool\n :param force: Force freezing, even if the freezing delay was not reached\n\n :type dry_ru... | def freeze(self, path, force=False, dry_run=False, email=):
'\n Launch a freeze task\n\n :type path: str\n :param path: Local path to a file or folder to freeze\n\n :type force: bool\n :param force: Force freezing, even if the freezing delay was not reached\n\n :type dry_ru... |
8c34b3e5cc9aa03d7c4ce87ef7696dfa11d1b84343d569717909d8fb007daa1e | def tree(self, path, max_depth=1):
'\n List files available from a remote repository for a local path as a tree\n\n :type path: str\n :param path: Local path\n\n :type max_depth: int\n :param max_depth: Restrict to a max depth. Set to 0 for all files.\n\n :rtype: None\n ... | List files available from a remote repository for a local path as a tree
:type path: str
:param path: Local path
:type max_depth: int
:param max_depth: Restrict to a max depth. Set to 0 for all files.
:rtype: None
:return: None | baricadr/file/__init__.py | tree | mboudet/barique | 0 | python | def tree(self, path, max_depth=1):
'\n List files available from a remote repository for a local path as a tree\n\n :type path: str\n :param path: Local path\n\n :type max_depth: int\n :param max_depth: Restrict to a max depth. Set to 0 for all files.\n\n :rtype: None\n ... | def tree(self, path, max_depth=1):
'\n List files available from a remote repository for a local path as a tree\n\n :type path: str\n :param path: Local path\n\n :type max_depth: int\n :param max_depth: Restrict to a max depth. Set to 0 for all files.\n\n :rtype: None\n ... |
c896126c8f7d3a2cb5a2dbaca0e79336241f38e03d6dcb410804671df4cea459 | def test_board_shape(self):
'Test board shape validation.'
board = np.zeros([1, 1])
self.assertRaises(TypeError, validate_board, board)
board = np.zeros([0, 0])
self.assertRaises(TypeError, validate_board, board)
board = np.zeros([2, 0])
self.assertRaises(TypeError, validate_board, board)
... | Test board shape validation. | game_of_pyfe/tests/test_utils.py | test_board_shape | jglezt/game-of-pyfe | 0 | python | def test_board_shape(self):
board = np.zeros([1, 1])
self.assertRaises(TypeError, validate_board, board)
board = np.zeros([0, 0])
self.assertRaises(TypeError, validate_board, board)
board = np.zeros([2, 0])
self.assertRaises(TypeError, validate_board, board)
board = np.zeros([0, 2])
... | def test_board_shape(self):
board = np.zeros([1, 1])
self.assertRaises(TypeError, validate_board, board)
board = np.zeros([0, 0])
self.assertRaises(TypeError, validate_board, board)
board = np.zeros([2, 0])
self.assertRaises(TypeError, validate_board, board)
board = np.zeros([0, 2])
... |
0f6317c1cc315cbf2e3eedb03ef6126a5394b0c420ea68a4c73ec54b0416213c | def test_values_board(self):
'Test board values validation.'
board = np.arange(4).reshape((2, 2))
self.assertRaises(ValueError, validate_board, board)
board = np.zeros([2, 2])
board[(0, 0)] = (- 1)
self.assertRaises(ValueError, validate_board, board)
board = np.ones([2, 2])
result = vali... | Test board values validation. | game_of_pyfe/tests/test_utils.py | test_values_board | jglezt/game-of-pyfe | 0 | python | def test_values_board(self):
board = np.arange(4).reshape((2, 2))
self.assertRaises(ValueError, validate_board, board)
board = np.zeros([2, 2])
board[(0, 0)] = (- 1)
self.assertRaises(ValueError, validate_board, board)
board = np.ones([2, 2])
result = validate_board(board)
self.asse... | def test_values_board(self):
board = np.arange(4).reshape((2, 2))
self.assertRaises(ValueError, validate_board, board)
board = np.zeros([2, 2])
board[(0, 0)] = (- 1)
self.assertRaises(ValueError, validate_board, board)
board = np.ones([2, 2])
result = validate_board(board)
self.asse... |
cd89b4ebd8a6c543e7c3912e525853dab46573cb174d313f3e3cc302ddb340db | def test_base_board(self):
'Test if correct board is returned.'
board = np.array([[1, 1, 0, 0, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])
expected_result = [[9608, 9608, 32, 32, 9608], [32, 32, 32, 32, 32], [32, 32, 32, 32, 32], [32, 32, 32, 32, 32], [32, 32, 32, 32, 32]]
r... | Test if correct board is returned. | game_of_pyfe/tests/test_utils.py | test_base_board | jglezt/game-of-pyfe | 0 | python | def test_base_board(self):
board = np.array([[1, 1, 0, 0, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])
expected_result = [[9608, 9608, 32, 32, 9608], [32, 32, 32, 32, 32], [32, 32, 32, 32, 32], [32, 32, 32, 32, 32], [32, 32, 32, 32, 32]]
result = create_printable_board(board... | def test_base_board(self):
board = np.array([[1, 1, 0, 0, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])
expected_result = [[9608, 9608, 32, 32, 9608], [32, 32, 32, 32, 32], [32, 32, 32, 32, 32], [32, 32, 32, 32, 32], [32, 32, 32, 32, 32]]
result = create_printable_board(board... |
894f93ebe0afd6e924712460cf28c46eb8c44ae379f24f966cc35d41d44df1a9 | def definition_document_comparison(document_json, aliases, definition, split_sentences_no_punct, prefix_depth=0.15):
"\n Given a parsed document, search within the first 'prefix_depth' of\n the sentences.\n "
split_sentences_no_punct = split_sentences_no_punct[:int((len(split_sentences_no_punct) * pref... | Given a parsed document, search within the first 'prefix_depth' of
the sentences. | prefix_search.py | definition_document_comparison | NLP-Capstone-Project/machine-dictionary | 4 | python | def definition_document_comparison(document_json, aliases, definition, split_sentences_no_punct, prefix_depth=0.15):
"\n Given a parsed document, search within the first 'prefix_depth' of\n the sentences.\n "
split_sentences_no_punct = split_sentences_no_punct[:int((len(split_sentences_no_punct) * pref... | def definition_document_comparison(document_json, aliases, definition, split_sentences_no_punct, prefix_depth=0.15):
"\n Given a parsed document, search within the first 'prefix_depth' of\n the sentences.\n "
split_sentences_no_punct = split_sentences_no_punct[:int((len(split_sentences_no_punct) * pref... |
1d8d3150c1982e651b1d1d4418157475627a03e57df41f9ae8154ebb2ca1195f | def resetTimers(self):
' reset timers, handle optional hold timer '
self.SetTimer.reset()
self.ResetTimer.reset()
if (self.HoldTimer is not None):
self.HoldTimer.reset() | reset timers, handle optional hold timer | psltdsim/perturbance/ShuntControlAgent.py | resetTimers | thadhaines/PSLTDSim | 0 | python | def resetTimers(self):
' '
self.SetTimer.reset()
self.ResetTimer.reset()
if (self.HoldTimer is not None):
self.HoldTimer.reset() | def resetTimers(self):
' '
self.SetTimer.reset()
self.ResetTimer.reset()
if (self.HoldTimer is not None):
self.HoldTimer.reset()<|docstring|>reset timers, handle optional hold timer<|endoftext|> |
e9d3f3fafbf3cd479e855c6b969fec4cf978b80c5a4ead61d42f8f39f458a3b8 | def step(self):
' check flags, send msg, else false '
updateMSG = False
if (self.HoldTimer is not None):
if (self.HoldTimer.actFlag == False):
return updateMSG
NumOn = len(self.OnShunts)
NumOff = len(self.OffShunts)
if self.SetTimer.actFlag:
if (NumOff > 0):
... | check flags, send msg, else false | psltdsim/perturbance/ShuntControlAgent.py | step | thadhaines/PSLTDSim | 0 | python | def step(self):
' '
updateMSG = False
if (self.HoldTimer is not None):
if (self.HoldTimer.actFlag == False):
return updateMSG
NumOn = len(self.OnShunts)
NumOff = len(self.OffShunts)
if self.SetTimer.actFlag:
if (NumOff > 0):
self.OffShunts[0].cv['St'] = 1... | def step(self):
' '
updateMSG = False
if (self.HoldTimer is not None):
if (self.HoldTimer.actFlag == False):
return updateMSG
NumOn = len(self.OnShunts)
NumOff = len(self.OffShunts)
if self.SetTimer.actFlag:
if (NumOff > 0):
self.OffShunts[0].cv['St'] = 1... |
b82a0de23345d638eba28d4e0b47fc1fe5f5dd6c4e7e6a74a0fd7ff84d6f6303 | def safe_rmtree(path):
"Removes path if it's not top level or user dir."
assert (not _top_level_dir(path)), path
assert (path != os.path.expanduser('~')), path
shutil.rmtree(path) | Removes path if it's not top level or user dir. | guild/util.py | safe_rmtree | olliethomas/guildai | 0 | python | def safe_rmtree(path):
assert (not _top_level_dir(path)), path
assert (path != os.path.expanduser('~')), path
shutil.rmtree(path) | def safe_rmtree(path):
assert (not _top_level_dir(path)), path
assert (path != os.path.expanduser('~')), path
shutil.rmtree(path)<|docstring|>Removes path if it's not top level or user dir.<|endoftext|> |
4025bea434371fd90b6487db2fba5e86e39d7b660893acff752ef8e191a2f875 | def platform_info():
'Returns a dict of system info.'
info = _platform_base_info()
info.update(_platform_psutil_info())
return info | Returns a dict of system info. | guild/util.py | platform_info | olliethomas/guildai | 0 | python | def platform_info():
info = _platform_base_info()
info.update(_platform_psutil_info())
return info | def platform_info():
info = _platform_base_info()
info.update(_platform_psutil_info())
return info<|docstring|>Returns a dict of system info.<|endoftext|> |
0f107ba88f269215cf0451983e9eef83d19e9d6703ec47ecdd06ff047bfecc5f | def _shorten_path_split_path(path, sep):
'Splits path into parts.\n\n Leading and repeated \'/\' chars are prepended to the\n part. E.g. "/foo/bar" is returned as ["/foo", "bar"] and\n "foo//bar" as ["foo", "/bar"].\n '
if (not path):
return []
parts = path.split(sep)
packed = []
... | Splits path into parts.
Leading and repeated '/' chars are prepended to the
part. E.g. "/foo/bar" is returned as ["/foo", "bar"] and
"foo//bar" as ["foo", "/bar"]. | guild/util.py | _shorten_path_split_path | olliethomas/guildai | 0 | python | def _shorten_path_split_path(path, sep):
'Splits path into parts.\n\n Leading and repeated \'/\' chars are prepended to the\n part. E.g. "/foo/bar" is returned as ["/foo", "bar"] and\n "foo//bar" as ["foo", "/bar"].\n '
if (not path):
return []
parts = path.split(sep)
packed = []
... | def _shorten_path_split_path(path, sep):
'Splits path into parts.\n\n Leading and repeated \'/\' chars are prepended to the\n part. E.g. "/foo/bar" is returned as ["/foo", "bar"] and\n "foo//bar" as ["foo", "/bar"].\n '
if (not path):
return []
parts = path.split(sep)
packed = []
... |
442ff2e281d0604894572304e27ed8642274fb4e7e5667df48366d3c643aeb93 | def _try_editor_bin():
'Returns /usr/bin/editor if it exists.\n\n This is the path configured by `update-alternatives` on Ubuntu\n systems.\n '
editor_bin = '/usr/bin/editor'
if os.path.exists(editor_bin):
return editor_bin
return None | Returns /usr/bin/editor if it exists.
This is the path configured by `update-alternatives` on Ubuntu
systems. | guild/util.py | _try_editor_bin | olliethomas/guildai | 0 | python | def _try_editor_bin():
'Returns /usr/bin/editor if it exists.\n\n This is the path configured by `update-alternatives` on Ubuntu\n systems.\n '
editor_bin = '/usr/bin/editor'
if os.path.exists(editor_bin):
return editor_bin
return None | def _try_editor_bin():
'Returns /usr/bin/editor if it exists.\n\n This is the path configured by `update-alternatives` on Ubuntu\n systems.\n '
editor_bin = '/usr/bin/editor'
if os.path.exists(editor_bin):
return editor_bin
return None<|docstring|>Returns /usr/bin/editor if it exists.
... |
e9a878d09924c548c9ff69487fe0e5867dcaf0b76acbc2ad8bb677e3997e87c3 | def patch_yaml_resolver():
"Patch yaml parsing to support Guild specific resolution rules.\n\n - Make '+' or '-' optional in scientific notation\n - Make use of decimal '.' optional in scientific notation\n\n This patch replaces the default 'tag:yaml.org,2002:float' resolver\n with an augmented set of r... | Patch yaml parsing to support Guild specific resolution rules.
- Make '+' or '-' optional in scientific notation
- Make use of decimal '.' optional in scientific notation
This patch replaces the default 'tag:yaml.org,2002:float' resolver
with an augmented set of regex patterns. Refer to
`yaml/resolver.py` for the ori... | guild/util.py | patch_yaml_resolver | olliethomas/guildai | 0 | python | def patch_yaml_resolver():
"Patch yaml parsing to support Guild specific resolution rules.\n\n - Make '+' or '-' optional in scientific notation\n - Make use of decimal '.' optional in scientific notation\n\n This patch replaces the default 'tag:yaml.org,2002:float' resolver\n with an augmented set of r... | def patch_yaml_resolver():
"Patch yaml parsing to support Guild specific resolution rules.\n\n - Make '+' or '-' optional in scientific notation\n - Make use of decimal '.' optional in scientific notation\n\n This patch replaces the default 'tag:yaml.org,2002:float' resolver\n with an augmented set of r... |
907e0ea7fa12280a41c04b317b759e83497f6494607fd074e0114deb0258c309 | def read(self, start=0, end=None):
'Read run output from start to end.\n\n Both start and end are zero-based indexes to run output lines\n and are both inclusive. Note this is different from the Python\n slice function where end is exclusive.\n '
self._read_next(end)
if (end is N... | Read run output from start to end.
Both start and end are zero-based indexes to run output lines
and are both inclusive. Note this is different from the Python
slice function where end is exclusive. | guild/util.py | read | olliethomas/guildai | 0 | python | def read(self, start=0, end=None):
'Read run output from start to end.\n\n Both start and end are zero-based indexes to run output lines\n and are both inclusive. Note this is different from the Python\n slice function where end is exclusive.\n '
self._read_next(end)
if (end is N... | def read(self, start=0, end=None):
'Read run output from start to end.\n\n Both start and end are zero-based indexes to run output lines\n and are both inclusive. Note this is different from the Python\n slice function where end is exclusive.\n '
self._read_next(end)
if (end is N... |
69b0e812d01424f6596e7b18e9ee8a2f37122aa60343971929a0e9fbb8dc2c5c | def get_classification(self, image):
'Determines the color of the traffic light in the image\n Args:\n image (cv::Mat): image containing the traffic light\n Returns:\n int: ID of traffic light color (specified in styx_msgs/TrafficLight)\n '
hsv_img = cv2.cvtColor(image... | Determines the color of the traffic light in the image
Args:
image (cv::Mat): image containing the traffic light
Returns:
int: ID of traffic light color (specified in styx_msgs/TrafficLight) | ros/src/tl_detector/light_classification/tl_classifier.py | get_classification | melsobky/CarND_T3_Capstone | 0 | python | def get_classification(self, image):
'Determines the color of the traffic light in the image\n Args:\n image (cv::Mat): image containing the traffic light\n Returns:\n int: ID of traffic light color (specified in styx_msgs/TrafficLight)\n '
hsv_img = cv2.cvtColor(image... | def get_classification(self, image):
'Determines the color of the traffic light in the image\n Args:\n image (cv::Mat): image containing the traffic light\n Returns:\n int: ID of traffic light color (specified in styx_msgs/TrafficLight)\n '
hsv_img = cv2.cvtColor(image... |
806c5934c91608e52e25511a9e480f4436c811f44359068860d534639eeb8423 | def _plot_to_json(plot):
'Convert plot to JSON objects necessary for rendering with `bokehJS`.\n\n Parameters\n ----------\n plot : bokeh.plotting.figure.Figure\n Bokeh plot object to be rendered.\n\n Returns\n -------\n (str, str)\n Returns (docs_json, render_items) json for the des... | Convert plot to JSON objects necessary for rendering with `bokehJS`.
Parameters
----------
plot : bokeh.plotting.figure.Figure
Bokeh plot object to be rendered.
Returns
-------
(str, str)
Returns (docs_json, render_items) json for the desired plot. | skyportal/plot.py | _plot_to_json | stefanv/skyportal | 0 | python | def _plot_to_json(plot):
'Convert plot to JSON objects necessary for rendering with `bokehJS`.\n\n Parameters\n ----------\n plot : bokeh.plotting.figure.Figure\n Bokeh plot object to be rendered.\n\n Returns\n -------\n (str, str)\n Returns (docs_json, render_items) json for the des... | def _plot_to_json(plot):
'Convert plot to JSON objects necessary for rendering with `bokehJS`.\n\n Parameters\n ----------\n plot : bokeh.plotting.figure.Figure\n Bokeh plot object to be rendered.\n\n Returns\n -------\n (str, str)\n Returns (docs_json, render_items) json for the des... |
4c3ca75225c31ca2291c04dc033e17edcc47b6d64a62a821a47bae6174489f08 | def photometry_plot(source_id):
'Create scatter plot of photometry for source.\n\n Parameters\n ----------\n source_id : int\n ID of source to be plotted.\n\n Returns\n -------\n (str, str)\n Returns (docs_json, render_items) json for the desired plot.\n '
color_map = {'ipr': ... | Create scatter plot of photometry for source.
Parameters
----------
source_id : int
ID of source to be plotted.
Returns
-------
(str, str)
Returns (docs_json, render_items) json for the desired plot. | skyportal/plot.py | photometry_plot | stefanv/skyportal | 0 | python | def photometry_plot(source_id):
'Create scatter plot of photometry for source.\n\n Parameters\n ----------\n source_id : int\n ID of source to be plotted.\n\n Returns\n -------\n (str, str)\n Returns (docs_json, render_items) json for the desired plot.\n '
color_map = {'ipr': ... | def photometry_plot(source_id):
'Create scatter plot of photometry for source.\n\n Parameters\n ----------\n source_id : int\n ID of source to be plotted.\n\n Returns\n -------\n (str, str)\n Returns (docs_json, render_items) json for the desired plot.\n '
color_map = {'ipr': ... |
633b19082afcf4ca62075a3b8381afe66130a1e0ed2bd89e475c986ed30e2fca | def spectroscopy_plot(source_id):
'TODO normalization? should this be handled at data ingestion or plot-time?'
source = Source.query.get(source_id)
spectra = Source.query.get(source_id).spectra
if (len(spectra) == 0):
return (None, None, None)
color_map = dict(zip([s.id for s in spectra], vi... | TODO normalization? should this be handled at data ingestion or plot-time? | skyportal/plot.py | spectroscopy_plot | stefanv/skyportal | 0 | python | def spectroscopy_plot(source_id):
source = Source.query.get(source_id)
spectra = Source.query.get(source_id).spectra
if (len(spectra) == 0):
return (None, None, None)
color_map = dict(zip([s.id for s in spectra], viridis(len(spectra))))
data = pd.concat([pd.DataFrame({'wavelength': s.wa... | def spectroscopy_plot(source_id):
source = Source.query.get(source_id)
spectra = Source.query.get(source_id).spectra
if (len(spectra) == 0):
return (None, None, None)
color_map = dict(zip([s.id for s in spectra], viridis(len(spectra))))
data = pd.concat([pd.DataFrame({'wavelength': s.wa... |
c95875569dcc5ffc8950d2c4ece5616d06ab78164eb865331804a7f284b936a2 | def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
'3x3 convolution with padding'
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation) | 3x3 convolution with padding | models/ResNetD.py | conv3x3 | HotaekHan/classification-pytorch | 5 | python | def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation) | def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation)<|docstring|>3x3 convolution with padding<|endoftext|> |
7447c07b06cc8d16674f31fc29f40a376c8d7a0321f9f661635b233109ed88c5 | def conv1x1(in_planes, out_planes, stride=1):
'1x1 convolution'
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) | 1x1 convolution | models/ResNetD.py | conv1x1 | HotaekHan/classification-pytorch | 5 | python | def conv1x1(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) | def conv1x1(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)<|docstring|>1x1 convolution<|endoftext|> |
7307e6a13cd9795fdfbab4064cd34a38beec580fac91befcbb165ae8e168c95e | def resnet50d(pretrained=False, progress=True, **kwargs):
'ResNet-50 model from\n `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress... | ResNet-50 model from
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr | models/ResNetD.py | resnet50d | HotaekHan/classification-pytorch | 5 | python | def resnet50d(pretrained=False, progress=True, **kwargs):
'ResNet-50 model from\n `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress... | def resnet50d(pretrained=False, progress=True, **kwargs):
'ResNet-50 model from\n `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress... |
c28c8726f82dffc5d85b71de6a9ceac7027abbd09dc5a6f4ffdeb94b8a569e1b | def resnet101d(pretrained=False, progress=True, **kwargs):
'ResNet-101 model from\n `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progre... | ResNet-101 model from
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr | models/ResNetD.py | resnet101d | HotaekHan/classification-pytorch | 5 | python | def resnet101d(pretrained=False, progress=True, **kwargs):
'ResNet-101 model from\n `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progre... | def resnet101d(pretrained=False, progress=True, **kwargs):
'ResNet-101 model from\n `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progre... |
d507b7c60a8f313208e5861d7e3df5bd89e452c978a438743e7e1f16e608c01c | def resnet152d(pretrained=False, progress=True, **kwargs):
'ResNet-152 model from\n `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progre... | ResNet-152 model from
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr | models/ResNetD.py | resnet152d | HotaekHan/classification-pytorch | 5 | python | def resnet152d(pretrained=False, progress=True, **kwargs):
'ResNet-152 model from\n `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progre... | def resnet152d(pretrained=False, progress=True, **kwargs):
'ResNet-152 model from\n `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progre... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.