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
536277f55e075a01d5c9a8b95b98a7534ffe72713e92632a62cd9821cfeead36
def crossover_update(self, n_parallel, measure_batch, callbacks): '\n Perform RL crossover on the population.\n ' scores = np.array([t.score for t in self.population]) scores += 1e-08 scores /= np.max(scores) indices = np.arange(len(self.population)) probabilities = (scores / np.sum(scores)) if (self.step_count >= self.pop_size): for i in range(ceil((self.pop_size / self.train_frequency))): batch_size = min(self.train_frequency, (self.pop_size - (i * self.train_frequency))) population_offset = ((i * self.train_frequency) - 1) transitions = self.rl_crossover(probabilities, indices, batch_size) self.measure_configs(transitions, n_parallel, measure_batch, callbacks) for (j, transition) in enumerate(transitions): reward = self.calculate_reward(transition.score) self.crossover_agent.memory.store_experience([transition.prev_state, transition.action, transition.state, reward]) self.population[(population_offset + j)] = transition if ((self.crossover_step_count > 0) and (((self.crossover_step_count + j) % self.update_frequency) == 0)): self.crossover_agent.increment_target() self.crossover_step_count += batch_size if (self.crossover_step_count > self.learn_start): self.crossover_agent.train(self.agent_batch_size) self.crossover_agent.reduce_epsilon() self.prev_fitness = np.mean(self.scores[(- self.pop_size):])
Perform RL crossover on the population.
rl_tuner/ga_dqn_tuner.py
crossover_update
lhutton1/benchmark-tvm
1
python
def crossover_update(self, n_parallel, measure_batch, callbacks): '\n \n ' scores = np.array([t.score for t in self.population]) scores += 1e-08 scores /= np.max(scores) indices = np.arange(len(self.population)) probabilities = (scores / np.sum(scores)) if (self.step_count >= self.pop_size): for i in range(ceil((self.pop_size / self.train_frequency))): batch_size = min(self.train_frequency, (self.pop_size - (i * self.train_frequency))) population_offset = ((i * self.train_frequency) - 1) transitions = self.rl_crossover(probabilities, indices, batch_size) self.measure_configs(transitions, n_parallel, measure_batch, callbacks) for (j, transition) in enumerate(transitions): reward = self.calculate_reward(transition.score) self.crossover_agent.memory.store_experience([transition.prev_state, transition.action, transition.state, reward]) self.population[(population_offset + j)] = transition if ((self.crossover_step_count > 0) and (((self.crossover_step_count + j) % self.update_frequency) == 0)): self.crossover_agent.increment_target() self.crossover_step_count += batch_size if (self.crossover_step_count > self.learn_start): self.crossover_agent.train(self.agent_batch_size) self.crossover_agent.reduce_epsilon() self.prev_fitness = np.mean(self.scores[(- self.pop_size):])
def crossover_update(self, n_parallel, measure_batch, callbacks): '\n \n ' scores = np.array([t.score for t in self.population]) scores += 1e-08 scores /= np.max(scores) indices = np.arange(len(self.population)) probabilities = (scores / np.sum(scores)) if (self.step_count >= self.pop_size): for i in range(ceil((self.pop_size / self.train_frequency))): batch_size = min(self.train_frequency, (self.pop_size - (i * self.train_frequency))) population_offset = ((i * self.train_frequency) - 1) transitions = self.rl_crossover(probabilities, indices, batch_size) self.measure_configs(transitions, n_parallel, measure_batch, callbacks) for (j, transition) in enumerate(transitions): reward = self.calculate_reward(transition.score) self.crossover_agent.memory.store_experience([transition.prev_state, transition.action, transition.state, reward]) self.population[(population_offset + j)] = transition if ((self.crossover_step_count > 0) and (((self.crossover_step_count + j) % self.update_frequency) == 0)): self.crossover_agent.increment_target() self.crossover_step_count += batch_size if (self.crossover_step_count > self.learn_start): self.crossover_agent.train(self.agent_batch_size) self.crossover_agent.reduce_epsilon() self.prev_fitness = np.mean(self.scores[(- self.pop_size):])<|docstring|>Perform RL crossover on the population.<|endoftext|>
d1feef3749d2f59859d5c7ca99509dac71062e0833c99aa4f3023c4ab64824ad
def measure_configs(self, transitions, n_parallel, measure_batch, callbacks): '\n Measure results for current population.\n ' for i in range(ceil((len(transitions) / n_parallel))): configs = [] batch_size = min(n_parallel, (len(transitions) - (i * n_parallel))) transitions_offset = ((i * n_parallel) - 1) for j in range(transitions_offset, (transitions_offset + batch_size)): gene = transitions[j].gene configs.append(self.space.get(knob2point(gene, self.dims))) inputs = [MeasureInput(self.task.target, self.task, config) for config in configs] (results, end_time) = measure_batch(inputs) for j in range(len(results)): self.step_count += 1 transition = transitions[(transitions_offset + j)] (input, result) = (inputs[j], results[j]) transition.input = inputs[j] transition.result = results[j] transition.score = ((input.task.flop / np.mean(result.costs)) if (result.error_no == 0) else 0.0) self.scores.append(transition.score) if (transition.score > self.best_flops): self.best_flops = transition.score self.best_config = transition.input.config self.best_measure_pair = (transition.input, transition.result) self.best_iter = self.step_count for callback in callbacks: inputs = [t.input for t in transitions] results = [t.result for t in transitions] callback(self, inputs, results)
Measure results for current population.
rl_tuner/ga_dqn_tuner.py
measure_configs
lhutton1/benchmark-tvm
1
python
def measure_configs(self, transitions, n_parallel, measure_batch, callbacks): '\n \n ' for i in range(ceil((len(transitions) / n_parallel))): configs = [] batch_size = min(n_parallel, (len(transitions) - (i * n_parallel))) transitions_offset = ((i * n_parallel) - 1) for j in range(transitions_offset, (transitions_offset + batch_size)): gene = transitions[j].gene configs.append(self.space.get(knob2point(gene, self.dims))) inputs = [MeasureInput(self.task.target, self.task, config) for config in configs] (results, end_time) = measure_batch(inputs) for j in range(len(results)): self.step_count += 1 transition = transitions[(transitions_offset + j)] (input, result) = (inputs[j], results[j]) transition.input = inputs[j] transition.result = results[j] transition.score = ((input.task.flop / np.mean(result.costs)) if (result.error_no == 0) else 0.0) self.scores.append(transition.score) if (transition.score > self.best_flops): self.best_flops = transition.score self.best_config = transition.input.config self.best_measure_pair = (transition.input, transition.result) self.best_iter = self.step_count for callback in callbacks: inputs = [t.input for t in transitions] results = [t.result for t in transitions] callback(self, inputs, results)
def measure_configs(self, transitions, n_parallel, measure_batch, callbacks): '\n \n ' for i in range(ceil((len(transitions) / n_parallel))): configs = [] batch_size = min(n_parallel, (len(transitions) - (i * n_parallel))) transitions_offset = ((i * n_parallel) - 1) for j in range(transitions_offset, (transitions_offset + batch_size)): gene = transitions[j].gene configs.append(self.space.get(knob2point(gene, self.dims))) inputs = [MeasureInput(self.task.target, self.task, config) for config in configs] (results, end_time) = measure_batch(inputs) for j in range(len(results)): self.step_count += 1 transition = transitions[(transitions_offset + j)] (input, result) = (inputs[j], results[j]) transition.input = inputs[j] transition.result = results[j] transition.score = ((input.task.flop / np.mean(result.costs)) if (result.error_no == 0) else 0.0) self.scores.append(transition.score) if (transition.score > self.best_flops): self.best_flops = transition.score self.best_config = transition.input.config self.best_measure_pair = (transition.input, transition.result) self.best_iter = self.step_count for callback in callbacks: inputs = [t.input for t in transitions] results = [t.result for t in transitions] callback(self, inputs, results)<|docstring|>Measure results for current population.<|endoftext|>
442f085446ee5e79b2571c8b18db66e18d65a34224d68234d545c43146517816
def save_model(self, save_path, save_name): "\n Save model to file, at 'save_path/save_name'.\n " abs_path = Path((save_path + save_name)).resolve() abs_path.mkdir(exist_ok=True, parents=True) abs_path_str = str(abs_path) self.mutation_agent.save_models((abs_path_str + '/mutate_policy_net.model'), (abs_path_str + '/mutate_target_net.model')) self.crossover_agent.save_models((abs_path_str + '/crossover_policy_net.model'), (abs_path_str + '/crossover_target_net.model'))
Save model to file, at 'save_path/save_name'.
rl_tuner/ga_dqn_tuner.py
save_model
lhutton1/benchmark-tvm
1
python
def save_model(self, save_path, save_name): "\n \n " abs_path = Path((save_path + save_name)).resolve() abs_path.mkdir(exist_ok=True, parents=True) abs_path_str = str(abs_path) self.mutation_agent.save_models((abs_path_str + '/mutate_policy_net.model'), (abs_path_str + '/mutate_target_net.model')) self.crossover_agent.save_models((abs_path_str + '/crossover_policy_net.model'), (abs_path_str + '/crossover_target_net.model'))
def save_model(self, save_path, save_name): "\n \n " abs_path = Path((save_path + save_name)).resolve() abs_path.mkdir(exist_ok=True, parents=True) abs_path_str = str(abs_path) self.mutation_agent.save_models((abs_path_str + '/mutate_policy_net.model'), (abs_path_str + '/mutate_target_net.model')) self.crossover_agent.save_models((abs_path_str + '/crossover_policy_net.model'), (abs_path_str + '/crossover_target_net.model'))<|docstring|>Save model to file, at 'save_path/save_name'.<|endoftext|>
bf18c31f93cc29eab2efc4d6e3007ad25dcd27ca289b4cc2939b808de8583ecd
def tune(self, n_trial, measure_option, early_stopping=None, callbacks=(), si_prefix='G'): '\n GADQNTuner requires custom tuning pipeline as it requires partial measurement of genes\n after crossover, before mutation.\n\n DISCLAIMER: In order to customise the tuning pipeline we had to reimplement the tune\n function. This method is mostly taken from Tuner with the exception of\n an implementation of a custom tuning pipeline.\n ' measure_batch = create_measure_batch(self.task, measure_option) n_parallel = getattr(measure_batch, 'n_parallel', 1) early_stopping = (early_stopping or 1000000000.0) format_si_prefix(0, si_prefix) GLOBAL_SCOPE.in_tuning = True do_crossover = True (self.mutation_agent, self.crossover_agent) = self.create_rl_agents(self.discount, int(ceil((n_trial / 2))), self.hidden_sizes, self.learning_rate) while (self.step_count < n_trial): if (not self.has_next()): break if (self.step_count < self.pop_size): for _ in range(self.pop_size): gene = point2knob(np.random.randint(len(self.space)), self.dims) while (knob2point(gene, self.dims) in self.visited): gene = point2knob(np.random.randint(len(self.space)), self.dims) transition = Transition(None, None, None, gene) self.population.append(transition) self.visited.add(knob2point(gene, self.dims)) self.measure_configs(self.population, n_parallel, measure_batch, callbacks) self.initial_score = np.mean([p.score for p in self.population]) self.reserve_elites() elif do_crossover: self.population.extend(self.elite_population) self.reserve_elites() self.crossover_update(n_parallel, measure_batch, callbacks) do_crossover = False else: self.mutate_update(n_parallel, measure_batch, callbacks) do_crossover = True self.ttl = (min((early_stopping + self.best_iter), n_trial) - self.step_count) if (self.step_count >= (self.best_iter + early_stopping)): break GLOBAL_SCOPE.in_tuning = False del measure_batch
GADQNTuner requires custom tuning pipeline as it requires partial measurement of genes after crossover, before mutation. DISCLAIMER: In order to customise the tuning pipeline we had to reimplement the tune function. This method is mostly taken from Tuner with the exception of an implementation of a custom tuning pipeline.
rl_tuner/ga_dqn_tuner.py
tune
lhutton1/benchmark-tvm
1
python
def tune(self, n_trial, measure_option, early_stopping=None, callbacks=(), si_prefix='G'): '\n GADQNTuner requires custom tuning pipeline as it requires partial measurement of genes\n after crossover, before mutation.\n\n DISCLAIMER: In order to customise the tuning pipeline we had to reimplement the tune\n function. This method is mostly taken from Tuner with the exception of\n an implementation of a custom tuning pipeline.\n ' measure_batch = create_measure_batch(self.task, measure_option) n_parallel = getattr(measure_batch, 'n_parallel', 1) early_stopping = (early_stopping or 1000000000.0) format_si_prefix(0, si_prefix) GLOBAL_SCOPE.in_tuning = True do_crossover = True (self.mutation_agent, self.crossover_agent) = self.create_rl_agents(self.discount, int(ceil((n_trial / 2))), self.hidden_sizes, self.learning_rate) while (self.step_count < n_trial): if (not self.has_next()): break if (self.step_count < self.pop_size): for _ in range(self.pop_size): gene = point2knob(np.random.randint(len(self.space)), self.dims) while (knob2point(gene, self.dims) in self.visited): gene = point2knob(np.random.randint(len(self.space)), self.dims) transition = Transition(None, None, None, gene) self.population.append(transition) self.visited.add(knob2point(gene, self.dims)) self.measure_configs(self.population, n_parallel, measure_batch, callbacks) self.initial_score = np.mean([p.score for p in self.population]) self.reserve_elites() elif do_crossover: self.population.extend(self.elite_population) self.reserve_elites() self.crossover_update(n_parallel, measure_batch, callbacks) do_crossover = False else: self.mutate_update(n_parallel, measure_batch, callbacks) do_crossover = True self.ttl = (min((early_stopping + self.best_iter), n_trial) - self.step_count) if (self.step_count >= (self.best_iter + early_stopping)): break GLOBAL_SCOPE.in_tuning = False del measure_batch
def tune(self, n_trial, measure_option, early_stopping=None, callbacks=(), si_prefix='G'): '\n GADQNTuner requires custom tuning pipeline as it requires partial measurement of genes\n after crossover, before mutation.\n\n DISCLAIMER: In order to customise the tuning pipeline we had to reimplement the tune\n function. This method is mostly taken from Tuner with the exception of\n an implementation of a custom tuning pipeline.\n ' measure_batch = create_measure_batch(self.task, measure_option) n_parallel = getattr(measure_batch, 'n_parallel', 1) early_stopping = (early_stopping or 1000000000.0) format_si_prefix(0, si_prefix) GLOBAL_SCOPE.in_tuning = True do_crossover = True (self.mutation_agent, self.crossover_agent) = self.create_rl_agents(self.discount, int(ceil((n_trial / 2))), self.hidden_sizes, self.learning_rate) while (self.step_count < n_trial): if (not self.has_next()): break if (self.step_count < self.pop_size): for _ in range(self.pop_size): gene = point2knob(np.random.randint(len(self.space)), self.dims) while (knob2point(gene, self.dims) in self.visited): gene = point2knob(np.random.randint(len(self.space)), self.dims) transition = Transition(None, None, None, gene) self.population.append(transition) self.visited.add(knob2point(gene, self.dims)) self.measure_configs(self.population, n_parallel, measure_batch, callbacks) self.initial_score = np.mean([p.score for p in self.population]) self.reserve_elites() elif do_crossover: self.population.extend(self.elite_population) self.reserve_elites() self.crossover_update(n_parallel, measure_batch, callbacks) do_crossover = False else: self.mutate_update(n_parallel, measure_batch, callbacks) do_crossover = True self.ttl = (min((early_stopping + self.best_iter), n_trial) - self.step_count) if (self.step_count >= (self.best_iter + early_stopping)): break GLOBAL_SCOPE.in_tuning = False del measure_batch<|docstring|>GADQNTuner requires custom tuning pipeline as it requires partial measurement of genes after crossover, before mutation. DISCLAIMER: In order to customise the tuning pipeline we had to reimplement the tune function. This method is mostly taken from Tuner with the exception of an implementation of a custom tuning pipeline.<|endoftext|>
38d4c57a85ca380be98cb37aea6cddfb509f23b328c63cb02406ddc5a10a67e3
def has_context(func): 'Provide automatic context for Nonterm production rules.' def wrapper(*args, **kwargs): result = func(*args, **kwargs) (obj, *args) = args if (len(args) == 1): arg = args[0] if (getattr(arg, 'val', None) is obj.val): if hasattr(arg, 'context'): obj.context = arg.context if hasattr(obj.val, 'context'): obj.val.context = obj.context return result if (getattr(obj, 'context', None) is None): obj.context = get_context(*args) force_context(obj.val, obj.context) return result return wrapper
Provide automatic context for Nonterm production rules.
edb/common/context.py
has_context
disfated/edgedb
4
python
def has_context(func): def wrapper(*args, **kwargs): result = func(*args, **kwargs) (obj, *args) = args if (len(args) == 1): arg = args[0] if (getattr(arg, 'val', None) is obj.val): if hasattr(arg, 'context'): obj.context = arg.context if hasattr(obj.val, 'context'): obj.val.context = obj.context return result if (getattr(obj, 'context', None) is None): obj.context = get_context(*args) force_context(obj.val, obj.context) return result return wrapper
def has_context(func): def wrapper(*args, **kwargs): result = func(*args, **kwargs) (obj, *args) = args if (len(args) == 1): arg = args[0] if (getattr(arg, 'val', None) is obj.val): if hasattr(arg, 'context'): obj.context = arg.context if hasattr(obj.val, 'context'): obj.val.context = obj.context return result if (getattr(obj, 'context', None) is None): obj.context = get_context(*args) force_context(obj.val, obj.context) return result return wrapper<|docstring|>Provide automatic context for Nonterm production rules.<|endoftext|>
c28b97100478bff1d9a67897db198eb4f8b425390eb732bdd76de40122677248
def iso86012datetime(time): 'Converts ISO 8601 time to datetime\n\n Parameters\n ----------\n time : ndarray or list\n Time\n\n Returns\n -------\n time_datetime : list\n Time in datetime format.\n\n ' time = np.array(time).astype('<M8[ns]').astype(str) fmt = '%Y-%m-%dT%H:%M:%S.%f' time_datetime = [datetime.datetime.strptime(t_[:(- 3)], fmt) for t_ in time] return time_datetime
Converts ISO 8601 time to datetime Parameters ---------- time : ndarray or list Time Returns ------- time_datetime : list Time in datetime format.
pyrfu/pyrf/iso86012datetime.py
iso86012datetime
ablotekar/irfu-python
2
python
def iso86012datetime(time): 'Converts ISO 8601 time to datetime\n\n Parameters\n ----------\n time : ndarray or list\n Time\n\n Returns\n -------\n time_datetime : list\n Time in datetime format.\n\n ' time = np.array(time).astype('<M8[ns]').astype(str) fmt = '%Y-%m-%dT%H:%M:%S.%f' time_datetime = [datetime.datetime.strptime(t_[:(- 3)], fmt) for t_ in time] return time_datetime
def iso86012datetime(time): 'Converts ISO 8601 time to datetime\n\n Parameters\n ----------\n time : ndarray or list\n Time\n\n Returns\n -------\n time_datetime : list\n Time in datetime format.\n\n ' time = np.array(time).astype('<M8[ns]').astype(str) fmt = '%Y-%m-%dT%H:%M:%S.%f' time_datetime = [datetime.datetime.strptime(t_[:(- 3)], fmt) for t_ in time] return time_datetime<|docstring|>Converts ISO 8601 time to datetime Parameters ---------- time : ndarray or list Time Returns ------- time_datetime : list Time in datetime format.<|endoftext|>
7fe3114dd2aa685a46da78f95b6aa69ad501b1f89b0b2d217f514093c026fd2f
@property def inputs(self): 'Enables to connect inputs to the operator\n\n Returns\n --------\n inputs : InputsCyclicSupportProvider \n ' return super().inputs
Enables to connect inputs to the operator Returns -------- inputs : InputsCyclicSupportProvider
ansys/dpf/core/operators/metadata/cyclic_support_provider.py
inputs
TheGoldfish01/pydpf-core
11
python
@property def inputs(self): 'Enables to connect inputs to the operator\n\n Returns\n --------\n inputs : InputsCyclicSupportProvider \n ' return super().inputs
@property def inputs(self): 'Enables to connect inputs to the operator\n\n Returns\n --------\n inputs : InputsCyclicSupportProvider \n ' return super().inputs<|docstring|>Enables to connect inputs to the operator Returns -------- inputs : InputsCyclicSupportProvider<|endoftext|>
72df262917ed479608bcc98b15aca85424a0bc00a75674495ecfcd9f0ffec857
@property def outputs(self): 'Enables to get outputs of the operator by evaluationg it\n\n Returns\n --------\n outputs : OutputsCyclicSupportProvider \n ' return super().outputs
Enables to get outputs of the operator by evaluationg it Returns -------- outputs : OutputsCyclicSupportProvider
ansys/dpf/core/operators/metadata/cyclic_support_provider.py
outputs
TheGoldfish01/pydpf-core
11
python
@property def outputs(self): 'Enables to get outputs of the operator by evaluationg it\n\n Returns\n --------\n outputs : OutputsCyclicSupportProvider \n ' return super().outputs
@property def outputs(self): 'Enables to get outputs of the operator by evaluationg it\n\n Returns\n --------\n outputs : OutputsCyclicSupportProvider \n ' return super().outputs<|docstring|>Enables to get outputs of the operator by evaluationg it Returns -------- outputs : OutputsCyclicSupportProvider<|endoftext|>
9601587d1c6ca9818f088aefe568feda75f03fa95ba80261e25bac8090f6e1f0
@property def streams_container(self): 'Allows to connect streams_container input to the operator\n\n - pindoc: Streams containing the result file.\n\n Parameters\n ----------\n my_streams_container : StreamsContainer, \n\n Examples\n --------\n >>> from ansys.dpf import core as dpf\n\n >>> op = dpf.operators.metadata.cyclic_support_provider()\n >>> op.inputs.streams_container.connect(my_streams_container)\n >>> #or\n >>> op.inputs.streams_container(my_streams_container)\n\n ' return self._streams_container
Allows to connect streams_container input to the operator - pindoc: Streams containing the result file. Parameters ---------- my_streams_container : StreamsContainer, Examples -------- >>> from ansys.dpf import core as dpf >>> op = dpf.operators.metadata.cyclic_support_provider() >>> op.inputs.streams_container.connect(my_streams_container) >>> #or >>> op.inputs.streams_container(my_streams_container)
ansys/dpf/core/operators/metadata/cyclic_support_provider.py
streams_container
TheGoldfish01/pydpf-core
11
python
@property def streams_container(self): 'Allows to connect streams_container input to the operator\n\n - pindoc: Streams containing the result file.\n\n Parameters\n ----------\n my_streams_container : StreamsContainer, \n\n Examples\n --------\n >>> from ansys.dpf import core as dpf\n\n >>> op = dpf.operators.metadata.cyclic_support_provider()\n >>> op.inputs.streams_container.connect(my_streams_container)\n >>> #or\n >>> op.inputs.streams_container(my_streams_container)\n\n ' return self._streams_container
@property def streams_container(self): 'Allows to connect streams_container input to the operator\n\n - pindoc: Streams containing the result file.\n\n Parameters\n ----------\n my_streams_container : StreamsContainer, \n\n Examples\n --------\n >>> from ansys.dpf import core as dpf\n\n >>> op = dpf.operators.metadata.cyclic_support_provider()\n >>> op.inputs.streams_container.connect(my_streams_container)\n >>> #or\n >>> op.inputs.streams_container(my_streams_container)\n\n ' return self._streams_container<|docstring|>Allows to connect streams_container input to the operator - pindoc: Streams containing the result file. Parameters ---------- my_streams_container : StreamsContainer, Examples -------- >>> from ansys.dpf import core as dpf >>> op = dpf.operators.metadata.cyclic_support_provider() >>> op.inputs.streams_container.connect(my_streams_container) >>> #or >>> op.inputs.streams_container(my_streams_container)<|endoftext|>
4ab912749dc5ed166710f92e186e604715758c1c52202e9296cbae8f411b48cf
@property def data_sources(self): 'Allows to connect data_sources input to the operator\n\n - pindoc: data sources containing the result file.\n\n Parameters\n ----------\n my_data_sources : DataSources, \n\n Examples\n --------\n >>> from ansys.dpf import core as dpf\n\n >>> op = dpf.operators.metadata.cyclic_support_provider()\n >>> op.inputs.data_sources.connect(my_data_sources)\n >>> #or\n >>> op.inputs.data_sources(my_data_sources)\n\n ' return self._data_sources
Allows to connect data_sources input to the operator - pindoc: data sources containing the result file. Parameters ---------- my_data_sources : DataSources, Examples -------- >>> from ansys.dpf import core as dpf >>> op = dpf.operators.metadata.cyclic_support_provider() >>> op.inputs.data_sources.connect(my_data_sources) >>> #or >>> op.inputs.data_sources(my_data_sources)
ansys/dpf/core/operators/metadata/cyclic_support_provider.py
data_sources
TheGoldfish01/pydpf-core
11
python
@property def data_sources(self): 'Allows to connect data_sources input to the operator\n\n - pindoc: data sources containing the result file.\n\n Parameters\n ----------\n my_data_sources : DataSources, \n\n Examples\n --------\n >>> from ansys.dpf import core as dpf\n\n >>> op = dpf.operators.metadata.cyclic_support_provider()\n >>> op.inputs.data_sources.connect(my_data_sources)\n >>> #or\n >>> op.inputs.data_sources(my_data_sources)\n\n ' return self._data_sources
@property def data_sources(self): 'Allows to connect data_sources input to the operator\n\n - pindoc: data sources containing the result file.\n\n Parameters\n ----------\n my_data_sources : DataSources, \n\n Examples\n --------\n >>> from ansys.dpf import core as dpf\n\n >>> op = dpf.operators.metadata.cyclic_support_provider()\n >>> op.inputs.data_sources.connect(my_data_sources)\n >>> #or\n >>> op.inputs.data_sources(my_data_sources)\n\n ' return self._data_sources<|docstring|>Allows to connect data_sources input to the operator - pindoc: data sources containing the result file. Parameters ---------- my_data_sources : DataSources, Examples -------- >>> from ansys.dpf import core as dpf >>> op = dpf.operators.metadata.cyclic_support_provider() >>> op.inputs.data_sources.connect(my_data_sources) >>> #or >>> op.inputs.data_sources(my_data_sources)<|endoftext|>
cd2c319f03179a268f0a81fdbca3daac1900dd6a3adafafd9e7066ccc5fadc8d
@property def sector_meshed_region(self): 'Allows to connect sector_meshed_region input to the operator\n\n - pindoc: mesh of the first sector.\n\n Parameters\n ----------\n my_sector_meshed_region : MeshedRegion, MeshesContainer, \n\n Examples\n --------\n >>> from ansys.dpf import core as dpf\n\n >>> op = dpf.operators.metadata.cyclic_support_provider()\n >>> op.inputs.sector_meshed_region.connect(my_sector_meshed_region)\n >>> #or\n >>> op.inputs.sector_meshed_region(my_sector_meshed_region)\n\n ' return self._sector_meshed_region
Allows to connect sector_meshed_region input to the operator - pindoc: mesh of the first sector. Parameters ---------- my_sector_meshed_region : MeshedRegion, MeshesContainer, Examples -------- >>> from ansys.dpf import core as dpf >>> op = dpf.operators.metadata.cyclic_support_provider() >>> op.inputs.sector_meshed_region.connect(my_sector_meshed_region) >>> #or >>> op.inputs.sector_meshed_region(my_sector_meshed_region)
ansys/dpf/core/operators/metadata/cyclic_support_provider.py
sector_meshed_region
TheGoldfish01/pydpf-core
11
python
@property def sector_meshed_region(self): 'Allows to connect sector_meshed_region input to the operator\n\n - pindoc: mesh of the first sector.\n\n Parameters\n ----------\n my_sector_meshed_region : MeshedRegion, MeshesContainer, \n\n Examples\n --------\n >>> from ansys.dpf import core as dpf\n\n >>> op = dpf.operators.metadata.cyclic_support_provider()\n >>> op.inputs.sector_meshed_region.connect(my_sector_meshed_region)\n >>> #or\n >>> op.inputs.sector_meshed_region(my_sector_meshed_region)\n\n ' return self._sector_meshed_region
@property def sector_meshed_region(self): 'Allows to connect sector_meshed_region input to the operator\n\n - pindoc: mesh of the first sector.\n\n Parameters\n ----------\n my_sector_meshed_region : MeshedRegion, MeshesContainer, \n\n Examples\n --------\n >>> from ansys.dpf import core as dpf\n\n >>> op = dpf.operators.metadata.cyclic_support_provider()\n >>> op.inputs.sector_meshed_region.connect(my_sector_meshed_region)\n >>> #or\n >>> op.inputs.sector_meshed_region(my_sector_meshed_region)\n\n ' return self._sector_meshed_region<|docstring|>Allows to connect sector_meshed_region input to the operator - pindoc: mesh of the first sector. Parameters ---------- my_sector_meshed_region : MeshedRegion, MeshesContainer, Examples -------- >>> from ansys.dpf import core as dpf >>> op = dpf.operators.metadata.cyclic_support_provider() >>> op.inputs.sector_meshed_region.connect(my_sector_meshed_region) >>> #or >>> op.inputs.sector_meshed_region(my_sector_meshed_region)<|endoftext|>
b943585ad44517f0a9f35fd682a1031302e06df21e74b9039785ff1c42129a5f
@property def expanded_meshed_region(self): 'Allows to connect expanded_meshed_region input to the operator\n\n - pindoc: if this pin is set, expanding the mesh is not necessary.\n\n Parameters\n ----------\n my_expanded_meshed_region : MeshedRegion, MeshesContainer, \n\n Examples\n --------\n >>> from ansys.dpf import core as dpf\n\n >>> op = dpf.operators.metadata.cyclic_support_provider()\n >>> op.inputs.expanded_meshed_region.connect(my_expanded_meshed_region)\n >>> #or\n >>> op.inputs.expanded_meshed_region(my_expanded_meshed_region)\n\n ' return self._expanded_meshed_region
Allows to connect expanded_meshed_region input to the operator - pindoc: if this pin is set, expanding the mesh is not necessary. Parameters ---------- my_expanded_meshed_region : MeshedRegion, MeshesContainer, Examples -------- >>> from ansys.dpf import core as dpf >>> op = dpf.operators.metadata.cyclic_support_provider() >>> op.inputs.expanded_meshed_region.connect(my_expanded_meshed_region) >>> #or >>> op.inputs.expanded_meshed_region(my_expanded_meshed_region)
ansys/dpf/core/operators/metadata/cyclic_support_provider.py
expanded_meshed_region
TheGoldfish01/pydpf-core
11
python
@property def expanded_meshed_region(self): 'Allows to connect expanded_meshed_region input to the operator\n\n - pindoc: if this pin is set, expanding the mesh is not necessary.\n\n Parameters\n ----------\n my_expanded_meshed_region : MeshedRegion, MeshesContainer, \n\n Examples\n --------\n >>> from ansys.dpf import core as dpf\n\n >>> op = dpf.operators.metadata.cyclic_support_provider()\n >>> op.inputs.expanded_meshed_region.connect(my_expanded_meshed_region)\n >>> #or\n >>> op.inputs.expanded_meshed_region(my_expanded_meshed_region)\n\n ' return self._expanded_meshed_region
@property def expanded_meshed_region(self): 'Allows to connect expanded_meshed_region input to the operator\n\n - pindoc: if this pin is set, expanding the mesh is not necessary.\n\n Parameters\n ----------\n my_expanded_meshed_region : MeshedRegion, MeshesContainer, \n\n Examples\n --------\n >>> from ansys.dpf import core as dpf\n\n >>> op = dpf.operators.metadata.cyclic_support_provider()\n >>> op.inputs.expanded_meshed_region.connect(my_expanded_meshed_region)\n >>> #or\n >>> op.inputs.expanded_meshed_region(my_expanded_meshed_region)\n\n ' return self._expanded_meshed_region<|docstring|>Allows to connect expanded_meshed_region input to the operator - pindoc: if this pin is set, expanding the mesh is not necessary. Parameters ---------- my_expanded_meshed_region : MeshedRegion, MeshesContainer, Examples -------- >>> from ansys.dpf import core as dpf >>> op = dpf.operators.metadata.cyclic_support_provider() >>> op.inputs.expanded_meshed_region.connect(my_expanded_meshed_region) >>> #or >>> op.inputs.expanded_meshed_region(my_expanded_meshed_region)<|endoftext|>
d9adb87f252c0069adce25cbe8ba40f6f92d86cc4f8434c1263ed5a31867f693
@property def sectors_to_expand(self): "Allows to connect sectors_to_expand input to the operator\n\n - pindoc: sectors to expand (start at 0), for multistage: use scopings container with 'stage' label.\n\n Parameters\n ----------\n my_sectors_to_expand : Scoping, ScopingsContainer, list, \n\n Examples\n --------\n >>> from ansys.dpf import core as dpf\n\n >>> op = dpf.operators.metadata.cyclic_support_provider()\n >>> op.inputs.sectors_to_expand.connect(my_sectors_to_expand)\n >>> #or\n >>> op.inputs.sectors_to_expand(my_sectors_to_expand)\n\n " return self._sectors_to_expand
Allows to connect sectors_to_expand input to the operator - pindoc: sectors to expand (start at 0), for multistage: use scopings container with 'stage' label. Parameters ---------- my_sectors_to_expand : Scoping, ScopingsContainer, list, Examples -------- >>> from ansys.dpf import core as dpf >>> op = dpf.operators.metadata.cyclic_support_provider() >>> op.inputs.sectors_to_expand.connect(my_sectors_to_expand) >>> #or >>> op.inputs.sectors_to_expand(my_sectors_to_expand)
ansys/dpf/core/operators/metadata/cyclic_support_provider.py
sectors_to_expand
TheGoldfish01/pydpf-core
11
python
@property def sectors_to_expand(self): "Allows to connect sectors_to_expand input to the operator\n\n - pindoc: sectors to expand (start at 0), for multistage: use scopings container with 'stage' label.\n\n Parameters\n ----------\n my_sectors_to_expand : Scoping, ScopingsContainer, list, \n\n Examples\n --------\n >>> from ansys.dpf import core as dpf\n\n >>> op = dpf.operators.metadata.cyclic_support_provider()\n >>> op.inputs.sectors_to_expand.connect(my_sectors_to_expand)\n >>> #or\n >>> op.inputs.sectors_to_expand(my_sectors_to_expand)\n\n " return self._sectors_to_expand
@property def sectors_to_expand(self): "Allows to connect sectors_to_expand input to the operator\n\n - pindoc: sectors to expand (start at 0), for multistage: use scopings container with 'stage' label.\n\n Parameters\n ----------\n my_sectors_to_expand : Scoping, ScopingsContainer, list, \n\n Examples\n --------\n >>> from ansys.dpf import core as dpf\n\n >>> op = dpf.operators.metadata.cyclic_support_provider()\n >>> op.inputs.sectors_to_expand.connect(my_sectors_to_expand)\n >>> #or\n >>> op.inputs.sectors_to_expand(my_sectors_to_expand)\n\n " return self._sectors_to_expand<|docstring|>Allows to connect sectors_to_expand input to the operator - pindoc: sectors to expand (start at 0), for multistage: use scopings container with 'stage' label. Parameters ---------- my_sectors_to_expand : Scoping, ScopingsContainer, list, Examples -------- >>> from ansys.dpf import core as dpf >>> op = dpf.operators.metadata.cyclic_support_provider() >>> op.inputs.sectors_to_expand.connect(my_sectors_to_expand) >>> #or >>> op.inputs.sectors_to_expand(my_sectors_to_expand)<|endoftext|>
e0af73fcce3b0875cd8007be40400f76f8a634ccc7a0543eaa24828e1bbcca53
@property def cyclic_support(self): 'Allows to get cyclic_support output of the operator\n\n\n Returns\n ----------\n my_cyclic_support : CyclicSupport, \n\n Examples\n --------\n >>> from ansys.dpf import core as dpf\n\n >>> op = dpf.operators.metadata.cyclic_support_provider()\n >>> # Connect inputs : op.inputs. ...\n >>> result_cyclic_support = op.outputs.cyclic_support() \n ' return self._cyclic_support
Allows to get cyclic_support output of the operator Returns ---------- my_cyclic_support : CyclicSupport, Examples -------- >>> from ansys.dpf import core as dpf >>> op = dpf.operators.metadata.cyclic_support_provider() >>> # Connect inputs : op.inputs. ... >>> result_cyclic_support = op.outputs.cyclic_support()
ansys/dpf/core/operators/metadata/cyclic_support_provider.py
cyclic_support
TheGoldfish01/pydpf-core
11
python
@property def cyclic_support(self): 'Allows to get cyclic_support output of the operator\n\n\n Returns\n ----------\n my_cyclic_support : CyclicSupport, \n\n Examples\n --------\n >>> from ansys.dpf import core as dpf\n\n >>> op = dpf.operators.metadata.cyclic_support_provider()\n >>> # Connect inputs : op.inputs. ...\n >>> result_cyclic_support = op.outputs.cyclic_support() \n ' return self._cyclic_support
@property def cyclic_support(self): 'Allows to get cyclic_support output of the operator\n\n\n Returns\n ----------\n my_cyclic_support : CyclicSupport, \n\n Examples\n --------\n >>> from ansys.dpf import core as dpf\n\n >>> op = dpf.operators.metadata.cyclic_support_provider()\n >>> # Connect inputs : op.inputs. ...\n >>> result_cyclic_support = op.outputs.cyclic_support() \n ' return self._cyclic_support<|docstring|>Allows to get cyclic_support output of the operator Returns ---------- my_cyclic_support : CyclicSupport, Examples -------- >>> from ansys.dpf import core as dpf >>> op = dpf.operators.metadata.cyclic_support_provider() >>> # Connect inputs : op.inputs. ... >>> result_cyclic_support = op.outputs.cyclic_support()<|endoftext|>
462bb45cb3fd330a138d9a09ffec7c36d8bbe21d42e2f2d8c64f20e1cee96081
@property def sector_meshes(self): 'Allows to get sector_meshes output of the operator\n\n\n Returns\n ----------\n my_sector_meshes : MeshesContainer, \n\n Examples\n --------\n >>> from ansys.dpf import core as dpf\n\n >>> op = dpf.operators.metadata.cyclic_support_provider()\n >>> # Connect inputs : op.inputs. ...\n >>> result_sector_meshes = op.outputs.sector_meshes() \n ' return self._sector_meshes
Allows to get sector_meshes output of the operator Returns ---------- my_sector_meshes : MeshesContainer, Examples -------- >>> from ansys.dpf import core as dpf >>> op = dpf.operators.metadata.cyclic_support_provider() >>> # Connect inputs : op.inputs. ... >>> result_sector_meshes = op.outputs.sector_meshes()
ansys/dpf/core/operators/metadata/cyclic_support_provider.py
sector_meshes
TheGoldfish01/pydpf-core
11
python
@property def sector_meshes(self): 'Allows to get sector_meshes output of the operator\n\n\n Returns\n ----------\n my_sector_meshes : MeshesContainer, \n\n Examples\n --------\n >>> from ansys.dpf import core as dpf\n\n >>> op = dpf.operators.metadata.cyclic_support_provider()\n >>> # Connect inputs : op.inputs. ...\n >>> result_sector_meshes = op.outputs.sector_meshes() \n ' return self._sector_meshes
@property def sector_meshes(self): 'Allows to get sector_meshes output of the operator\n\n\n Returns\n ----------\n my_sector_meshes : MeshesContainer, \n\n Examples\n --------\n >>> from ansys.dpf import core as dpf\n\n >>> op = dpf.operators.metadata.cyclic_support_provider()\n >>> # Connect inputs : op.inputs. ...\n >>> result_sector_meshes = op.outputs.sector_meshes() \n ' return self._sector_meshes<|docstring|>Allows to get sector_meshes output of the operator Returns ---------- my_sector_meshes : MeshesContainer, Examples -------- >>> from ansys.dpf import core as dpf >>> op = dpf.operators.metadata.cyclic_support_provider() >>> # Connect inputs : op.inputs. ... >>> result_sector_meshes = op.outputs.sector_meshes()<|endoftext|>
a26a7c5af083b251adbf871f5053502eaea61a2dea5bdddfe6d6de02c8e4d186
def __init__(self, name, type_, ext=None, conf=None, url=None, classifier=None): "Initializes a new artifact specification.\n\n name: The name of the published artifact. This name must not include revision.\n type_: The type of the published artifact. It's usually its extension, but not necessarily.\n For instance, ivy files are of type 'ivy' but have 'xml' extension.\n ext: The extension of the published artifact.\n conf: The public configuration in which this artifact is published. The '*' wildcard can\n be used to designate all public configurations.\n url: The url at which this artifact can be found if it isn't located at the standard\n location in the repository\n classifier: The maven classifier of this artifact.\n " self.name = name self.type_ = type_ self.ext = ext self.conf = conf self.url = url self.classifier = classifier
Initializes a new artifact specification. name: The name of the published artifact. This name must not include revision. type_: The type of the published artifact. It's usually its extension, but not necessarily. For instance, ivy files are of type 'ivy' but have 'xml' extension. ext: The extension of the published artifact. conf: The public configuration in which this artifact is published. The '*' wildcard can be used to designate all public configurations. url: The url at which this artifact can be found if it isn't located at the standard location in the repository classifier: The maven classifier of this artifact.
src/python/twitter/pants/targets/jar_dependency.py
__init__
wfarner/commons
1
python
def __init__(self, name, type_, ext=None, conf=None, url=None, classifier=None): "Initializes a new artifact specification.\n\n name: The name of the published artifact. This name must not include revision.\n type_: The type of the published artifact. It's usually its extension, but not necessarily.\n For instance, ivy files are of type 'ivy' but have 'xml' extension.\n ext: The extension of the published artifact.\n conf: The public configuration in which this artifact is published. The '*' wildcard can\n be used to designate all public configurations.\n url: The url at which this artifact can be found if it isn't located at the standard\n location in the repository\n classifier: The maven classifier of this artifact.\n " self.name = name self.type_ = type_ self.ext = ext self.conf = conf self.url = url self.classifier = classifier
def __init__(self, name, type_, ext=None, conf=None, url=None, classifier=None): "Initializes a new artifact specification.\n\n name: The name of the published artifact. This name must not include revision.\n type_: The type of the published artifact. It's usually its extension, but not necessarily.\n For instance, ivy files are of type 'ivy' but have 'xml' extension.\n ext: The extension of the published artifact.\n conf: The public configuration in which this artifact is published. The '*' wildcard can\n be used to designate all public configurations.\n url: The url at which this artifact can be found if it isn't located at the standard\n location in the repository\n classifier: The maven classifier of this artifact.\n " self.name = name self.type_ = type_ self.ext = ext self.conf = conf self.url = url self.classifier = classifier<|docstring|>Initializes a new artifact specification. name: The name of the published artifact. This name must not include revision. type_: The type of the published artifact. It's usually its extension, but not necessarily. For instance, ivy files are of type 'ivy' but have 'xml' extension. ext: The extension of the published artifact. conf: The public configuration in which this artifact is published. The '*' wildcard can be used to designate all public configurations. url: The url at which this artifact can be found if it isn't located at the standard location in the repository classifier: The maven classifier of this artifact.<|endoftext|>
46aaf56cd8f6ddcb140a6b424a155b8a96814cd3a15efc3cdd94b8b909c85af8
def exclude(self, org, name=None): 'Adds a transitive dependency of this jar to the exclude list.' self.excludes.append(Exclude(org, name)) return self
Adds a transitive dependency of this jar to the exclude list.
src/python/twitter/pants/targets/jar_dependency.py
exclude
wfarner/commons
1
python
def exclude(self, org, name=None): self.excludes.append(Exclude(org, name)) return self
def exclude(self, org, name=None): self.excludes.append(Exclude(org, name)) return self<|docstring|>Adds a transitive dependency of this jar to the exclude list.<|endoftext|>
d3891bf8628758d1f3272f0fc1950e8b6dafa813ec3a6dd5951ecc5e1198b808
def intransitive(self): 'Declares this Dependency intransitive, indicating only the jar for the dependency itself\n should be downloaded and placed on the classpath' self.transitive = False return self
Declares this Dependency intransitive, indicating only the jar for the dependency itself should be downloaded and placed on the classpath
src/python/twitter/pants/targets/jar_dependency.py
intransitive
wfarner/commons
1
python
def intransitive(self): 'Declares this Dependency intransitive, indicating only the jar for the dependency itself\n should be downloaded and placed on the classpath' self.transitive = False return self
def intransitive(self): 'Declares this Dependency intransitive, indicating only the jar for the dependency itself\n should be downloaded and placed on the classpath' self.transitive = False return self<|docstring|>Declares this Dependency intransitive, indicating only the jar for the dependency itself should be downloaded and placed on the classpath<|endoftext|>
4ab891c199d5766c0a571879caa2e28259eaf4800a091abcf4ef3eb5304b74e0
def with_artifact(self, name=None, type_=None, ext=None, url=None, configuration=None, classifier=None): 'Sets an alternative artifact to fetch or adds additional artifacts if called multiple times.\n ' artifact = Artifact((name or self.name), (type_ or 'jar'), ext=ext, url=url, conf=configuration, classifier=classifier) self.artifacts.append(artifact) return self
Sets an alternative artifact to fetch or adds additional artifacts if called multiple times.
src/python/twitter/pants/targets/jar_dependency.py
with_artifact
wfarner/commons
1
python
def with_artifact(self, name=None, type_=None, ext=None, url=None, configuration=None, classifier=None): '\n ' artifact = Artifact((name or self.name), (type_ or 'jar'), ext=ext, url=url, conf=configuration, classifier=classifier) self.artifacts.append(artifact) return self
def with_artifact(self, name=None, type_=None, ext=None, url=None, configuration=None, classifier=None): '\n ' artifact = Artifact((name or self.name), (type_ or 'jar'), ext=ext, url=url, conf=configuration, classifier=classifier) self.artifacts.append(artifact) return self<|docstring|>Sets an alternative artifact to fetch or adds additional artifacts if called multiple times.<|endoftext|>
77425b60e9026e5eee33a83fe75a58e3e66f2d3995c0c661ee478a9e318bbd56
def error(file: str, line: int=0, col: int=0, message: str='error', warn: bool=False) -> None: 'write an error to stdout' kind = ('warning' if warn else 'error') print(f'::{kind} file={file},line={line},col={col}::{message}')
write an error to stdout
.github/workflows/github.py
error
vainl/wechatpy
2,428
python
def error(file: str, line: int=0, col: int=0, message: str='error', warn: bool=False) -> None: kind = ('warning' if warn else 'error') print(f'::{kind} file={file},line={line},col={col}::{message}')
def error(file: str, line: int=0, col: int=0, message: str='error', warn: bool=False) -> None: kind = ('warning' if warn else 'error') print(f'::{kind} file={file},line={line},col={col}::{message}')<|docstring|>write an error to stdout<|endoftext|>
94a77141871501b28f9c80e40e5dbc5d3cace1e1f0fceaa205423d5160738230
def main(file_path: str) -> None: 'read the given file, and print errors' data = '' with open(file_path) as file: data = file.read() for line in data.split('\n'): match = MYPY.match(line) if match: values = match.groupdict() error(values['file'], line=int(values['line']), col=int(values['col']), message=values['msg'])
read the given file, and print errors
.github/workflows/github.py
main
vainl/wechatpy
2,428
python
def main(file_path: str) -> None: data = with open(file_path) as file: data = file.read() for line in data.split('\n'): match = MYPY.match(line) if match: values = match.groupdict() error(values['file'], line=int(values['line']), col=int(values['col']), message=values['msg'])
def main(file_path: str) -> None: data = with open(file_path) as file: data = file.read() for line in data.split('\n'): match = MYPY.match(line) if match: values = match.groupdict() error(values['file'], line=int(values['line']), col=int(values['col']), message=values['msg'])<|docstring|>read the given file, and print errors<|endoftext|>
16d46a85b67e3fe55f232574db383f8f29928f90a5b9e9ac2a4851e24f423beb
def to_glow(model, method_compile_spec): 'Lower a model to Glow\n\n to_glow is a wrapper around the torch._C._jit_to_backend which lowers the\n the specified module `mod` to Glow using the the MethodCompileSpec\n `method_compile_spec`. MethodCompileSpec is a dictionary from method name\n in `mod` such as \'forward\' to GlowCompileSpec for that method\n\n Args:\n model: Model to be lowered to glow\n specs_and_examples: Either a dicionary from method name to\n GlowCompileSpec or just a GlowCompileSpec and method\n name is assumed to be "forward"\n\n Return:\n A copy of the model that has been lowered to Glow and will run on\n Glow backend devices\n ' if isinstance(method_compile_spec, collections.Mapping): for (k, v) in method_compile_spec.items(): if (not isinstance(v, list)): method_compile_spec[k] = [v] elif isinstance(method_compile_spec, list): method_compile_spec = {'forward', method_compile_spec} else: method_compile_spec = {'forward', [method_compile_spec]} return torch._C._jit_to_backend('glow', model._c, method_compile_spec)
Lower a model to Glow to_glow is a wrapper around the torch._C._jit_to_backend which lowers the the specified module `mod` to Glow using the the MethodCompileSpec `method_compile_spec`. MethodCompileSpec is a dictionary from method name in `mod` such as 'forward' to GlowCompileSpec for that method Args: model: Model to be lowered to glow specs_and_examples: Either a dicionary from method name to GlowCompileSpec or just a GlowCompileSpec and method name is assumed to be "forward" Return: A copy of the model that has been lowered to Glow and will run on Glow backend devices
torch_glow/torch_glow/to_glow.py
to_glow
truthiswill/glow
0
python
def to_glow(model, method_compile_spec): 'Lower a model to Glow\n\n to_glow is a wrapper around the torch._C._jit_to_backend which lowers the\n the specified module `mod` to Glow using the the MethodCompileSpec\n `method_compile_spec`. MethodCompileSpec is a dictionary from method name\n in `mod` such as \'forward\' to GlowCompileSpec for that method\n\n Args:\n model: Model to be lowered to glow\n specs_and_examples: Either a dicionary from method name to\n GlowCompileSpec or just a GlowCompileSpec and method\n name is assumed to be "forward"\n\n Return:\n A copy of the model that has been lowered to Glow and will run on\n Glow backend devices\n ' if isinstance(method_compile_spec, collections.Mapping): for (k, v) in method_compile_spec.items(): if (not isinstance(v, list)): method_compile_spec[k] = [v] elif isinstance(method_compile_spec, list): method_compile_spec = {'forward', method_compile_spec} else: method_compile_spec = {'forward', [method_compile_spec]} return torch._C._jit_to_backend('glow', model._c, method_compile_spec)
def to_glow(model, method_compile_spec): 'Lower a model to Glow\n\n to_glow is a wrapper around the torch._C._jit_to_backend which lowers the\n the specified module `mod` to Glow using the the MethodCompileSpec\n `method_compile_spec`. MethodCompileSpec is a dictionary from method name\n in `mod` such as \'forward\' to GlowCompileSpec for that method\n\n Args:\n model: Model to be lowered to glow\n specs_and_examples: Either a dicionary from method name to\n GlowCompileSpec or just a GlowCompileSpec and method\n name is assumed to be "forward"\n\n Return:\n A copy of the model that has been lowered to Glow and will run on\n Glow backend devices\n ' if isinstance(method_compile_spec, collections.Mapping): for (k, v) in method_compile_spec.items(): if (not isinstance(v, list)): method_compile_spec[k] = [v] elif isinstance(method_compile_spec, list): method_compile_spec = {'forward', method_compile_spec} else: method_compile_spec = {'forward', [method_compile_spec]} return torch._C._jit_to_backend('glow', model._c, method_compile_spec)<|docstring|>Lower a model to Glow to_glow is a wrapper around the torch._C._jit_to_backend which lowers the the specified module `mod` to Glow using the the MethodCompileSpec `method_compile_spec`. MethodCompileSpec is a dictionary from method name in `mod` such as 'forward' to GlowCompileSpec for that method Args: model: Model to be lowered to glow specs_and_examples: Either a dicionary from method name to GlowCompileSpec or just a GlowCompileSpec and method name is assumed to be "forward" Return: A copy of the model that has been lowered to Glow and will run on Glow backend devices<|endoftext|>
3269327e621ef8c39ae12dedee4783acb46c9fba2518a71e7399467ecfedcd7c
def check_module_names(module_names): "Checks that module names don't overlap at all" assert ('' not in module_names), 'Use to_glow to lower top level module' for path1 in module_names: for path2 in module_names: if (path1 == path2): continue assert (path1 not in path2), f"Can't to_glow a module nested inside another to_glow module, found {path2} inside of {path1}"
Checks that module names don't overlap at all
torch_glow/torch_glow/to_glow.py
check_module_names
truthiswill/glow
0
python
def check_module_names(module_names): assert ( not in module_names), 'Use to_glow to lower top level module' for path1 in module_names: for path2 in module_names: if (path1 == path2): continue assert (path1 not in path2), f"Can't to_glow a module nested inside another to_glow module, found {path2} inside of {path1}"
def check_module_names(module_names): assert ( not in module_names), 'Use to_glow to lower top level module' for path1 in module_names: for path2 in module_names: if (path1 == path2): continue assert (path1 not in path2), f"Can't to_glow a module nested inside another to_glow module, found {path2} inside of {path1}"<|docstring|>Checks that module names don't overlap at all<|endoftext|>
b67423d0139da39b054cc15e8cefc5d7d9119cb4d5248133db4aa89fd6e7ec9d
def to_glow_selective(model, specs_and_examples, inplace=False): 'Selectively lowers submodules of the given module to Glow.\n\n Instead of using to_glow to lower an entire module to Glow,\n to_glow_selective can be used to selective find and replace submodules in\n the given module with a version of the module that is traced and lowered\n to Glow. Each specified submodule is lowered independently and so will be\n a separate compilation unit in Glow.\n\n Args:\n model: top-level model to be selectively lowered\n specs_and_examples: A dictionary with keys that name submodules\n recursively from model and values that are either\n dicionaries from method name to tuple of\n GlowCompileSpec used for calling to_glow and example\n inputs used for tracing or just that tuple without\n the method name and method name is assumed to be\n "forward"\n inplace: Carry out model transformations in-place, the original module\n is mutated\n\n Return:\n Model with selectively lowered submodules\n ' check_module_names(list(specs_and_examples.keys())) if (not inplace): model = copy.deepcopy(model) for (path, per_module_info) in specs_and_examples.items(): if isinstance(per_module_info, collections.Mapping): assert ((len(per_module_info) == 1) and ('forward' in per_module_info)), 'Only forward method is supported by to_glow_selective for now' (spec, example_inputs) = per_module_info['forward'] elif isinstance(per_module_info, tuple): (spec, example_inputs) = per_module_info else: raise ValueError("For each submodule, to_glow_selective expects either a dictionary of method name -> (GlowCompileSpec, example_inputs) or just\n (GlowCompileSpec, example_inputs) and 'forward' method is assumed") submod = get_submodule(model, path) submod = torch.jit.trace(submod, example_inputs) submod = to_glow(submod, {'forward': spec}) set_submodule(model, path, submod) return model
Selectively lowers submodules of the given module to Glow. Instead of using to_glow to lower an entire module to Glow, to_glow_selective can be used to selective find and replace submodules in the given module with a version of the module that is traced and lowered to Glow. Each specified submodule is lowered independently and so will be a separate compilation unit in Glow. Args: model: top-level model to be selectively lowered specs_and_examples: A dictionary with keys that name submodules recursively from model and values that are either dicionaries from method name to tuple of GlowCompileSpec used for calling to_glow and example inputs used for tracing or just that tuple without the method name and method name is assumed to be "forward" inplace: Carry out model transformations in-place, the original module is mutated Return: Model with selectively lowered submodules
torch_glow/torch_glow/to_glow.py
to_glow_selective
truthiswill/glow
0
python
def to_glow_selective(model, specs_and_examples, inplace=False): 'Selectively lowers submodules of the given module to Glow.\n\n Instead of using to_glow to lower an entire module to Glow,\n to_glow_selective can be used to selective find and replace submodules in\n the given module with a version of the module that is traced and lowered\n to Glow. Each specified submodule is lowered independently and so will be\n a separate compilation unit in Glow.\n\n Args:\n model: top-level model to be selectively lowered\n specs_and_examples: A dictionary with keys that name submodules\n recursively from model and values that are either\n dicionaries from method name to tuple of\n GlowCompileSpec used for calling to_glow and example\n inputs used for tracing or just that tuple without\n the method name and method name is assumed to be\n "forward"\n inplace: Carry out model transformations in-place, the original module\n is mutated\n\n Return:\n Model with selectively lowered submodules\n ' check_module_names(list(specs_and_examples.keys())) if (not inplace): model = copy.deepcopy(model) for (path, per_module_info) in specs_and_examples.items(): if isinstance(per_module_info, collections.Mapping): assert ((len(per_module_info) == 1) and ('forward' in per_module_info)), 'Only forward method is supported by to_glow_selective for now' (spec, example_inputs) = per_module_info['forward'] elif isinstance(per_module_info, tuple): (spec, example_inputs) = per_module_info else: raise ValueError("For each submodule, to_glow_selective expects either a dictionary of method name -> (GlowCompileSpec, example_inputs) or just\n (GlowCompileSpec, example_inputs) and 'forward' method is assumed") submod = get_submodule(model, path) submod = torch.jit.trace(submod, example_inputs) submod = to_glow(submod, {'forward': spec}) set_submodule(model, path, submod) return model
def to_glow_selective(model, specs_and_examples, inplace=False): 'Selectively lowers submodules of the given module to Glow.\n\n Instead of using to_glow to lower an entire module to Glow,\n to_glow_selective can be used to selective find and replace submodules in\n the given module with a version of the module that is traced and lowered\n to Glow. Each specified submodule is lowered independently and so will be\n a separate compilation unit in Glow.\n\n Args:\n model: top-level model to be selectively lowered\n specs_and_examples: A dictionary with keys that name submodules\n recursively from model and values that are either\n dicionaries from method name to tuple of\n GlowCompileSpec used for calling to_glow and example\n inputs used for tracing or just that tuple without\n the method name and method name is assumed to be\n "forward"\n inplace: Carry out model transformations in-place, the original module\n is mutated\n\n Return:\n Model with selectively lowered submodules\n ' check_module_names(list(specs_and_examples.keys())) if (not inplace): model = copy.deepcopy(model) for (path, per_module_info) in specs_and_examples.items(): if isinstance(per_module_info, collections.Mapping): assert ((len(per_module_info) == 1) and ('forward' in per_module_info)), 'Only forward method is supported by to_glow_selective for now' (spec, example_inputs) = per_module_info['forward'] elif isinstance(per_module_info, tuple): (spec, example_inputs) = per_module_info else: raise ValueError("For each submodule, to_glow_selective expects either a dictionary of method name -> (GlowCompileSpec, example_inputs) or just\n (GlowCompileSpec, example_inputs) and 'forward' method is assumed") submod = get_submodule(model, path) submod = torch.jit.trace(submod, example_inputs) submod = to_glow(submod, {'forward': spec}) set_submodule(model, path, submod) return model<|docstring|>Selectively lowers submodules of the given module to Glow. Instead of using to_glow to lower an entire module to Glow, to_glow_selective can be used to selective find and replace submodules in the given module with a version of the module that is traced and lowered to Glow. Each specified submodule is lowered independently and so will be a separate compilation unit in Glow. Args: model: top-level model to be selectively lowered specs_and_examples: A dictionary with keys that name submodules recursively from model and values that are either dicionaries from method name to tuple of GlowCompileSpec used for calling to_glow and example inputs used for tracing or just that tuple without the method name and method name is assumed to be "forward" inplace: Carry out model transformations in-place, the original module is mutated Return: Model with selectively lowered submodules<|endoftext|>
0fe541690206b5f41484ab50207ead5dfee9b96aa996f8adfb3f905a96e1efbf
def randcorr(n, dof=None): '\n Return a random correlation matrix of order `n` and rank `dof`.\n\n Written by Robert Kern and taken from \n http://permalink.gmane.org/gmane.comp.python.scientific.devel/9657\n ' if (dof is None): dof = n vecs = np.random.randn(n, dof) vecs /= np.sqrt((vecs * vecs).sum(axis=(- 1)))[(:, None)] M = np.matrix(np.dot(vecs, vecs.T)) np.fill_diagonal(M, 1) return M
Return a random correlation matrix of order `n` and rank `dof`. Written by Robert Kern and taken from http://permalink.gmane.org/gmane.comp.python.scientific.devel/9657
test_shrink.py
randcorr
vsego/shrinking
1
python
def randcorr(n, dof=None): '\n Return a random correlation matrix of order `n` and rank `dof`.\n\n Written by Robert Kern and taken from \n http://permalink.gmane.org/gmane.comp.python.scientific.devel/9657\n ' if (dof is None): dof = n vecs = np.random.randn(n, dof) vecs /= np.sqrt((vecs * vecs).sum(axis=(- 1)))[(:, None)] M = np.matrix(np.dot(vecs, vecs.T)) np.fill_diagonal(M, 1) return M
def randcorr(n, dof=None): '\n Return a random correlation matrix of order `n` and rank `dof`.\n\n Written by Robert Kern and taken from \n http://permalink.gmane.org/gmane.comp.python.scientific.devel/9657\n ' if (dof is None): dof = n vecs = np.random.randn(n, dof) vecs /= np.sqrt((vecs * vecs).sum(axis=(- 1)))[(:, None)] M = np.matrix(np.dot(vecs, vecs.T)) np.fill_diagonal(M, 1) return M<|docstring|>Return a random correlation matrix of order `n` and rank `dof`. Written by Robert Kern and taken from http://permalink.gmane.org/gmane.comp.python.scientific.devel/9657<|endoftext|>
413857db48f399339ca9aa3d44e83dcafb58c023c453a6b17e929fb3bb99f4ae
def mkmatrix(m, n): '\n Return a random invalid correlation matrix of order `m+n` with\n a positive definite top left block of order `m`.\n ' while True: A = randcorr(m) B = np.identity(n) Y = np.matrix((np.random.randn(m, n) / ((m + n) ** 1.2))) M0 = np.bmat([[A, Y], [Y.T, B]]) if (not shrinking.checkPD(M0, False)): return M0
Return a random invalid correlation matrix of order `m+n` with a positive definite top left block of order `m`.
test_shrink.py
mkmatrix
vsego/shrinking
1
python
def mkmatrix(m, n): '\n Return a random invalid correlation matrix of order `m+n` with\n a positive definite top left block of order `m`.\n ' while True: A = randcorr(m) B = np.identity(n) Y = np.matrix((np.random.randn(m, n) / ((m + n) ** 1.2))) M0 = np.bmat([[A, Y], [Y.T, B]]) if (not shrinking.checkPD(M0, False)): return M0
def mkmatrix(m, n): '\n Return a random invalid correlation matrix of order `m+n` with\n a positive definite top left block of order `m`.\n ' while True: A = randcorr(m) B = np.identity(n) Y = np.matrix((np.random.randn(m, n) / ((m + n) ** 1.2))) M0 = np.bmat([[A, Y], [Y.T, B]]) if (not shrinking.checkPD(M0, False)): return M0<|docstring|>Return a random invalid correlation matrix of order `m+n` with a positive definite top left block of order `m`.<|endoftext|>
2c6d99e3b9d81583a9dedf6aa64b695fc45eb5b58c128c9dcd01f2c735280023
def run(m=10, n=10): '\n Run a single test:\n - generate a random invalid correlation matrix of order m+n,\n - shrink it with all 5 methods,\n - draw a graph :math:`\\alpha \\mapsto \\lambda_{\\min}(S(\\alpha))`.\n ' M0 = mkmatrix(m, n) st = time() print(('Bisection: %.6f (%.5f sec)' % (shrinking.bisection(M0, fbs=m), timing(st)))) st = time() print(('BisectionFB: %.6f (%.5f sec)' % (shrinking.bisectionFB(M0, fbSize=m), timing(st)))) st = time() print(('Newton: %.6f (%.5f sec)' % (shrinking.newton(M0, fbs=m), timing(st)))) st = time() print(('GEP: %.6f (%.5f sec)' % (shrinking.GEP(M0, fbs=m), timing(st)))) st = time() print(('GEPFB: %.6f (%.5f sec)' % (shrinking.GEPFB(M0, fbSize=m), timing(st)))) alphas = np.linspace(0, 1, 20) Svalues = np.array([list((scipy.linalg.eigvalsh(shrinking.SFB(M0, m, alpha), check_finite=False) for alpha in alphas))]).transpose() plt.plot(alphas, Svalues[0]) if (not displayOnlyLambdaMin): for p in range(1, n): plt.plot(alphas, Svalues[p], color='0.71') plt.axhline(color='black') alpha = shrinking.bisectionFB(M0, fbSize=m) plt.plot([alpha], [0], 'rD') plt.annotate('$\\alpha_*$', xy=(alpha, 0), xytext=((- 20), 20), textcoords='offset points', ha='right', va='bottom', bbox=dict(boxstyle='round,pad=0.5', fc='#ffffb0', alpha=0.7), arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0')) if displayOnlyLambdaMin: plt.legend(['$\\lambda_{\\min}$'], loc='lower right') else: plt.legend(['$\\lambda_{\\min}$', '$\\lambda > \\lambda_{\\min}$'], loc='lower right') (x1, x2, y1, y2) = plt.axis() plt.xlabel('$\\alpha$', fontsize=17) if displayOnlyLambdaMin: plt.suptitle('$\\alpha \\mapsto \\lambda_{\\min}(S(\\alpha))$', fontsize=23) plt.ylabel('$\\lambda_{\\min}(S(\\alpha))$', fontsize=17) else: plt.suptitle('$\\alpha \\mapsto \\lambda(S(\\alpha))$', fontsize=23) ym = max(map(abs, [Svalues[0][0], (10 * Svalues[0][(- 1)])])) plt.axis((x1, x2, Svalues[0][0], (5 * ym))) plt.ylabel('$\\lambda(S(\\alpha))$', fontsize=17) plt.subplots_adjust(left=0.17, right=0.97) plt.show()
Run a single test: - generate a random invalid correlation matrix of order m+n, - shrink it with all 5 methods, - draw a graph :math:`\alpha \mapsto \lambda_{\min}(S(\alpha))`.
test_shrink.py
run
vsego/shrinking
1
python
def run(m=10, n=10): '\n Run a single test:\n - generate a random invalid correlation matrix of order m+n,\n - shrink it with all 5 methods,\n - draw a graph :math:`\\alpha \\mapsto \\lambda_{\\min}(S(\\alpha))`.\n ' M0 = mkmatrix(m, n) st = time() print(('Bisection: %.6f (%.5f sec)' % (shrinking.bisection(M0, fbs=m), timing(st)))) st = time() print(('BisectionFB: %.6f (%.5f sec)' % (shrinking.bisectionFB(M0, fbSize=m), timing(st)))) st = time() print(('Newton: %.6f (%.5f sec)' % (shrinking.newton(M0, fbs=m), timing(st)))) st = time() print(('GEP: %.6f (%.5f sec)' % (shrinking.GEP(M0, fbs=m), timing(st)))) st = time() print(('GEPFB: %.6f (%.5f sec)' % (shrinking.GEPFB(M0, fbSize=m), timing(st)))) alphas = np.linspace(0, 1, 20) Svalues = np.array([list((scipy.linalg.eigvalsh(shrinking.SFB(M0, m, alpha), check_finite=False) for alpha in alphas))]).transpose() plt.plot(alphas, Svalues[0]) if (not displayOnlyLambdaMin): for p in range(1, n): plt.plot(alphas, Svalues[p], color='0.71') plt.axhline(color='black') alpha = shrinking.bisectionFB(M0, fbSize=m) plt.plot([alpha], [0], 'rD') plt.annotate('$\\alpha_*$', xy=(alpha, 0), xytext=((- 20), 20), textcoords='offset points', ha='right', va='bottom', bbox=dict(boxstyle='round,pad=0.5', fc='#ffffb0', alpha=0.7), arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0')) if displayOnlyLambdaMin: plt.legend(['$\\lambda_{\\min}$'], loc='lower right') else: plt.legend(['$\\lambda_{\\min}$', '$\\lambda > \\lambda_{\\min}$'], loc='lower right') (x1, x2, y1, y2) = plt.axis() plt.xlabel('$\\alpha$', fontsize=17) if displayOnlyLambdaMin: plt.suptitle('$\\alpha \\mapsto \\lambda_{\\min}(S(\\alpha))$', fontsize=23) plt.ylabel('$\\lambda_{\\min}(S(\\alpha))$', fontsize=17) else: plt.suptitle('$\\alpha \\mapsto \\lambda(S(\\alpha))$', fontsize=23) ym = max(map(abs, [Svalues[0][0], (10 * Svalues[0][(- 1)])])) plt.axis((x1, x2, Svalues[0][0], (5 * ym))) plt.ylabel('$\\lambda(S(\\alpha))$', fontsize=17) plt.subplots_adjust(left=0.17, right=0.97) plt.show()
def run(m=10, n=10): '\n Run a single test:\n - generate a random invalid correlation matrix of order m+n,\n - shrink it with all 5 methods,\n - draw a graph :math:`\\alpha \\mapsto \\lambda_{\\min}(S(\\alpha))`.\n ' M0 = mkmatrix(m, n) st = time() print(('Bisection: %.6f (%.5f sec)' % (shrinking.bisection(M0, fbs=m), timing(st)))) st = time() print(('BisectionFB: %.6f (%.5f sec)' % (shrinking.bisectionFB(M0, fbSize=m), timing(st)))) st = time() print(('Newton: %.6f (%.5f sec)' % (shrinking.newton(M0, fbs=m), timing(st)))) st = time() print(('GEP: %.6f (%.5f sec)' % (shrinking.GEP(M0, fbs=m), timing(st)))) st = time() print(('GEPFB: %.6f (%.5f sec)' % (shrinking.GEPFB(M0, fbSize=m), timing(st)))) alphas = np.linspace(0, 1, 20) Svalues = np.array([list((scipy.linalg.eigvalsh(shrinking.SFB(M0, m, alpha), check_finite=False) for alpha in alphas))]).transpose() plt.plot(alphas, Svalues[0]) if (not displayOnlyLambdaMin): for p in range(1, n): plt.plot(alphas, Svalues[p], color='0.71') plt.axhline(color='black') alpha = shrinking.bisectionFB(M0, fbSize=m) plt.plot([alpha], [0], 'rD') plt.annotate('$\\alpha_*$', xy=(alpha, 0), xytext=((- 20), 20), textcoords='offset points', ha='right', va='bottom', bbox=dict(boxstyle='round,pad=0.5', fc='#ffffb0', alpha=0.7), arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0')) if displayOnlyLambdaMin: plt.legend(['$\\lambda_{\\min}$'], loc='lower right') else: plt.legend(['$\\lambda_{\\min}$', '$\\lambda > \\lambda_{\\min}$'], loc='lower right') (x1, x2, y1, y2) = plt.axis() plt.xlabel('$\\alpha$', fontsize=17) if displayOnlyLambdaMin: plt.suptitle('$\\alpha \\mapsto \\lambda_{\\min}(S(\\alpha))$', fontsize=23) plt.ylabel('$\\lambda_{\\min}(S(\\alpha))$', fontsize=17) else: plt.suptitle('$\\alpha \\mapsto \\lambda(S(\\alpha))$', fontsize=23) ym = max(map(abs, [Svalues[0][0], (10 * Svalues[0][(- 1)])])) plt.axis((x1, x2, Svalues[0][0], (5 * ym))) plt.ylabel('$\\lambda(S(\\alpha))$', fontsize=17) plt.subplots_adjust(left=0.17, right=0.97) plt.show()<|docstring|>Run a single test: - generate a random invalid correlation matrix of order m+n, - shrink it with all 5 methods, - draw a graph :math:`\alpha \mapsto \lambda_{\min}(S(\alpha))`.<|endoftext|>
998b456d351012bb6c3eeb73bbf6a28ab3c729e065b4b8ce1b2eb6a3fe2f9bb4
@requires_auth def delete(self): 'Delete this label.\n\n :returns:\n True if successfully deleted, False otherwise\n :rtype:\n bool\n ' return self._boolean(self._delete(self._api), 204, 404)
Delete this label. :returns: True if successfully deleted, False otherwise :rtype: bool
github3/issues/label.py
delete
Stevoisiak/github3.py
0
python
@requires_auth def delete(self): 'Delete this label.\n\n :returns:\n True if successfully deleted, False otherwise\n :rtype:\n bool\n ' return self._boolean(self._delete(self._api), 204, 404)
@requires_auth def delete(self): 'Delete this label.\n\n :returns:\n True if successfully deleted, False otherwise\n :rtype:\n bool\n ' return self._boolean(self._delete(self._api), 204, 404)<|docstring|>Delete this label. :returns: True if successfully deleted, False otherwise :rtype: bool<|endoftext|>
36fd75aa40aaf928b7db1a5ced8b174c3b3cb642d2054dc29f48cd4bf31672ad
@requires_auth def update(self, name, color): "Update this label.\n\n :param str name:\n (required), new name of the label\n :param str color:\n (required), color code, e.g., 626262, no leading '#'\n :returns:\n True if successfully updated, False otherwise\n :rtype:\n bool\n " json = None if (name and color): if (color[0] == '#'): color = color[1:] json = self._json(self._patch(self._api, data=dumps({'name': name, 'color': color})), 200) if json: self._update_attributes(json) return True return False
Update this label. :param str name: (required), new name of the label :param str color: (required), color code, e.g., 626262, no leading '#' :returns: True if successfully updated, False otherwise :rtype: bool
github3/issues/label.py
update
Stevoisiak/github3.py
0
python
@requires_auth def update(self, name, color): "Update this label.\n\n :param str name:\n (required), new name of the label\n :param str color:\n (required), color code, e.g., 626262, no leading '#'\n :returns:\n True if successfully updated, False otherwise\n :rtype:\n bool\n " json = None if (name and color): if (color[0] == '#'): color = color[1:] json = self._json(self._patch(self._api, data=dumps({'name': name, 'color': color})), 200) if json: self._update_attributes(json) return True return False
@requires_auth def update(self, name, color): "Update this label.\n\n :param str name:\n (required), new name of the label\n :param str color:\n (required), color code, e.g., 626262, no leading '#'\n :returns:\n True if successfully updated, False otherwise\n :rtype:\n bool\n " json = None if (name and color): if (color[0] == '#'): color = color[1:] json = self._json(self._patch(self._api, data=dumps({'name': name, 'color': color})), 200) if json: self._update_attributes(json) return True return False<|docstring|>Update this label. :param str name: (required), new name of the label :param str color: (required), color code, e.g., 626262, no leading '#' :returns: True if successfully updated, False otherwise :rtype: bool<|endoftext|>
adb35b15fef3a80c01568d3a9ac4fd8a80c3a69fa6f56192032ad95223c80b3d
def query(self, size: int=None, start_index: int=None): 'Query parameters setter.' self._meta.query = parse_camelcase(locals()) return self
Query parameters setter.
pyot/models/val/ranked.py
query
paaksing/Pyot
60
python
def query(self, size: int=None, start_index: int=None): self._meta.query = parse_camelcase(locals()) return self
def query(self, size: int=None, start_index: int=None): self._meta.query = parse_camelcase(locals()) return self<|docstring|>Query parameters setter.<|endoftext|>
0428fc8593f5e347344cdfae5bb2eb60d04805b7fb0e96cec9527b5aecd096b0
def _handle_exception(self, e: usb.core.USBError) -> bool: '\n Handles the USBError thrown by the USB device while reading data.\n\n It will return True if operation can continue, and false if operation should be terminated.\n ' if ((e.errno in [60, 110]) and (e.backend_error_code != (- 116))): return True elif (e.errno == 5): logger.error('io error occurred, is the USB device still plugged in?') self.stop() self.device.close() return False else: logger.error(f'USB error occurred: {e}') self.stop() self.device.close() return False
Handles the USBError thrown by the USB device while reading data. It will return True if operation can continue, and false if operation should be terminated.
src/lightuptraining/sources/antplus/usbdevice/thread.py
_handle_exception
marcelblijleven/light-up-training
1
python
def _handle_exception(self, e: usb.core.USBError) -> bool: '\n Handles the USBError thrown by the USB device while reading data.\n\n It will return True if operation can continue, and false if operation should be terminated.\n ' if ((e.errno in [60, 110]) and (e.backend_error_code != (- 116))): return True elif (e.errno == 5): logger.error('io error occurred, is the USB device still plugged in?') self.stop() self.device.close() return False else: logger.error(f'USB error occurred: {e}') self.stop() self.device.close() return False
def _handle_exception(self, e: usb.core.USBError) -> bool: '\n Handles the USBError thrown by the USB device while reading data.\n\n It will return True if operation can continue, and false if operation should be terminated.\n ' if ((e.errno in [60, 110]) and (e.backend_error_code != (- 116))): return True elif (e.errno == 5): logger.error('io error occurred, is the USB device still plugged in?') self.stop() self.device.close() return False else: logger.error(f'USB error occurred: {e}') self.stop() self.device.close() return False<|docstring|>Handles the USBError thrown by the USB device while reading data. It will return True if operation can continue, and false if operation should be terminated.<|endoftext|>
3725669be627563e895fcda181b868876cdb6390b2f2f4778538fe75d0c8cb55
def _try_read(self) -> bool: '\n Tries reading from the USB device. If data is read, it will be added to the message queue\n\n It will return True if operation can continue, and false if operation should be terminated.\n Any exception is allowed to bubble up to the run method\n ' data = self.endpoint_in.read(self.read_size) if (not data): logger.debug('received no data, stopping usb thread') self.stop() return False logger.debug(f'read data from USB device: {data}') for byte in data: self.message_queue.put(byte) return True
Tries reading from the USB device. If data is read, it will be added to the message queue It will return True if operation can continue, and false if operation should be terminated. Any exception is allowed to bubble up to the run method
src/lightuptraining/sources/antplus/usbdevice/thread.py
_try_read
marcelblijleven/light-up-training
1
python
def _try_read(self) -> bool: '\n Tries reading from the USB device. If data is read, it will be added to the message queue\n\n It will return True if operation can continue, and false if operation should be terminated.\n Any exception is allowed to bubble up to the run method\n ' data = self.endpoint_in.read(self.read_size) if (not data): logger.debug('received no data, stopping usb thread') self.stop() return False logger.debug(f'read data from USB device: {data}') for byte in data: self.message_queue.put(byte) return True
def _try_read(self) -> bool: '\n Tries reading from the USB device. If data is read, it will be added to the message queue\n\n It will return True if operation can continue, and false if operation should be terminated.\n Any exception is allowed to bubble up to the run method\n ' data = self.endpoint_in.read(self.read_size) if (not data): logger.debug('received no data, stopping usb thread') self.stop() return False logger.debug(f'read data from USB device: {data}') for byte in data: self.message_queue.put(byte) return True<|docstring|>Tries reading from the USB device. If data is read, it will be added to the message queue It will return True if operation can continue, and false if operation should be terminated. Any exception is allowed to bubble up to the run method<|endoftext|>
703d5234aafc6af7b3e4f1ea07c41dad55205c05fa847ef589d20e200292096b
def run(self) -> None: '\n Runs the thread and starts reading data\n ' while self._run: try: if (not self._try_read()): break except usb.core.USBError as e: if (not self._handle_exception(e)): break except KeyboardInterrupt: break logger.debug('exiting USB read thread') self.message_queue.put(None) if self.device.is_open: self.device.close() return
Runs the thread and starts reading data
src/lightuptraining/sources/antplus/usbdevice/thread.py
run
marcelblijleven/light-up-training
1
python
def run(self) -> None: '\n \n ' while self._run: try: if (not self._try_read()): break except usb.core.USBError as e: if (not self._handle_exception(e)): break except KeyboardInterrupt: break logger.debug('exiting USB read thread') self.message_queue.put(None) if self.device.is_open: self.device.close() return
def run(self) -> None: '\n \n ' while self._run: try: if (not self._try_read()): break except usb.core.USBError as e: if (not self._handle_exception(e)): break except KeyboardInterrupt: break logger.debug('exiting USB read thread') self.message_queue.put(None) if self.device.is_open: self.device.close() return<|docstring|>Runs the thread and starts reading data<|endoftext|>
81b587a15c0872c4635000a6494a89df41152b49751d2fc0fe76689fc000157c
def stop(self) -> None: '\n Stops reading data\n ' self._run = False
Stops reading data
src/lightuptraining/sources/antplus/usbdevice/thread.py
stop
marcelblijleven/light-up-training
1
python
def stop(self) -> None: '\n \n ' self._run = False
def stop(self) -> None: '\n \n ' self._run = False<|docstring|>Stops reading data<|endoftext|>
fecc3cb73027191570f040462c8e32d391c5f8e3abbd9c5ffa79d7c106c341d6
def get_structure(self): "\n {\n CONTROL_NAME: {\n 'xf_type': XF_TYPE,\n 'bind': Bind,\n 'control': Control,\n 'parent': {\n CONTROL_NAME: {\n 'xf_type': XF_TYPE,\n 'bind': Bind,\n 'control': Control,\n 'parent': None,\n }\n }\n },\n ...\n }\n "
{ CONTROL_NAME: { 'xf_type': XF_TYPE, 'bind': Bind, 'control': Control, 'parent': { CONTROL_NAME: { 'xf_type': XF_TYPE, 'bind': Bind, 'control': Control, 'parent': None, } } }, ... }
orbeon_xml_api/builder.py
get_structure
euroblaze/orbeon-xml-api
2
python
def get_structure(self): "\n {\n CONTROL_NAME: {\n 'xf_type': XF_TYPE,\n 'bind': Bind,\n 'control': Control,\n 'parent': {\n CONTROL_NAME: {\n 'xf_type': XF_TYPE,\n 'bind': Bind,\n 'control': Control,\n 'parent': None,\n }\n }\n },\n ...\n }\n "
def get_structure(self): "\n {\n CONTROL_NAME: {\n 'xf_type': XF_TYPE,\n 'bind': Bind,\n 'control': Control,\n 'parent': {\n CONTROL_NAME: {\n 'xf_type': XF_TYPE,\n 'bind': Bind,\n 'control': Control,\n 'parent': None,\n }\n }\n },\n ...\n }\n "<|docstring|>{ CONTROL_NAME: { 'xf_type': XF_TYPE, 'bind': Bind, 'control': Control, 'parent': { CONTROL_NAME: { 'xf_type': XF_TYPE, 'bind': Bind, 'control': Control, 'parent': None, } } }, ... }<|endoftext|>
e632a3eb6d2a7b612de84c389436d79851f52ff173c8daaa3efb229464eaa8b9
@typechecked def get_coeffs(year: float) -> tuple[(list, list)]: '\n Processes coefficients\n\n Args:\n year : Between 1900.0 and 2030.0\n Returns:\n g and h\n ' if ((year < 1900.0) or (year > 2030.0)): if DEBUG: warnings.warn(f'Will not work with a date of {year:f}. Date must be in the range 1900.0 <= year <= 2030.0. On return [], []', RuntimeWarning) return ([], []) if ((year > 2025.0) and DEBUG): warnings.warn(f'This version of the IGRF is intended for use up to 2025.0 .Values for {year:f} will be computed but may be of reduced accuracy.', RuntimeWarning) if (year >= 2020.0): t = (year - 2020.0) tc = 1.0 ll = (3060 + 195) nmx = 13 nc = (nmx * (nmx + 2)) else: t = (0.2 * (year - 1900.0)) ll = int(t) t = (t - ll) if (year < 1995.0): nmx = 10 nc = (nmx * (nmx + 2)) ll = (nc * ll) else: nmx = 13 nc = (nmx * (nmx + 2)) ll = int((0.2 * (year - 1995.0))) ll = ((120 * 19) + (nc * ll)) tc = (1.0 - t) (g, h) = ([], []) temp = (ll - 1) for n in range((nmx + 1)): gsub = [] hsub = [] if (n == 0): gsub.append(None) for m in range((n + 1)): if (m != 0): gsub.append(((tc * GH[temp]) + (t * GH[(temp + nc)]))) hsub.append(((tc * GH[(temp + 1)]) + (t * GH[((temp + nc) + 1)]))) temp += 2 else: gsub.append(((tc * GH[temp]) + (t * GH[(temp + nc)]))) hsub.append(None) temp += 1 g.append(gsub) h.append(hsub) return (g, h)
Processes coefficients Args: year : Between 1900.0 and 2030.0 Returns: g and h
src/pyCRGI/pure/_coeffs.py
get_coeffs
pleiszenburg/pyIGRF
1
python
@typechecked def get_coeffs(year: float) -> tuple[(list, list)]: '\n Processes coefficients\n\n Args:\n year : Between 1900.0 and 2030.0\n Returns:\n g and h\n ' if ((year < 1900.0) or (year > 2030.0)): if DEBUG: warnings.warn(f'Will not work with a date of {year:f}. Date must be in the range 1900.0 <= year <= 2030.0. On return [], []', RuntimeWarning) return ([], []) if ((year > 2025.0) and DEBUG): warnings.warn(f'This version of the IGRF is intended for use up to 2025.0 .Values for {year:f} will be computed but may be of reduced accuracy.', RuntimeWarning) if (year >= 2020.0): t = (year - 2020.0) tc = 1.0 ll = (3060 + 195) nmx = 13 nc = (nmx * (nmx + 2)) else: t = (0.2 * (year - 1900.0)) ll = int(t) t = (t - ll) if (year < 1995.0): nmx = 10 nc = (nmx * (nmx + 2)) ll = (nc * ll) else: nmx = 13 nc = (nmx * (nmx + 2)) ll = int((0.2 * (year - 1995.0))) ll = ((120 * 19) + (nc * ll)) tc = (1.0 - t) (g, h) = ([], []) temp = (ll - 1) for n in range((nmx + 1)): gsub = [] hsub = [] if (n == 0): gsub.append(None) for m in range((n + 1)): if (m != 0): gsub.append(((tc * GH[temp]) + (t * GH[(temp + nc)]))) hsub.append(((tc * GH[(temp + 1)]) + (t * GH[((temp + nc) + 1)]))) temp += 2 else: gsub.append(((tc * GH[temp]) + (t * GH[(temp + nc)]))) hsub.append(None) temp += 1 g.append(gsub) h.append(hsub) return (g, h)
@typechecked def get_coeffs(year: float) -> tuple[(list, list)]: '\n Processes coefficients\n\n Args:\n year : Between 1900.0 and 2030.0\n Returns:\n g and h\n ' if ((year < 1900.0) or (year > 2030.0)): if DEBUG: warnings.warn(f'Will not work with a date of {year:f}. Date must be in the range 1900.0 <= year <= 2030.0. On return [], []', RuntimeWarning) return ([], []) if ((year > 2025.0) and DEBUG): warnings.warn(f'This version of the IGRF is intended for use up to 2025.0 .Values for {year:f} will be computed but may be of reduced accuracy.', RuntimeWarning) if (year >= 2020.0): t = (year - 2020.0) tc = 1.0 ll = (3060 + 195) nmx = 13 nc = (nmx * (nmx + 2)) else: t = (0.2 * (year - 1900.0)) ll = int(t) t = (t - ll) if (year < 1995.0): nmx = 10 nc = (nmx * (nmx + 2)) ll = (nc * ll) else: nmx = 13 nc = (nmx * (nmx + 2)) ll = int((0.2 * (year - 1995.0))) ll = ((120 * 19) + (nc * ll)) tc = (1.0 - t) (g, h) = ([], []) temp = (ll - 1) for n in range((nmx + 1)): gsub = [] hsub = [] if (n == 0): gsub.append(None) for m in range((n + 1)): if (m != 0): gsub.append(((tc * GH[temp]) + (t * GH[(temp + nc)]))) hsub.append(((tc * GH[(temp + 1)]) + (t * GH[((temp + nc) + 1)]))) temp += 2 else: gsub.append(((tc * GH[temp]) + (t * GH[(temp + nc)]))) hsub.append(None) temp += 1 g.append(gsub) h.append(hsub) return (g, h)<|docstring|>Processes coefficients Args: year : Between 1900.0 and 2030.0 Returns: g and h<|endoftext|>
60912c8292499ff28b81a2b8ba077231ae504ff3f59a75cfdb3c06ab34fc8af0
def __call__(self, args, wd, h5mngr, term): 'Execute the history command.' if (not self._parse_args(args, term)): return term.print(term.history.dump())
Execute the history command.
h5sh/commands/history.py
__call__
jl-wynen/h5shell
1
python
def __call__(self, args, wd, h5mngr, term): if (not self._parse_args(args, term)): return term.print(term.history.dump())
def __call__(self, args, wd, h5mngr, term): if (not self._parse_args(args, term)): return term.print(term.history.dump())<|docstring|>Execute the history command.<|endoftext|>
24afc1f1a06ffc070d68004aded629cef7e62c9d60490f6713511e4998bd1ec2
def get(url: str, dp: frictionless.package.Package, force: bool=False): '\n Retrieve data and check update.\n Parameters\n ----------\n url : str\n URL of the Gitlab repository (raw).\n dp : frictionless.package.Package\n Datapackage against which validating the data.\n force : Boolean, optional\n If True, new data will be uploaded even if the same as in the db. The default is False.\n Returns\n -------\n DataFrame\n Data in EnerMaps format.\n frictionless.package.Package\n Pakage descring the data.\n ' new_dp = frictionless.Package((url + 'datapackage.json')) new_dp.resources[RESOURCE_IDX]['path'] = (url + new_dp.resources[0]['path']) new_dp.resources[RESOURCE_IDX]['scheme'] = 'https' isChangedStats = False name = new_dp['name'] logging.info('Creating datapackage for input data') if (dp is not None): if ('stats' in dp['resources'][RESOURCE_IDX].keys()): isChangedStats = (dp['resources'][RESOURCE_IDX]['stats'] != new_dp['resources'][RESOURCE_IDX]['stats']) else: isChangedStats = False isChangedVersion = (dp['version'] != new_dp['version']) if (isChangedStats or isChangedVersion): logging.info('Data has changed') if utilities.isDPvalid(dp, new_dp): (enermaps_data, spatial) = prepare(new_dp, name) elif force: logging.info('Forced update') if utilities.isDPvalid(dp, new_dp): (enermaps_data, spatial) = prepare(new_dp, name) else: logging.info('Data has not changed. Use --force if you want to reupload.') return (None, None, None) else: dp = new_dp if utilities.isDPvalid(dp, new_dp): (enermaps_data, spatial) = prepare(new_dp, name) return (enermaps_data, spatial, new_dp)
Retrieve data and check update. Parameters ---------- url : str URL of the Gitlab repository (raw). dp : frictionless.package.Package Datapackage against which validating the data. force : Boolean, optional If True, new data will be uploaded even if the same as in the db. The default is False. Returns ------- DataFrame Data in EnerMaps format. frictionless.package.Package Pakage descring the data.
data-integration/getJRC-PPDB-OPEN.py
get
historeno/enermaps
5
python
def get(url: str, dp: frictionless.package.Package, force: bool=False): '\n Retrieve data and check update.\n Parameters\n ----------\n url : str\n URL of the Gitlab repository (raw).\n dp : frictionless.package.Package\n Datapackage against which validating the data.\n force : Boolean, optional\n If True, new data will be uploaded even if the same as in the db. The default is False.\n Returns\n -------\n DataFrame\n Data in EnerMaps format.\n frictionless.package.Package\n Pakage descring the data.\n ' new_dp = frictionless.Package((url + 'datapackage.json')) new_dp.resources[RESOURCE_IDX]['path'] = (url + new_dp.resources[0]['path']) new_dp.resources[RESOURCE_IDX]['scheme'] = 'https' isChangedStats = False name = new_dp['name'] logging.info('Creating datapackage for input data') if (dp is not None): if ('stats' in dp['resources'][RESOURCE_IDX].keys()): isChangedStats = (dp['resources'][RESOURCE_IDX]['stats'] != new_dp['resources'][RESOURCE_IDX]['stats']) else: isChangedStats = False isChangedVersion = (dp['version'] != new_dp['version']) if (isChangedStats or isChangedVersion): logging.info('Data has changed') if utilities.isDPvalid(dp, new_dp): (enermaps_data, spatial) = prepare(new_dp, name) elif force: logging.info('Forced update') if utilities.isDPvalid(dp, new_dp): (enermaps_data, spatial) = prepare(new_dp, name) else: logging.info('Data has not changed. Use --force if you want to reupload.') return (None, None, None) else: dp = new_dp if utilities.isDPvalid(dp, new_dp): (enermaps_data, spatial) = prepare(new_dp, name) return (enermaps_data, spatial, new_dp)
def get(url: str, dp: frictionless.package.Package, force: bool=False): '\n Retrieve data and check update.\n Parameters\n ----------\n url : str\n URL of the Gitlab repository (raw).\n dp : frictionless.package.Package\n Datapackage against which validating the data.\n force : Boolean, optional\n If True, new data will be uploaded even if the same as in the db. The default is False.\n Returns\n -------\n DataFrame\n Data in EnerMaps format.\n frictionless.package.Package\n Pakage descring the data.\n ' new_dp = frictionless.Package((url + 'datapackage.json')) new_dp.resources[RESOURCE_IDX]['path'] = (url + new_dp.resources[0]['path']) new_dp.resources[RESOURCE_IDX]['scheme'] = 'https' isChangedStats = False name = new_dp['name'] logging.info('Creating datapackage for input data') if (dp is not None): if ('stats' in dp['resources'][RESOURCE_IDX].keys()): isChangedStats = (dp['resources'][RESOURCE_IDX]['stats'] != new_dp['resources'][RESOURCE_IDX]['stats']) else: isChangedStats = False isChangedVersion = (dp['version'] != new_dp['version']) if (isChangedStats or isChangedVersion): logging.info('Data has changed') if utilities.isDPvalid(dp, new_dp): (enermaps_data, spatial) = prepare(new_dp, name) elif force: logging.info('Forced update') if utilities.isDPvalid(dp, new_dp): (enermaps_data, spatial) = prepare(new_dp, name) else: logging.info('Data has not changed. Use --force if you want to reupload.') return (None, None, None) else: dp = new_dp if utilities.isDPvalid(dp, new_dp): (enermaps_data, spatial) = prepare(new_dp, name) return (enermaps_data, spatial, new_dp)<|docstring|>Retrieve data and check update. Parameters ---------- url : str URL of the Gitlab repository (raw). dp : frictionless.package.Package Datapackage against which validating the data. force : Boolean, optional If True, new data will be uploaded even if the same as in the db. The default is False. Returns ------- DataFrame Data in EnerMaps format. frictionless.package.Package Pakage descring the data.<|endoftext|>
9c75171305a1cee01c00c79a5f63e5b03ab56c5eebd84523d4288a6ab502a502
def prepare(dp: frictionless.package.Package, name: str): '\n\n Prepare data in EnerMaps format.\n\n Parameters\n ----------\n dp : frictionless.package.Package\n Valid datapackage\n name : str\n Name of the dataset (used for constructing the FID)\n\n Returns\n -------\n DataFrame\n Data in EnerMaps format.\n GeoDataFrame\n Spatial data in EnerMaps format.\n\n ' data = read_datapackage(dp, RESOURCE_NAME) if (ID == 'index'): data['fid'] = ((name + '_') + data.index.astype(str)) else: data['fid'] = ((name + '_') + data[ID].astype(str)) spatial = gpd.GeoDataFrame(data['fid'], columns=['fid'], geometry=gpd.points_from_xy(data[SPATIAL_VARS[1]], data[SPATIAL_VARS[0]]), crs='EPSG:4326') spatial = spatial.loc[((~ spatial['geometry'].is_empty), :)] def np_encoder(object): 'Source: https://stackoverflow.com/a/65151218.' if isinstance(object, np.generic): return object.item() other_cols = [x for x in data.columns if (x not in ((VALUE_VARS + SPATIAL_VARS) + ID_VARS))] data.loc[(:, other_cols)].loc[(:, (data[other_cols].dtypes == 'int64'))] = data.loc[(:, other_cols)].loc[(:, (data[other_cols].dtypes == 'int64'))].astype(int) data = data.replace({np.nan: None}) data['fields'] = data[other_cols].to_dict(orient='records') data['fields'] = data['fields'].apply((lambda x: json.dumps(x, default=np_encoder))) data = data.melt(id_vars=['fid', 'fields'], value_vars=VALUE_VARS) data = data.dropna() data = data.loc[(data['fid'].isin(spatial['fid']), :)] enermaps_data = utilities.ENERMAPS_DF enermaps_data['fid'] = data['fid'] enermaps_data['value'] = data['value'] enermaps_data['variable'] = data['variable'] enermaps_data['fields'] = data['fields'] enermaps_data['unit'] = UNIT enermaps_data['israster'] = ISRASTER return (enermaps_data, spatial)
Prepare data in EnerMaps format. Parameters ---------- dp : frictionless.package.Package Valid datapackage name : str Name of the dataset (used for constructing the FID) Returns ------- DataFrame Data in EnerMaps format. GeoDataFrame Spatial data in EnerMaps format.
data-integration/getJRC-PPDB-OPEN.py
prepare
historeno/enermaps
5
python
def prepare(dp: frictionless.package.Package, name: str): '\n\n Prepare data in EnerMaps format.\n\n Parameters\n ----------\n dp : frictionless.package.Package\n Valid datapackage\n name : str\n Name of the dataset (used for constructing the FID)\n\n Returns\n -------\n DataFrame\n Data in EnerMaps format.\n GeoDataFrame\n Spatial data in EnerMaps format.\n\n ' data = read_datapackage(dp, RESOURCE_NAME) if (ID == 'index'): data['fid'] = ((name + '_') + data.index.astype(str)) else: data['fid'] = ((name + '_') + data[ID].astype(str)) spatial = gpd.GeoDataFrame(data['fid'], columns=['fid'], geometry=gpd.points_from_xy(data[SPATIAL_VARS[1]], data[SPATIAL_VARS[0]]), crs='EPSG:4326') spatial = spatial.loc[((~ spatial['geometry'].is_empty), :)] def np_encoder(object): 'Source: https://stackoverflow.com/a/65151218.' if isinstance(object, np.generic): return object.item() other_cols = [x for x in data.columns if (x not in ((VALUE_VARS + SPATIAL_VARS) + ID_VARS))] data.loc[(:, other_cols)].loc[(:, (data[other_cols].dtypes == 'int64'))] = data.loc[(:, other_cols)].loc[(:, (data[other_cols].dtypes == 'int64'))].astype(int) data = data.replace({np.nan: None}) data['fields'] = data[other_cols].to_dict(orient='records') data['fields'] = data['fields'].apply((lambda x: json.dumps(x, default=np_encoder))) data = data.melt(id_vars=['fid', 'fields'], value_vars=VALUE_VARS) data = data.dropna() data = data.loc[(data['fid'].isin(spatial['fid']), :)] enermaps_data = utilities.ENERMAPS_DF enermaps_data['fid'] = data['fid'] enermaps_data['value'] = data['value'] enermaps_data['variable'] = data['variable'] enermaps_data['fields'] = data['fields'] enermaps_data['unit'] = UNIT enermaps_data['israster'] = ISRASTER return (enermaps_data, spatial)
def prepare(dp: frictionless.package.Package, name: str): '\n\n Prepare data in EnerMaps format.\n\n Parameters\n ----------\n dp : frictionless.package.Package\n Valid datapackage\n name : str\n Name of the dataset (used for constructing the FID)\n\n Returns\n -------\n DataFrame\n Data in EnerMaps format.\n GeoDataFrame\n Spatial data in EnerMaps format.\n\n ' data = read_datapackage(dp, RESOURCE_NAME) if (ID == 'index'): data['fid'] = ((name + '_') + data.index.astype(str)) else: data['fid'] = ((name + '_') + data[ID].astype(str)) spatial = gpd.GeoDataFrame(data['fid'], columns=['fid'], geometry=gpd.points_from_xy(data[SPATIAL_VARS[1]], data[SPATIAL_VARS[0]]), crs='EPSG:4326') spatial = spatial.loc[((~ spatial['geometry'].is_empty), :)] def np_encoder(object): 'Source: https://stackoverflow.com/a/65151218.' if isinstance(object, np.generic): return object.item() other_cols = [x for x in data.columns if (x not in ((VALUE_VARS + SPATIAL_VARS) + ID_VARS))] data.loc[(:, other_cols)].loc[(:, (data[other_cols].dtypes == 'int64'))] = data.loc[(:, other_cols)].loc[(:, (data[other_cols].dtypes == 'int64'))].astype(int) data = data.replace({np.nan: None}) data['fields'] = data[other_cols].to_dict(orient='records') data['fields'] = data['fields'].apply((lambda x: json.dumps(x, default=np_encoder))) data = data.melt(id_vars=['fid', 'fields'], value_vars=VALUE_VARS) data = data.dropna() data = data.loc[(data['fid'].isin(spatial['fid']), :)] enermaps_data = utilities.ENERMAPS_DF enermaps_data['fid'] = data['fid'] enermaps_data['value'] = data['value'] enermaps_data['variable'] = data['variable'] enermaps_data['fields'] = data['fields'] enermaps_data['unit'] = UNIT enermaps_data['israster'] = ISRASTER return (enermaps_data, spatial)<|docstring|>Prepare data in EnerMaps format. Parameters ---------- dp : frictionless.package.Package Valid datapackage name : str Name of the dataset (used for constructing the FID) Returns ------- DataFrame Data in EnerMaps format. GeoDataFrame Spatial data in EnerMaps format.<|endoftext|>
1ffa6eb90596ab7e8e0f107b38fd22804dd02de54def41054a5ce16c07bef373
def np_encoder(object): 'Source: https://stackoverflow.com/a/65151218.' if isinstance(object, np.generic): return object.item()
Source: https://stackoverflow.com/a/65151218.
data-integration/getJRC-PPDB-OPEN.py
np_encoder
historeno/enermaps
5
python
def np_encoder(object): if isinstance(object, np.generic): return object.item()
def np_encoder(object): if isinstance(object, np.generic): return object.item()<|docstring|>Source: https://stackoverflow.com/a/65151218.<|endoftext|>
70a8f95262831e1e2357f082e21c8413bd66659ff37e6b42316d25e5e94e869a
@click.command('web') @existing_cluster_id_option @verbosity_option @node_transport_option def web(cluster_id: str, transport: Transport) -> None: '\n Open the browser at the web UI.\n\n Note that the web UI may not be available at first.\n Consider using ``minidcos docker wait`` before running this command.\n ' check_cluster_id_exists(new_cluster_id=cluster_id, existing_cluster_ids=existing_cluster_ids()) cluster_containers = ClusterContainers(cluster_id=cluster_id, transport=transport) launch_web_ui(cluster=cluster_containers.cluster)
Open the browser at the web UI. Note that the web UI may not be available at first. Consider using ``minidcos docker wait`` before running this command.
src/dcos_e2e_cli/dcos_docker/commands/web.py
web
jkoelker/dcos-e2e
63
python
@click.command('web') @existing_cluster_id_option @verbosity_option @node_transport_option def web(cluster_id: str, transport: Transport) -> None: '\n Open the browser at the web UI.\n\n Note that the web UI may not be available at first.\n Consider using ``minidcos docker wait`` before running this command.\n ' check_cluster_id_exists(new_cluster_id=cluster_id, existing_cluster_ids=existing_cluster_ids()) cluster_containers = ClusterContainers(cluster_id=cluster_id, transport=transport) launch_web_ui(cluster=cluster_containers.cluster)
@click.command('web') @existing_cluster_id_option @verbosity_option @node_transport_option def web(cluster_id: str, transport: Transport) -> None: '\n Open the browser at the web UI.\n\n Note that the web UI may not be available at first.\n Consider using ``minidcos docker wait`` before running this command.\n ' check_cluster_id_exists(new_cluster_id=cluster_id, existing_cluster_ids=existing_cluster_ids()) cluster_containers = ClusterContainers(cluster_id=cluster_id, transport=transport) launch_web_ui(cluster=cluster_containers.cluster)<|docstring|>Open the browser at the web UI. Note that the web UI may not be available at first. Consider using ``minidcos docker wait`` before running this command.<|endoftext|>
808f52f62164e478ff57915b9cf389985a81bb4083b8dcda03c193cab4cc8736
def main(argv=sys.argv): ' The main script ' args = parse_args(argv) action = args.app_action train_folder_path = args.trp test_folder_path = args.tep folder_or_image = ('' if (args.path is None) else args.path) generate_model_name = args.gen_name model = args.model if (action == 'train'): new_model = model if (not new_model): if (generate_model_name in truth_values): if (train_folder_path and test_folder_path): new_model = generate_name(train_folder_path) train_model(new_model, train_folder_path, test_folder_path) return print('\n Both training folder and test folder arguments are required') return if (default_model in all_models()): print('Retraining the default model is forbidden. Supply model name or Delete the default model manually and proceed') return new_model = default_model print('Training the default model now...') return train(new_model) new_model = (model + model_extension) if (new_model in all_models()): print("There's already a model with that name. Please choose another name or find a model with name {}. Delete it and try again".format(new_model)) return if (train_folder_path and test_folder_path): return train_model(new_model, train_folder_path, test_folder_path) print('\n Both training folder and test folder arguments are required') return elif (action == 'predict'): if (not model): model = default_model else: model = (model + model_extension) if (model not in all_models()): print('No such model has been trained') return if (not os.path.isdir(folder_or_image)): if os.path.isfile(folder_or_image): if (not folder_or_image.endswith(image_extensions)): print('\nError: An image file is required. Try again\n') return input_type = 'file' predictor(input_type, folder_or_image, model) return print('\nError: Invalid path. Kindly supply a valid folder or image path\n') return input_type = 'folder' predictor(input_type, folder_or_image, model) if (input_type == 'folder'): print(f''' Done! The results are in {folder_or_image}''') elif (action == 'delete'): if (not model): print('\n You must supply a model to delete') return model = (model + model_extension) if (model not in all_models()): print('That model does not exist') return model_delete(model) return elif (action == 'retrieve_models'): print(all_models()) return else: print('\nAction command is not supported\n for help: run python3 app.py -h')
The main script
app.py
main
Parakconcepts/mlclassification
0
python
def main(argv=sys.argv): ' ' args = parse_args(argv) action = args.app_action train_folder_path = args.trp test_folder_path = args.tep folder_or_image = ( if (args.path is None) else args.path) generate_model_name = args.gen_name model = args.model if (action == 'train'): new_model = model if (not new_model): if (generate_model_name in truth_values): if (train_folder_path and test_folder_path): new_model = generate_name(train_folder_path) train_model(new_model, train_folder_path, test_folder_path) return print('\n Both training folder and test folder arguments are required') return if (default_model in all_models()): print('Retraining the default model is forbidden. Supply model name or Delete the default model manually and proceed') return new_model = default_model print('Training the default model now...') return train(new_model) new_model = (model + model_extension) if (new_model in all_models()): print("There's already a model with that name. Please choose another name or find a model with name {}. Delete it and try again".format(new_model)) return if (train_folder_path and test_folder_path): return train_model(new_model, train_folder_path, test_folder_path) print('\n Both training folder and test folder arguments are required') return elif (action == 'predict'): if (not model): model = default_model else: model = (model + model_extension) if (model not in all_models()): print('No such model has been trained') return if (not os.path.isdir(folder_or_image)): if os.path.isfile(folder_or_image): if (not folder_or_image.endswith(image_extensions)): print('\nError: An image file is required. Try again\n') return input_type = 'file' predictor(input_type, folder_or_image, model) return print('\nError: Invalid path. Kindly supply a valid folder or image path\n') return input_type = 'folder' predictor(input_type, folder_or_image, model) if (input_type == 'folder'): print(f' Done! The results are in {folder_or_image}') elif (action == 'delete'): if (not model): print('\n You must supply a model to delete') return model = (model + model_extension) if (model not in all_models()): print('That model does not exist') return model_delete(model) return elif (action == 'retrieve_models'): print(all_models()) return else: print('\nAction command is not supported\n for help: run python3 app.py -h')
def main(argv=sys.argv): ' ' args = parse_args(argv) action = args.app_action train_folder_path = args.trp test_folder_path = args.tep folder_or_image = ( if (args.path is None) else args.path) generate_model_name = args.gen_name model = args.model if (action == 'train'): new_model = model if (not new_model): if (generate_model_name in truth_values): if (train_folder_path and test_folder_path): new_model = generate_name(train_folder_path) train_model(new_model, train_folder_path, test_folder_path) return print('\n Both training folder and test folder arguments are required') return if (default_model in all_models()): print('Retraining the default model is forbidden. Supply model name or Delete the default model manually and proceed') return new_model = default_model print('Training the default model now...') return train(new_model) new_model = (model + model_extension) if (new_model in all_models()): print("There's already a model with that name. Please choose another name or find a model with name {}. Delete it and try again".format(new_model)) return if (train_folder_path and test_folder_path): return train_model(new_model, train_folder_path, test_folder_path) print('\n Both training folder and test folder arguments are required') return elif (action == 'predict'): if (not model): model = default_model else: model = (model + model_extension) if (model not in all_models()): print('No such model has been trained') return if (not os.path.isdir(folder_or_image)): if os.path.isfile(folder_or_image): if (not folder_or_image.endswith(image_extensions)): print('\nError: An image file is required. Try again\n') return input_type = 'file' predictor(input_type, folder_or_image, model) return print('\nError: Invalid path. Kindly supply a valid folder or image path\n') return input_type = 'folder' predictor(input_type, folder_or_image, model) if (input_type == 'folder'): print(f' Done! The results are in {folder_or_image}') elif (action == 'delete'): if (not model): print('\n You must supply a model to delete') return model = (model + model_extension) if (model not in all_models()): print('That model does not exist') return model_delete(model) return elif (action == 'retrieve_models'): print(all_models()) return else: print('\nAction command is not supported\n for help: run python3 app.py -h')<|docstring|>The main script<|endoftext|>
87f32e9bfc9da7bffe7be634cff24b8a53456917a17e1068155a51d1b9d64fc8
def resource_path(relative_path): ' Get absolute path to resource, works for dev and for PyInstaller ' try: base_path = sys._MEIPASS except Exception: base_path = os.path.abspath('.') return os.path.join(base_path, relative_path)
Get absolute path to resource, works for dev and for PyInstaller
main.py
resource_path
Axvia/Exather
0
python
def resource_path(relative_path): ' ' try: base_path = sys._MEIPASS except Exception: base_path = os.path.abspath('.') return os.path.join(base_path, relative_path)
def resource_path(relative_path): ' ' try: base_path = sys._MEIPASS except Exception: base_path = os.path.abspath('.') return os.path.join(base_path, relative_path)<|docstring|>Get absolute path to resource, works for dev and for PyInstaller<|endoftext|>
79d8c3833caaf9bd83b64b2ac904b5a50bcb6c16480369fec6402c93e77495ba
def remove_placeholder(self, event): 'Remove placeholder text, if present' if (self.get() == self.placeholder): self.delete(0, 'end')
Remove placeholder text, if present
main.py
remove_placeholder
Axvia/Exather
0
python
def remove_placeholder(self, event): if (self.get() == self.placeholder): self.delete(0, 'end')
def remove_placeholder(self, event): if (self.get() == self.placeholder): self.delete(0, 'end')<|docstring|>Remove placeholder text, if present<|endoftext|>
58df5985179800badc41f06c7049e62d1bebf31109ecef98cb90f927e16baa1f
def add_placeholder(self, event): 'Add placeholder text if the widget is empty' if (self.placeholder and (self.get() == '')): self.insert(0, self.placeholder)
Add placeholder text if the widget is empty
main.py
add_placeholder
Axvia/Exather
0
python
def add_placeholder(self, event): if (self.placeholder and (self.get() == )): self.insert(0, self.placeholder)
def add_placeholder(self, event): if (self.placeholder and (self.get() == )): self.insert(0, self.placeholder)<|docstring|>Add placeholder text if the widget is empty<|endoftext|>
86fda775ce61d4158994463f7981047457252d9ce8e44dfaa0b3f390de38fbf3
def __init__(self, policy_parser, policy_template='json/policy_template.json'): '\n Creates instance of policy filter.\n :param policy_parser: Specific parser for the policy.\n :param policy_template: Specific template that represents output policy file.\n ' self.json_data = policy_parser.json self.policy_template = policy_template
Creates instance of policy filter. :param policy_parser: Specific parser for the policy. :param policy_template: Specific template that represents output policy file.
cysecuretools/targets/common/policy_filter.py
__init__
cypresssemiconductorco/cysecuretools
9
python
def __init__(self, policy_parser, policy_template='json/policy_template.json'): '\n Creates instance of policy filter.\n :param policy_parser: Specific parser for the policy.\n :param policy_template: Specific template that represents output policy file.\n ' self.json_data = policy_parser.json self.policy_template = policy_template
def __init__(self, policy_parser, policy_template='json/policy_template.json'): '\n Creates instance of policy filter.\n :param policy_parser: Specific parser for the policy.\n :param policy_template: Specific template that represents output policy file.\n ' self.json_data = policy_parser.json self.policy_template = policy_template<|docstring|>Creates instance of policy filter. :param policy_parser: Specific parser for the policy. :param policy_template: Specific template that represents output policy file.<|endoftext|>
03052c6dfb3bd369cc49a240b52ab727d54db0333e9fc612e9d64eeca88f6189
def filter_policy(self): '\n From aggregated policy file and creates policy file that contains information for provisioning only.\n :return: Path to the filtered policy file.\n ' sdk_path = os.path.dirname(os.path.realpath(__file__)) policy_template = (self.policy_template if os.path.isabs(self.policy_template) else os.path.join(sdk_path, self.policy_template)) with open(policy_template) as f: file_content = f.read() json_template = json.loads(file_content) self.parse_node(self.json_data, json_template) json_template = self.filter_extra_fields(self.json_data, json_template) custom_data_list = 'custom_data_sections' if (custom_data_list in self.json_data): for field in self.json_data[custom_data_list]: json_template = self.add_custom_nodes(self.json_data, json_template, field) filtered_policy = os.path.join(sdk_path, 'json/filtered.json') if (not os.path.exists(os.path.dirname(filtered_policy))): try: os.makedirs(os.path.dirname(filtered_policy)) except OSError as exc: if (exc.errno != errno.EEXIST): raise with open(filtered_policy, 'w') as fp: json.dump(json_template, fp, indent=4) return filtered_policy
From aggregated policy file and creates policy file that contains information for provisioning only. :return: Path to the filtered policy file.
cysecuretools/targets/common/policy_filter.py
filter_policy
cypresssemiconductorco/cysecuretools
9
python
def filter_policy(self): '\n From aggregated policy file and creates policy file that contains information for provisioning only.\n :return: Path to the filtered policy file.\n ' sdk_path = os.path.dirname(os.path.realpath(__file__)) policy_template = (self.policy_template if os.path.isabs(self.policy_template) else os.path.join(sdk_path, self.policy_template)) with open(policy_template) as f: file_content = f.read() json_template = json.loads(file_content) self.parse_node(self.json_data, json_template) json_template = self.filter_extra_fields(self.json_data, json_template) custom_data_list = 'custom_data_sections' if (custom_data_list in self.json_data): for field in self.json_data[custom_data_list]: json_template = self.add_custom_nodes(self.json_data, json_template, field) filtered_policy = os.path.join(sdk_path, 'json/filtered.json') if (not os.path.exists(os.path.dirname(filtered_policy))): try: os.makedirs(os.path.dirname(filtered_policy)) except OSError as exc: if (exc.errno != errno.EEXIST): raise with open(filtered_policy, 'w') as fp: json.dump(json_template, fp, indent=4) return filtered_policy
def filter_policy(self): '\n From aggregated policy file and creates policy file that contains information for provisioning only.\n :return: Path to the filtered policy file.\n ' sdk_path = os.path.dirname(os.path.realpath(__file__)) policy_template = (self.policy_template if os.path.isabs(self.policy_template) else os.path.join(sdk_path, self.policy_template)) with open(policy_template) as f: file_content = f.read() json_template = json.loads(file_content) self.parse_node(self.json_data, json_template) json_template = self.filter_extra_fields(self.json_data, json_template) custom_data_list = 'custom_data_sections' if (custom_data_list in self.json_data): for field in self.json_data[custom_data_list]: json_template = self.add_custom_nodes(self.json_data, json_template, field) filtered_policy = os.path.join(sdk_path, 'json/filtered.json') if (not os.path.exists(os.path.dirname(filtered_policy))): try: os.makedirs(os.path.dirname(filtered_policy)) except OSError as exc: if (exc.errno != errno.EEXIST): raise with open(filtered_policy, 'w') as fp: json.dump(json_template, fp, indent=4) return filtered_policy<|docstring|>From aggregated policy file and creates policy file that contains information for provisioning only. :return: Path to the filtered policy file.<|endoftext|>
71d32602fd4d9e086c5f730508890427c7205415d8d3601c5773a6cce7a3ca45
def parse_node(self, data, template): '\n Recursive function that copies JSON data from the data dictionary to the template dictionary.\n Copies the fields only that exist in template.\n :param data: Dictionary that contains data to copy.\n :param template: Dictionary, which is template that contains placeholders where to copy the data.\n ' for (t_key, t_value) in template.items(): for (d_key, d_value) in data.items(): if (d_key == t_key): if isinstance(d_value, list): d_i = 0 t_i = 0 for t_elem in t_value: if (len(d_value) > d_i): d_elem = d_value[d_i] if (not isinstance(d_elem, dict)): if (t_i == d_i): t_value[t_i] = d_elem else: self.parse_node(d_elem, t_elem) else: del t_value[t_i:] d_i += 1 t_i += 1 elif (not isinstance(d_value, dict)): template[t_key] = d_value break else: self.parse_node(d_value, t_value)
Recursive function that copies JSON data from the data dictionary to the template dictionary. Copies the fields only that exist in template. :param data: Dictionary that contains data to copy. :param template: Dictionary, which is template that contains placeholders where to copy the data.
cysecuretools/targets/common/policy_filter.py
parse_node
cypresssemiconductorco/cysecuretools
9
python
def parse_node(self, data, template): '\n Recursive function that copies JSON data from the data dictionary to the template dictionary.\n Copies the fields only that exist in template.\n :param data: Dictionary that contains data to copy.\n :param template: Dictionary, which is template that contains placeholders where to copy the data.\n ' for (t_key, t_value) in template.items(): for (d_key, d_value) in data.items(): if (d_key == t_key): if isinstance(d_value, list): d_i = 0 t_i = 0 for t_elem in t_value: if (len(d_value) > d_i): d_elem = d_value[d_i] if (not isinstance(d_elem, dict)): if (t_i == d_i): t_value[t_i] = d_elem else: self.parse_node(d_elem, t_elem) else: del t_value[t_i:] d_i += 1 t_i += 1 elif (not isinstance(d_value, dict)): template[t_key] = d_value break else: self.parse_node(d_value, t_value)
def parse_node(self, data, template): '\n Recursive function that copies JSON data from the data dictionary to the template dictionary.\n Copies the fields only that exist in template.\n :param data: Dictionary that contains data to copy.\n :param template: Dictionary, which is template that contains placeholders where to copy the data.\n ' for (t_key, t_value) in template.items(): for (d_key, d_value) in data.items(): if (d_key == t_key): if isinstance(d_value, list): d_i = 0 t_i = 0 for t_elem in t_value: if (len(d_value) > d_i): d_elem = d_value[d_i] if (not isinstance(d_elem, dict)): if (t_i == d_i): t_value[t_i] = d_elem else: self.parse_node(d_elem, t_elem) else: del t_value[t_i:] d_i += 1 t_i += 1 elif (not isinstance(d_value, dict)): template[t_key] = d_value break else: self.parse_node(d_value, t_value)<|docstring|>Recursive function that copies JSON data from the data dictionary to the template dictionary. Copies the fields only that exist in template. :param data: Dictionary that contains data to copy. :param template: Dictionary, which is template that contains placeholders where to copy the data.<|endoftext|>
8a48b3c86530df9da0a1e98de3a80e57882f3457e8df69e5822be8eaad4836d8
@staticmethod def filter_extra_fields(data, template): '\n Filters fields that exist in template, but do not exist in policy.\n :param data: Policy data.\n :param template: Template data.\n :return: Filtered dictionary.\n ' tc = copy.deepcopy(template) for i in range(len(data['boot_upgrade']['firmware'])): dslot = data['boot_upgrade']['firmware'][i] tslot = template['boot_upgrade']['firmware'][i] for t_i in tslot: if (t_i not in dslot): del tc['boot_upgrade']['firmware'][i][t_i] return tc
Filters fields that exist in template, but do not exist in policy. :param data: Policy data. :param template: Template data. :return: Filtered dictionary.
cysecuretools/targets/common/policy_filter.py
filter_extra_fields
cypresssemiconductorco/cysecuretools
9
python
@staticmethod def filter_extra_fields(data, template): '\n Filters fields that exist in template, but do not exist in policy.\n :param data: Policy data.\n :param template: Template data.\n :return: Filtered dictionary.\n ' tc = copy.deepcopy(template) for i in range(len(data['boot_upgrade']['firmware'])): dslot = data['boot_upgrade']['firmware'][i] tslot = template['boot_upgrade']['firmware'][i] for t_i in tslot: if (t_i not in dslot): del tc['boot_upgrade']['firmware'][i][t_i] return tc
@staticmethod def filter_extra_fields(data, template): '\n Filters fields that exist in template, but do not exist in policy.\n :param data: Policy data.\n :param template: Template data.\n :return: Filtered dictionary.\n ' tc = copy.deepcopy(template) for i in range(len(data['boot_upgrade']['firmware'])): dslot = data['boot_upgrade']['firmware'][i] tslot = template['boot_upgrade']['firmware'][i] for t_i in tslot: if (t_i not in dslot): del tc['boot_upgrade']['firmware'][i][t_i] return tc<|docstring|>Filters fields that exist in template, but do not exist in policy. :param data: Policy data. :param template: Template data. :return: Filtered dictionary.<|endoftext|>
e5608de712a99da01f3d643b73e0f5f94aa3d7a1949fd5cae4e01a2ed414e921
@staticmethod def add_custom_nodes(data, template, obj): '\n Copies custom JSON data from the data dictionary to the template dictionary.\n :param data: Dictionary that contains data to copy.\n :param template: Dictionary, which is template that contains placeholders where to copy the data.\n :param obj: data key to copy\n :return: Updated dictionary.\n ' tc = copy.deepcopy(template) for item in data: if (item == obj): logger.debug("Copying custom section '{}': {}".format(item, data[item])) tc[obj] = data[item] return tc
Copies custom JSON data from the data dictionary to the template dictionary. :param data: Dictionary that contains data to copy. :param template: Dictionary, which is template that contains placeholders where to copy the data. :param obj: data key to copy :return: Updated dictionary.
cysecuretools/targets/common/policy_filter.py
add_custom_nodes
cypresssemiconductorco/cysecuretools
9
python
@staticmethod def add_custom_nodes(data, template, obj): '\n Copies custom JSON data from the data dictionary to the template dictionary.\n :param data: Dictionary that contains data to copy.\n :param template: Dictionary, which is template that contains placeholders where to copy the data.\n :param obj: data key to copy\n :return: Updated dictionary.\n ' tc = copy.deepcopy(template) for item in data: if (item == obj): logger.debug("Copying custom section '{}': {}".format(item, data[item])) tc[obj] = data[item] return tc
@staticmethod def add_custom_nodes(data, template, obj): '\n Copies custom JSON data from the data dictionary to the template dictionary.\n :param data: Dictionary that contains data to copy.\n :param template: Dictionary, which is template that contains placeholders where to copy the data.\n :param obj: data key to copy\n :return: Updated dictionary.\n ' tc = copy.deepcopy(template) for item in data: if (item == obj): logger.debug("Copying custom section '{}': {}".format(item, data[item])) tc[obj] = data[item] return tc<|docstring|>Copies custom JSON data from the data dictionary to the template dictionary. :param data: Dictionary that contains data to copy. :param template: Dictionary, which is template that contains placeholders where to copy the data. :param obj: data key to copy :return: Updated dictionary.<|endoftext|>
15e4790d6ab440ed66389a6e67b6f508e16f11bdf00eb44f4a80244b936ff5e0
def visit_Raise(self, node: ast.Raise) -> None: '\n Checks how ``raise`` keyword is used.\n\n Raises:\n RaiseNotImplementedViolation\n\n ' self._check_exception_type(node) self.generic_visit(node)
Checks how ``raise`` keyword is used. Raises: RaiseNotImplementedViolation
wemake_python_styleguide/visitors/ast/keywords.py
visit_Raise
piglei/wemake-python-styleguide
1
python
def visit_Raise(self, node: ast.Raise) -> None: '\n Checks how ``raise`` keyword is used.\n\n Raises:\n RaiseNotImplementedViolation\n\n ' self._check_exception_type(node) self.generic_visit(node)
def visit_Raise(self, node: ast.Raise) -> None: '\n Checks how ``raise`` keyword is used.\n\n Raises:\n RaiseNotImplementedViolation\n\n ' self._check_exception_type(node) self.generic_visit(node)<|docstring|>Checks how ``raise`` keyword is used. Raises: RaiseNotImplementedViolation<|endoftext|>
91d4b95d5c14d4b5949a0580cff30a487e396f853da30369917d9594e126da71
def visit_Return(self, node: ast.Return) -> None: '\n Checks ``return`` statements for consistency.\n\n Raises:\n InconsistentReturnViolation\n\n ' self._check_last_return_in_function(node) self.generic_visit(node)
Checks ``return`` statements for consistency. Raises: InconsistentReturnViolation
wemake_python_styleguide/visitors/ast/keywords.py
visit_Return
piglei/wemake-python-styleguide
1
python
def visit_Return(self, node: ast.Return) -> None: '\n Checks ``return`` statements for consistency.\n\n Raises:\n InconsistentReturnViolation\n\n ' self._check_last_return_in_function(node) self.generic_visit(node)
def visit_Return(self, node: ast.Return) -> None: '\n Checks ``return`` statements for consistency.\n\n Raises:\n InconsistentReturnViolation\n\n ' self._check_last_return_in_function(node) self.generic_visit(node)<|docstring|>Checks ``return`` statements for consistency. Raises: InconsistentReturnViolation<|endoftext|>
8fa09e1d8af76f9a6697d391b27370c432b07a923d6e397955e79255e1f7f77c
def visit_any_function(self, node: AnyFunctionDef) -> None: '\n Helper to get all ``return`` and ``yield`` nodes in a function at once.\n\n Raises:\n InconsistentReturnViolation\n InconsistentYieldViolation\n\n ' self._check_return_values(node) self._check_yield_values(node) self.generic_visit(node)
Helper to get all ``return`` and ``yield`` nodes in a function at once. Raises: InconsistentReturnViolation InconsistentYieldViolation
wemake_python_styleguide/visitors/ast/keywords.py
visit_any_function
piglei/wemake-python-styleguide
1
python
def visit_any_function(self, node: AnyFunctionDef) -> None: '\n Helper to get all ``return`` and ``yield`` nodes in a function at once.\n\n Raises:\n InconsistentReturnViolation\n InconsistentYieldViolation\n\n ' self._check_return_values(node) self._check_yield_values(node) self.generic_visit(node)
def visit_any_function(self, node: AnyFunctionDef) -> None: '\n Helper to get all ``return`` and ``yield`` nodes in a function at once.\n\n Raises:\n InconsistentReturnViolation\n InconsistentYieldViolation\n\n ' self._check_return_values(node) self._check_yield_values(node) self.generic_visit(node)<|docstring|>Helper to get all ``return`` and ``yield`` nodes in a function at once. Raises: InconsistentReturnViolation InconsistentYieldViolation<|endoftext|>
45c4edb829ecb9e77da87124411fdb93e82b98ae494657fb0bca033825ec6386
def visit(self, node: ast.AST) -> None: '\n Used to find wrong keywords.\n\n Raises:\n WrongKeywordViolation\n\n ' self._check_keyword(node) self.generic_visit(node)
Used to find wrong keywords. Raises: WrongKeywordViolation
wemake_python_styleguide/visitors/ast/keywords.py
visit
piglei/wemake-python-styleguide
1
python
def visit(self, node: ast.AST) -> None: '\n Used to find wrong keywords.\n\n Raises:\n WrongKeywordViolation\n\n ' self._check_keyword(node) self.generic_visit(node)
def visit(self, node: ast.AST) -> None: '\n Used to find wrong keywords.\n\n Raises:\n WrongKeywordViolation\n\n ' self._check_keyword(node) self.generic_visit(node)<|docstring|>Used to find wrong keywords. Raises: WrongKeywordViolation<|endoftext|>
a0eddb387f84c8ea68911cc275b0e057b3a4c8217e7342ceba666f7cb2b20c49
def visit_withitem(self, node: ast.withitem) -> None: '\n Checks that all variables inside context managers defined correctly.\n\n Raises:\n ContextManagerVariableDefinitionViolation\n\n ' self._check_variable_definitions(node) self.generic_visit(node)
Checks that all variables inside context managers defined correctly. Raises: ContextManagerVariableDefinitionViolation
wemake_python_styleguide/visitors/ast/keywords.py
visit_withitem
piglei/wemake-python-styleguide
1
python
def visit_withitem(self, node: ast.withitem) -> None: '\n Checks that all variables inside context managers defined correctly.\n\n Raises:\n ContextManagerVariableDefinitionViolation\n\n ' self._check_variable_definitions(node) self.generic_visit(node)
def visit_withitem(self, node: ast.withitem) -> None: '\n Checks that all variables inside context managers defined correctly.\n\n Raises:\n ContextManagerVariableDefinitionViolation\n\n ' self._check_variable_definitions(node) self.generic_visit(node)<|docstring|>Checks that all variables inside context managers defined correctly. Raises: ContextManagerVariableDefinitionViolation<|endoftext|>
2f52a8c8b5c63265902f8b0e5c6ce36aa029a4a3d7ef6520e1c8582838c6f96a
def visit_any_with(self, node: AnyWith) -> None: '\n Checks the number of assignments for context managers.\n\n Raises:\n MultipleContextManagerAssignmentsViolation\n\n ' self._check_target_assignment(node) self.generic_visit(node)
Checks the number of assignments for context managers. Raises: MultipleContextManagerAssignmentsViolation
wemake_python_styleguide/visitors/ast/keywords.py
visit_any_with
piglei/wemake-python-styleguide
1
python
def visit_any_with(self, node: AnyWith) -> None: '\n Checks the number of assignments for context managers.\n\n Raises:\n MultipleContextManagerAssignmentsViolation\n\n ' self._check_target_assignment(node) self.generic_visit(node)
def visit_any_with(self, node: AnyWith) -> None: '\n Checks the number of assignments for context managers.\n\n Raises:\n MultipleContextManagerAssignmentsViolation\n\n ' self._check_target_assignment(node) self.generic_visit(node)<|docstring|>Checks the number of assignments for context managers. Raises: MultipleContextManagerAssignmentsViolation<|endoftext|>
0bdc74699418d7c7adf60d58cae2aac32a7abadb3314d893155041e283010a5f
def __init__(self, *args, **kwargs) -> None: 'Here we store the information about ``yield`` locations.' super().__init__(*args, **kwargs) self._yield_locations: Dict[(int, ast.Expr)] = {}
Here we store the information about ``yield`` locations.
wemake_python_styleguide/visitors/ast/keywords.py
__init__
piglei/wemake-python-styleguide
1
python
def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._yield_locations: Dict[(int, ast.Expr)] = {}
def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._yield_locations: Dict[(int, ast.Expr)] = {}<|docstring|>Here we store the information about ``yield`` locations.<|endoftext|>
079cd8a9c87138d141920878ff7010bc8cdbfdc7eed34a6665365033e8e5a7f9
def visit_any_function(self, node: AnyFunctionDef) -> None: '\n We use this visitor method to check for consecutive ``yield`` nodes.\n\n Raises:\n ConsecutiveYieldsViolation\n\n ' self._check_consecutive_yields(node) self.generic_visit(node)
We use this visitor method to check for consecutive ``yield`` nodes. Raises: ConsecutiveYieldsViolation
wemake_python_styleguide/visitors/ast/keywords.py
visit_any_function
piglei/wemake-python-styleguide
1
python
def visit_any_function(self, node: AnyFunctionDef) -> None: '\n We use this visitor method to check for consecutive ``yield`` nodes.\n\n Raises:\n ConsecutiveYieldsViolation\n\n ' self._check_consecutive_yields(node) self.generic_visit(node)
def visit_any_function(self, node: AnyFunctionDef) -> None: '\n We use this visitor method to check for consecutive ``yield`` nodes.\n\n Raises:\n ConsecutiveYieldsViolation\n\n ' self._check_consecutive_yields(node) self.generic_visit(node)<|docstring|>We use this visitor method to check for consecutive ``yield`` nodes. Raises: ConsecutiveYieldsViolation<|endoftext|>
57a3057332f62e675e845d7678b9931c1988f77ca63d9dd93e4101fd926f5f9c
def visit_YieldFrom(self, node: ast.YieldFrom) -> None: '\n Visits `yield from` nodes.\n\n Raises:\n IncorrectYieldFromTargetViolation\n\n ' self._check_yield_from_type(node) self._check_yield_from_empty(node) self.generic_visit(node)
Visits `yield from` nodes. Raises: IncorrectYieldFromTargetViolation
wemake_python_styleguide/visitors/ast/keywords.py
visit_YieldFrom
piglei/wemake-python-styleguide
1
python
def visit_YieldFrom(self, node: ast.YieldFrom) -> None: '\n Visits `yield from` nodes.\n\n Raises:\n IncorrectYieldFromTargetViolation\n\n ' self._check_yield_from_type(node) self._check_yield_from_empty(node) self.generic_visit(node)
def visit_YieldFrom(self, node: ast.YieldFrom) -> None: '\n Visits `yield from` nodes.\n\n Raises:\n IncorrectYieldFromTargetViolation\n\n ' self._check_yield_from_type(node) self._check_yield_from_empty(node) self.generic_visit(node)<|docstring|>Visits `yield from` nodes. Raises: IncorrectYieldFromTargetViolation<|endoftext|>
c1ac2b06f5a129688be20bfc12ab8e31c98a9b40e35c937aaa21925cff747027
def visit_any_function(self, node: AnyFunctionDef) -> None: '\n Helper to get all ``return`` variables in a function at once.\n\n Raises:\n InconsistentReturnVariableViolation\n\n ' self._check_variables_for_return(node) self.generic_visit(node)
Helper to get all ``return`` variables in a function at once. Raises: InconsistentReturnVariableViolation
wemake_python_styleguide/visitors/ast/keywords.py
visit_any_function
piglei/wemake-python-styleguide
1
python
def visit_any_function(self, node: AnyFunctionDef) -> None: '\n Helper to get all ``return`` variables in a function at once.\n\n Raises:\n InconsistentReturnVariableViolation\n\n ' self._check_variables_for_return(node) self.generic_visit(node)
def visit_any_function(self, node: AnyFunctionDef) -> None: '\n Helper to get all ``return`` variables in a function at once.\n\n Raises:\n InconsistentReturnVariableViolation\n\n ' self._check_variables_for_return(node) self.generic_visit(node)<|docstring|>Helper to get all ``return`` variables in a function at once. Raises: InconsistentReturnVariableViolation<|endoftext|>
70369034b93b606530eacd876e308a10e70ed1804e13aa9404dbd530621d5d3d
def visit_While(self, node: ast.While) -> None: '\n Visits ``while`` keyword and tests that loop will execute.\n\n Raises:\n WrongKeywordConditionViolation\n\n ' self._check_condition(node, node.test) self.generic_visit(node)
Visits ``while`` keyword and tests that loop will execute. Raises: WrongKeywordConditionViolation
wemake_python_styleguide/visitors/ast/keywords.py
visit_While
piglei/wemake-python-styleguide
1
python
def visit_While(self, node: ast.While) -> None: '\n Visits ``while`` keyword and tests that loop will execute.\n\n Raises:\n WrongKeywordConditionViolation\n\n ' self._check_condition(node, node.test) self.generic_visit(node)
def visit_While(self, node: ast.While) -> None: '\n Visits ``while`` keyword and tests that loop will execute.\n\n Raises:\n WrongKeywordConditionViolation\n\n ' self._check_condition(node, node.test) self.generic_visit(node)<|docstring|>Visits ``while`` keyword and tests that loop will execute. Raises: WrongKeywordConditionViolation<|endoftext|>
382d059470588ece7b8e6b7875d19f53c7e8e17d41acbad59c4deedd318f27a6
def visit_Assert(self, node: ast.Assert) -> None: '\n Visits ``assert`` keyword and tests that condition is correct.\n\n Raises:\n WrongKeywordConditionViolation\n\n ' self._check_condition(node, node.test) self.generic_visit(node)
Visits ``assert`` keyword and tests that condition is correct. Raises: WrongKeywordConditionViolation
wemake_python_styleguide/visitors/ast/keywords.py
visit_Assert
piglei/wemake-python-styleguide
1
python
def visit_Assert(self, node: ast.Assert) -> None: '\n Visits ``assert`` keyword and tests that condition is correct.\n\n Raises:\n WrongKeywordConditionViolation\n\n ' self._check_condition(node, node.test) self.generic_visit(node)
def visit_Assert(self, node: ast.Assert) -> None: '\n Visits ``assert`` keyword and tests that condition is correct.\n\n Raises:\n WrongKeywordConditionViolation\n\n ' self._check_condition(node, node.test) self.generic_visit(node)<|docstring|>Visits ``assert`` keyword and tests that condition is correct. Raises: WrongKeywordConditionViolation<|endoftext|>
93ed55f1c3e9ce4bbd35c6efada6ce6af54ed1b2a9d3d4df0ea57936e57e60f8
def __init__(self): 'Performs essential initialization for TimeStamp model' super().__init__() self._timestamp = time.time()
Performs essential initialization for TimeStamp model
radloggerpy/models/timestamp.py
__init__
Dantali0n/RadLoggerPy
0
python
def __init__(self): super().__init__() self._timestamp = time.time()
def __init__(self): super().__init__() self._timestamp = time.time()<|docstring|>Performs essential initialization for TimeStamp model<|endoftext|>
1f64ad710b54e95719b9b16209cf0c244b488f585f9928f157e09c53c6c0d8e3
def set_timestamp(self, timestamp): 'Set the internal timestamp to the passed timestamp in Epoch\n\n :param timestamp: The timestamp in Epoch such as from time.time()\n :type timestamp: float\n ' self._timestamp = timestamp
Set the internal timestamp to the passed timestamp in Epoch :param timestamp: The timestamp in Epoch such as from time.time() :type timestamp: float
radloggerpy/models/timestamp.py
set_timestamp
Dantali0n/RadLoggerPy
0
python
def set_timestamp(self, timestamp): 'Set the internal timestamp to the passed timestamp in Epoch\n\n :param timestamp: The timestamp in Epoch such as from time.time()\n :type timestamp: float\n ' self._timestamp = timestamp
def set_timestamp(self, timestamp): 'Set the internal timestamp to the passed timestamp in Epoch\n\n :param timestamp: The timestamp in Epoch such as from time.time()\n :type timestamp: float\n ' self._timestamp = timestamp<|docstring|>Set the internal timestamp to the passed timestamp in Epoch :param timestamp: The timestamp in Epoch such as from time.time() :type timestamp: float<|endoftext|>
e80f3f7b9092f68066f4d2c23240b134667373216a5b0bb7dd47f256236670a2
def update_timestamp(self): 'Update the internal timestamp to the current time.time() Epoch' self._timestamp = time.time()
Update the internal timestamp to the current time.time() Epoch
radloggerpy/models/timestamp.py
update_timestamp
Dantali0n/RadLoggerPy
0
python
def update_timestamp(self): self._timestamp = time.time()
def update_timestamp(self): self._timestamp = time.time()<|docstring|>Update the internal timestamp to the current time.time() Epoch<|endoftext|>
68c5f83ccbdfffb08471b352ad0bc9f8bcd613aaf77718e908c15e58c96d187c
def get_timestamp(self): 'Retrieve and return the internal timestamp\n\n :return: Epoch, time.time() representation of current time\n :rtype: float\n ' return self._timestamp
Retrieve and return the internal timestamp :return: Epoch, time.time() representation of current time :rtype: float
radloggerpy/models/timestamp.py
get_timestamp
Dantali0n/RadLoggerPy
0
python
def get_timestamp(self): 'Retrieve and return the internal timestamp\n\n :return: Epoch, time.time() representation of current time\n :rtype: float\n ' return self._timestamp
def get_timestamp(self): 'Retrieve and return the internal timestamp\n\n :return: Epoch, time.time() representation of current time\n :rtype: float\n ' return self._timestamp<|docstring|>Retrieve and return the internal timestamp :return: Epoch, time.time() representation of current time :rtype: float<|endoftext|>
7a288a5970ed3d4fe47aa5cefa3a6adda56787140c90e193d9a3ba19a31a015f
def get_arg_kinds(arg_types): "\n Translate `arg_types` of a Term to a canonical form.\n\n Parameters\n ----------\n arg_types : tuple of strings\n The term argument types, as given in the `arg_types` attribute.\n\n Returns\n -------\n arg_kinds : list of strings\n The argument kinds - one of 'virtual_variable', 'state_variable',\n 'parameter_variable', 'opt_material', 'user'.\n " arg_kinds = [] for (ii, arg_type) in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if (ii > 0): msg = ('opt_material at position %d, must be at 0!' % ii) raise ValueError(msg) else: arg_kinds.append('user') return arg_kinds
Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'user'.
sfepy/terms/terms.py
get_arg_kinds
vondrejc/sfepy
0
python
def get_arg_kinds(arg_types): "\n Translate `arg_types` of a Term to a canonical form.\n\n Parameters\n ----------\n arg_types : tuple of strings\n The term argument types, as given in the `arg_types` attribute.\n\n Returns\n -------\n arg_kinds : list of strings\n The argument kinds - one of 'virtual_variable', 'state_variable',\n 'parameter_variable', 'opt_material', 'user'.\n " arg_kinds = [] for (ii, arg_type) in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if (ii > 0): msg = ('opt_material at position %d, must be at 0!' % ii) raise ValueError(msg) else: arg_kinds.append('user') return arg_kinds
def get_arg_kinds(arg_types): "\n Translate `arg_types` of a Term to a canonical form.\n\n Parameters\n ----------\n arg_types : tuple of strings\n The term argument types, as given in the `arg_types` attribute.\n\n Returns\n -------\n arg_kinds : list of strings\n The argument kinds - one of 'virtual_variable', 'state_variable',\n 'parameter_variable', 'opt_material', 'user'.\n " arg_kinds = [] for (ii, arg_type) in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if (ii > 0): msg = ('opt_material at position %d, must be at 0!' % ii) raise ValueError(msg) else: arg_kinds.append('user') return arg_kinds<|docstring|>Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'user'.<|endoftext|>
754c4b0108148e9aef905901dd43011b9388a220a2f3533db3fbe643a569e63a
def get_shape_kind(integration): '\n Get data shape kind for given integration type.\n ' if (integration == 'surface'): shape_kind = 'surface' elif (integration in ('volume', 'plate', 'surface_extra')): shape_kind = 'volume' elif (integration == 'point'): shape_kind = 'point' else: raise NotImplementedError(('unsupported term integration! (%s)' % integration)) return shape_kind
Get data shape kind for given integration type.
sfepy/terms/terms.py
get_shape_kind
vondrejc/sfepy
0
python
def get_shape_kind(integration): '\n \n ' if (integration == 'surface'): shape_kind = 'surface' elif (integration in ('volume', 'plate', 'surface_extra')): shape_kind = 'volume' elif (integration == 'point'): shape_kind = 'point' else: raise NotImplementedError(('unsupported term integration! (%s)' % integration)) return shape_kind
def get_shape_kind(integration): '\n \n ' if (integration == 'surface'): shape_kind = 'surface' elif (integration in ('volume', 'plate', 'surface_extra')): shape_kind = 'volume' elif (integration == 'point'): shape_kind = 'point' else: raise NotImplementedError(('unsupported term integration! (%s)' % integration)) return shape_kind<|docstring|>Get data shape kind for given integration type.<|endoftext|>
519b3eb210452e7dc6a6173e6e174d3651c5d1082d8f2aedf9cfe3d99c9ff733
def split_complex_args(args): "\n Split complex arguments to real and imaginary parts.\n\n Returns\n -------\n newargs : dictionary\n Dictionary with lists corresponding to `args` such that each\n argument of numpy.complex128 data type is split to its real and\n imaginary part. The output depends on the number of complex\n arguments in 'args':\n\n - 0: list (key 'r') identical to input one\n\n - 1: two lists with keys 'r', 'i' corresponding to real\n and imaginary parts\n\n - 2: output dictionary contains four lists:\n\n - 'r' - real(arg1), real(arg2)\n - 'i' - imag(arg1), imag(arg2)\n - 'ri' - real(arg1), imag(arg2)\n - 'ir' - imag(arg1), real(arg2)\n " newargs = {} cai = [] for (ii, arg) in enumerate(args): if (isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128)): cai.append(ii) if (len(cai) > 0): newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if (len(cai) == 2): arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif (len(cai) > 2): raise NotImplementedError(('more than 2 complex arguments! (%d)' % len(cai))) else: newargs['r'] = args[:] return newargs
Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2)
sfepy/terms/terms.py
split_complex_args
vondrejc/sfepy
0
python
def split_complex_args(args): "\n Split complex arguments to real and imaginary parts.\n\n Returns\n -------\n newargs : dictionary\n Dictionary with lists corresponding to `args` such that each\n argument of numpy.complex128 data type is split to its real and\n imaginary part. The output depends on the number of complex\n arguments in 'args':\n\n - 0: list (key 'r') identical to input one\n\n - 1: two lists with keys 'r', 'i' corresponding to real\n and imaginary parts\n\n - 2: output dictionary contains four lists:\n\n - 'r' - real(arg1), real(arg2)\n - 'i' - imag(arg1), imag(arg2)\n - 'ri' - real(arg1), imag(arg2)\n - 'ir' - imag(arg1), real(arg2)\n " newargs = {} cai = [] for (ii, arg) in enumerate(args): if (isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128)): cai.append(ii) if (len(cai) > 0): newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if (len(cai) == 2): arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif (len(cai) > 2): raise NotImplementedError(('more than 2 complex arguments! (%d)' % len(cai))) else: newargs['r'] = args[:] return newargs
def split_complex_args(args): "\n Split complex arguments to real and imaginary parts.\n\n Returns\n -------\n newargs : dictionary\n Dictionary with lists corresponding to `args` such that each\n argument of numpy.complex128 data type is split to its real and\n imaginary part. The output depends on the number of complex\n arguments in 'args':\n\n - 0: list (key 'r') identical to input one\n\n - 1: two lists with keys 'r', 'i' corresponding to real\n and imaginary parts\n\n - 2: output dictionary contains four lists:\n\n - 'r' - real(arg1), real(arg2)\n - 'i' - imag(arg1), imag(arg2)\n - 'ri' - real(arg1), imag(arg2)\n - 'ir' - imag(arg1), real(arg2)\n " newargs = {} cai = [] for (ii, arg) in enumerate(args): if (isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128)): cai.append(ii) if (len(cai) > 0): newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if (len(cai) == 2): arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif (len(cai) > 2): raise NotImplementedError(('more than 2 complex arguments! (%d)' % len(cai))) else: newargs['r'] = args[:] return newargs<|docstring|>Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2)<|endoftext|>
c60f46c5eda599f8efe179965880b634feba7e6afc0a98bb78b6769830eefa5e
@staticmethod def from_desc(term_descs, regions, integrals=None): '\n Create terms, assign each term its region.\n ' from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = ("term '%s' is not in %s" % (td.name, sorted(term_table.keys()))) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError(('region "%s" does not exist!' % td.region)) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms
Create terms, assign each term its region.
sfepy/terms/terms.py
from_desc
vondrejc/sfepy
0
python
@staticmethod def from_desc(term_descs, regions, integrals=None): '\n \n ' from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = ("term '%s' is not in %s" % (td.name, sorted(term_table.keys()))) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError(('region "%s" does not exist!' % td.region)) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms
@staticmethod def from_desc(term_descs, regions, integrals=None): '\n \n ' from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = ("term '%s' is not in %s" % (td.name, sorted(term_table.keys()))) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError(('region "%s" does not exist!' % td.region)) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms<|docstring|>Create terms, assign each term its region.<|endoftext|>
76e303b77c1f9d53c3573a79b0756ece894608fa1838cf6ab40de2918542833a
def assign_args(self, variables, materials, user=None): '\n Assign all term arguments.\n ' for term in self: term.assign_args(variables, materials, user)
Assign all term arguments.
sfepy/terms/terms.py
assign_args
vondrejc/sfepy
0
python
def assign_args(self, variables, materials, user=None): '\n \n ' for term in self: term.assign_args(variables, materials, user)
def assign_args(self, variables, materials, user=None): '\n \n ' for term in self: term.assign_args(variables, materials, user)<|docstring|>Assign all term arguments.<|endoftext|>
93f6815374459ea9d892623bdc0fd2538a3887b001291d02e9e90f9588804ed3
def set_integral(self, integral): '\n Set the term integral.\n ' self.integral = integral if (self.integral is not None): self.integral_name = self.integral.name
Set the term integral.
sfepy/terms/terms.py
set_integral
vondrejc/sfepy
0
python
def set_integral(self, integral): '\n \n ' self.integral = integral if (self.integral is not None): self.integral_name = self.integral.name
def set_integral(self, integral): '\n \n ' self.integral = integral if (self.integral is not None): self.integral_name = self.integral.name<|docstring|>Set the term integral.<|endoftext|>
f29c9b75e8bc95867e32123a6d11ee57d8451dfd184cc3d14cc9fcf4083e8957
def __call__(self, diff_var=None, chunk_size=None, **kwargs): '\n Subclasses either implement __call__ or plug in a proper _call().\n ' return self._call(diff_var, chunk_size, **kwargs)
Subclasses either implement __call__ or plug in a proper _call().
sfepy/terms/terms.py
__call__
vondrejc/sfepy
0
python
def __call__(self, diff_var=None, chunk_size=None, **kwargs): '\n \n ' return self._call(diff_var, chunk_size, **kwargs)
def __call__(self, diff_var=None, chunk_size=None, **kwargs): '\n \n ' return self._call(diff_var, chunk_size, **kwargs)<|docstring|>Subclasses either implement __call__ or plug in a proper _call().<|endoftext|>
aefeb9288af6a20b2bab40cbdd0d8b0285f11f427f373a526e63767418eee0f7
def assign_args(self, variables, materials, user=None): '\n Check term argument existence in variables, materials, user data\n and assign the arguments to terms. Also check compatibility of\n field and term subdomain lists (igs).\n ' if (user is None): user = {} kwargs = {} for arg_name in self.arg_names: if isinstance(arg_name, basestr): if (arg_name in variables.names): kwargs[arg_name] = variables[arg_name] elif (arg_name in user): kwargs[arg_name] = user[arg_name] else: raise ValueError(('argument %s not found!' % arg_name)) else: arg_name = arg_name[0] if (arg_name in materials.names): kwargs[arg_name] = materials[arg_name] else: raise ValueError(('material argument %s not found!' % arg_name)) self.setup_args(**kwargs)
Check term argument existence in variables, materials, user data and assign the arguments to terms. Also check compatibility of field and term subdomain lists (igs).
sfepy/terms/terms.py
assign_args
vondrejc/sfepy
0
python
def assign_args(self, variables, materials, user=None): '\n Check term argument existence in variables, materials, user data\n and assign the arguments to terms. Also check compatibility of\n field and term subdomain lists (igs).\n ' if (user is None): user = {} kwargs = {} for arg_name in self.arg_names: if isinstance(arg_name, basestr): if (arg_name in variables.names): kwargs[arg_name] = variables[arg_name] elif (arg_name in user): kwargs[arg_name] = user[arg_name] else: raise ValueError(('argument %s not found!' % arg_name)) else: arg_name = arg_name[0] if (arg_name in materials.names): kwargs[arg_name] = materials[arg_name] else: raise ValueError(('material argument %s not found!' % arg_name)) self.setup_args(**kwargs)
def assign_args(self, variables, materials, user=None): '\n Check term argument existence in variables, materials, user data\n and assign the arguments to terms. Also check compatibility of\n field and term subdomain lists (igs).\n ' if (user is None): user = {} kwargs = {} for arg_name in self.arg_names: if isinstance(arg_name, basestr): if (arg_name in variables.names): kwargs[arg_name] = variables[arg_name] elif (arg_name in user): kwargs[arg_name] = user[arg_name] else: raise ValueError(('argument %s not found!' % arg_name)) else: arg_name = arg_name[0] if (arg_name in materials.names): kwargs[arg_name] = materials[arg_name] else: raise ValueError(('material argument %s not found!' % arg_name)) self.setup_args(**kwargs)<|docstring|>Check term argument existence in variables, materials, user data and assign the arguments to terms. Also check compatibility of field and term subdomain lists (igs).<|endoftext|>
460376bee6c628553cd8f946f27d9eca9de338929c543f58ee0152539b51687d
def classify_args(self): '\n Classify types of the term arguments and find matching call\n signature.\n\n A state variable can be in place of a parameter variable and\n vice versa.\n ' self.names = Struct(name='arg_names', material=[], variable=[], user=[], state=[], virtual=[], parameter=[]) if isinstance(self.arg_types[0], tuple): arg_types = self.arg_types[0] else: arg_types = self.arg_types if (len(arg_types) == (len(self.args) + 1)): self.args.insert(0, (None, None)) self.arg_names.insert(0, (None, None)) if isinstance(self.arg_types[0], tuple): assert_((len(self.modes) == len(self.arg_types))) matched = [] for (it, arg_types) in enumerate(self.arg_types): arg_kinds = get_arg_kinds(arg_types) if self._check_variables(arg_kinds): matched.append((it, arg_kinds)) if (len(matched) == 1): (i_match, arg_kinds) = matched[0] arg_types = self.arg_types[i_match] self.mode = self.modes[i_match] elif (len(matched) == 0): msg = ('cannot match arguments! (%s)' % self.arg_names) raise ValueError(msg) else: msg = ('ambiguous arguments! (%s)' % self.arg_names) raise ValueError(msg) else: arg_types = self.arg_types arg_kinds = get_arg_kinds(self.arg_types) self.mode = Struct.get(self, 'mode', None) if (not self._check_variables(arg_kinds)): raise ValueError(('cannot match variables! (%s)' % self.arg_names)) self.ats = list(arg_types) for (ii, arg_kind) in enumerate(arg_kinds): name = self.arg_names[ii] if arg_kind.endswith('variable'): names = self.names.variable if (arg_kind == 'virtual_variable'): self.names.virtual.append(name) elif (arg_kind == 'state_variable'): self.names.state.append(name) elif (arg_kind == 'parameter_variable'): self.names.parameter.append(name) elif arg_kind.endswith('material'): names = self.names.material else: names = self.names.user names.append(name) self.n_virtual = len(self.names.virtual) if (self.n_virtual > 1): raise ValueError(('at most one virtual variable is allowed! (%d)' % self.n_virtual)) self.set_arg_types() self.setup_integration()
Classify types of the term arguments and find matching call signature. A state variable can be in place of a parameter variable and vice versa.
sfepy/terms/terms.py
classify_args
vondrejc/sfepy
0
python
def classify_args(self): '\n Classify types of the term arguments and find matching call\n signature.\n\n A state variable can be in place of a parameter variable and\n vice versa.\n ' self.names = Struct(name='arg_names', material=[], variable=[], user=[], state=[], virtual=[], parameter=[]) if isinstance(self.arg_types[0], tuple): arg_types = self.arg_types[0] else: arg_types = self.arg_types if (len(arg_types) == (len(self.args) + 1)): self.args.insert(0, (None, None)) self.arg_names.insert(0, (None, None)) if isinstance(self.arg_types[0], tuple): assert_((len(self.modes) == len(self.arg_types))) matched = [] for (it, arg_types) in enumerate(self.arg_types): arg_kinds = get_arg_kinds(arg_types) if self._check_variables(arg_kinds): matched.append((it, arg_kinds)) if (len(matched) == 1): (i_match, arg_kinds) = matched[0] arg_types = self.arg_types[i_match] self.mode = self.modes[i_match] elif (len(matched) == 0): msg = ('cannot match arguments! (%s)' % self.arg_names) raise ValueError(msg) else: msg = ('ambiguous arguments! (%s)' % self.arg_names) raise ValueError(msg) else: arg_types = self.arg_types arg_kinds = get_arg_kinds(self.arg_types) self.mode = Struct.get(self, 'mode', None) if (not self._check_variables(arg_kinds)): raise ValueError(('cannot match variables! (%s)' % self.arg_names)) self.ats = list(arg_types) for (ii, arg_kind) in enumerate(arg_kinds): name = self.arg_names[ii] if arg_kind.endswith('variable'): names = self.names.variable if (arg_kind == 'virtual_variable'): self.names.virtual.append(name) elif (arg_kind == 'state_variable'): self.names.state.append(name) elif (arg_kind == 'parameter_variable'): self.names.parameter.append(name) elif arg_kind.endswith('material'): names = self.names.material else: names = self.names.user names.append(name) self.n_virtual = len(self.names.virtual) if (self.n_virtual > 1): raise ValueError(('at most one virtual variable is allowed! (%d)' % self.n_virtual)) self.set_arg_types() self.setup_integration()
def classify_args(self): '\n Classify types of the term arguments and find matching call\n signature.\n\n A state variable can be in place of a parameter variable and\n vice versa.\n ' self.names = Struct(name='arg_names', material=[], variable=[], user=[], state=[], virtual=[], parameter=[]) if isinstance(self.arg_types[0], tuple): arg_types = self.arg_types[0] else: arg_types = self.arg_types if (len(arg_types) == (len(self.args) + 1)): self.args.insert(0, (None, None)) self.arg_names.insert(0, (None, None)) if isinstance(self.arg_types[0], tuple): assert_((len(self.modes) == len(self.arg_types))) matched = [] for (it, arg_types) in enumerate(self.arg_types): arg_kinds = get_arg_kinds(arg_types) if self._check_variables(arg_kinds): matched.append((it, arg_kinds)) if (len(matched) == 1): (i_match, arg_kinds) = matched[0] arg_types = self.arg_types[i_match] self.mode = self.modes[i_match] elif (len(matched) == 0): msg = ('cannot match arguments! (%s)' % self.arg_names) raise ValueError(msg) else: msg = ('ambiguous arguments! (%s)' % self.arg_names) raise ValueError(msg) else: arg_types = self.arg_types arg_kinds = get_arg_kinds(self.arg_types) self.mode = Struct.get(self, 'mode', None) if (not self._check_variables(arg_kinds)): raise ValueError(('cannot match variables! (%s)' % self.arg_names)) self.ats = list(arg_types) for (ii, arg_kind) in enumerate(arg_kinds): name = self.arg_names[ii] if arg_kind.endswith('variable'): names = self.names.variable if (arg_kind == 'virtual_variable'): self.names.virtual.append(name) elif (arg_kind == 'state_variable'): self.names.state.append(name) elif (arg_kind == 'parameter_variable'): self.names.parameter.append(name) elif arg_kind.endswith('material'): names = self.names.material else: names = self.names.user names.append(name) self.n_virtual = len(self.names.virtual) if (self.n_virtual > 1): raise ValueError(('at most one virtual variable is allowed! (%d)' % self.n_virtual)) self.set_arg_types() self.setup_integration()<|docstring|>Classify types of the term arguments and find matching call signature. A state variable can be in place of a parameter variable and vice versa.<|endoftext|>
f7e2ebbc73b042df7b71aab856eaa5ddb0105588b6bed8f140498420d9f9985e
def check_args(self): '\n Common checking to all terms.\n\n Check compatibility of field and term subdomain lists (igs).\n ' vns = self.get_variable_names() for name in vns: field = self._kwargs[name].get_field() if (field is None): continue if (not nm.all(in1d(self.region.vertices, field.region.vertices))): msg = (('%s: incompatible regions: (self, field %s)' + '(%s in %s)') % (self.name, field.name, self.region.vertices, field.region.vertices)) raise ValueError(msg)
Common checking to all terms. Check compatibility of field and term subdomain lists (igs).
sfepy/terms/terms.py
check_args
vondrejc/sfepy
0
python
def check_args(self): '\n Common checking to all terms.\n\n Check compatibility of field and term subdomain lists (igs).\n ' vns = self.get_variable_names() for name in vns: field = self._kwargs[name].get_field() if (field is None): continue if (not nm.all(in1d(self.region.vertices, field.region.vertices))): msg = (('%s: incompatible regions: (self, field %s)' + '(%s in %s)') % (self.name, field.name, self.region.vertices, field.region.vertices)) raise ValueError(msg)
def check_args(self): '\n Common checking to all terms.\n\n Check compatibility of field and term subdomain lists (igs).\n ' vns = self.get_variable_names() for name in vns: field = self._kwargs[name].get_field() if (field is None): continue if (not nm.all(in1d(self.region.vertices, field.region.vertices))): msg = (('%s: incompatible regions: (self, field %s)' + '(%s in %s)') % (self.name, field.name, self.region.vertices, field.region.vertices)) raise ValueError(msg)<|docstring|>Common checking to all terms. Check compatibility of field and term subdomain lists (igs).<|endoftext|>
5fcaaedec17a96a0ce26bc3da9095f85242d41aa2e3971b3c9c6fd6e5eaf8db9
def get_state_names(self): '\n If variables are given, return only true unknowns whose data are of\n the current time step (0).\n ' variables = self.get_state_variables() return [var.name for var in variables]
If variables are given, return only true unknowns whose data are of the current time step (0).
sfepy/terms/terms.py
get_state_names
vondrejc/sfepy
0
python
def get_state_names(self): '\n If variables are given, return only true unknowns whose data are of\n the current time step (0).\n ' variables = self.get_state_variables() return [var.name for var in variables]
def get_state_names(self): '\n If variables are given, return only true unknowns whose data are of\n the current time step (0).\n ' variables = self.get_state_variables() return [var.name for var in variables]<|docstring|>If variables are given, return only true unknowns whose data are of the current time step (0).<|endoftext|>
bf40a3860dd371295e7b28ea1800f994fe91b2d6a36e495a1ef71a87f0bac214
def get_conn_key(self): 'The key to be used in DOF connectivity information.' key = ((self.name,) + tuple(self.arg_names)) key += (self.integral_name, self.region.name) return key
The key to be used in DOF connectivity information.
sfepy/terms/terms.py
get_conn_key
vondrejc/sfepy
0
python
def get_conn_key(self): key = ((self.name,) + tuple(self.arg_names)) key += (self.integral_name, self.region.name) return key
def get_conn_key(self): key = ((self.name,) + tuple(self.arg_names)) key += (self.integral_name, self.region.name) return key<|docstring|>The key to be used in DOF connectivity information.<|endoftext|>
129812b359e797874e197150937c1de5d3a65c7b8540898b230425d553936764
def get_args_by_name(self, arg_names): '\n Return arguments by name.\n ' out = [] for name in arg_names: try: ii = self.arg_names.index(name) except ValueError: raise ValueError(('non-existing argument! (%s)' % name)) out.append(self.args[ii]) return out
Return arguments by name.
sfepy/terms/terms.py
get_args_by_name
vondrejc/sfepy
0
python
def get_args_by_name(self, arg_names): '\n \n ' out = [] for name in arg_names: try: ii = self.arg_names.index(name) except ValueError: raise ValueError(('non-existing argument! (%s)' % name)) out.append(self.args[ii]) return out
def get_args_by_name(self, arg_names): '\n \n ' out = [] for name in arg_names: try: ii = self.arg_names.index(name) except ValueError: raise ValueError(('non-existing argument! (%s)' % name)) out.append(self.args[ii]) return out<|docstring|>Return arguments by name.<|endoftext|>
d223c8c6521a13ac0969ead2dd1b7f66b918673bf487317587cb2cd5c2622025
def get_args(self, arg_types=None, **kwargs): '\n Return arguments by type as specified in arg_types (or\n self.ats). Arguments in **kwargs can override the ones assigned\n at the term construction - this is useful for passing user data.\n ' ats = self.ats if (arg_types is None): arg_types = ats args = [] (iname, region_name, ig) = self.get_current_group() for at in arg_types: ii = ats.index(at) arg_name = self.arg_names[ii] if isinstance(arg_name, basestr): if (arg_name in kwargs): args.append(kwargs[arg_name]) else: args.append(self.args[ii]) else: (mat, par_name) = self.args[ii] if (mat is not None): mat_data = mat.get_data((region_name, self.integral_name), ig, par_name) else: mat_data = None args.append(mat_data) return args
Return arguments by type as specified in arg_types (or self.ats). Arguments in **kwargs can override the ones assigned at the term construction - this is useful for passing user data.
sfepy/terms/terms.py
get_args
vondrejc/sfepy
0
python
def get_args(self, arg_types=None, **kwargs): '\n Return arguments by type as specified in arg_types (or\n self.ats). Arguments in **kwargs can override the ones assigned\n at the term construction - this is useful for passing user data.\n ' ats = self.ats if (arg_types is None): arg_types = ats args = [] (iname, region_name, ig) = self.get_current_group() for at in arg_types: ii = ats.index(at) arg_name = self.arg_names[ii] if isinstance(arg_name, basestr): if (arg_name in kwargs): args.append(kwargs[arg_name]) else: args.append(self.args[ii]) else: (mat, par_name) = self.args[ii] if (mat is not None): mat_data = mat.get_data((region_name, self.integral_name), ig, par_name) else: mat_data = None args.append(mat_data) return args
def get_args(self, arg_types=None, **kwargs): '\n Return arguments by type as specified in arg_types (or\n self.ats). Arguments in **kwargs can override the ones assigned\n at the term construction - this is useful for passing user data.\n ' ats = self.ats if (arg_types is None): arg_types = ats args = [] (iname, region_name, ig) = self.get_current_group() for at in arg_types: ii = ats.index(at) arg_name = self.arg_names[ii] if isinstance(arg_name, basestr): if (arg_name in kwargs): args.append(kwargs[arg_name]) else: args.append(self.args[ii]) else: (mat, par_name) = self.args[ii] if (mat is not None): mat_data = mat.get_data((region_name, self.integral_name), ig, par_name) else: mat_data = None args.append(mat_data) return args<|docstring|>Return arguments by type as specified in arg_types (or self.ats). Arguments in **kwargs can override the ones assigned at the term construction - this is useful for passing user data.<|endoftext|>
dc91edd08de08071ff61cec7c6e0e2057a29b48226b0f345ea75c2b6bd22a91d
def get_kwargs(self, keys, **kwargs): 'Extract arguments from **kwargs listed in keys (default is\n None).' return [kwargs.get(name) for name in keys]
Extract arguments from **kwargs listed in keys (default is None).
sfepy/terms/terms.py
get_kwargs
vondrejc/sfepy
0
python
def get_kwargs(self, keys, **kwargs): 'Extract arguments from **kwargs listed in keys (default is\n None).' return [kwargs.get(name) for name in keys]
def get_kwargs(self, keys, **kwargs): 'Extract arguments from **kwargs listed in keys (default is\n None).' return [kwargs.get(name) for name in keys]<|docstring|>Extract arguments from **kwargs listed in keys (default is None).<|endoftext|>
6d99783a51814ef503f82851920e06c0ffb70bdbfac9c9231546031b50ab84a8
def get_arg_name(self, arg_type, full=False, join=None): "\n Get the name of the argument specified by `arg_type.`\n\n Parameters\n ----------\n arg_type : str\n The argument type string.\n full : bool\n If True, return the full name. For example, if the name of a\n variable argument is 'u' and its time derivative is\n requested, the full name is 'du/dt'.\n join : str, optional\n Optionally, the material argument name tuple can be joined\n to a single string using the `join` string.\n\n Returns\n -------\n name : str\n The argument name.\n " try: ii = self.ats.index(arg_type) except ValueError: return None name = self.arg_names[ii] if full: if self.arg_derivatives[name]: name = ('d%s/%s' % (name, self.arg_derivatives[name])) if ((join is not None) and isinstance(name, tuple)): name = join.join(name) return name
Get the name of the argument specified by `arg_type.` Parameters ---------- arg_type : str The argument type string. full : bool If True, return the full name. For example, if the name of a variable argument is 'u' and its time derivative is requested, the full name is 'du/dt'. join : str, optional Optionally, the material argument name tuple can be joined to a single string using the `join` string. Returns ------- name : str The argument name.
sfepy/terms/terms.py
get_arg_name
vondrejc/sfepy
0
python
def get_arg_name(self, arg_type, full=False, join=None): "\n Get the name of the argument specified by `arg_type.`\n\n Parameters\n ----------\n arg_type : str\n The argument type string.\n full : bool\n If True, return the full name. For example, if the name of a\n variable argument is 'u' and its time derivative is\n requested, the full name is 'du/dt'.\n join : str, optional\n Optionally, the material argument name tuple can be joined\n to a single string using the `join` string.\n\n Returns\n -------\n name : str\n The argument name.\n " try: ii = self.ats.index(arg_type) except ValueError: return None name = self.arg_names[ii] if full: if self.arg_derivatives[name]: name = ('d%s/%s' % (name, self.arg_derivatives[name])) if ((join is not None) and isinstance(name, tuple)): name = join.join(name) return name
def get_arg_name(self, arg_type, full=False, join=None): "\n Get the name of the argument specified by `arg_type.`\n\n Parameters\n ----------\n arg_type : str\n The argument type string.\n full : bool\n If True, return the full name. For example, if the name of a\n variable argument is 'u' and its time derivative is\n requested, the full name is 'du/dt'.\n join : str, optional\n Optionally, the material argument name tuple can be joined\n to a single string using the `join` string.\n\n Returns\n -------\n name : str\n The argument name.\n " try: ii = self.ats.index(arg_type) except ValueError: return None name = self.arg_names[ii] if full: if self.arg_derivatives[name]: name = ('d%s/%s' % (name, self.arg_derivatives[name])) if ((join is not None) and isinstance(name, tuple)): name = join.join(name) return name<|docstring|>Get the name of the argument specified by `arg_type.` Parameters ---------- arg_type : str The argument type string. full : bool If True, return the full name. For example, if the name of a variable argument is 'u' and its time derivative is requested, the full name is 'du/dt'. join : str, optional Optionally, the material argument name tuple can be joined to a single string using the `join` string. Returns ------- name : str The argument name.<|endoftext|>
774768d9c96b8e5a318d9e71341a29ec57511650d6354a3536cd568e1b2367f0
def get_geometry_types(self): '\n Returns\n -------\n out : dict\n The required geometry types for each variable argument.\n ' return self.geometry_types
Returns ------- out : dict The required geometry types for each variable argument.
sfepy/terms/terms.py
get_geometry_types
vondrejc/sfepy
0
python
def get_geometry_types(self): '\n Returns\n -------\n out : dict\n The required geometry types for each variable argument.\n ' return self.geometry_types
def get_geometry_types(self): '\n Returns\n -------\n out : dict\n The required geometry types for each variable argument.\n ' return self.geometry_types<|docstring|>Returns ------- out : dict The required geometry types for each variable argument.<|endoftext|>
95c5aefc6135ca13421ee91541d42ff166c66832f6f2c4e62daf05393876d331
def get_assembling_cells(self, shape=None): '\n Return the assembling cell indices into a DOF connectivity.\n ' cells = nm.arange(shape[0], dtype=nm.int32) return cells
Return the assembling cell indices into a DOF connectivity.
sfepy/terms/terms.py
get_assembling_cells
vondrejc/sfepy
0
python
def get_assembling_cells(self, shape=None): '\n \n ' cells = nm.arange(shape[0], dtype=nm.int32) return cells
def get_assembling_cells(self, shape=None): '\n \n ' cells = nm.arange(shape[0], dtype=nm.int32) return cells<|docstring|>Return the assembling cell indices into a DOF connectivity.<|endoftext|>
2312577baeef14d1621f3fbed408ca8f26a8d0a4ed3865845bd9c7ab4fcadfa3
def advance(self, ts): '\n Advance to the next time step. Implemented in subclasses.\n '
Advance to the next time step. Implemented in subclasses.
sfepy/terms/terms.py
advance
vondrejc/sfepy
0
python
def advance(self, ts): '\n \n '
def advance(self, ts): '\n \n '<|docstring|>Advance to the next time step. Implemented in subclasses.<|endoftext|>
14d4c6ef43fe2c4fee0d2f55e93137fff5f4e5d73430a61cf4b002ca0905def7
def get_vector(self, variable): 'Get the vector stored in `variable` according to self.arg_steps\n and self.arg_derivatives. Supports only the backward difference w.r.t.\n time.' name = variable.name return variable(step=self.arg_steps[name], derivative=self.arg_derivatives[name])
Get the vector stored in `variable` according to self.arg_steps and self.arg_derivatives. Supports only the backward difference w.r.t. time.
sfepy/terms/terms.py
get_vector
vondrejc/sfepy
0
python
def get_vector(self, variable): 'Get the vector stored in `variable` according to self.arg_steps\n and self.arg_derivatives. Supports only the backward difference w.r.t.\n time.' name = variable.name return variable(step=self.arg_steps[name], derivative=self.arg_derivatives[name])
def get_vector(self, variable): 'Get the vector stored in `variable` according to self.arg_steps\n and self.arg_derivatives. Supports only the backward difference w.r.t.\n time.' name = variable.name return variable(step=self.arg_steps[name], derivative=self.arg_derivatives[name])<|docstring|>Get the vector stored in `variable` according to self.arg_steps and self.arg_derivatives. Supports only the backward difference w.r.t. time.<|endoftext|>
9387f1cd297fb25cdf1dd375a0d5d5eeae7dfd3b7b27cebe9bddc4f7ad93db0e
def get_approximation(self, variable, get_saved=False): '\n Return approximation corresponding to `variable`. Also return\n the corresponding geometry (actual or saved, according to\n `get_saved`).\n ' (geo, _, key) = self.get_mapping(variable, get_saved=get_saved, return_key=True) ig = key[2] ap = variable.get_approximation(ig) return (ap, geo)
Return approximation corresponding to `variable`. Also return the corresponding geometry (actual or saved, according to `get_saved`).
sfepy/terms/terms.py
get_approximation
vondrejc/sfepy
0
python
def get_approximation(self, variable, get_saved=False): '\n Return approximation corresponding to `variable`. Also return\n the corresponding geometry (actual or saved, according to\n `get_saved`).\n ' (geo, _, key) = self.get_mapping(variable, get_saved=get_saved, return_key=True) ig = key[2] ap = variable.get_approximation(ig) return (ap, geo)
def get_approximation(self, variable, get_saved=False): '\n Return approximation corresponding to `variable`. Also return\n the corresponding geometry (actual or saved, according to\n `get_saved`).\n ' (geo, _, key) = self.get_mapping(variable, get_saved=get_saved, return_key=True) ig = key[2] ap = variable.get_approximation(ig) return (ap, geo)<|docstring|>Return approximation corresponding to `variable`. Also return the corresponding geometry (actual or saved, according to `get_saved`).<|endoftext|>
a0b8a20e07b87a4ab46ab79e6ba69fcdbd168e762810ba67ef9ff76d973ee3e7
def get_qp_key(self): '\n Return a key identifying uniquely the term quadrature points.\n ' return (self.region.name, self.integral.name)
Return a key identifying uniquely the term quadrature points.
sfepy/terms/terms.py
get_qp_key
vondrejc/sfepy
0
python
def get_qp_key(self): '\n \n ' return (self.region.name, self.integral.name)
def get_qp_key(self): '\n \n ' return (self.region.name, self.integral.name)<|docstring|>Return a key identifying uniquely the term quadrature points.<|endoftext|>
308a27cd791fdcf310b78ec2efad6bf49c19598e5452fa15026f12becf617867
def get_physical_qps(self): '\n Get physical quadrature points corresponding to the term region\n and integral.\n ' from sfepy.discrete.common.mappings import get_physical_qps, PhysicalQPs if (self.integration == 'point'): phys_qps = PhysicalQPs(self.region.igs) elif (self.integration == 'plate'): phys_qps = get_physical_qps(self.region, self.integral, map_kind='v') else: phys_qps = get_physical_qps(self.region, self.integral) return phys_qps
Get physical quadrature points corresponding to the term region and integral.
sfepy/terms/terms.py
get_physical_qps
vondrejc/sfepy
0
python
def get_physical_qps(self): '\n Get physical quadrature points corresponding to the term region\n and integral.\n ' from sfepy.discrete.common.mappings import get_physical_qps, PhysicalQPs if (self.integration == 'point'): phys_qps = PhysicalQPs(self.region.igs) elif (self.integration == 'plate'): phys_qps = get_physical_qps(self.region, self.integral, map_kind='v') else: phys_qps = get_physical_qps(self.region, self.integral) return phys_qps
def get_physical_qps(self): '\n Get physical quadrature points corresponding to the term region\n and integral.\n ' from sfepy.discrete.common.mappings import get_physical_qps, PhysicalQPs if (self.integration == 'point'): phys_qps = PhysicalQPs(self.region.igs) elif (self.integration == 'plate'): phys_qps = get_physical_qps(self.region, self.integral, map_kind='v') else: phys_qps = get_physical_qps(self.region, self.integral) return phys_qps<|docstring|>Get physical quadrature points corresponding to the term region and integral.<|endoftext|>
d62e889029a42f42167ba6372e4771a85036554bbd4341bdd6870e5a45e9d6f0
def get_mapping(self, variable, get_saved=False, return_key=False): '\n Get the reference mapping from a variable.\n\n Notes\n -----\n This is a convenience wrapper of Field.get_mapping() that\n initializes the arguments using the term data.\n ' integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: (region, ig_map, ig_map_i) = self.region.get_mirror_region() ig = ig_map_i[self.char_fun.ig] else: region = self.region ig = self.char_fun.ig out = variable.field.get_mapping(ig, region, self.integral, integration, get_saved=get_saved, return_key=return_key) return out
Get the reference mapping from a variable. Notes ----- This is a convenience wrapper of Field.get_mapping() that initializes the arguments using the term data.
sfepy/terms/terms.py
get_mapping
vondrejc/sfepy
0
python
def get_mapping(self, variable, get_saved=False, return_key=False): '\n Get the reference mapping from a variable.\n\n Notes\n -----\n This is a convenience wrapper of Field.get_mapping() that\n initializes the arguments using the term data.\n ' integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: (region, ig_map, ig_map_i) = self.region.get_mirror_region() ig = ig_map_i[self.char_fun.ig] else: region = self.region ig = self.char_fun.ig out = variable.field.get_mapping(ig, region, self.integral, integration, get_saved=get_saved, return_key=return_key) return out
def get_mapping(self, variable, get_saved=False, return_key=False): '\n Get the reference mapping from a variable.\n\n Notes\n -----\n This is a convenience wrapper of Field.get_mapping() that\n initializes the arguments using the term data.\n ' integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: (region, ig_map, ig_map_i) = self.region.get_mirror_region() ig = ig_map_i[self.char_fun.ig] else: region = self.region ig = self.char_fun.ig out = variable.field.get_mapping(ig, region, self.integral, integration, get_saved=get_saved, return_key=return_key) return out<|docstring|>Get the reference mapping from a variable. Notes ----- This is a convenience wrapper of Field.get_mapping() that initializes the arguments using the term data.<|endoftext|>
829a186855efcd6a0999d652220ac40069591d84b8f7635e308ca870e4e92af7
def get_data_shape(self, variable): '\n Get data shape information from variable.\n\n Notes\n -----\n This is a convenience wrapper of FieldVariable.get_data_shape() that\n initializes the arguments using the term data.\n ' integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: (region, ig_map, ig_map_i) = self.region.get_mirror_region() ig = ig_map_i[self.char_fun.ig] else: region = self.region ig = self.char_fun.ig out = variable.get_data_shape(ig, self.integral, integration, region.name) return out
Get data shape information from variable. Notes ----- This is a convenience wrapper of FieldVariable.get_data_shape() that initializes the arguments using the term data.
sfepy/terms/terms.py
get_data_shape
vondrejc/sfepy
0
python
def get_data_shape(self, variable): '\n Get data shape information from variable.\n\n Notes\n -----\n This is a convenience wrapper of FieldVariable.get_data_shape() that\n initializes the arguments using the term data.\n ' integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: (region, ig_map, ig_map_i) = self.region.get_mirror_region() ig = ig_map_i[self.char_fun.ig] else: region = self.region ig = self.char_fun.ig out = variable.get_data_shape(ig, self.integral, integration, region.name) return out
def get_data_shape(self, variable): '\n Get data shape information from variable.\n\n Notes\n -----\n This is a convenience wrapper of FieldVariable.get_data_shape() that\n initializes the arguments using the term data.\n ' integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: (region, ig_map, ig_map_i) = self.region.get_mirror_region() ig = ig_map_i[self.char_fun.ig] else: region = self.region ig = self.char_fun.ig out = variable.get_data_shape(ig, self.integral, integration, region.name) return out<|docstring|>Get data shape information from variable. Notes ----- This is a convenience wrapper of FieldVariable.get_data_shape() that initializes the arguments using the term data.<|endoftext|>
bf8e6df6bbc0c19b79934325fdec75a3b4cfa69efc7babad81baa2e2b88ae43b
def get(self, variable, quantity_name, bf=None, integration=None, step=None, time_derivative=None): '\n Get the named quantity related to the variable.\n\n Notes\n -----\n This is a convenience wrapper of Variable.evaluate() that\n initializes the arguments using the term data.\n ' name = variable.name step = get_default(step, self.arg_steps[name]) time_derivative = get_default(time_derivative, self.arg_derivatives[name]) integration = get_default(integration, self.geometry_types[name]) data = variable.evaluate(self.char_fun.ig, mode=quantity_name, region=self.region, integral=self.integral, integration=integration, step=step, time_derivative=time_derivative, is_trace=self.arg_traces[name], bf=bf) return data
Get the named quantity related to the variable. Notes ----- This is a convenience wrapper of Variable.evaluate() that initializes the arguments using the term data.
sfepy/terms/terms.py
get
vondrejc/sfepy
0
python
def get(self, variable, quantity_name, bf=None, integration=None, step=None, time_derivative=None): '\n Get the named quantity related to the variable.\n\n Notes\n -----\n This is a convenience wrapper of Variable.evaluate() that\n initializes the arguments using the term data.\n ' name = variable.name step = get_default(step, self.arg_steps[name]) time_derivative = get_default(time_derivative, self.arg_derivatives[name]) integration = get_default(integration, self.geometry_types[name]) data = variable.evaluate(self.char_fun.ig, mode=quantity_name, region=self.region, integral=self.integral, integration=integration, step=step, time_derivative=time_derivative, is_trace=self.arg_traces[name], bf=bf) return data
def get(self, variable, quantity_name, bf=None, integration=None, step=None, time_derivative=None): '\n Get the named quantity related to the variable.\n\n Notes\n -----\n This is a convenience wrapper of Variable.evaluate() that\n initializes the arguments using the term data.\n ' name = variable.name step = get_default(step, self.arg_steps[name]) time_derivative = get_default(time_derivative, self.arg_derivatives[name]) integration = get_default(integration, self.geometry_types[name]) data = variable.evaluate(self.char_fun.ig, mode=quantity_name, region=self.region, integral=self.integral, integration=integration, step=step, time_derivative=time_derivative, is_trace=self.arg_traces[name], bf=bf) return data<|docstring|>Get the named quantity related to the variable. Notes ----- This is a convenience wrapper of Variable.evaluate() that initializes the arguments using the term data.<|endoftext|>
cedc2fbeff4461525add662a5e61753ddc057d9149022aedd14e6206f14eb4c3
def check_shapes(self, *args, **kwargs): '\n Default implementation of function to check term argument shapes\n at run-time.\n ' pass
Default implementation of function to check term argument shapes at run-time.
sfepy/terms/terms.py
check_shapes
vondrejc/sfepy
0
python
def check_shapes(self, *args, **kwargs): '\n Default implementation of function to check term argument shapes\n at run-time.\n ' pass
def check_shapes(self, *args, **kwargs): '\n Default implementation of function to check term argument shapes\n at run-time.\n ' pass<|docstring|>Default implementation of function to check term argument shapes at run-time.<|endoftext|>
3b062e396055387fba2c9b5f51f7eaa4616c2101345f853ba8761bd32022b5ac
def evaluate(self, mode='eval', diff_var=None, standalone=True, ret_status=False, **kwargs): "\n Evaluate the term.\n\n Parameters\n ----------\n mode : 'eval' (default), or 'weak'\n The term evaluation mode.\n\n Returns\n -------\n val : float or array\n In 'eval' mode, the term returns a single value (the\n integral, it does not need to be a scalar), while in 'weak'\n mode it returns an array for each element.\n status : int, optional\n The flag indicating evaluation success (0) or failure\n (nonzero). Only provided if `ret_status` is True.\n iels : array of ints, optional\n The local elements indices in 'weak' mode. Only provided in\n non-'eval' modes.\n " if standalone: self.standalone_setup() kwargs = kwargs.copy() term_mode = kwargs.pop('term_mode', None) if (mode == 'eval'): val = 0.0 status = 0 for ig in self.iter_groups(): args = self.get_args(**kwargs) self.check_shapes(*args) _args = (tuple(args) + (mode, term_mode, diff_var)) fargs = self.call_get_fargs(_args, kwargs) (shape, dtype) = self.get_eval_shape(*_args, **kwargs) if (dtype == nm.float64): (_v, stat) = self.eval_real(shape, fargs, mode, term_mode, **kwargs) elif (dtype == nm.complex128): (_v, stat) = self.eval_complex(shape, fargs, mode, term_mode, **kwargs) else: raise ValueError(('unsupported term dtype! (%s)' % dtype)) val += _v status += stat val *= self.sign elif (mode in ('el_avg', 'el', 'qp')): vals = None iels = nm.empty((0, 2), dtype=nm.int32) status = 0 for ig in self.iter_groups(): args = self.get_args(**kwargs) self.check_shapes(*args) _args = (tuple(args) + (mode, term_mode, diff_var)) fargs = self.call_get_fargs(_args, kwargs) (shape, dtype) = self.get_eval_shape(*_args, **kwargs) if (dtype == nm.float64): (val, stat) = self.eval_real(shape, fargs, mode, term_mode, **kwargs) elif (dtype == nm.complex128): (val, stat) = self.eval_complex(shape, fargs, mode, term_mode, **kwargs) if (vals is None): vals = val else: vals = nm.r_[(vals, val)] _iels = self.get_assembling_cells(val.shape) aux = nm.c_[(nm.repeat(ig, _iels.shape[0])[(:, None)], _iels[(:, None)])] iels = nm.r_[(iels, aux)] status += stat vals *= self.sign elif (mode == 'weak'): vals = [] iels = [] status = 0 varr = self.get_virtual_variable() if (diff_var is not None): varc = self.get_variables(as_list=False)[diff_var] for ig in self.iter_groups(): args = self.get_args(**kwargs) self.check_shapes(*args) _args = (tuple(args) + (mode, term_mode, diff_var)) fargs = self.call_get_fargs(_args, kwargs) (n_elr, n_qpr, dim, n_enr, n_cr) = self.get_data_shape(varr) n_row = (n_cr * n_enr) if (diff_var is None): shape = (n_elr, 1, n_row, 1) else: (n_elc, n_qpc, dim, n_enc, n_cc) = self.get_data_shape(varc) n_col = (n_cc * n_enc) shape = (n_elr, 1, n_row, n_col) if (varr.dtype == nm.float64): (val, stat) = self.eval_real(shape, fargs, mode, term_mode, diff_var, **kwargs) elif (varr.dtype == nm.complex128): (val, stat) = self.eval_complex(shape, fargs, mode, term_mode, diff_var, **kwargs) else: raise ValueError(('unsupported term dtype! (%s)' % varr.dtype)) vals.append((self.sign * val)) iels.append((ig, self.get_assembling_cells(val.shape))) status += stat if (mode == 'eval'): out = (val,) else: out = (vals, iels) if goptions['check_term_finiteness']: assert_(nm.isfinite(out[0]).all(), msg=('%+.2e * %s.%d.%s(%s) term values not finite!' % (self.sign, self.name, self.integral.order, self.region.name, self.arg_str))) if ret_status: out = (out + (status,)) if (len(out) == 1): out = out[0] return out
Evaluate the term. Parameters ---------- mode : 'eval' (default), or 'weak' The term evaluation mode. Returns ------- val : float or array In 'eval' mode, the term returns a single value (the integral, it does not need to be a scalar), while in 'weak' mode it returns an array for each element. status : int, optional The flag indicating evaluation success (0) or failure (nonzero). Only provided if `ret_status` is True. iels : array of ints, optional The local elements indices in 'weak' mode. Only provided in non-'eval' modes.
sfepy/terms/terms.py
evaluate
vondrejc/sfepy
0
python
def evaluate(self, mode='eval', diff_var=None, standalone=True, ret_status=False, **kwargs): "\n Evaluate the term.\n\n Parameters\n ----------\n mode : 'eval' (default), or 'weak'\n The term evaluation mode.\n\n Returns\n -------\n val : float or array\n In 'eval' mode, the term returns a single value (the\n integral, it does not need to be a scalar), while in 'weak'\n mode it returns an array for each element.\n status : int, optional\n The flag indicating evaluation success (0) or failure\n (nonzero). Only provided if `ret_status` is True.\n iels : array of ints, optional\n The local elements indices in 'weak' mode. Only provided in\n non-'eval' modes.\n " if standalone: self.standalone_setup() kwargs = kwargs.copy() term_mode = kwargs.pop('term_mode', None) if (mode == 'eval'): val = 0.0 status = 0 for ig in self.iter_groups(): args = self.get_args(**kwargs) self.check_shapes(*args) _args = (tuple(args) + (mode, term_mode, diff_var)) fargs = self.call_get_fargs(_args, kwargs) (shape, dtype) = self.get_eval_shape(*_args, **kwargs) if (dtype == nm.float64): (_v, stat) = self.eval_real(shape, fargs, mode, term_mode, **kwargs) elif (dtype == nm.complex128): (_v, stat) = self.eval_complex(shape, fargs, mode, term_mode, **kwargs) else: raise ValueError(('unsupported term dtype! (%s)' % dtype)) val += _v status += stat val *= self.sign elif (mode in ('el_avg', 'el', 'qp')): vals = None iels = nm.empty((0, 2), dtype=nm.int32) status = 0 for ig in self.iter_groups(): args = self.get_args(**kwargs) self.check_shapes(*args) _args = (tuple(args) + (mode, term_mode, diff_var)) fargs = self.call_get_fargs(_args, kwargs) (shape, dtype) = self.get_eval_shape(*_args, **kwargs) if (dtype == nm.float64): (val, stat) = self.eval_real(shape, fargs, mode, term_mode, **kwargs) elif (dtype == nm.complex128): (val, stat) = self.eval_complex(shape, fargs, mode, term_mode, **kwargs) if (vals is None): vals = val else: vals = nm.r_[(vals, val)] _iels = self.get_assembling_cells(val.shape) aux = nm.c_[(nm.repeat(ig, _iels.shape[0])[(:, None)], _iels[(:, None)])] iels = nm.r_[(iels, aux)] status += stat vals *= self.sign elif (mode == 'weak'): vals = [] iels = [] status = 0 varr = self.get_virtual_variable() if (diff_var is not None): varc = self.get_variables(as_list=False)[diff_var] for ig in self.iter_groups(): args = self.get_args(**kwargs) self.check_shapes(*args) _args = (tuple(args) + (mode, term_mode, diff_var)) fargs = self.call_get_fargs(_args, kwargs) (n_elr, n_qpr, dim, n_enr, n_cr) = self.get_data_shape(varr) n_row = (n_cr * n_enr) if (diff_var is None): shape = (n_elr, 1, n_row, 1) else: (n_elc, n_qpc, dim, n_enc, n_cc) = self.get_data_shape(varc) n_col = (n_cc * n_enc) shape = (n_elr, 1, n_row, n_col) if (varr.dtype == nm.float64): (val, stat) = self.eval_real(shape, fargs, mode, term_mode, diff_var, **kwargs) elif (varr.dtype == nm.complex128): (val, stat) = self.eval_complex(shape, fargs, mode, term_mode, diff_var, **kwargs) else: raise ValueError(('unsupported term dtype! (%s)' % varr.dtype)) vals.append((self.sign * val)) iels.append((ig, self.get_assembling_cells(val.shape))) status += stat if (mode == 'eval'): out = (val,) else: out = (vals, iels) if goptions['check_term_finiteness']: assert_(nm.isfinite(out[0]).all(), msg=('%+.2e * %s.%d.%s(%s) term values not finite!' % (self.sign, self.name, self.integral.order, self.region.name, self.arg_str))) if ret_status: out = (out + (status,)) if (len(out) == 1): out = out[0] return out
def evaluate(self, mode='eval', diff_var=None, standalone=True, ret_status=False, **kwargs): "\n Evaluate the term.\n\n Parameters\n ----------\n mode : 'eval' (default), or 'weak'\n The term evaluation mode.\n\n Returns\n -------\n val : float or array\n In 'eval' mode, the term returns a single value (the\n integral, it does not need to be a scalar), while in 'weak'\n mode it returns an array for each element.\n status : int, optional\n The flag indicating evaluation success (0) or failure\n (nonzero). Only provided if `ret_status` is True.\n iels : array of ints, optional\n The local elements indices in 'weak' mode. Only provided in\n non-'eval' modes.\n " if standalone: self.standalone_setup() kwargs = kwargs.copy() term_mode = kwargs.pop('term_mode', None) if (mode == 'eval'): val = 0.0 status = 0 for ig in self.iter_groups(): args = self.get_args(**kwargs) self.check_shapes(*args) _args = (tuple(args) + (mode, term_mode, diff_var)) fargs = self.call_get_fargs(_args, kwargs) (shape, dtype) = self.get_eval_shape(*_args, **kwargs) if (dtype == nm.float64): (_v, stat) = self.eval_real(shape, fargs, mode, term_mode, **kwargs) elif (dtype == nm.complex128): (_v, stat) = self.eval_complex(shape, fargs, mode, term_mode, **kwargs) else: raise ValueError(('unsupported term dtype! (%s)' % dtype)) val += _v status += stat val *= self.sign elif (mode in ('el_avg', 'el', 'qp')): vals = None iels = nm.empty((0, 2), dtype=nm.int32) status = 0 for ig in self.iter_groups(): args = self.get_args(**kwargs) self.check_shapes(*args) _args = (tuple(args) + (mode, term_mode, diff_var)) fargs = self.call_get_fargs(_args, kwargs) (shape, dtype) = self.get_eval_shape(*_args, **kwargs) if (dtype == nm.float64): (val, stat) = self.eval_real(shape, fargs, mode, term_mode, **kwargs) elif (dtype == nm.complex128): (val, stat) = self.eval_complex(shape, fargs, mode, term_mode, **kwargs) if (vals is None): vals = val else: vals = nm.r_[(vals, val)] _iels = self.get_assembling_cells(val.shape) aux = nm.c_[(nm.repeat(ig, _iels.shape[0])[(:, None)], _iels[(:, None)])] iels = nm.r_[(iels, aux)] status += stat vals *= self.sign elif (mode == 'weak'): vals = [] iels = [] status = 0 varr = self.get_virtual_variable() if (diff_var is not None): varc = self.get_variables(as_list=False)[diff_var] for ig in self.iter_groups(): args = self.get_args(**kwargs) self.check_shapes(*args) _args = (tuple(args) + (mode, term_mode, diff_var)) fargs = self.call_get_fargs(_args, kwargs) (n_elr, n_qpr, dim, n_enr, n_cr) = self.get_data_shape(varr) n_row = (n_cr * n_enr) if (diff_var is None): shape = (n_elr, 1, n_row, 1) else: (n_elc, n_qpc, dim, n_enc, n_cc) = self.get_data_shape(varc) n_col = (n_cc * n_enc) shape = (n_elr, 1, n_row, n_col) if (varr.dtype == nm.float64): (val, stat) = self.eval_real(shape, fargs, mode, term_mode, diff_var, **kwargs) elif (varr.dtype == nm.complex128): (val, stat) = self.eval_complex(shape, fargs, mode, term_mode, diff_var, **kwargs) else: raise ValueError(('unsupported term dtype! (%s)' % varr.dtype)) vals.append((self.sign * val)) iels.append((ig, self.get_assembling_cells(val.shape))) status += stat if (mode == 'eval'): out = (val,) else: out = (vals, iels) if goptions['check_term_finiteness']: assert_(nm.isfinite(out[0]).all(), msg=('%+.2e * %s.%d.%s(%s) term values not finite!' % (self.sign, self.name, self.integral.order, self.region.name, self.arg_str))) if ret_status: out = (out + (status,)) if (len(out) == 1): out = out[0] return out<|docstring|>Evaluate the term. Parameters ---------- mode : 'eval' (default), or 'weak' The term evaluation mode. Returns ------- val : float or array In 'eval' mode, the term returns a single value (the integral, it does not need to be a scalar), while in 'weak' mode it returns an array for each element. status : int, optional The flag indicating evaluation success (0) or failure (nonzero). Only provided if `ret_status` is True. iels : array of ints, optional The local elements indices in 'weak' mode. Only provided in non-'eval' modes.<|endoftext|>
8a0e98d072fee048a5a59054860d2c03a89497aa444925e85c72c1365859eb55
def generate_python_protocol_classes_from_json(parsed_json: Union[(List, Dict)], file_name: str='json'): "\n\n :param file_name: name to be used to save file and for root class when top level json is a list. Ending '_interface' will\n be appended to ending of file name\n :param parsed_json:\n :return:\n " all_text = _generate_classes_text(file_name, parsed_json) print(all_text) if file_name.endswith('.py'): file_name = file_name.strip('.py') file_name += '_protocol.py' else: file_name += '_protocol.py' if os.path.exists(file_name): raise Exception(f"File '{file_name}' already exists") else: with open(file_name, 'w') as file: file.write(all_text) print(f"Saved file '{file_name}'")
:param file_name: name to be used to save file and for root class when top level json is a list. Ending '_interface' will be appended to ending of file name :param parsed_json: :return:
json2pytocol/json_to_python_protocol.py
generate_python_protocol_classes_from_json
piacenti/protoson
0
python
def generate_python_protocol_classes_from_json(parsed_json: Union[(List, Dict)], file_name: str='json'): "\n\n :param file_name: name to be used to save file and for root class when top level json is a list. Ending '_interface' will\n be appended to ending of file name\n :param parsed_json:\n :return:\n " all_text = _generate_classes_text(file_name, parsed_json) print(all_text) if file_name.endswith('.py'): file_name = file_name.strip('.py') file_name += '_protocol.py' else: file_name += '_protocol.py' if os.path.exists(file_name): raise Exception(f"File '{file_name}' already exists") else: with open(file_name, 'w') as file: file.write(all_text) print(f"Saved file '{file_name}'")
def generate_python_protocol_classes_from_json(parsed_json: Union[(List, Dict)], file_name: str='json'): "\n\n :param file_name: name to be used to save file and for root class when top level json is a list. Ending '_interface' will\n be appended to ending of file name\n :param parsed_json:\n :return:\n " all_text = _generate_classes_text(file_name, parsed_json) print(all_text) if file_name.endswith('.py'): file_name = file_name.strip('.py') file_name += '_protocol.py' else: file_name += '_protocol.py' if os.path.exists(file_name): raise Exception(f"File '{file_name}' already exists") else: with open(file_name, 'w') as file: file.write(all_text) print(f"Saved file '{file_name}'")<|docstring|>:param file_name: name to be used to save file and for root class when top level json is a list. Ending '_interface' will be appended to ending of file name :param parsed_json: :return:<|endoftext|>
5dd3cd3c26619a6b9b7159c74fe0626a85b324b95031c71900eba324e12717d1
def _dict_to_dot_map(map_or_list_of_maps: Union[(List, Dict)], root_name_when_list='root'): '\n Turns dictionary created from json into a dotMap where items can be accessed as members. We also\n cleanup the json when there are spaces in keys. We create a sibling key with spaces replaced by underscores\n pointing to the same value, we then remove the previous key\n :param map_or_list_of_maps:\n :param root_name_when_list: name to be used for root class when top level json is a list\n :return:\n ' _normalize(map_or_list_of_maps) json_map = None if isinstance(map_or_list_of_maps, dict): json_map = DotMap(map_or_list_of_maps) elif isinstance(map_or_list_of_maps, list): json_map = DotMap({root_name_when_list: map_or_list_of_maps}) return json_map
Turns dictionary created from json into a dotMap where items can be accessed as members. We also cleanup the json when there are spaces in keys. We create a sibling key with spaces replaced by underscores pointing to the same value, we then remove the previous key :param map_or_list_of_maps: :param root_name_when_list: name to be used for root class when top level json is a list :return:
json2pytocol/json_to_python_protocol.py
_dict_to_dot_map
piacenti/protoson
0
python
def _dict_to_dot_map(map_or_list_of_maps: Union[(List, Dict)], root_name_when_list='root'): '\n Turns dictionary created from json into a dotMap where items can be accessed as members. We also\n cleanup the json when there are spaces in keys. We create a sibling key with spaces replaced by underscores\n pointing to the same value, we then remove the previous key\n :param map_or_list_of_maps:\n :param root_name_when_list: name to be used for root class when top level json is a list\n :return:\n ' _normalize(map_or_list_of_maps) json_map = None if isinstance(map_or_list_of_maps, dict): json_map = DotMap(map_or_list_of_maps) elif isinstance(map_or_list_of_maps, list): json_map = DotMap({root_name_when_list: map_or_list_of_maps}) return json_map
def _dict_to_dot_map(map_or_list_of_maps: Union[(List, Dict)], root_name_when_list='root'): '\n Turns dictionary created from json into a dotMap where items can be accessed as members. We also\n cleanup the json when there are spaces in keys. We create a sibling key with spaces replaced by underscores\n pointing to the same value, we then remove the previous key\n :param map_or_list_of_maps:\n :param root_name_when_list: name to be used for root class when top level json is a list\n :return:\n ' _normalize(map_or_list_of_maps) json_map = None if isinstance(map_or_list_of_maps, dict): json_map = DotMap(map_or_list_of_maps) elif isinstance(map_or_list_of_maps, list): json_map = DotMap({root_name_when_list: map_or_list_of_maps}) return json_map<|docstring|>Turns dictionary created from json into a dotMap where items can be accessed as members. We also cleanup the json when there are spaces in keys. We create a sibling key with spaces replaced by underscores pointing to the same value, we then remove the previous key :param map_or_list_of_maps: :param root_name_when_list: name to be used for root class when top level json is a list :return:<|endoftext|>
783f470b26771a3c8e9e8c786a0c55f55ee4194980ad4513230685359a57d309
def sample_user(email='example@example.com', password='test@123', **kwargs): 'Create a sample user' return get_user_model().objects.create_user(email, password, **kwargs)
Create a sample user
app/core/tests/test_models.py
sample_user
swastik-goyal/recipe-app-api
0
python
def sample_user(email='example@example.com', password='test@123', **kwargs): return get_user_model().objects.create_user(email, password, **kwargs)
def sample_user(email='example@example.com', password='test@123', **kwargs): return get_user_model().objects.create_user(email, password, **kwargs)<|docstring|>Create a sample user<|endoftext|>
2545d1449d8e156061a94964516905be6738e828baf5d9a89de030ee89beae8a
def test_create_user_with_email_successful(self): 'Test creating a new user with an email is successful' email = 'example@example.com' password = 'password1' user = get_user_model().objects.create_user(email=email, password=password) self.assertEqual(user.email, email) self.assertTrue(user.check_password(password))
Test creating a new user with an email is successful
app/core/tests/test_models.py
test_create_user_with_email_successful
swastik-goyal/recipe-app-api
0
python
def test_create_user_with_email_successful(self): email = 'example@example.com' password = 'password1' user = get_user_model().objects.create_user(email=email, password=password) self.assertEqual(user.email, email) self.assertTrue(user.check_password(password))
def test_create_user_with_email_successful(self): email = 'example@example.com' password = 'password1' user = get_user_model().objects.create_user(email=email, password=password) self.assertEqual(user.email, email) self.assertTrue(user.check_password(password))<|docstring|>Test creating a new user with an email is successful<|endoftext|>
cc08a28bac9b7bd93f04f39212b1d52d479d64c33da286261b85be6033e7a979
def test_new_user_email_normalised(self): 'Test the email for a new user is normalised' email = 'example@example.com' user = get_user_model().objects.create_user(email=email, password='test@123') self.assertEqual(user.email, email.lower())
Test the email for a new user is normalised
app/core/tests/test_models.py
test_new_user_email_normalised
swastik-goyal/recipe-app-api
0
python
def test_new_user_email_normalised(self): email = 'example@example.com' user = get_user_model().objects.create_user(email=email, password='test@123') self.assertEqual(user.email, email.lower())
def test_new_user_email_normalised(self): email = 'example@example.com' user = get_user_model().objects.create_user(email=email, password='test@123') self.assertEqual(user.email, email.lower())<|docstring|>Test the email for a new user is normalised<|endoftext|>
246d4f5cd8668a7b8d5a860d878c75f57956e41549f45f0f74bfc67734933221
def test_new_user_invalid_email(self): 'Test creating user with no email should fail' with self.assertRaises(ValueError): get_user_model().objects.create_user(None, 'test@123')
Test creating user with no email should fail
app/core/tests/test_models.py
test_new_user_invalid_email
swastik-goyal/recipe-app-api
0
python
def test_new_user_invalid_email(self): with self.assertRaises(ValueError): get_user_model().objects.create_user(None, 'test@123')
def test_new_user_invalid_email(self): with self.assertRaises(ValueError): get_user_model().objects.create_user(None, 'test@123')<|docstring|>Test creating user with no email should fail<|endoftext|>