max_stars_repo_path
stringlengths
3
286
max_stars_repo_name
stringlengths
4
130
max_stars_count
int64
0
191k
id
stringlengths
1
8
content
stringlengths
1
1.04M
score
float64
-1.09
4.13
int_score
int64
0
4
rasa/train.py
Amirali-Shirkh/rasa-for-botfront
0
2
import asyncio import os import tempfile from contextlib import ExitStack from typing import Text, Optional, List, Union, Dict from rasa.importers.importer import TrainingDataImporter from rasa import model from rasa.model import FingerprintComparisonResult from rasa.core.domain import Domain from rasa.utils.common import TempDirectoryPath from rasa.cli.utils import ( print_success, print_warning, print_error, bcolors, print_color, ) from rasa.constants import DEFAULT_MODELS_PATH, DEFAULT_CORE_SUBDIRECTORY_NAME def train( domain: Text, config: Text, training_files: Union[Text, List[Text]], output: Text = DEFAULT_MODELS_PATH, force_training: bool = False, fixed_model_name: Optional[Text] = None, persist_nlu_training_data: bool = False, additional_arguments: Optional[Dict] = None, loop: Optional[asyncio.AbstractEventLoop] = None, ) -> Optional[Text]: if loop is None: try: loop = asyncio.get_event_loop() except RuntimeError: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) return loop.run_until_complete( train_async( domain=domain, config=config, training_files=training_files, output_path=output, force_training=force_training, fixed_model_name=fixed_model_name, persist_nlu_training_data=persist_nlu_training_data, additional_arguments=additional_arguments, ) ) async def train_async( domain: Union[Domain, Text], config: Dict[Text, Text], training_files: Optional[Union[Text, List[Text]]], output_path: Text = DEFAULT_MODELS_PATH, force_training: bool = False, fixed_model_name: Optional[Text] = None, persist_nlu_training_data: bool = False, additional_arguments: Optional[Dict] = None, ) -> Optional[Text]: """Trains a Rasa model (Core and NLU). Args: domain: Path to the domain file. config: Dict of paths to the config for Core and NLU. Keys are language codes training_files: Paths to the training data for Core and NLU. output_path: Output path. force_training: If `True` retrain model even if data has not changed. fixed_model_name: Name of model to be stored. persist_nlu_training_data: `True` if the NLU training data should be persisted with the model. additional_arguments: Additional training parameters. Returns: Path of the trained model archive. """ # file_importer = TrainingDataImporter.load_from_config( # config, domain, training_files # ) with ExitStack() as stack: train_path = stack.enter_context(TempDirectoryPath(tempfile.mkdtemp())) # bf mod from rasa_addons.importers import BotfrontFileImporter file_importer = BotfrontFileImporter(config, domain, training_files) # domain = await file_importer.get_domain() # if domain.is_empty(): # return await handle_domain_if_not_exists( # file_importer, output_path, fixed_model_name # ) # /bf mod return await _train_async_internal( file_importer, train_path, output_path, force_training, fixed_model_name, persist_nlu_training_data, additional_arguments, ) async def handle_domain_if_not_exists( file_importer: TrainingDataImporter, output_path, fixed_model_name ): nlu_model_only = await _train_nlu_with_validated_data( file_importer, output=output_path, fixed_model_name=fixed_model_name ) print_warning( "Core training was skipped because no valid domain file was found. Only an nlu-model was created." "Please specify a valid domain using '--domain' argument or check if the provided domain file exists." ) return nlu_model_only async def _train_async_internal( file_importer: TrainingDataImporter, train_path: Text, output_path: Text, force_training: bool, fixed_model_name: Optional[Text], persist_nlu_training_data: bool, additional_arguments: Optional[Dict], ) -> Optional[Text]: """Trains a Rasa model (Core and NLU). Use only from `train_async`. Args: file_importer: `TrainingDataImporter` which supplies the training data. train_path: Directory in which to train the model. output_path: Output path. force_training: If `True` retrain model even if data has not changed. persist_nlu_training_data: `True` if the NLU training data should be persisted with the model. fixed_model_name: Name of model to be stored. additional_arguments: Additional training parameters. Returns: Path of the trained model archive. """ stories, nlu_data = await asyncio.gather( file_importer.get_stories(), file_importer.get_nlu_data() ) # if stories.is_empty() and nlu_data.is_empty(): # print_error( # "No training data given. Please provide stories and NLU data in " # "order to train a Rasa model using the '--data' argument." # ) # return # if nlu_data.is_empty(): # print_warning("No NLU data present. Just a Rasa Core model will be trained.") # return await _train_core_with_validated_data( # file_importer, # output=output_path, # fixed_model_name=fixed_model_name, # additional_arguments=additional_arguments, # ) new_fingerprint = await model.model_fingerprint(file_importer) old_model = model.get_latest_model(output_path) fingerprint_comparison = FingerprintComparisonResult(force_training=force_training) if not force_training: fingerprint_comparison = model.should_retrain( new_fingerprint, old_model, train_path ) # bf mod > if fingerprint_comparison.nlu == True: # replace True with list of all langs fingerprint_comparison.nlu = list(new_fingerprint.get("nlu-config", {}).keys()) domain = await file_importer.get_domain() core_untrainable = domain.is_empty() or stories.is_empty() nlu_untrainable = [l for l, d in nlu_data.items() if d.is_empty()] fingerprint_comparison.core = fingerprint_comparison.core and not core_untrainable fingerprint_comparison.nlu = [l for l in fingerprint_comparison.nlu if l not in nlu_untrainable] if core_untrainable: print_color("Skipping Core training since domain or stories are empty.", color=bcolors.OKBLUE) for lang in nlu_untrainable: print_color("No NLU data found for language <{}>, skipping training...".format(lang), color=bcolors.OKBLUE) # </ bf mod if fingerprint_comparison.is_training_required(): await _do_training( file_importer, output_path=output_path, train_path=train_path, fingerprint_comparison_result=fingerprint_comparison, fixed_model_name=fixed_model_name, persist_nlu_training_data=persist_nlu_training_data, additional_arguments=additional_arguments, ) return model.package_model( fingerprint=new_fingerprint, output_directory=output_path, train_path=train_path, fixed_model_name=fixed_model_name, ) print_success( "Nothing changed. You can use the old model stored at '{}'." "".format(os.path.abspath(old_model)) ) return old_model async def _do_training( file_importer: TrainingDataImporter, output_path: Text, train_path: Text, fingerprint_comparison_result: Optional[FingerprintComparisonResult] = None, fixed_model_name: Optional[Text] = None, persist_nlu_training_data: bool = False, additional_arguments: Optional[Dict] = None, ): if not fingerprint_comparison_result: fingerprint_comparison_result = FingerprintComparisonResult() if fingerprint_comparison_result.should_retrain_core(): await _train_core_with_validated_data( file_importer, output=output_path, train_path=train_path, fixed_model_name=fixed_model_name, additional_arguments=additional_arguments, ) elif fingerprint_comparison_result.should_retrain_nlg(): print_color( "Core stories/configuration did not change. " "Only the templates section has been changed. A new model with " "the updated templates will be created.", color=bcolors.OKBLUE, ) await model.update_model_with_new_domain(file_importer, train_path) else: print_color( "Core stories/configuration did not change. No need to retrain Core model.", color=bcolors.OKBLUE, ) if fingerprint_comparison_result.should_retrain_nlu(): await _train_nlu_with_validated_data( file_importer, output=output_path, train_path=train_path, fixed_model_name=fixed_model_name, retrain_nlu=fingerprint_comparison_result.nlu, persist_nlu_training_data=persist_nlu_training_data, ) else: print_color( "NLU data/configuration did not change. No need to retrain NLU model.", color=bcolors.OKBLUE, ) def train_core( domain: Union[Domain, Text], config: Text, stories: Text, output: Text, train_path: Optional[Text] = None, fixed_model_name: Optional[Text] = None, additional_arguments: Optional[Dict] = None, ) -> Optional[Text]: loop = asyncio.get_event_loop() return loop.run_until_complete( train_core_async( domain=domain, config=config, stories=stories, output=output, train_path=train_path, fixed_model_name=fixed_model_name, additional_arguments=additional_arguments, ) ) async def train_core_async( domain: Union[Domain, Text], config: Text, stories: Text, output: Text, train_path: Optional[Text] = None, fixed_model_name: Optional[Text] = None, additional_arguments: Optional[Dict] = None, ) -> Optional[Text]: """Trains a Core model. Args: domain: Path to the domain file. config: Path to the config file for Core. stories: Path to the Core training data. output: Output path. train_path: If `None` the model will be trained in a temporary directory, otherwise in the provided directory. fixed_model_name: Name of model to be stored. uncompress: If `True` the model will not be compressed. additional_arguments: Additional training parameters. Returns: If `train_path` is given it returns the path to the model archive, otherwise the path to the directory with the trained model files. """ file_importer = TrainingDataImporter.load_core_importer_from_config( config, domain, [stories] ) domain = await file_importer.get_domain() if domain.is_empty(): print_error( "Core training was skipped because no valid domain file was found. " "Please specify a valid domain using '--domain' argument or check if the provided domain file exists." ) return None if not await file_importer.get_stories(): print_error( "No stories given. Please provide stories in order to " "train a Rasa Core model using the '--stories' argument." ) return return await _train_core_with_validated_data( file_importer, output=output, train_path=train_path, fixed_model_name=fixed_model_name, additional_arguments=additional_arguments, ) async def _train_core_with_validated_data( file_importer: TrainingDataImporter, output: Text, train_path: Optional[Text] = None, fixed_model_name: Optional[Text] = None, additional_arguments: Optional[Dict] = None, ) -> Optional[Text]: """Train Core with validated training and config data.""" import rasa.core.train with ExitStack() as stack: if train_path: # If the train path was provided, do nothing on exit. _train_path = train_path else: # Otherwise, create a temp train path and clean it up on exit. _train_path = stack.enter_context(TempDirectoryPath(tempfile.mkdtemp())) # normal (not compare) training print_color("Training Core model...", color=bcolors.OKBLUE) domain, config = await asyncio.gather( file_importer.get_domain(), file_importer.get_config() ) await rasa.core.train( domain_file=domain, training_resource=file_importer, output_path=os.path.join(_train_path, DEFAULT_CORE_SUBDIRECTORY_NAME), policy_config=config, additional_arguments=additional_arguments, ) print_color("Core model training completed.", color=bcolors.OKBLUE) if train_path is None: # Only Core was trained. new_fingerprint = await model.model_fingerprint(file_importer) return model.package_model( fingerprint=new_fingerprint, output_directory=output, train_path=_train_path, fixed_model_name=fixed_model_name, model_prefix="core-", ) return _train_path def train_nlu( config: Text, nlu_data: Text, output: Text, train_path: Optional[Text] = None, fixed_model_name: Optional[Text] = None, persist_nlu_training_data: bool = False, ) -> Optional[Text]: """Trains an NLU model. Args: config: Path to the config file for NLU. nlu_data: Path to the NLU training data. output: Output path. train_path: If `None` the model will be trained in a temporary directory, otherwise in the provided directory. fixed_model_name: Name of the model to be stored. persist_nlu_training_data: `True` if the NLU training data should be persisted with the model. Returns: If `train_path` is given it returns the path to the model archive, otherwise the path to the directory with the trained model files. """ loop = asyncio.get_event_loop() return loop.run_until_complete( _train_nlu_async( config, nlu_data, output, train_path, fixed_model_name, persist_nlu_training_data, ) ) async def _train_nlu_async( config: Text, nlu_data: Text, output: Text, train_path: Optional[Text] = None, fixed_model_name: Optional[Text] = None, persist_nlu_training_data: bool = False, ): if not nlu_data: print_error( "No NLU data given. Please provide NLU data in order to train " "a Rasa NLU model using the '--nlu' argument." ) return # training NLU only hence the training files still have to be selected file_importer = TrainingDataImporter.load_nlu_importer_from_config( config, training_data_paths=[nlu_data] ) training_datas = await file_importer.get_nlu_data() if training_datas.is_empty(): print_error( f"Path '{nlu_data}' doesn't contain valid NLU data in it. " "Please verify the data format. " "The NLU model training will be skipped now." ) return return await _train_nlu_with_validated_data( file_importer, output=output, train_path=train_path, fixed_model_name=fixed_model_name, persist_nlu_training_data=persist_nlu_training_data, ) async def _train_nlu_with_validated_data( file_importer: TrainingDataImporter, output: Text, train_path: Optional[Text] = None, fixed_model_name: Optional[Text] = None, persist_nlu_training_data: bool = False, retrain_nlu: Union[bool, List[Text]] = True ) -> Optional[Text]: """Train NLU with validated training and config data.""" import rasa.nlu.train with ExitStack() as stack: models = {} from rasa.nlu import config as cfg_loader if train_path: # If the train path was provided, do nothing on exit. _train_path = train_path else: # Otherwise, create a temp train path and clean it up on exit. _train_path = stack.enter_context(TempDirectoryPath(tempfile.mkdtemp())) # bf mod config = await file_importer.get_nlu_config(retrain_nlu) for lang in config: if config[lang]: print_color("Start training {} NLU model ...".format(lang), color=bcolors.OKBLUE) _, models[lang], _ = await rasa.nlu.train( config[lang], file_importer, _train_path, fixed_model_name="nlu-{}".format(lang), persist_nlu_training_data=persist_nlu_training_data, ) else: print_color("NLU data for language <{}> didn't change, skipping training...".format(lang), color=bcolors.OKBLUE) # /bf mod print_color("NLU model training completed.", color=bcolors.OKBLUE) if train_path is None: # Only NLU was trained new_fingerprint = await model.model_fingerprint(file_importer) return model.package_model( fingerprint=new_fingerprint, output_directory=output, train_path=_train_path, fixed_model_name=fixed_model_name, model_prefix="nlu-", ) return _train_path
1.414063
1
map_download/cmd/TerrainDownloader.py
cugxy/map_download
27
10
# -*- coding: utf-8 -*- # coding=utf-8 import json import os import math import logging import requests import time from map_download.cmd.BaseDownloader import DownloadEngine, BaseDownloaderThread, latlng2tile_terrain, BoundBox def get_access_token(token): resp = None request_count = 0 url = "https://api.cesium.com/v1/assets/1/endpoint" while True: if request_count > 4: break try: request_count += 1 param = {'access_token': token} resp = requests.get(url, params=param, timeout=2) if resp.status_code != 200: continue break except Exception as e: resp = None time.sleep(3) if resp is None: return None resp_json = resp.json() return resp_json.get('accessToken') class TerrainDownloaderThread(BaseDownloaderThread): URL = "https://assets.cesium.com/1/{z}/{x}/{y}.terrain?extensions=octvertexnormals-watermask&v=1.1.0" def __init__(self, root_dir, bbox, token, task_q, logger=None, write_db=False): super(TerrainDownloaderThread, self).__init__( root_dir, bbox, task_q, logger, write_db=write_db, db_file_name='Terrain.db') self.token = token self._init_metadata( format='terrain', bounds='%f,%f,%f,%f' % (self.bbox.min_lng, self.bbox.min_lat, self.bbox.max_lng, self.bbox.max_lat)) def get_url(self, x, y, z): return self.URL.format(x=x, y=y, z=z) def _download(self, x, y, z): file_path = '%s/%s/%i/%i/%i.%s' % (self.root_dir, 'Terrain', z, x, y, 'terrain') if os.path.exists(file_path): self._data2DB(x, y, z, file_path) return 0 os.makedirs(os.path.dirname(file_path), exist_ok=True) resp = None requre_count = 0 _url = '' access_token = get_access_token(self.token) if access_token is None: return -1 param = {'extensions': 'octvertexnormals-watermask', 'v': '1.1.0', 'access_token': access_token} while True: if requre_count > 4: break try: _url = self.get_url(x, y, z) resp = requests.get(_url, params=param, stream=True, timeout=2) break except Exception as e: resp = None time.sleep(3) requre_count += 1 if resp is None: return -1 if resp.status_code != 200: return -1 try: with open(file_path, 'wb') as f: for chunk in resp.iter_content(chunk_size=1024): if chunk: f.write(chunk) except Exception as e: return -1 self._data2DB(x, y, z, file_path) return 1 class TerrainDownloadEngine(DownloadEngine): root_dir = '' def __init__(self, root_dir, bbox, token, thread_num, logger=None, write_db=False): super(TerrainDownloadEngine, self).__init__(bbox, thread_num, logger, write_db=write_db) self.root_dir = root_dir self.token = token def bbox2xyz(self, bbox, z): min_x, min_y = latlng2tile_terrain(bbox.min_lat, bbox.min_lng, z) max_x, max_y = latlng2tile_terrain(bbox.max_lat, bbox.max_lng, z) return math.floor(min_x), math.floor(min_y), math.ceil(max_x) + 1, math.ceil(max_y) + 1 def generate_metadata(self): try: metadatas = { "attribution": "© Analytical Graphics Inc., © CGIAR-CSI, Produced using Copernicus data and " "information funded by the European Union - EU-DEM layers", "available": [ [ { "endX": 1, "endY": 0, "startX": 0, "startY": 0 } ], [ { "endX": 3, "endY": 1, "startX": 0, "startY": 0 } ], [ { "endX": 7, "endY": 3, "startX": 0, "startY": 0 } ], [ { "endX": 15, "endY": 7, "startX": 0, "startY": 0 } ], [ { "endX": 31, "endY": 15, "startX": 0, "startY": 0 } ], [ { "endX": 63, "endY": 31, "startX": 0, "startY": 0 } ], [ { "endX": 127, "endY": 63, "startX": 0, "startY": 0 } ], [ { "endX": 255, "endY": 127, "startX": 0, "startY": 0 } ], [ { "endX": 511, "endY": 255, "startX": 0, "startY": 0 } ], [ { "endX": 1023, "endY": 511, "startX": 0, "startY": 0 } ], [ { "endX": 2047, "endY": 1023, "startX": 0, "startY": 0 } ], [ { "endX": 4095, "endY": 2047, "startX": 0, "startY": 0 } ], [ { "endX": 8191, "endY": 4095, "startX": 0, "startY": 0 } ], [ { "endX": 16383, "endY": 8191, "startX": 0, "startY": 0 } ], [ { "endX": 32767, "endY": 16383, "startX": 0, "startY": 0 } ] ], "bounds": [-180, -90, 180, 90, ], "description": "STK World Terrain Premium Tileset, v1.3. 10m - 30m resolution CONUS, 30m resolution " "SRTM between 60N and 60S, 30m Europe. Minimum global coverage of 1000m.", "extensions": ["watermask", "vertexnormals", "octvertexnormals", ], "format": "quantized-mesh-1.0", "maxzoom": 13, "minzoom": 0, "name": "world", "projection": "EPSG:4326", "scheme": "tms", "tilejson": "2.1.0", "tiles": ["{z}/{x}/{y}.terrain?v={version}", ], "version": "1.31376.0" } _dir = os.path.join(self.root_dir, 'Terrain') os.makedirs(_dir, exist_ok=True) metadatas_path = os.path.join(_dir, 'layer.json') with open(metadatas_path, 'w') as f: json.dump(metadatas, f) except Exception as e: if self.logger is not None: self.logger.exception(e) def run(self): try: self.generate_metadata() count = 0 bboxs = self.cut_bbox() for bbox in bboxs: _count = self.get_task_count(bbox) count += _count self.division_done_signal.emit(count) for bbox in bboxs: while True: if not self.running: time.sleep(0.01) else: break task_q = self.get_task_queue(bbox) self.threads = [] for i in range(self.thread_num): thread = TerrainDownloaderThread(self.root_dir, self.bbox, self.token, task_q, self.logger, write_db=self.write_db) thread.sub_progressBar_updated_signal.connect(self.sub_update_progressBar) self.threads.append(thread) for thread in self.threads: thread.start() for thread in self.threads: thread.wait() for t in self.threads: t.stop() t.quit() self.threads = [] self.download_done_signal.emit() except Exception as e: if self.logger is not None: self.logger.error(e) if __name__ == '__main__': if 1: logger = logging.getLogger('down') try: root = r'/Users/cugxy/Documents/data/downloader' formatter = logging.Formatter('%(levelname)s-%(message)s') hdlr = logging.StreamHandler() log_file = os.path.join(root, 'down.log') file_hdlr = logging.FileHandler(log_file) file_hdlr.setFormatter(formatter) logger.addHandler(file_hdlr) logger.addHandler(hdlr) logger.setLevel(logging.INFO) min_lng = -180.0 max_lng = 180.0 min_lat = -90.0 max_lat = 90.0 start_zoom = 0 end_zoom = 5 bbox = BoundBox(max_lat, max_lng, min_lat, min_lng, start_zoom, end_zoom) d = TerrainDownloadEngine(root, bbox, 8, logger) d.start() time.sleep(10000) logger.error('main thread out') except Exception as e: logger.error(e) if 0: accessToken = get_access_token() pass
1.648438
2
pandas_datareaders_unofficial/datareaders/google_finance_options.py
movermeyer/pandas_datareaders_unofficial
18
18
#!/usr/bin/env python # -*- coding: utf-8 -*- from .base import DataReaderBase from ..tools import COL, _get_dates, to_float, to_int import pandas as pd #from pandas.tseries.frequencies import to_offset from six.moves import cStringIO as StringIO import logging import traceback import datetime import json import token, tokenize def ymd_to_date(y, m, d): """ Returns date >>> expiration = {u'd': 1, u'm': 12, u'y': 2014} >>> ymd_to_date(**expiration) datetime.date(2014, 12, 1) >>> ymd_to_date(2014, 3, 1) datetime.date(2014, 3, 1) """ return(datetime.date(year=y, month=m, day=d)) def date_to_ymd(date): """ Returns dict like {'y': ..., 'm': ..., 'd': ...} >>> date_to_ymd(datetime.date(year=2010, month=1, day=3)) {'y': 2010, 'm': 1, 'd': 3} """ d = { 'y': date.year, 'm': date.month, 'd': date.day } return(d) def fix_lazy_json(in_text): """ Handle lazy JSON - to fix expecting property name this function fixes the json output from google http://stackoverflow.com/questions/4033633/handling-lazy-json-in-python-expecting-property-name """ tokengen = tokenize.generate_tokens(StringIO(in_text).readline) result = [] for tokid, tokval, _, _, _ in tokengen: # fix unquoted strings if (tokid == token.NAME): if tokval not in ['true', 'false', 'null', '-Infinity', 'Infinity', 'NaN']: tokid = token.STRING tokval = u'"%s"' % tokval # fix single-quoted strings elif (tokid == token.STRING): if tokval.startswith ("'"): tokval = u'"%s"' % tokval[1:-1].replace ('"', '\\"') # remove invalid commas elif (tokid == token.OP) and ((tokval == '}') or (tokval == ']')): if (len(result) > 0) and (result[-1][1] == ','): result.pop() # fix single-quoted strings elif (tokid == token.STRING): if tokval.startswith ("'"): tokval = u'"%s"' % tokval[1:-1].replace ('"', '\\"') result.append((tokid, tokval)) return tokenize.untokenize(result) def json_decode(json_string): try: ret = json.loads(json_string) except: json_string = fix_lazy_json(json_string) ret = json.loads(json_string) return ret class DataReaderGoogleFinanceOptions(DataReaderBase): """ DataReader to fetch data from Google Finance Options see https://www.google.com/finance/option_chain https://github.com/makmac213/python-google-option-chain http://www.drtomstarke.com/index.php/option-chains-from-google-finance-api """ def init(self, *args, **kwargs): self._get_multi = self._get_multi_todict def _get_one(self, name, *args, **kwargs): return(self._get_one_raw(name, 'All', 'json')) def _get_one_raw(self, symbol, typ='All', output='json', y='2014', m='12', d='1'): url = "https://www.google.com/finance/option_chain" params = { 'q': symbol, 'type': typ, 'output': output, } data = self._get_content(url, params) d = {} lst = [] for typ in [u'puts', u'calls']: df_typ = pd.DataFrame(data[typ]) df_typ['Type'] = typ lst.append(df_typ) del data[typ] for i, expiration in enumerate(data['expirations']): params = { 'q': symbol, 'output': output, 'expy': expiration['y'], 'expm': expiration['m'], 'expd': expiration['d'], } data = self._get_content(url, params) for typ in [u'puts', u'calls']: df_typ = pd.DataFrame(data[typ]) df_typ['Type'] = typ lst.append(df_typ) del data[typ] lst.append(df_typ) df = pd.concat(lst, axis=0, ignore_index=True) d_cols = { "a": "Ask", "b": "Bid", "p": "Last", "strike": "Strike", "expiry": "Expiry", "vol": "Volume", "name": "Name" } df = df.rename(columns=d_cols) """ d_cols = { "a": "ask", "b": "bid", "c": "change", "cid": "identity code", "cp": "cp" "cs": change direction. "chg" = up, "chr" = down, "chg"? "e": # I think this tells us something about what country where the stock is traded. "OPRA" means USA. "expiry": expiration date for this option "name": I don't know. I have never seen a value for this "oi": open interest. How many of these are currently being held by others. See, http://www.investopedia.com/terms/o/openinterest.asp "p": price, last "s": option code. Basically, Stock Symbol + 7 if mini option + date + "C" or "P" + price "strike": "strike price for this option" "vol": "the volume of options traded." } """ for col in ['Ask', 'Bid', 'c', 'cp', 'Last', 'Strike']: df[col] = df[col].map(to_float) for col in ['Volume', 'oi', 'cid']: df[col] = df[col].map(to_int) df['Expiry'] = pd.to_datetime(df['Expiry']) data['options'] = df data['underlying_id'] = int(data['underlying_id']) data['expiry'] = ymd_to_date(**data['expiry']) for i, expiration in enumerate(data['expirations']): data['expirations'][i] = ymd_to_date(**expiration) #for col in ['Volume']: # df[col] = df[col].fillna(0) #d = {} #d["options"] = df #return(d) return(data) def _get_content(self, url, params): #response = requests.get(url, params=params) response = self.session.get(url, params=params) if response.status_code == 200: content_json = response.text data = json_decode(content_json) return(data) if __name__ == "__main__": import doctest doctest.testmod()
1.898438
2
model/contact.py
hubogeri/python_training
0
26
from sys import maxsize class Contact: def __init__(self, fname=None, mname=None, lname=None, nick=None, title=None, comp=None, addr=None, home=None, mobile=None, work=None, fax=None, email1=None, email2=None, email3=None, homepage=None, bday=None, bmonth=None, byear=None, aday=None, amonth=None, ayear=None, secaddr=None, secphone=None, note=None, id =None): self.fname = fname self.mname = mname self.lname = lname self.nick = nick self.title = title self.comp = comp self.addr = addr self.home = home self.mobile = mobile self.work = work self.fax = fax self.email1 = email1 self.email2 = email2 self.email3 = email3 self.homepage = homepage self.bday = bday self.bmonth = bmonth self.byear = byear self.aday = aday self.amonth = amonth self.ayear = ayear self.secaddr = secaddr self.secphone = secphone self.note = note self.id = id def __repr__(self): return "%s:%s:%s" % (self.id, self.fname, self.lname) def __eq__(self, other): return (self.id is None or other.id is None or self.id == other.id) and self.fname == other.fname and self.lname == other.lname def id_or_max(self): if self.id: return int(self.id) else: return maxsize
2.859375
3
using_paramiko.py
allupramodreddy/cisco_py
0
34
#!/usr/local/bin/python3 import paramiko,time #using as SSH Client client = paramiko.SSHClient() # check dir(client) to find available options. # auto adjust host key verification with yes or no client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # time for connecting to remote Cisco IOS """ Manually taking input addr = input('Provide IP address to connect to: ') user = input('Username: ') pwd = <PASSWORD>('Password: ')""" # Taking input from files f1 = open("devices.txt","r") f2 = open("commands.txt","r") for line in f1: client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) data = line.split(" ") # print(data) addr = data[0] user = data[1] pwd = data[2] f3 = open(addr+".txt","w+") # print(addr +" "+ user +" " +pwd) client.connect(addr,username=user,password=<PASSWORD>,allow_agent=False,look_for_keys=False) # we have to ask for Shell device_access = client.invoke_shell() for line in f2: device_access.send(line) time.sleep(1) output = device_access.recv(55000).decode('ascii') f3.write(output) """ THIS CODE IS FOR SINGLE COMMAND, FOR MULTIPLE COMMANDS CODE BELOW # send command to the device device_access.send("ter len 0\nshow run \n") time.sleep(2) # receive output from the device, convert it to byte-like format and print it print(device_access.recv(550000).decode('ascii')) # We can print the same to a file too with open("csr1000v.txt","w") as f: f.write(device_access.recv(550000).decode('ascii'))"""
2.03125
2
src/fetchWords.py
theyadev/thierry-bot
0
42
import requests words_list = requests.get("https://raw.githubusercontent.com/atebits/Words/master/Words/fr.txt").text words_list = filter(lambda x: len(x) > 4, words_list.split('\n')) path = input("Chemin d'écriture ? (words.txt) ") if path == "": path = "./words.txt" with open(path, "w", encoding="utf-8") as file: file.write('\n'.join(words_list))
1.671875
2
paccmann_chemistry/utils/hyperparams.py
PaccMann/paccmann_chemistry
9
50
"""Model Parameters Module.""" import torch.optim as optim from .search import SamplingSearch, GreedySearch, BeamSearch SEARCH_FACTORY = { 'sampling': SamplingSearch, 'greedy': GreedySearch, 'beam': BeamSearch, } OPTIMIZER_FACTORY = { 'adadelta': optim.Adadelta, 'adagrad': optim.Adagrad, 'adam': optim.Adam, 'adamax': optim.Adamax, 'rmsprop': optim.RMSprop, 'sgd': optim.SGD }
1.1875
1
src/Components/missions/GEMS/mcd43c.py
GEOS-ESM/AeroApps
2
58
""" Reads climate modeling grid 0.05 degree MCD43 BRDF files. """ import os import sys from numpy import loadtxt, array, tile, where, concatenate, flipud from numpy import ones from datetime import date, datetime, timedelta from glob import glob from pyhdf.SD import SD, HDF4Error MISSING = 32.767 SDS = dict ( LAND = ('BRDF_Albedo_Parameter1_Band1','BRDF_Albedo_Parameter1_Band2', 'BRDF_Albedo_Parameter1_Band3','BRDF_Albedo_Parameter1_Band4', 'BRDF_Albedo_Parameter1_Band5','BRDF_Albedo_Parameter1_Band6', 'BRDF_Albedo_Parameter1_Band7', 'BRDF_Albedo_Parameter2_Band1','BRDF_Albedo_Parameter2_Band2', 'BRDF_Albedo_Parameter2_Band3','BRDF_Albedo_Parameter2_Band4', 'BRDF_Albedo_Parameter2_Band5','BRDF_Albedo_Parameter2_Band6', 'BRDF_Albedo_Parameter2_Band7', 'BRDF_Albedo_Parameter3_Band1','BRDF_Albedo_Parameter3_Band2', 'BRDF_Albedo_Parameter3_Band3','BRDF_Albedo_Parameter3_Band4', 'BRDF_Albedo_Parameter3_Band5','BRDF_Albedo_Parameter3_Band6', 'BRDF_Albedo_Parameter3_Band7'), QUAL = ('BRDF_Albedo_Quality', 'Snow_BRDF_Albedo', 'BRDF_Albedo_Ancillary', ) ) ALIAS = dict ( BRDF_Albedo_Parameter1_Band1 = 'KISO_b1_645', BRDF_Albedo_Parameter1_Band2 = 'KISO_b2_856', BRDF_Albedo_Parameter1_Band3 = 'KISO_b3_465', BRDF_Albedo_Parameter1_Band4 = 'KISO_b4_553', BRDF_Albedo_Parameter1_Band5 = 'KISO_b5_1241', BRDF_Albedo_Parameter1_Band6 = 'KISO_b6_1629', BRDF_Albedo_Parameter1_Band7 = 'KISO_b7_2114', BRDF_Albedo_Parameter2_Band1 = 'KVOL_b1_645', BRDF_Albedo_Parameter2_Band2 = 'KVOL_b2_856', BRDF_Albedo_Parameter2_Band3 = 'KVOL_b3_465', BRDF_Albedo_Parameter2_Band4 = 'KVOL_b4_553', BRDF_Albedo_Parameter2_Band5 = 'KVOL_b5_1241', BRDF_Albedo_Parameter2_Band6 = 'KVOL_b6_1629', BRDF_Albedo_Parameter2_Band7 = 'KVOL_b7_2114', BRDF_Albedo_Parameter3_Band1 = 'KGEO_b1_645', BRDF_Albedo_Parameter3_Band2 = 'KGEO_b2_856', BRDF_Albedo_Parameter3_Band3 = 'KGEO_b3_465', BRDF_Albedo_Parameter3_Band4 = 'KGEO_b4_553', BRDF_Albedo_Parameter3_Band5 = 'KGEO_b5_1241', BRDF_Albedo_Parameter3_Band6 = 'KGEO_b6_1629', BRDF_Albedo_Parameter3_Band7 = 'KGEO_b7_2114', ) #........................................................................... class McD43C(object): """ This class implements the MODIS LAND BRDF 16-day Level 3 products, MCD43C1 (0.05 degree horz res), """ def __init__ (self,Path,lon,lat,Verb=1): """ Reads files for one day of Level 3 MCD43C1 present on a given *Path* and returns an object with all 3 kernels coeff. On input, Required parameters: Path -- for now a single file. Eventually implement a single directory, or a list of files and directories. """ if type(lon) is list: lon = array(lon) lat = array(lat) # List of HDF files for a given date #----------------------------------- self.verb = Verb self.SDS = SDS['LAND'] #self.Tfiles = glob(Path + '*.hdf') if type(Path) is str: self.Files = [Path] else: self.Files = Path # From a list of lat and lon, return the # dx, dy on the grid # ------------------------------------- self.nobs = len(lon) self._findNearest(Path,lon,lat) # Read BRDF kernel in a MODIS tile # --------------------------------- self.read_BRDF() # Result #--- def _findNearest(self,path,lon,lat): """Given a list of lat, lon, return numbers to find the position of the nearest neighbor on the grid (dx,dy) """ dLon = 0.05 dLat = 0.05 Lon0 = -180 - dLon Lat0 = -90 + dLat self.dx = (0.5+(lon-Lon0)/dLon).astype(int) self.dy = (0.5+(lat-Lat0)/dLat).astype(int) if self.verb: print 'dx','dy', self.dx,self.dy #--- def read_BRDF(self): """Reads MCD43C1 file with Level 3 BRDF kernels for each MODIS band.""" # Create empty lists for SDS to be read from file # ----------------------------------------------- for name in self.SDS: self.__dict__[name] = [] BRDF = MISSING * ones((len(self.SDS),self.nobs)) for fn in self.Files: try: if self.verb: print "[] Working on "+fn hfile = SD(fn) except HDF4Error: if self.verb > 2: print "- %s: not recognized as an HDF file"%filename return # Read select variables (reshape to allow concatenation later) # ------------------------------------------------------------ for sds in self.SDS: if self.verb: print 'sds',self.SDS.index(sds) v = hfile.select(sds).get() a = hfile.select(sds).attributes() if a['scale_factor']!=1.0 or a['add_offset']!=0.0: v = a['scale_factor'] * v + a['add_offset'] if self.verb: print array(self.dx), BRDF.shape, BRDF[self.SDS.index(sds),:], v.shape v = flipud(v) BRDF[self.SDS.index(sds),:] = v[array(self.dy), array(self.dx)] for sds in self.SDS: self.__dict__[sds] = BRDF[self.SDS.index(sds),:] if sds in ALIAS.keys(): self.__dict__[ALIAS[sds]] = self.__dict__[sds] #--- #............................................................................ if __name__ == "__main__": path = '/nobackup/3/pcastell/MODIS/MCD43C1/MCD43C1.A2005361.005.2008094071946.hdf' lon = [-2.,-120.,15.2,17.2,170.1] lat = [88.,40.,-20.,-20.,-55.5] lon = np.arange(-180,180,1) lat = np.arange(-90,90,1) lon,lat = np.meshgrid(lon,lat) ex = McD43C(path,lon.flatten(),lat.flatte())
1.28125
1
tests/wasp1/AllAnswerSets/aggregates_count_boundvariables_1.test.py
bernardocuteri/wasp
19
66
input = """ c(2). p(1). a(2). d(2,2,1). okay(X):- c(X), #count{V:a(V),d(V,X,1)} = 1. ouch(X):- p(X), #count{V:a(V),d(V,X,1)} = 1. """ output = """ {a(2), c(2), d(2,2,1), okay(2), p(1)} """
0.9375
1
Robustness Check/Calculating Risk Factors/calculate_momentum_factor.py
behnoud-bazrafshan/ThesisPortfolio
0
74
import pandas as pd import numpy as np import jdatetime pd.options.mode.chained_assignment = None # Read Bourseview data for market cap # Concat all 75 tickers' data me_list = [] for file_number in range(1, 76): print(file_number) me_path = f'E:/Thesis/New Sampling/Daily Data - Bourseview/'\ f'{file_number}.xlsx' me_df = pd.read_excel( me_path, skiprows=7, usecols=[2, 3, 11], names=['date', 'open', 'market_cap'], na_values='-' ) # Change order from old to new dates me_df = me_df[::-1].reset_index(drop=True) me_df['date'] = me_df['date'].str.replace('-', '') # Delete non-traded days me_df.dropna(subset=['open'], inplace=True) me_df.drop(columns='open', inplace=True) # Create monthly dataframe me_df = me_df.groupby(me_df['date'].str[:6]).last() me_df = me_df.drop(columns=['date']).reset_index() me_df.insert(1, 'ticker_num', file_number) me_list.append(me_df) me_df = pd.concat(me_list, ignore_index=True) me_df = me_df.loc[(me_df['date'] >= '139212') & (me_df['date'] <= '139900')] me_df.reset_index(drop=True, inplace=True) # Read rahavard 365 data for calculating returns close_list = [] for file_number in range(1, 76): rahavard_path = f'E:/Thesis/New Sampling/Daily Data - Rahavard 365/'\ f'{file_number}.txt' df = pd.read_csv( rahavard_path, usecols=[2, 7], names=['date', 'close'], header=0, dtype={'date': str}, parse_dates=[0] ) # Solve index reading problem, pandas add 2 index to the df df.reset_index(drop=True, inplace=True) # Convert to shamsi dates df['date'] = df['date'].apply( lambda x: jdatetime.date.fromgregorian(date=x).strftime('%Y%m%d') ) # Create monthly dataframe df = df.groupby(df['date'].str[:6]).last() df = df.drop(columns=['date']).reset_index() df.insert(1, 'ticker_num', file_number) df['monthly_return'] = df['close'].pct_change() close_list.append(df) df = pd.concat(close_list, ignore_index=True) df = df.loc[(df['date'] >= '139212') & (df['date'] <= '139900')] # Read index df for indicating open market days index_path = r'E:\Thesis\New Sampling\TEDPIX\شاخص كل6.xls' index_df = pd.read_excel( index_path, usecols=[1], names=['date'], dtype={'date': str} ) index_df.dropna(inplace=True) # The list of all months months = index_df['date'].str[:6].unique().tolist() # The list of months that we need for calculating market cap me_months = [ '139312', '139401', '139402', '139403', '139404', '139405', '139406', '139407', '139408', '139409', '139410', '139411', '139412', '139501', '139502', '139503', '139504', '139505', '139506', '139507', '139508', '139509', '139510', '139511', '139512', '139601', '139602', '139603', '139604', '139605', '139606', '139607', '139608', '139609', '139610', '139611', '139612', '139701', '139702', '139703', '139704', '139705', '139706', '139707', '139708', '139709', '139710', '139711', '139712', '139801', '139802', '139803', '139804', '139805', '139806', '139807', '139808', '139809', '139810', '139811', '139812' ] # The list of months that we need for camculating MOM mom_months = me_months[1:] # Merge market cap and price dfs merged_df = pd.merge(df, me_df, on=['ticker_num', 'date']) # First, create a NaN column, and then add t-13 prices merged_df.insert(5, 't-13 price', np.nan) for month in mom_months: # Find t-13 prices for ticker in range(1, 76): t_13 = months[months.index(month) - 13] t_13_condtion = (merged_df['date'] == t_13) ticker_condition = (merged_df['ticker_num'] == ticker) try: t_13_price = merged_df.loc[ t_13_condtion & ticker_condition ]['close'].values[0] previous_month = me_months[me_months.index(month) - 1] t_1_condtion = (merged_df['date'] == previous_month) merged_df.loc[ (t_1_condtion & ticker_condition), 't-13 price' ] = t_13_price except: pass # Calculate last 12 months return for month t (t-1, t-12) merged_df['past_year_return'] = ( (merged_df['close'] / merged_df['t-13 price']) - 1 ) mom_list = [] for month in mom_months: # Check t-13 price condition and t-1 market cap condition previous_month = months[months.index(month) - 1] me_condition = (merged_df['date'] == previous_month) mom_condition = (merged_df['past_year_return'].notna()) portfo_const_df = merged_df.loc[me_condition & mom_condition] # Split each month ME into two groups conditions = [ ( portfo_const_df['market_cap'] > portfo_const_df['market_cap'].median() ), ( portfo_const_df['market_cap'] <= portfo_const_df['market_cap'].median() ) ] portfolio_size = np.select(conditions, ['B', 'S']).tolist() portfo_const_df.insert(6, 'size', portfolio_size) # Split each me portfolio into 3 MOM group q = [0, .3, .7, 1] labels = ['L', 'M', 'H'] x_b = portfo_const_df.loc[ portfo_const_df['size'] == 'B' ]['past_year_return'] b_mom = pd.qcut(x=x_b, q=q, labels=labels).to_dict() x_s = portfo_const_df.loc[ portfo_const_df['size'] == 'S' ]['past_year_return'] s_mom = pd.qcut(x=x_s, q=q, labels=labels).to_dict() portfo_const_df['mom'] = pd.Series(b_mom) portfo_const_df['mom'].update(pd.Series(s_mom)) # Extrect portfolio ticker numbers portfo_const_df['portfolio'] = ( portfo_const_df['size'] + portfo_const_df['mom'] ) bh = portfo_const_df.loc[ portfo_const_df['portfolio'] == 'BH' ]['ticker_num'].tolist() bl = portfo_const_df.loc[ portfo_const_df['portfolio'] == 'BL' ]['ticker_num'].tolist() sh = portfo_const_df.loc[ portfo_const_df['portfolio'] == 'SH' ]['ticker_num'].tolist() sl = portfo_const_df.loc[ portfo_const_df['portfolio'] == 'SL' ]['ticker_num'].tolist() # Calculating value-weighted return for each portfolio in month t # Set conditions month_condition = (merged_df['date'] == month) bh_condition = merged_df['ticker_num'].isin(bh) bl_condition = merged_df['ticker_num'].isin(bl) sh_condition = merged_df['ticker_num'].isin(sh) sl_condition = merged_df['ticker_num'].isin(sl) # Construct portfolios bh_portfolio = merged_df.loc[month_condition & bh_condition] bl_portfolio = merged_df.loc[month_condition & bl_condition] sh_portfolio = merged_df.loc[month_condition & sh_condition] sl_portfolio = merged_df.loc[month_condition & sl_condition] # Calculate value-weighted returns bh_return = np.average( bh_portfolio.monthly_return, weights=bh_portfolio.market_cap ) bl_return = np.average( bl_portfolio.monthly_return, weights=bl_portfolio.market_cap ) sh_return = np.average( sh_portfolio.monthly_return, weights=sh_portfolio.market_cap ) sl_return = np.average( sl_portfolio.monthly_return, weights=sl_portfolio.market_cap ) # Calculate MOM, and add it to a list mom = ( ((sh_return + bh_return) / 2) - ((sl_return + bl_return) / 2) ) mom_list.append(mom) mom_df = pd.Series(mom_list).to_excel('mom.xlsx')
1.875
2
src/entity/002_createRdf.py
toyo-bunko/paper_app
1
82
import shutil import os import json import glob import yaml import sys import urllib import ssl import csv import time import requests import json import csv from rdflib import URIRef, BNode, Literal, Graph from rdflib.namespace import RDF, RDFS, FOAF, XSD from rdflib import Namespace all = Graph() with open("data/dict.json") as f: ln_map = json.load(f) st_path = "../data/index.json" with open(st_path) as f: result = json.load(f) uris = [] for obj in result: fields = ["spatial", "agential"] for field in fields: values = obj[field] for value in values: uri = "chname:"+value if field == "spatial": uri = "place:"+value if uri not in uris: uris.append(uri) for uri in uris: print(uri) tmp = uri.split(":") prefix = tmp[0] suffix = tmp[1] ln = suffix ln_org = "" if ln in ln_map: ln_org = ln ln = ln_map[ln] if len(ln) > 20: continue # ln = obj["uri"].split(":")[1] ''' wiki_path = "data/wikidata/"+ln+".json" wiki = {} if os.path.exists(wiki_path): with open(wiki_path) as f: wiki = json.load(f) # sameAs stmt = (subject, URIRef("http://www.w3.org/2002/07/owl#sameAs"), URIRef(wiki_url)) all.add(stmt) obj = wiki["entities"][wiki_url.split("/")[-1]] # description if "descriptions" in obj and "ja" in obj["descriptions"]: stmt = (subject, URIRef("http://schema.org/description"), Literal(obj["descriptions"]["ja"]["value"], lang="ja")) all.add(stmt) # label if "labels" in obj and "ja" in obj["labels"]: stmt = (subject, RDFS.label, Literal(obj["labels"]["ja"]["value"])) all.add(stmt) ln = wiki_url.split("/")[-1] ''' db_path = "data/dbpedia_ja/"+ln+".json" wiki_path = "data/wikidata/"+ln+".json" db = {} wiki = {} if os.path.exists(db_path): with open(db_path) as f: db = json.load(f) if os.path.exists(wiki_path): with open(wiki_path) as f: wiki = json.load(f) db_uri = "http://ja.dbpedia.org/resource/"+ln if db_uri not in db: print("not" , db_uri) continue # ###### subject = URIRef("https://shibusawa-dlab.github.io/lab1/api/"+prefix+"/"+ln) if prefix == "chname": stmt = (subject, RDF.type, URIRef("https://jpsearch.go.jp/term/type/Agent")) all.add(stmt) elif prefix == "time": stmt = (subject, RDF.type, URIRef("https://jpsearch.go.jp/term/type/Time")) all.add(stmt) elif prefix == "place": stmt = (subject, RDF.type, URIRef("https://jpsearch.go.jp/term/type/Place")) all.add(stmt) elif prefix == "event": stmt = (subject, RDF.type, URIRef("https://jpsearch.go.jp/term/type/Event")) all.add(stmt) elif prefix == "org": stmt = (subject, RDF.type, URIRef("https://jpsearch.go.jp/term/type/Organization")) all.add(stmt) elif prefix == "keyword": stmt = (subject, RDF.type, URIRef("https://jpsearch.go.jp/term/type/Keyword")) all.add(stmt) elif prefix == "type": stmt = (subject, RDF.type, URIRef("https://jpsearch.go.jp/term/type/Type")) all.add(stmt) # ###### obj = db[db_uri] stmt = (subject, URIRef("http://www.w3.org/2002/07/owl#sameAs"), URIRef(db_uri)) all.add(stmt) if "http://dbpedia.org/ontology/thumbnail" in obj: stmt = (subject, URIRef("http://schema.org/image"), URIRef(obj["http://dbpedia.org/ontology/thumbnail"][0]["value"])) all.add(stmt) if "http://www.w3.org/2000/01/rdf-schema#label" in obj: labels = obj["http://www.w3.org/2000/01/rdf-schema#label"] for label in labels: if label["lang"] == "ja": stmt = (subject, RDFS.label, Literal(label["value"])) all.add(stmt) if "http://www.w3.org/2000/01/rdf-schema#comment" in obj: labels = obj["http://www.w3.org/2000/01/rdf-schema#comment"] for label in labels: stmt = (subject, URIRef("http://schema.org/description"), Literal(label["value"], lang=label["lang"])) all.add(stmt) if "http://www.w3.org/2002/07/owl#sameAs" in obj: labels = obj["http://www.w3.org/2002/07/owl#sameAs"] for label in labels: value = label["value"] if "http://dbpedia.org" in value or "http://ja.dbpedia.org" in value or "www.wikidata.org" in value: stmt = (subject, URIRef("http://www.w3.org/2002/07/owl#sameAs"), URIRef(value)) all.add(stmt) # 位置情報 ''' if "point" in obj and prefix == "place": value = obj["point"]["value"].split(" ") # addGeo関数 geoUri = addGeo({ "lat" : float(value[0]), "long": float(value[1]) }) stmt = (subject, URIRef("http://schema.org/geo"), geoUri) if suffix not in places: places[suffix] = { "lat" : float(value[0]), "long": float(value[1]) } all.add(stmt) ''' # 正規化前 if ln_org != "" and ln != ln_org: stmt = (subject, URIRef("http://schema.org/name"), Literal(ln_org)) all.add(stmt) path = "data/all.json" all.serialize(destination=path, format='json-ld') all.serialize(destination=path.replace(".json", ".rdf"), format='pretty-xml')
1.671875
2
sympy/combinatorics/testutil.py
ethankward/sympy
2
90
from sympy.combinatorics import Permutation from sympy.combinatorics.util import _distribute_gens_by_base rmul = Permutation.rmul def _cmp_perm_lists(first, second): """ Compare two lists of permutations as sets. This is used for testing purposes. Since the array form of a permutation is currently a list, Permutation is not hashable and cannot be put into a set. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.testutil import _cmp_perm_lists >>> a = Permutation([0, 2, 3, 4, 1]) >>> b = Permutation([1, 2, 0, 4, 3]) >>> c = Permutation([3, 4, 0, 1, 2]) >>> ls1 = [a, b, c] >>> ls2 = [b, c, a] >>> _cmp_perm_lists(ls1, ls2) True """ return {tuple(a) for a in first} == \ {tuple(a) for a in second} def _naive_list_centralizer(self, other, af=False): from sympy.combinatorics.perm_groups import PermutationGroup """ Return a list of elements for the centralizer of a subgroup/set/element. This is a brute force implementation that goes over all elements of the group and checks for membership in the centralizer. It is used to test ``.centralizer()`` from ``sympy.combinatorics.perm_groups``. Examples ======== >>> from sympy.combinatorics.testutil import _naive_list_centralizer >>> from sympy.combinatorics.named_groups import DihedralGroup >>> D = DihedralGroup(4) >>> _naive_list_centralizer(D, D) [Permutation([0, 1, 2, 3]), Permutation([2, 3, 0, 1])] See Also ======== sympy.combinatorics.perm_groups.centralizer """ from sympy.combinatorics.permutations import _af_commutes_with if hasattr(other, 'generators'): elements = list(self.generate_dimino(af=True)) gens = [x._array_form for x in other.generators] commutes_with_gens = lambda x: all(_af_commutes_with(x, gen) for gen in gens) centralizer_list = [] if not af: for element in elements: if commutes_with_gens(element): centralizer_list.append(Permutation._af_new(element)) else: for element in elements: if commutes_with_gens(element): centralizer_list.append(element) return centralizer_list elif hasattr(other, 'getitem'): return _naive_list_centralizer(self, PermutationGroup(other), af) elif hasattr(other, 'array_form'): return _naive_list_centralizer(self, PermutationGroup([other]), af) def _verify_bsgs(group, base, gens): """ Verify the correctness of a base and strong generating set. This is a naive implementation using the definition of a base and a strong generating set relative to it. There are other procedures for verifying a base and strong generating set, but this one will serve for more robust testing. Examples ======== >>> from sympy.combinatorics.named_groups import AlternatingGroup >>> from sympy.combinatorics.testutil import _verify_bsgs >>> A = AlternatingGroup(4) >>> A.schreier_sims() >>> _verify_bsgs(A, A.base, A.strong_gens) True See Also ======== sympy.combinatorics.perm_groups.PermutationGroup.schreier_sims """ from sympy.combinatorics.perm_groups import PermutationGroup strong_gens_distr = _distribute_gens_by_base(base, gens) current_stabilizer = group for i in range(len(base)): candidate = PermutationGroup(strong_gens_distr[i]) if current_stabilizer.order() != candidate.order(): return False current_stabilizer = current_stabilizer.stabilizer(base[i]) if current_stabilizer.order() != 1: return False return True def _verify_centralizer(group, arg, centr=None): """ Verify the centralizer of a group/set/element inside another group. This is used for testing ``.centralizer()`` from ``sympy.combinatorics.perm_groups`` Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... AlternatingGroup) >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.testutil import _verify_centralizer >>> S = SymmetricGroup(5) >>> A = AlternatingGroup(5) >>> centr = PermutationGroup([Permutation([0, 1, 2, 3, 4])]) >>> _verify_centralizer(S, A, centr) True See Also ======== _naive_list_centralizer, sympy.combinatorics.perm_groups.PermutationGroup.centralizer, _cmp_perm_lists """ if centr is None: centr = group.centralizer(arg) centr_list = list(centr.generate_dimino(af=True)) centr_list_naive = _naive_list_centralizer(group, arg, af=True) return _cmp_perm_lists(centr_list, centr_list_naive) def _verify_normal_closure(group, arg, closure=None): from sympy.combinatorics.perm_groups import PermutationGroup """ Verify the normal closure of a subgroup/subset/element in a group. This is used to test sympy.combinatorics.perm_groups.PermutationGroup.normal_closure Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... AlternatingGroup) >>> from sympy.combinatorics.testutil import _verify_normal_closure >>> S = SymmetricGroup(3) >>> A = AlternatingGroup(3) >>> _verify_normal_closure(S, A, closure=A) True See Also ======== sympy.combinatorics.perm_groups.PermutationGroup.normal_closure """ if closure is None: closure = group.normal_closure(arg) conjugates = set() if hasattr(arg, 'generators'): subgr_gens = arg.generators elif hasattr(arg, '__getitem__'): subgr_gens = arg elif hasattr(arg, 'array_form'): subgr_gens = [arg] for el in group.generate_dimino(): for gen in subgr_gens: conjugates.add(gen ^ el) naive_closure = PermutationGroup(list(conjugates)) return closure.is_subgroup(naive_closure) def canonicalize_naive(g, dummies, sym, *v): """ Canonicalize tensor formed by tensors of the different types g permutation representing the tensor dummies list of dummy indices msym symmetry of the metric v is a list of (base_i, gens_i, n_i, sym_i) for tensors of type `i` base_i, gens_i BSGS for tensors of this type n_i number ot tensors of type `i` sym_i symmetry under exchange of two component tensors of type `i` None no symmetry 0 commuting 1 anticommuting Return 0 if the tensor is zero, else return the array form of the permutation representing the canonical form of the tensor. Examples ======== >>> from sympy.combinatorics.testutil import canonicalize_naive >>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs >>> from sympy.combinatorics import Permutation, PermutationGroup >>> g = Permutation([1, 3, 2, 0, 4, 5]) >>> base2, gens2 = get_symmetric_group_sgs(2) >>> canonicalize_naive(g, [2, 3], 0, (base2, gens2, 2, 0)) [0, 2, 1, 3, 4, 5] """ from sympy.combinatorics.perm_groups import PermutationGroup from sympy.combinatorics.tensor_can import gens_products, dummy_sgs from sympy.combinatorics.permutations import Permutation, _af_rmul v1 = [] for i in range(len(v)): base_i, gens_i, n_i, sym_i = v[i] v1.append((base_i, gens_i, [[]]*n_i, sym_i)) size, sbase, sgens = gens_products(*v1) dgens = dummy_sgs(dummies, sym, size-2) if isinstance(sym, int): num_types = 1 dummies = [dummies] sym = [sym] else: num_types = len(sym) dgens = [] for i in range(num_types): dgens.extend(dummy_sgs(dummies[i], sym[i], size - 2)) S = PermutationGroup(sgens) D = PermutationGroup([Permutation(x) for x in dgens]) dlist = list(D.generate(af=True)) g = g.array_form st = set() for s in S.generate(af=True): h = _af_rmul(g, s) for d in dlist: q = tuple(_af_rmul(d, h)) st.add(q) a = list(st) a.sort() prev = (0,)*size for h in a: if h[:-2] == prev[:-2]: if h[-1] != prev[-1]: return 0 prev = h return list(a[0]) def graph_certificate(gr): """ Return a certificate for the graph gr adjacency list The graph is assumed to be unoriented and without external lines. Associate to each vertex of the graph a symmetric tensor with number of indices equal to the degree of the vertex; indices are contracted when they correspond to the same line of the graph. The canonical form of the tensor gives a certificate for the graph. This is not an efficient algorithm to get the certificate of a graph. Examples ======== >>> from sympy.combinatorics.testutil import graph_certificate >>> gr1 = {0:[1, 2, 3, 5], 1:[0, 2, 4], 2:[0, 1, 3, 4], 3:[0, 2, 4], 4:[1, 2, 3, 5], 5:[0, 4]} >>> gr2 = {0:[1, 5], 1:[0, 2, 3, 4], 2:[1, 3, 5], 3:[1, 2, 4, 5], 4:[1, 3, 5], 5:[0, 2, 3, 4]} >>> c1 = graph_certificate(gr1) >>> c2 = graph_certificate(gr2) >>> c1 [0, 2, 4, 6, 1, 8, 10, 12, 3, 14, 16, 18, 5, 9, 15, 7, 11, 17, 13, 19, 20, 21] >>> c1 == c2 True """ from sympy.combinatorics.permutations import _af_invert from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, canonicalize items = list(gr.items()) items.sort(key=lambda x: len(x[1]), reverse=True) pvert = [x[0] for x in items] pvert = _af_invert(pvert) # the indices of the tensor are twice the number of lines of the graph num_indices = 0 for v, neigh in items: num_indices += len(neigh) # associate to each vertex its indices; for each line # between two vertices assign the # even index to the vertex which comes first in items, # the odd index to the other vertex vertices = [[] for i in items] i = 0 for v, neigh in items: for v2 in neigh: if pvert[v] < pvert[v2]: vertices[pvert[v]].append(i) vertices[pvert[v2]].append(i+1) i += 2 g = [] for v in vertices: g.extend(v) assert len(g) == num_indices g += [num_indices, num_indices + 1] size = num_indices + 2 assert sorted(g) == list(range(size)) g = Permutation(g) vlen = [0]*(len(vertices[0])+1) for neigh in vertices: vlen[len(neigh)] += 1 v = [] for i in range(len(vlen)): n = vlen[i] if n: base, gens = get_symmetric_group_sgs(i) v.append((base, gens, n, 0)) v.reverse() dummies = list(range(num_indices)) can = canonicalize(g, dummies, 0, *v) return can
3.015625
3
dags/treinos_igti/treino03.py
rafaelols/airflow
0
98
from airflow import DAG from airflow.operators.bash_operator import BashOperator from airflow.operators.python_operator import PythonOperator, BranchPythonOperator from datetime import datetime, timedelta import pandas as pd import random # Default args definition default_args = { 'owner': 'Rafael', 'depends_on_past': False, 'start_date': datetime(2020, 11, 29, 18, 20), 'email': ['<EMAIL>', '<EMAIL>'], 'email_on_failure': False, 'email_on_retry': False, 'retries': 1, 'Retry_delay': timedelta(minutes=1) } # Dag definition dag = DAG( 'treino-03', description="Extrai dados do Titanic e calcula idade media para homens ou mulheres", default_args = default_args, schedule_interval='*/20 * * * *' ) get_data = BashOperator( task_id='get-data', bash_command='curl https://raw.githubusercontent.com/A3Data/hermione/master/hermione/file_text/train.csv -o /usr/local/airflow/data/train.csv', dag=dag ) def sorteia_h_m(): return random.choice(['male', 'female']) escolhe_h_m = PythonOperator( task_id='escolhe-h-m', python_callable=sorteia_h_m, dag=dag ) def MouF(**context): value=context['task_instance'].xcom_pull(task_ids='escolhe-h-m') if value == 'male': return 'branch_homem' else: return 'branch_mulher' male_female = BranchPythonOperator( task_id='condicional', python_callable=MouF, provide_context=True, dag=dag ) def mean_homem(): df = pd.read_csv('/usr/local/airflow/data/train.csv') med = df.loc[df.Sex == 'male'].Age.mean() print(f'Media de idade dos homens no Titanic: {med}') branch_homem = PythonOperator( task_id='branch_homem', python_callable=mean_homem, dag=dag ) def mean_mulher(): df = pd.read_csv('/usr/local/airflow/data/train.csv') med = df.loc[df.Sex == 'female'].Age.mean() print(f'Media de idade das mulheres no Titanic: {med}') branch_mulher = PythonOperator( task_id='branch_mulher', python_callable=mean_mulher, dag=dag ) get_data >> escolhe_h_m >> male_female >> [branch_homem, branch_mulher]
1.5
2
src/topicModel.py
daidaotong/SingleView
0
106
from gensim import corpora, models, similarities, matutils,utils from gensim.models import KeyedVectors import numpy as np #Word2vec Experiment testString = ['PAST_MEDICAL_HISTORY','PAST_SURGICAL_HISTORY','PHYSICAL_EXAMINATION'] ''' word_vectors = KeyedVectors.load_word2vec_format('~/Downloads/GoogleNews-vectors-negative300.bin', binary=True) #model.save("file.txt") print word_vectors.most_similar(positive=['woman', 'king'], negative=['man']) print "******************************************************" print word_vectors.similarity('woman', 'man') #print word_vectors.most_similar(positive=['san_francisco']) print word_vectors.most_similar(positive=['SURGICAL']) #word_vectors.similarity(testString[0],testString[1]) ''' a=[1,4,3,6,3,6] print a[:-1] #print zip(a[:-1],a[1:]) print np.random.randn(3, 2)
2.140625
2
slim/nets/inception_resnet_v2.py
PPTMiao/mtl-ssl
90
114
# Copyright 2016 The TensorFlow 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. # ============================================================================== """Contains the definition of the Inception Resnet V2 architecture. As described in http://arxiv.org/abs/1602.07261. Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning <NAME>, <NAME>, <NAME>, <NAME> """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf slim = tf.contrib.slim def block35(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None): """Builds the 35x35 resnet block.""" with tf.variable_scope(scope, 'Block35', [net], reuse=reuse): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 32, 1, scope='Conv2d_1x1') with tf.variable_scope('Branch_1'): tower_conv1_0 = slim.conv2d(net, 32, 1, scope='Conv2d_0a_1x1') tower_conv1_1 = slim.conv2d(tower_conv1_0, 32, 3, scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): tower_conv2_0 = slim.conv2d(net, 32, 1, scope='Conv2d_0a_1x1') tower_conv2_1 = slim.conv2d(tower_conv2_0, 48, 3, scope='Conv2d_0b_3x3') tower_conv2_2 = slim.conv2d(tower_conv2_1, 64, 3, scope='Conv2d_0c_3x3') mixed = tf.concat(axis=3, values=[tower_conv, tower_conv1_1, tower_conv2_2]) up = slim.conv2d(mixed, net.get_shape()[3], 1, normalizer_fn=None, activation_fn=None, scope='Conv2d_1x1') net += scale * up if activation_fn: net = activation_fn(net) return net def block17(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None): """Builds the 17x17 resnet block.""" with tf.variable_scope(scope, 'Block17', [net], reuse=reuse): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 192, 1, scope='Conv2d_1x1') with tf.variable_scope('Branch_1'): tower_conv1_0 = slim.conv2d(net, 128, 1, scope='Conv2d_0a_1x1') tower_conv1_1 = slim.conv2d(tower_conv1_0, 160, [1, 7], scope='Conv2d_0b_1x7') tower_conv1_2 = slim.conv2d(tower_conv1_1, 192, [7, 1], scope='Conv2d_0c_7x1') mixed = tf.concat(axis=3, values=[tower_conv, tower_conv1_2]) up = slim.conv2d(mixed, net.get_shape()[3], 1, normalizer_fn=None, activation_fn=None, scope='Conv2d_1x1') net += scale * up if activation_fn: net = activation_fn(net) return net def block8(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None): """Builds the 8x8 resnet block.""" with tf.variable_scope(scope, 'Block8', [net], reuse=reuse): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 192, 1, scope='Conv2d_1x1') with tf.variable_scope('Branch_1'): tower_conv1_0 = slim.conv2d(net, 192, 1, scope='Conv2d_0a_1x1') tower_conv1_1 = slim.conv2d(tower_conv1_0, 224, [1, 3], scope='Conv2d_0b_1x3') tower_conv1_2 = slim.conv2d(tower_conv1_1, 256, [3, 1], scope='Conv2d_0c_3x1') mixed = tf.concat(axis=3, values=[tower_conv, tower_conv1_2]) up = slim.conv2d(mixed, net.get_shape()[3], 1, normalizer_fn=None, activation_fn=None, scope='Conv2d_1x1') net += scale * up if activation_fn: net = activation_fn(net) return net def inception_resnet_v2_base(inputs, final_endpoint='Conv2d_7b_1x1', output_stride=16, align_feature_maps=False, scope=None): """Inception model from http://arxiv.org/abs/1602.07261. Constructs an Inception Resnet v2 network from inputs to the given final endpoint. This method can construct the network up to the final inception block Conv2d_7b_1x1. Args: inputs: a tensor of size [batch_size, height, width, channels]. final_endpoint: specifies the endpoint to construct the network up to. It can be one of ['Conv2d_1a_3x3', 'Conv2d_2a_3x3', 'Conv2d_2b_3x3', 'MaxPool_3a_3x3', 'Conv2d_3b_1x1', 'Conv2d_4a_3x3', 'MaxPool_5a_3x3', 'Mixed_5b', 'Mixed_6a', 'PreAuxLogits', 'Mixed_7a', 'Conv2d_7b_1x1'] output_stride: A scalar that specifies the requested ratio of input to output spatial resolution. Only supports 8 and 16. align_feature_maps: When true, changes all the VALID paddings in the network to SAME padding so that the feature maps are aligned. scope: Optional variable_scope. Returns: tensor_out: output tensor corresponding to the final_endpoint. end_points: a set of activations for external use, for example summaries or losses. Raises: ValueError: if final_endpoint is not set to one of the predefined values, or if the output_stride is not 8 or 16, or if the output_stride is 8 and we request an end point after 'PreAuxLogits'. """ if output_stride != 8 and output_stride != 16: raise ValueError('output_stride must be 8 or 16.') padding = 'SAME' if align_feature_maps else 'VALID' end_points = {} def add_and_check_final(name, net): end_points[name] = net return name == final_endpoint with tf.variable_scope(scope, 'InceptionResnetV2', [inputs]): with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d], stride=1, padding='SAME'): # 149 x 149 x 32 net = slim.conv2d(inputs, 32, 3, stride=2, padding=padding, scope='Conv2d_1a_3x3') if add_and_check_final('Conv2d_1a_3x3', net): return net, end_points # 147 x 147 x 32 net = slim.conv2d(net, 32, 3, padding=padding, scope='Conv2d_2a_3x3') if add_and_check_final('Conv2d_2a_3x3', net): return net, end_points # 147 x 147 x 64 net = slim.conv2d(net, 64, 3, scope='Conv2d_2b_3x3') if add_and_check_final('Conv2d_2b_3x3', net): return net, end_points # 73 x 73 x 64 net = slim.max_pool2d(net, 3, stride=2, padding=padding, scope='MaxPool_3a_3x3') if add_and_check_final('MaxPool_3a_3x3', net): return net, end_points # 73 x 73 x 80 net = slim.conv2d(net, 80, 1, padding=padding, scope='Conv2d_3b_1x1') if add_and_check_final('Conv2d_3b_1x1', net): return net, end_points # 71 x 71 x 192 net = slim.conv2d(net, 192, 3, padding=padding, scope='Conv2d_4a_3x3') if add_and_check_final('Conv2d_4a_3x3', net): return net, end_points # 35 x 35 x 192 net = slim.max_pool2d(net, 3, stride=2, padding=padding, scope='MaxPool_5a_3x3') if add_and_check_final('MaxPool_5a_3x3', net): return net, end_points # 35 x 35 x 320 with tf.variable_scope('Mixed_5b'): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 96, 1, scope='Conv2d_1x1') with tf.variable_scope('Branch_1'): tower_conv1_0 = slim.conv2d(net, 48, 1, scope='Conv2d_0a_1x1') tower_conv1_1 = slim.conv2d(tower_conv1_0, 64, 5, scope='Conv2d_0b_5x5') with tf.variable_scope('Branch_2'): tower_conv2_0 = slim.conv2d(net, 64, 1, scope='Conv2d_0a_1x1') tower_conv2_1 = slim.conv2d(tower_conv2_0, 96, 3, scope='Conv2d_0b_3x3') tower_conv2_2 = slim.conv2d(tower_conv2_1, 96, 3, scope='Conv2d_0c_3x3') with tf.variable_scope('Branch_3'): tower_pool = slim.avg_pool2d(net, 3, stride=1, padding='SAME', scope='AvgPool_0a_3x3') tower_pool_1 = slim.conv2d(tower_pool, 64, 1, scope='Conv2d_0b_1x1') net = tf.concat( [tower_conv, tower_conv1_1, tower_conv2_2, tower_pool_1], 3) if add_and_check_final('Mixed_5b', net): return net, end_points # TODO(alemi): Register intermediate endpoints net = slim.repeat(net, 10, block35, scale=0.17) # 17 x 17 x 1088 if output_stride == 8, # 33 x 33 x 1088 if output_stride == 16 use_atrous = output_stride == 8 with tf.variable_scope('Mixed_6a'): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 384, 3, stride=1 if use_atrous else 2, padding=padding, scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_1'): tower_conv1_0 = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1') tower_conv1_1 = slim.conv2d(tower_conv1_0, 256, 3, scope='Conv2d_0b_3x3') tower_conv1_2 = slim.conv2d(tower_conv1_1, 384, 3, stride=1 if use_atrous else 2, padding=padding, scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_2'): tower_pool = slim.max_pool2d(net, 3, stride=1 if use_atrous else 2, padding=padding, scope='MaxPool_1a_3x3') net = tf.concat([tower_conv, tower_conv1_2, tower_pool], 3) if add_and_check_final('Mixed_6a', net): return net, end_points # TODO(alemi): register intermediate endpoints with slim.arg_scope([slim.conv2d], rate=2 if use_atrous else 1): net = slim.repeat(net, 20, block17, scale=0.10) if add_and_check_final('PreAuxLogits', net): return net, end_points if output_stride == 8: # TODO(gpapan): Properly support output_stride for the rest of the net. raise ValueError('output_stride==8 is only supported up to the ' 'PreAuxlogits end_point for now.') # 8 x 8 x 2080 with tf.variable_scope('Mixed_7a'): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1') tower_conv_1 = slim.conv2d(tower_conv, 384, 3, stride=2, padding=padding, scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_1'): tower_conv1 = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1') tower_conv1_1 = slim.conv2d(tower_conv1, 288, 3, stride=2, padding=padding, scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_2'): tower_conv2 = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1') tower_conv2_1 = slim.conv2d(tower_conv2, 288, 3, scope='Conv2d_0b_3x3') tower_conv2_2 = slim.conv2d(tower_conv2_1, 320, 3, stride=2, padding=padding, scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_3'): tower_pool = slim.max_pool2d(net, 3, stride=2, padding=padding, scope='MaxPool_1a_3x3') net = tf.concat( [tower_conv_1, tower_conv1_1, tower_conv2_2, tower_pool], 3) if add_and_check_final('Mixed_7a', net): return net, end_points # TODO(alemi): register intermediate endpoints net = slim.repeat(net, 9, block8, scale=0.20) net = block8(net, activation_fn=None) # 8 x 8 x 1536 net = slim.conv2d(net, 1536, 1, scope='Conv2d_7b_1x1') if add_and_check_final('Conv2d_7b_1x1', net): return net, end_points raise ValueError('final_endpoint (%s) not recognized', final_endpoint) def inception_resnet_v2(inputs, num_classes=1001, is_training=True, dropout_keep_prob=0.8, reuse=None, scope='InceptionResnetV2', create_aux_logits=True): """Creates the Inception Resnet V2 model. Args: inputs: a 4-D tensor of size [batch_size, height, width, 3]. num_classes: number of predicted classes. is_training: whether is training or not. dropout_keep_prob: float, the fraction to keep before final layer. reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. scope: Optional variable_scope. create_aux_logits: Whether to include the auxilliary logits. Returns: logits: the logits outputs of the model. end_points: the set of end_points from the inception model. """ end_points = {} with tf.variable_scope(scope, 'InceptionResnetV2', [inputs, num_classes], reuse=reuse) as scope: with slim.arg_scope([slim.batch_norm, slim.dropout], is_training=is_training): net, end_points = inception_resnet_v2_base(inputs, scope=scope) if create_aux_logits: with tf.variable_scope('AuxLogits'): aux = end_points['PreAuxLogits'] aux = slim.avg_pool2d(aux, 5, stride=3, padding='VALID', scope='Conv2d_1a_3x3') aux = slim.conv2d(aux, 128, 1, scope='Conv2d_1b_1x1') aux = slim.conv2d(aux, 768, aux.get_shape()[1:3], padding='VALID', scope='Conv2d_2a_5x5') aux = slim.flatten(aux) aux = slim.fully_connected(aux, num_classes, activation_fn=None, scope='Logits') end_points['AuxLogits'] = aux with tf.variable_scope('Logits'): net = slim.avg_pool2d(net, net.get_shape()[1:3], padding='VALID', scope='AvgPool_1a_8x8') net = slim.flatten(net) net = slim.dropout(net, dropout_keep_prob, is_training=is_training, scope='Dropout') end_points['PreLogitsFlatten'] = net logits = slim.fully_connected(net, num_classes, activation_fn=None, scope='Logits') end_points['Logits'] = logits end_points['Predictions'] = tf.nn.softmax(logits, name='Predictions') return logits, end_points inception_resnet_v2.default_image_size = 299 def inception_resnet_v2_arg_scope(weight_decay=0.00004, batch_norm_decay=0.9997, batch_norm_epsilon=0.001, trainable=True): """Returns the scope with the default parameters for inception_resnet_v2. Args: weight_decay: the weight decay for weights variables. batch_norm_decay: decay for the moving average of batch_norm momentums. batch_norm_epsilon: small float added to variance to avoid dividing by zero. Returns: a arg_scope with the parameters needed for inception_resnet_v2. """ # Set weight_decay for weights in conv2d and fully_connected layers. with slim.arg_scope([slim.conv2d, slim.fully_connected], weights_regularizer=slim.l2_regularizer(weight_decay), biases_regularizer=slim.l2_regularizer(weight_decay), trainable=trainable): batch_norm_params = { 'decay': batch_norm_decay, 'epsilon': batch_norm_epsilon, 'trainable': trainable } # Set activation_fn and parameters for batch_norm. with slim.arg_scope([slim.conv2d], activation_fn=tf.nn.relu, normalizer_fn=slim.batch_norm, normalizer_params=batch_norm_params) as scope: return scope
1.992188
2
examples/Testing/flopy3_plotdata.py
ritchie46/flopy
1
122
from __future__ import print_function import os import numpy as np import matplotlib.pyplot as plt import flopy fb = flopy.modflow.Modflow.load('freyberg', version='mf2005', model_ws=os.path.join('..', 'data', 'freyberg'), verbose=True) dis = fb.dis top = fb.dis.top fb.dis.top.plot(grid=True, colorbar=True) fb.dis.botm.plot(grid=True, colorbar=True) fb.dis.plot() plt.show() fb.dis.plot() plt.show() fig = plt.figure(figsize=(8, 8)) ax = fig.add_subplot(1,2,1, aspect='equal') fb.dis.top.plot(grid=True, axes=ax, colorbar=True) ax = fig.add_subplot(1,2,2, aspect='equal') fb.dis.botm.plot(grid=True, axes=ax, colorbar=True) plt.show() print('this is the end my friend')
1.46875
1
day06/part1.py
bugra-yilmaz/adventofcode2021
0
130
import os.path from collections import Counter import pytest INPUT_TXT = os.path.join(os.path.dirname(__file__), 'input.txt') def compute(s: str) -> int: lines = s.splitlines() numbers = Counter(int(f) for f in lines[0].split(",")) for d in range(80): numbers2 = Counter({8: numbers[0], 6: numbers[0]}) for k, v in numbers.items(): if k >= 1: numbers2[k - 1] += v numbers = numbers2 return sum(numbers.values()) INPUT_S = '''\ 3,4,3,1,2 ''' EXPECTED = 5934 @pytest.mark.parametrize( ('input_s', 'expected'), ( (INPUT_S, EXPECTED), ), ) def test(input_s: str, expected: int) -> None: assert compute(input_s) == expected def main() -> int: with open(INPUT_TXT, "r") as f: print(compute(f.read())) return 0 if __name__ == '__main__': raise SystemExit(main())
2.1875
2
third_party/protobuf/protobuf.gyp
meego-tablet-ux/meego-app-browser
1
138
# Copyright (c) 2009 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'conditions': [ ['OS!="win"', { 'variables': { 'config_h_dir': '.', # crafted for gcc/linux. }, }, { # else, OS=="win" 'variables': { 'config_h_dir': 'vsprojects', # crafted for msvc. }, 'target_defaults': { 'msvs_disabled_warnings': [ 4018, # signed/unsigned mismatch in comparison 4244, # implicit conversion, possible loss of data 4355, # 'this' used in base member initializer list ], 'defines!': [ 'WIN32_LEAN_AND_MEAN', # Protobuf defines this itself. ], }, }] ], 'targets': [ # The "lite" lib is about 1/7th the size of the heavy lib, # but it doesn't support some of the more exotic features of # protobufs, like reflection. To generate C++ code that can link # against the lite version of the library, add the option line: # # option optimize_for = LITE_RUNTIME; # # to your .proto file. { 'target_name': 'protobuf_lite', 'type': '<(library)', 'toolsets': ['host', 'target'], 'sources': [ 'src/google/protobuf/stubs/common.h', 'src/google/protobuf/stubs/once.h', 'src/google/protobuf/extension_set.h', 'src/google/protobuf/generated_message_util.h', 'src/google/protobuf/message_lite.h', 'src/google/protobuf/repeated_field.h', 'src/google/protobuf/unknown_field_set.cc', 'src/google/protobuf/unknown_field_set.h', 'src/google/protobuf/wire_format_lite.h', 'src/google/protobuf/wire_format_lite_inl.h', 'src/google/protobuf/io/coded_stream.h', 'src/google/protobuf/io/zero_copy_stream.h', 'src/google/protobuf/io/zero_copy_stream_impl_lite.h', 'src/google/protobuf/stubs/common.cc', 'src/google/protobuf/stubs/once.cc', 'src/google/protobuf/stubs/hash.h', 'src/google/protobuf/stubs/map-util.h', 'src/google/protobuf/stubs/stl_util-inl.h', 'src/google/protobuf/extension_set.cc', 'src/google/protobuf/generated_message_util.cc', 'src/google/protobuf/message_lite.cc', 'src/google/protobuf/repeated_field.cc', 'src/google/protobuf/wire_format_lite.cc', 'src/google/protobuf/io/coded_stream.cc', 'src/google/protobuf/io/coded_stream_inl.h', 'src/google/protobuf/io/zero_copy_stream.cc', 'src/google/protobuf/io/zero_copy_stream_impl_lite.cc', '<(config_h_dir)/config.h', ], 'include_dirs': [ '<(config_h_dir)', 'src', ], # This macro must be defined to suppress the use of dynamic_cast<>, # which requires RTTI. 'defines': [ 'GOOGLE_PROTOBUF_NO_RTTI', ], 'direct_dependent_settings': { 'include_dirs': [ '<(config_h_dir)', 'src', ], 'defines': [ 'GOOGLE_PROTOBUF_NO_RTTI', ], }, }, # This is the full, heavy protobuf lib that's needed for c++ .proto's # that don't specify the LITE_RUNTIME option. The protocol # compiler itself (protoc) falls into that category. # # DO NOT LINK AGAINST THIS TARGET IN CHROME CODE --agl { 'target_name': 'protobuf_full_do_not_use', 'type': '<(library)', 'toolsets': ['host','target'], 'sources': [ 'src/google/protobuf/descriptor.h', 'src/google/protobuf/descriptor.pb.h', 'src/google/protobuf/descriptor_database.h', 'src/google/protobuf/dynamic_message.h', 'src/google/protobuf/generated_message_reflection.h', 'src/google/protobuf/message.h', 'src/google/protobuf/reflection_ops.h', 'src/google/protobuf/service.h', 'src/google/protobuf/text_format.h', 'src/google/protobuf/unknown_field_set.h', 'src/google/protobuf/wire_format.h', 'src/google/protobuf/io/gzip_stream.h', 'src/google/protobuf/io/printer.h', 'src/google/protobuf/io/tokenizer.h', 'src/google/protobuf/io/zero_copy_stream_impl.h', 'src/google/protobuf/compiler/code_generator.h', 'src/google/protobuf/compiler/command_line_interface.h', 'src/google/protobuf/compiler/importer.h', 'src/google/protobuf/compiler/parser.h', 'src/google/protobuf/stubs/strutil.cc', 'src/google/protobuf/stubs/strutil.h', 'src/google/protobuf/stubs/substitute.cc', 'src/google/protobuf/stubs/substitute.h', 'src/google/protobuf/stubs/structurally_valid.cc', 'src/google/protobuf/descriptor.cc', 'src/google/protobuf/descriptor.pb.cc', 'src/google/protobuf/descriptor_database.cc', 'src/google/protobuf/dynamic_message.cc', 'src/google/protobuf/extension_set_heavy.cc', 'src/google/protobuf/generated_message_reflection.cc', 'src/google/protobuf/message.cc', 'src/google/protobuf/reflection_ops.cc', 'src/google/protobuf/service.cc', 'src/google/protobuf/text_format.cc', 'src/google/protobuf/unknown_field_set.cc', 'src/google/protobuf/wire_format.cc', # This file pulls in zlib, but it's not actually used by protoc, so # instead of compiling zlib for the host, let's just exclude this. # 'src/src/google/protobuf/io/gzip_stream.cc', 'src/google/protobuf/io/printer.cc', 'src/google/protobuf/io/tokenizer.cc', 'src/google/protobuf/io/zero_copy_stream_impl.cc', 'src/google/protobuf/compiler/importer.cc', 'src/google/protobuf/compiler/parser.cc', ], 'dependencies': [ 'protobuf_lite', ], 'export_dependent_settings': [ 'protobuf_lite', ], }, { 'target_name': 'protoc', 'type': 'executable', 'toolsets': ['host'], 'sources': [ 'src/google/protobuf/compiler/code_generator.cc', 'src/google/protobuf/compiler/command_line_interface.cc', 'src/google/protobuf/compiler/plugin.cc', 'src/google/protobuf/compiler/plugin.pb.cc', 'src/google/protobuf/compiler/subprocess.cc', 'src/google/protobuf/compiler/subprocess.h', 'src/google/protobuf/compiler/zip_writer.cc', 'src/google/protobuf/compiler/zip_writer.h', 'src/google/protobuf/compiler/cpp/cpp_enum.cc', 'src/google/protobuf/compiler/cpp/cpp_enum.h', 'src/google/protobuf/compiler/cpp/cpp_enum_field.cc', 'src/google/protobuf/compiler/cpp/cpp_enum_field.h', 'src/google/protobuf/compiler/cpp/cpp_extension.cc', 'src/google/protobuf/compiler/cpp/cpp_extension.h', 'src/google/protobuf/compiler/cpp/cpp_field.cc', 'src/google/protobuf/compiler/cpp/cpp_field.h', 'src/google/protobuf/compiler/cpp/cpp_file.cc', 'src/google/protobuf/compiler/cpp/cpp_file.h', 'src/google/protobuf/compiler/cpp/cpp_generator.cc', 'src/google/protobuf/compiler/cpp/cpp_helpers.cc', 'src/google/protobuf/compiler/cpp/cpp_helpers.h', 'src/google/protobuf/compiler/cpp/cpp_message.cc', 'src/google/protobuf/compiler/cpp/cpp_message.h', 'src/google/protobuf/compiler/cpp/cpp_message_field.cc', 'src/google/protobuf/compiler/cpp/cpp_message_field.h', 'src/google/protobuf/compiler/cpp/cpp_primitive_field.cc', 'src/google/protobuf/compiler/cpp/cpp_primitive_field.h', 'src/google/protobuf/compiler/cpp/cpp_service.cc', 'src/google/protobuf/compiler/cpp/cpp_service.h', 'src/google/protobuf/compiler/cpp/cpp_string_field.cc', 'src/google/protobuf/compiler/cpp/cpp_string_field.h', 'src/google/protobuf/compiler/java/java_enum.cc', 'src/google/protobuf/compiler/java/java_enum.h', 'src/google/protobuf/compiler/java/java_enum_field.cc', 'src/google/protobuf/compiler/java/java_enum_field.h', 'src/google/protobuf/compiler/java/java_extension.cc', 'src/google/protobuf/compiler/java/java_extension.h', 'src/google/protobuf/compiler/java/java_field.cc', 'src/google/protobuf/compiler/java/java_field.h', 'src/google/protobuf/compiler/java/java_file.cc', 'src/google/protobuf/compiler/java/java_file.h', 'src/google/protobuf/compiler/java/java_generator.cc', 'src/google/protobuf/compiler/java/java_helpers.cc', 'src/google/protobuf/compiler/java/java_helpers.h', 'src/google/protobuf/compiler/java/java_message.cc', 'src/google/protobuf/compiler/java/java_message.h', 'src/google/protobuf/compiler/java/java_message_field.cc', 'src/google/protobuf/compiler/java/java_message_field.h', 'src/google/protobuf/compiler/java/java_primitive_field.cc', 'src/google/protobuf/compiler/java/java_primitive_field.h', 'src/google/protobuf/compiler/java/java_service.cc', 'src/google/protobuf/compiler/java/java_service.h', 'src/google/protobuf/compiler/java/java_string_field.cc', 'src/google/protobuf/compiler/java/java_string_field.h', 'src/google/protobuf/compiler/python/python_generator.cc', 'src/google/protobuf/compiler/main.cc', ], 'dependencies': [ 'protobuf_full_do_not_use', ], 'include_dirs': [ '<(config_h_dir)', 'src/src', ], }, { # Generate the python module needed by all protoc-generated Python code. 'target_name': 'py_proto', 'type': 'none', 'copies': [ { 'destination': '<(PRODUCT_DIR)/pyproto/google/', 'files': [ # google/ module gets an empty __init__.py. '__init__.py', ], }, { 'destination': '<(PRODUCT_DIR)/pyproto/google/protobuf', 'files': [ 'python/google/protobuf/__init__.py', 'python/google/protobuf/descriptor.py', 'python/google/protobuf/message.py', 'python/google/protobuf/reflection.py', 'python/google/protobuf/service.py', 'python/google/protobuf/service_reflection.py', 'python/google/protobuf/text_format.py', # TODO(ncarter): protoc's python generator treats descriptor.proto # specially, but it's not possible to trigger the special treatment # unless you run protoc from ./src/src (the treatment is based # on the path to the .proto file matching a constant exactly). # I'm not sure how to convince gyp to execute a rule from a # different directory. Until this is resolved, use a copy of # descriptor_pb2.py that I manually generated. 'descriptor_pb2.py', ], }, { 'destination': '<(PRODUCT_DIR)/pyproto/google/protobuf/internal', 'files': [ 'python/google/protobuf/internal/__init__.py', 'python/google/protobuf/internal/api_implementation.py', 'python/google/protobuf/internal/containers.py', 'python/google/protobuf/internal/cpp_message.py', 'python/google/protobuf/internal/decoder.py', 'python/google/protobuf/internal/encoder.py', 'python/google/protobuf/internal/generator_test.py', 'python/google/protobuf/internal/message_listener.py', 'python/google/protobuf/internal/python_message.py', 'python/google/protobuf/internal/type_checkers.py', 'python/google/protobuf/internal/wire_format.py', ], }, ], # # We can't generate a proper descriptor_pb2.py -- see earlier comment. # 'rules': [ # { # 'rule_name': 'genproto', # 'extension': 'proto', # 'inputs': [ # '<(PRODUCT_DIR)/<(EXECUTABLE_PREFIX)protoc<(EXECUTABLE_SUFFIX)', # ], # 'variables': { # # The protoc compiler requires a proto_path argument with the # # directory containing the .proto file. # 'rule_input_relpath': 'src/google/protobuf', # }, # 'outputs': [ # '<(PRODUCT_DIR)/pyproto/google/protobuf/<(RULE_INPUT_ROOT)_pb2.py', # ], # 'action': [ # '<(PRODUCT_DIR)/<(EXECUTABLE_PREFIX)protoc<(EXECUTABLE_SUFFIX)', # '-I./src', # '-I.', # '--python_out=<(PRODUCT_DIR)/pyproto/google/protobuf', # 'google/protobuf/descriptor.proto', # ], # 'message': 'Generating Python code from <(RULE_INPUT_PATH)', # }, # ], # 'dependencies': [ # 'protoc#host', # ], # 'sources': [ # 'src/google/protobuf/descriptor.proto', # ], }, ], } # Local Variables: # tab-width:2 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=2 shiftwidth=2:
0.953125
1
kiwi_scp/commands/cmd_cmd.py
yavook/kiwi-scp
0
146
from typing import Tuple import click from .cmd import KiwiCommandType, KiwiCommand from .decorators import kiwi_command from ..executable import COMPOSE_EXE from ..instance import Instance from ..project import Project @click.argument( "compose_args", metavar="[ARG]...", nargs=-1, ) @click.argument( "compose_cmd", metavar="COMMAND", ) @kiwi_command( short_help="Run docker-compose command", # ignore arguments looking like options # just pass everything down to docker-compose context_settings={"ignore_unknown_options": True}, ) class CmdCommand(KiwiCommand): """Run raw docker-compose command in a project""" type = KiwiCommandType.PROJECT enabled_only = True @classmethod def run_for_project(cls, instance: Instance, project: Project, compose_cmd: str = None, compose_args: Tuple[str] = None) -> None: COMPOSE_EXE.run([compose_cmd, *compose_args], **project.process_kwargs)
1.773438
2
catalyst/exchange/live_graph_clock.py
erlendve/catalyst
0
154
import pandas as pd from catalyst.constants import LOG_LEVEL from catalyst.exchange.utils.stats_utils import prepare_stats from catalyst.gens.sim_engine import ( BAR, SESSION_START ) from logbook import Logger log = Logger('LiveGraphClock', level=LOG_LEVEL) class LiveGraphClock(object): """Realtime clock for live trading. This class is a drop-in replacement for :class:`zipline.gens.sim_engine.MinuteSimulationClock`. This mixes the clock with a live graph. Notes ----- This seemingly awkward approach allows us to run the program using a single thread. This is important because Matplotlib does not play nice with multi-threaded environments. Zipline probably does not either. Matplotlib has a pause() method which is a wrapper around time.sleep() used in the SimpleClock. The key difference is that users can still interact with the chart during the pause cycles. This is what enables us to keep a single thread. This is also why we are not using the 'animate' callback of Matplotlib. We need to direct access to the __iter__ method in order to yield events to Zipline. The :param:`time_skew` parameter represents the time difference between the exchange and the live trading machine's clock. It's not used currently. """ def __init__(self, sessions, context, callback=None, time_skew=pd.Timedelta('0s')): self.sessions = sessions self.time_skew = time_skew self._last_emit = None self._before_trading_start_bar_yielded = True self.context = context self.callback = callback def __iter__(self): from matplotlib import pyplot as plt yield pd.Timestamp.utcnow(), SESSION_START while True: current_time = pd.Timestamp.utcnow() current_minute = current_time.floor('1T') if self._last_emit is None or current_minute > self._last_emit: log.debug('emitting minutely bar: {}'.format(current_minute)) self._last_emit = current_minute yield current_minute, BAR recorded_cols = list(self.context.recorded_vars.keys()) df, _ = prepare_stats( self.context.frame_stats, recorded_cols=recorded_cols ) self.callback(self.context, df) else: # I can't use the "animate" reactive approach here because # I need to yield from the main loop. # Workaround: https://stackoverflow.com/a/33050617/814633 plt.pause(1)
2.03125
2
otp/chat/ChatInputNormal.py
P1ayerOne/src
0
162
from direct.showbase import DirectObject from otp.otpbase import OTPGlobals import sys from direct.gui.DirectGui import * from pandac.PandaModules import * from otp.otpbase import OTPLocalizer class ChatInputNormal(DirectObject.DirectObject): ExecNamespace = None def __init__(self, chatMgr): self.chatMgr = chatMgr self.normalPos = Vec3(-1.083, 0, 0.804) self.whisperPos = Vec3(0.0, 0, 0.71) self.whisperAvatarName = None self.whisperAvatarId = None self.toPlayer = 0 wantHistory = 0 if __dev__: wantHistory = 1 self.wantHistory = base.config.GetBool('want-chat-history', wantHistory) self.history = [''] self.historySize = base.config.GetInt('chat-history-size', 10) self.historyIndex = 0 return def typeCallback(self, extraArgs): messenger.send('enterNormalChat') def delete(self): self.ignore('arrow_up-up') self.ignore('arrow_down-up') self.chatFrame.destroy() del self.chatFrame del self.chatButton del self.cancelButton del self.chatEntry del self.whisperLabel del self.chatMgr def activateByData(self, whisperAvatarId = None, toPlayer = 0): self.toPlayer = toPlayer self.whisperAvatarId = whisperAvatarId self.whisperAvatarName = base.talkAssistant.findName(self.whisperAvatarId, self.toPlayer) if self.whisperAvatarId: self.chatFrame.setPos(self.whisperPos) self.whisperLabel['text'] = OTPLocalizer.ChatInputWhisperLabel % self.whisperAvatarName self.whisperLabel.show() else: self.chatFrame.setPos(self.normalPos) self.whisperLabel.hide() self.chatEntry['focus'] = 1 self.chatFrame.show() if self.wantHistory: self.accept('arrow_up-up', self.getPrevHistory) self.accept('arrow_down-up', self.getNextHistory) def deactivate(self): self.chatEntry.set('') self.chatEntry['focus'] = 0 self.chatFrame.hide() self.whisperLabel.hide() base.win.closeIme() self.ignore('arrow_up-up') self.ignore('arrow_down-up') def checkForOverRide(self): return False def sendChat(self, text): if self.checkForOverRide(): self.chatEntry.enterText('') return self.deactivate() self.chatMgr.fsm.request('mainMenu') if text: if self.toPlayer: if self.whisperAvatarId: self.whisperAvatarName = None self.whisperAvatarId = None self.toPlayer = 0 elif self.whisperAvatarId: self.chatMgr.sendWhisperString(text, self.whisperAvatarId) self.whisperAvatarName = None self.whisperAvatarId = None else: if self.chatMgr.execChat: if text[0] == '>': text = self.__execMessage(text[1:]) base.localAvatar.setChatAbsolute(text, CFSpeech | CFTimeout) return base.talkAssistant.sendOpenTalk(text) if self.wantHistory: self.addToHistory(text) return def chatOverflow(self, overflowText): self.sendChat(self.chatEntry.get()) def __execMessage(self, message): if not ChatInputNormal.ExecNamespace: ChatInputNormal.ExecNamespace = {} exec('from pandac.PandaModules import *', globals(), self.ExecNamespace) self.importExecNamespace() try: if not isClient(): print('EXECWARNING ChatInputNormal eval: %s' % message) printStack() return str(eval(message, globals(), ChatInputNormal.ExecNamespace)) except SyntaxError: try: if not isClient(): print('EXECWARNING ChatInputNormal exec: %s' % message) printStack() exec(message, globals(), ChatInputNormal.ExecNamespace) return 'ok' except: exception = sys.exc_info()[0] extraInfo = sys.exc_info()[1] if extraInfo: return str(extraInfo) else: return str(exception) except: exception = sys.exc_info()[0] extraInfo = sys.exc_info()[1] if extraInfo: return str(extraInfo) else: return str(exception) def cancelButtonPressed(self): self.chatEntry.set('') self.chatMgr.fsm.request('mainMenu') def chatButtonPressed(self): self.sendChat(self.chatEntry.get()) def importExecNamespace(self): pass def addToHistory(self, text): self.history = [text] + self.history[:self.historySize - 1] self.historyIndex = 0 def getPrevHistory(self): self.chatEntry.set(self.history[self.historyIndex]) self.historyIndex += 1 self.historyIndex %= len(self.history) def getNextHistory(self): self.chatEntry.set(self.history[self.historyIndex]) self.historyIndex -= 1 self.historyIndex %= len(self.history) def setPos(self, posX, posY = None, posZ = None): if posX and posY and posZ: self.chatFrame.setPos(posX, posY, posZ) else: self.chatFrame.setPos(posX)
1.398438
1
autolatex-master/exemplos_codigo/certificados/certificados.py
luizgui05/autolatex.
0
170
import os import sys import sqlite3 con = None filename = 'certificado' # Abrir banco de dados para ler nomes. try: con = sqlite3.connect('math.db') cur = con.cursor() cur.execute('select * from math') data = cur.fetchall() except sqlite3.Error, e: print "Error %s:" % e.args[0] sys.exit(1) finally: if con: con.close() # Gerar um certificado para cada nome. for row in data: f = open(filename+'.tex','r+') old = f.readlines() if old[0][1:4] == 'def': offset = 1 else: offset = 0 f.seek(0) f.write('\\def\\name {'+row[0]+'}\n') f.writelines(old[offset:]) f.close() # Compilar arquivo LaTeX try: os.system('pdflatex '+filename+'.tex') os.system('mv '+filename+'.pdf '+filename+'_'+row[0].replace(' ','_')+'.pdf') #os.system('xdg-open '+filename+'.pdf &') except OSError: print('LaTeX not installed.')
1.789063
2
splash/render_options.py
tashidexiaoL/splashnew
3,612
178
# -*- coding: utf-8 -*- import os import json from splash import defaults from splash.utils import to_bytes, path_join_secure from splash.errors import BadOption class RenderOptions(object): """ Options that control how to render a response. """ _REQUIRED = object() def __init__(self, data, max_timeout): self.data = data self.max_timeout = max_timeout @classmethod def raise_error(cls, argument, description, type='bad_argument', **kwargs): params = { 'type': type, 'argument': argument, 'description': description } params.update(kwargs) raise BadOption(params) @classmethod def fromrequest(cls, request, max_timeout): """ Initialize options from a Twisted Request. """ # 1. GET / POST data data = {key.decode('utf-8'): values[0].decode('utf-8') for key, values in request.args.items()} if request.method == b'POST': content_type = request.getHeader(b'content-type') if content_type: request.content.seek(0) # 2. application/json POST data if b'application/json' in content_type: try: content = request.content.read().decode('utf-8') data.update(json.loads(content)) except ValueError as e: raise BadOption({ 'type': 'invalid_json', 'description': "Can't decode JSON", 'message': str(e), }) # 3. js_source from application/javascript POST requests if b'application/javascript' in content_type: data['js_source'] = request.content.read().decode('utf-8') request.content.seek(0) data['uid'] = id(request) return cls(data, max_timeout) def get_expired_args(self, cache): """ Return a list of argument names from load_args which can't be loaded """ return cache.get_missing(self.get_load_args().items()) def save_args_to_cache(self, cache): """ Process save_args and put all values to cache. Return a list of (name, key) pairs. """ save_args = self.get_save_args() save_values = [self.data.get(name) for name in save_args] keys = cache.add_many(save_values) return list(zip(save_args, keys)) def load_cached_args(self, cache): load_args = self.get_load_args() for name, key in (load_args or {}).items(): self.data[name] = cache[key] def get(self, name, default=_REQUIRED, type=str, range=None): value = self.data.get(name) if value is not None: if type is not None: try: value = type(value) except ValueError: msg = "Argument %r has a wrong type" % (name,) self.raise_error(name, msg, required_type=type.__name__) if range is not None and not (range[0] <= value <= range[1]): self.raise_error(name, 'Argument is out of the allowed range', min=range[0], max=range[1], value=value) return value elif default is self._REQUIRED: self.raise_error(name, 'Required argument is missing: %s' % name, type='argument_required') else: return default def _get_bool(self, name, default=_REQUIRED): return self.get(name, default, type=int, range=(0, 1)) def _get_url(self, name, default=_REQUIRED): url = self.get(name, default, type=None) if isinstance(url, bytes): url = url.decode('utf8') return url def get_uid(self): return self.get('uid') def get_url(self): return self._get_url("url") def get_baseurl(self): return self._get_url("baseurl", default=None) def get_wait(self): return self.get("wait", defaults.WAIT_TIME, type=float, range=(0, self.get_timeout())) def get_timeout(self): default = min(self.max_timeout, defaults.TIMEOUT) return self.get("timeout", default, type=float, range=(0, self.max_timeout)) def get_resource_timeout(self): return self.get("resource_timeout", defaults.RESOURCE_TIMEOUT, type=float, range=(0, 1e6)) def get_response_body(self): return self._get_bool("response_body", defaults.RESPONSE_BODY_ENABLED) def get_request_body(self): return self._get_bool("request_body", defaults.REQUEST_BODY_ENABLED) def get_images(self): return self._get_bool("images", defaults.AUTOLOAD_IMAGES) def get_proxy(self): return self.get("proxy", default=None) def get_js_source(self): return self.get("js_source", default=None) def get_width(self): return self.get("width", None, type=int, range=(1, defaults.MAX_WIDTH)) def get_height(self): return self.get("height", None, type=int, range=(1, defaults.MAX_HEIGTH)) def get_scale_method(self): scale_method = self.get("scale_method", defaults.IMAGE_SCALE_METHOD) allowed_scale_methods = ['raster', 'vector'] if scale_method not in allowed_scale_methods: self.raise_error( argument='scale_method', description="Invalid 'scale_method': %s" % scale_method, allowed=allowed_scale_methods, received=scale_method, ) return scale_method def get_quality(self): return self.get("quality", defaults.JPEG_QUALITY, type=int, range=(0, 100)) def get_http_method(self): method = self.get("http_method", "GET") if method.upper() not in ["POST", "GET"]: self.raise_error("http_method", "Unsupported HTTP method {}".format(method)) return method def get_body(self): body = self.get("body", None, to_bytes) method = self.get("http_method", "GET").upper() if method == 'GET' and body: self.raise_error("body", "GET request should not have a body") return body def get_render_all(self, wait=None): result = self._get_bool("render_all", False) if result == 1 and wait == 0: self.raise_error("render_all", "Pass non-zero 'wait' to render full webpage") return result def get_lua_source(self): return self.get("lua_source") def get_js_profile(self, js_profiles_path): js_profile = self.get("js", default=None) if not js_profile: return js_profile if js_profiles_path is None: self.raise_error('js', 'Javascript profiles are not enabled on server') try: profile_dir = path_join_secure(js_profiles_path, js_profile) except ValueError as e: # security check fails print(e) self.raise_error('js', 'Javascript profile does not exist') if not os.path.isdir(profile_dir): self.raise_error('js', 'Javascript profile does not exist') return profile_dir def get_headers(self): headers = self.get("headers", default=None, type=None) if headers is None: return headers if not isinstance(headers, (list, tuple, dict)): self.raise_error( argument='headers', description="'headers' must be either a JSON array of " "(name, value) pairs or a JSON object" ) if isinstance(headers, (list, tuple)): for el in headers: string_only = all(isinstance(e, str) for e in el) if not (isinstance(el, (list, tuple)) and len(el) == 2 and string_only): self.raise_error( argument='headers', description="'headers' must be either a JSON array of " "(name, value) pairs or a JSON object" ) return headers def get_save_args(self): save_args = self.get("save_args", default=None, type=None) if save_args is None: return [] if isinstance(save_args, str): # comma-separated string save_args = save_args.split(',') if not isinstance(save_args, list): self.raise_error( argument="save_args", description="'save_args' should be either a comma-separated " "string or a JSON array with argument names", ) # JSON array if not all(isinstance(a, str) for a in save_args): self.raise_error( argument="save_args", description="'save_args' should be a list of strings", ) return save_args def get_load_args(self): load_args = self.get("load_args", default=None, type=None) if load_args is None: return {} if isinstance(load_args, str): try: load_args = dict( kv.split("=", 1) for kv in load_args.split(';') ) except ValueError: self.raise_error( argument="load_args", description="'load_args' string value is not a " "semicolon-separated list of name=hash pairs" ) if not isinstance(load_args, dict): self.raise_error( argument="load_args", description="'load_args' should be either a JSON object with " "argument hashes or a semicolon-separated list " "of name=hash pairs" ) return load_args def get_viewport(self, wait=None): viewport = self.get("viewport", defaults.VIEWPORT_SIZE) if viewport == 'full': if wait == 0: self.raise_error("viewport", "Pass non-zero 'wait' to render full webpage") else: try: validate_size_str(viewport) except ValueError as e: self.raise_error("viewport", str(e)) return viewport def get_filters(self, pool=None, adblock_rules=None): filter_names = self.get('filters', '') filter_names = [f for f in filter_names.split(',') if f] if pool is None and adblock_rules is None: # skip validation return filter_names if not filter_names: return filter_names if pool is not None: adblock_rules = pool.network_manager_factory.adblock_rules if adblock_rules is None: self.raise_error( "filters", "Invalid filter names: %s" % (filter_names,) ) if adblock_rules is not None: unknown_filters = adblock_rules.get_unknown_filters(filter_names) if unknown_filters: self.raise_error( "filters", "Invalid filter names: %s" % (unknown_filters,) ) return filter_names def get_allowed_domains(self): allowed_domains = self.get("allowed_domains", default=None) if allowed_domains is not None: return allowed_domains.split(',') def get_allowed_content_types(self): content_types = self.get("allowed_content_types", default=['*']) if isinstance(content_types, str): content_types = list(filter(None, content_types.split(','))) return content_types def get_forbidden_content_types(self): content_types = self.get("forbidden_content_types", default=[]) if isinstance(content_types, str): content_types = list(filter(None, content_types.split(','))) return content_types def get_html5_media(self): return self._get_bool("html5_media", defaults.HTML5_MEDIA_ENABLED) def get_engine(self, browser_engines_enabled=None): engine = self.get("engine", default="webkit", type=str) if engine not in {"webkit", "chromium"}: self.raise_error("engine", "Unknown render engine {}".format(engine)) if browser_engines_enabled is not None: if engine not in browser_engines_enabled: self.raise_error("engine", "Disabled render engine {}".format(engine)) return engine def get_http2(self): engine = self.get_engine() if self.get_engine() == "webkit": default = defaults.WEBKIT_HTTP2_ENABLED else: assert engine == 'chromium' default = defaults.CHROMIUM_HTTP2_ENABLED return self._get_bool("http2", default) def get_common_params(self, js_profiles_path): wait = self.get_wait() return { 'url': self.get_url(), 'baseurl': self.get_baseurl(), 'wait': wait, 'resource_timeout': self.get_resource_timeout(), 'viewport': self.get_viewport(wait), 'render_all': self.get_render_all(wait), 'images': self.get_images(), 'headers': self.get_headers(), 'proxy': self.get_proxy(), 'js_profile': self.get_js_profile(js_profiles_path), 'js_source': self.get_js_source(), 'http_method': self.get_http_method(), 'body': self.get_body(), 'html5_media': self.get_html5_media(), 'http2': self.get_http2(), # 'lua': self.get_lua(), } def get_image_params(self): return { 'width': self.get_width(), 'height': self.get_height(), 'scale_method': self.get_scale_method() } def get_png_params(self): return self.get_image_params() def get_jpeg_params(self): params = {'quality': self.get_quality()} params.update(self.get_image_params()) return params def get_include_params(self): return dict( html=self._get_bool("html", defaults.DO_HTML), iframes=self._get_bool("iframes", defaults.DO_IFRAMES), png=self._get_bool("png", defaults.DO_PNG), jpeg=self._get_bool("jpeg", defaults.DO_JPEG), script=self._get_bool("script", defaults.SHOW_SCRIPT), console=self._get_bool("console", defaults.SHOW_CONSOLE), history=self._get_bool("history", defaults.SHOW_HISTORY), har=self._get_bool("har", defaults.SHOW_HAR), ) def validate_size_str(size_str): """ Validate size string in WxH format. Can be used to validate both viewport and window size strings. Does not special-case ``'full'`` viewport. Raises ``ValueError`` if anything goes wrong. :param size_str: string to validate """ max_width = defaults.VIEWPORT_MAX_WIDTH max_heigth = defaults.VIEWPORT_MAX_HEIGTH max_area = defaults.VIEWPORT_MAX_AREA try: w, h = map(int, size_str.split('x')) except ValueError: raise ValueError("Invalid viewport format: %s" % size_str) else: if not ((0 < w <= max_width) and (0 < h <= max_heigth) and (w * h < max_area)): raise ValueError("Viewport (%dx%d, area=%d) is out of range (%dx%d, area=%d)" % (w, h, w * h, max_width, max_heigth, max_area))
1.703125
2
glue/__init__.py
HPLegion/glue
550
186
# Set up configuration variables __all__ = ['custom_viewer', 'qglue', 'test'] import os import sys from pkg_resources import get_distribution, DistributionNotFound try: __version__ = get_distribution('glue-core').version except DistributionNotFound: __version__ = 'undefined' from ._mpl_backend import MatplotlibBackendSetter sys.meta_path.append(MatplotlibBackendSetter()) from glue.viewers.custom.helper import custom_viewer # Load user's configuration file from .config import load_configuration env = load_configuration() from .qglue import qglue from .main import load_plugins # noqa def test(no_optional_skip=False): from pytest import main root = os.path.abspath(os.path.dirname(__file__)) args = [root, '-x'] if no_optional_skip: args.append('--no-optional-skip') return main(args=args) from glue._settings_helpers import load_settings load_settings() # In PyQt 5.5+, PyQt overrides the default exception catching and fatally # crashes the Qt application without printing out any details about the error. # Below we revert the exception hook to the original Python one. Note that we # can't just do sys.excepthook = sys.__excepthook__ otherwise PyQt will detect # the default excepthook is in place and override it. def handle_exception(exc_type, exc_value, exc_traceback): sys.__excepthook__(exc_type, exc_value, exc_traceback) sys.excepthook = handle_exception
1.46875
1
settings.py
Cradac/mattermost-octane-integration
0
194
''' This is the Settings File for the Mattermost-Octane Bridge. You can change various variables here to customize and set up the client. ''' '''----------------------Mattermost Webhook Configuration----------------------''' #URL of the webhook from mattermost. To create one go to `Main Menu -> Integrations -> Incoming Webhooks` and press `Add Incoming Webhook` mm_webhook_url = 'http://localhost:8065/hooks/yuro8xrfeffj787cj1bwc4ziue' #Override the channel to send the notifications to, use the channel name as a String mm_channel = None #Set a custom Username to display in Mattermost mm_username = 'Defect Notification' #Set a custom Profile Image for the Client mm_profileimage = 'https://i.imgur.com/7Wg3Tgs.png' #Telekom T Image #The latter two need to be enabled in the settings.json of the Mattermost server '''----------------------------Flask Configuration----------------------------''' #set external IP for the Flask Server to create a Webhook for ALM Octane #local: 127.0.0.1 / False #default external: 0.0.0.0 (will default to only available external adress) external_ip = False #default: 5000 port = 5000 #external webhook verify token can be set here, if set as `None` it will be autogenerated & changed on each startup. wh_token = None
1.515625
2
source/conf.py
Tatsh/upkeep
3
202
# SPDX-License-Identifier: MIT # pylint: disable=redefined-builtin,invalid-name """See https://www.sphinx-doc.org/en/master/usage/configuration.html""" from typing import Sequence import os import sys # region Path setup sys.path.insert(0, os.path.abspath('..')) # endregion # region Project information project = 'Upkeep' copyright = '2020, <NAME>' author = '<NAME>' # The short X.Y version version = '1.2.7' # The full version, including alpha/beta/rc tags release = f'v{version}' # endregion # region General configuration # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns: Sequence[str] = [] master_doc = 'index' # endregion # region Options for HTML output # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'alabaster' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # endregion # region Extension configuration # endregion
1.273438
1
subject/tests/functional/test_glance_replicator.py
laoyigrace/subject
0
210
# 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. """Functional test cases for subject-replicator""" import sys from subject.tests import functional from subject.tests.utils import execute class TestGlanceReplicator(functional.FunctionalTest): """Functional tests for subject-replicator""" def test_compare(self): # Test for issue: https://bugs.launchpad.net/glance/+bug/1598928 cmd = ('%s -m subject.cmd.replicator ' 'compare az1:9292 az2:9292 --debug' % (sys.executable,)) exitcode, out, err = execute(cmd, raise_error=False) self.assertIn( 'Request: GET http://az1:9292/v1/subjects/detail?is_public=None', err )
1.320313
1
tests/test_i18n.py
vthriller/flask-kajiki
0
218
from kajiki import i18n from flask import request from flask_kajiki import render_template # N. B. settting i18n.gettext would affect tests from all modules, # so we test for request path that only functions from this module could set def gettext(s): if request.path == '/test_i18n': return s.upper() return s i18n.gettext = gettext def test_does_translations(app): """Callback interface is able to inject Translator filter""" with app.test_request_context(path='/test_i18n'): rendered = render_template('i18n.html') # TODO DOCTYPE; see also render_args expected = '<p>HELLO!</p>' assert rendered == expected
1.554688
2
unwind.py
0x1F9F1/binja-msvc
9
226
from binaryninja import log from .utils import BinjaStruct, read_pe_header, split_bits, update_percentage # https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx RUNTIME_FUNCTION_t = BinjaStruct('<III', names = ('BeginAddress', 'EndAddress', 'UnwindData')) def read_runtime_function(view, address): runtime_function, address = RUNTIME_FUNCTION_t.read(view, address, 4) if runtime_function is not None: runtime_function['BeginAddress'] += view.start runtime_function['EndAddress'] += view.start runtime_function['UnwindData'] += view.start return runtime_function, address UNWIND_INFO_t = BinjaStruct('<BBBB', names = ('VersionAndFlags', 'SizeOfProlog', 'CountOfCodes', 'FrameRegisterAndOffset')) UNW_FLAG_NHANDLER = 0x0 UNW_FLAG_EHANDLER = 0x1 UNW_FLAG_UHANDLER = 0x2 UNW_FLAG_FHANDLER = 0x3 UNW_FLAG_CHAININFO = 0x4 def read_unwind_info(view, address): unwind_info, address = UNWIND_INFO_t.read(view, address) if unwind_info is not None: split_bits(unwind_info, 'VersionAndFlags', [ ('Version', 0, 3), ('Flags', 3, 5) ]) split_bits(unwind_info, 'FrameRegisterAndOffset', [ ('FrameRegister', 0, 4), ('FrameOffset', 4, 4) ]) if unwind_info['Version'] == 1: unwind_codes = [ ] for i in range(unwind_info['CountOfCodes']): unwind_code, address = read_unwind_code(view, address) unwind_codes.append(unwind_code) unwind_info['UnwindCodes'] = unwind_codes if unwind_info['Flags'] & UNW_FLAG_CHAININFO: unwind_info['FunctionEntry'], address = read_runtime_function(view, address) return unwind_info, address UNWIND_CODE_t = BinjaStruct('<BB', names = ('CodeOffset', 'UnwindOpAndInfo')) def read_unwind_code(view, address): unwind_code, address = UNWIND_CODE_t.read(view, address) if unwind_code is not None: split_bits(unwind_code, 'UnwindOpAndInfo', [ ('UnwindOp', 0, 4), ('OpInfo', 4, 4) ]) return unwind_code, address def parse_unwind_info(thread, view): base_address = view.start pe = read_pe_header(view) unwind_directory = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] unwind_entrys = base_address + unwind_directory.VirtualAddress unwind_entrys_end = unwind_entrys + unwind_directory.Size funcs = set() log.log_info('Exception Data @ 0x{0:X} => 0x{1:X}'.format(unwind_entrys, unwind_entrys_end)) for runtime_address in range(unwind_entrys, unwind_entrys_end, 12): if thread.cancelled: break update_percentage(thread, unwind_entrys, unwind_entrys_end, runtime_address, 'Parsing Unwind Info - Found {0} functions'.format(len(funcs))) runtime_function, _ = read_runtime_function(view, runtime_address) if runtime_function is None: continue start_address = runtime_function['BeginAddress'] if not view.is_offset_executable(start_address): continue if view.get_functions_containing(start_address): continue info_address = runtime_function['UnwindData'] unwind_info, _ = read_unwind_info(view, info_address) if unwind_info is None: continue if 'FunctionEntry' in unwind_info: continue funcs.add(start_address) if not thread.cancelled: thread.progress = 'Creating {0} Function'.format(len(funcs)) log.log_info('Found {0} functions'.format(len(funcs))) for func in funcs: view.create_user_function(func)
1.265625
1
Chest X-Ray Multilabel Image classification using CNN - Pytorch/Arch2.py
farzanaaswin0708/CNN-for-Visual-recognition
0
234
#!/usr/bin/env python # coding: utf-8 # In[ ]: ################################################################################ # CSE 253: Programming Assignment 3 # Winter 2019 # Code author: <NAME> (+ modifications by <NAME>) # # Filename: baseline_cnn.py # # Description: # # This file contains the starter code for the baseline architecture you will use # to get a little practice with PyTorch and compare the results of with your # improved architecture. # # Be sure to fill in the code in the areas marked #TODO. ################################################################################ # PyTorch and neural network imports import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as func import torch.nn.init as torch_init import torch.optim as optim # Data utils and dataloader import torchvision from torchvision import transforms, utils from xray_dataloader_zscored import ChestXrayDataset, create_split_loaders import matplotlib.pyplot as plt import numpy as np import os class Arch2CNN(nn.Module): """ <<<<<<< HEAD conv1 -> maxpool -> conv2 -> maxpool -> conv3 -> conv4 ->maxpool -> conv5 -> conv6 -> maxpool -> conv7 -> conv8 -> maxpool -> fc1 -> fc2 -> fc3 (outputs) ======= conv1 -> conv2 -> maxpool -> conv3 -> conv4 -> conv5 -> maxpool -> fc1 -> fc2 -> fc3 (outputs) >>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 """ def __init__(self): super(Arch2CNN, self).__init__() # conv1: 1 input channel, 4 output channels, [3x3] kernel size self.conv1 = nn.Conv2d(in_channels=1, out_channels=4, kernel_size=3) # Add batch-normalization to the outputs of conv1 self.conv1_normed = nn.BatchNorm2d(4) # Initialized weights using the Xavier-Normal method torch_init.xavier_normal_(self.conv1.weight) self.pool1 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Fill in the remaining initializations replacing each '_' with # the necessary value based on the provided specs for each layer #TODO: conv2: 4 input channels, 8 output channels, [3x3] kernel, initialization: xavier self.conv2 = nn.Conv2d(in_channels=4, out_channels=8, kernel_size=3) self.conv2_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv2.weight) #Maxpool self.pool2 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv3: X input channels, 12 output channels, [8x8] kernel, initialization: xavier self.conv3 = nn.Conv2d(in_channels=8, out_channels=16, kernel_size=3) self.conv3_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv3.weight) #TODO: conv4: X input channels, 10 output channels, [6x6] kernel, initialization: xavier self.conv4 = nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3) self.conv4_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv4.weight) self.pool3 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv5: X input channels, 8 output channels, [5x5] kernel, initialization: xavier self.conv5 = nn.Conv2d(in_channels=16, out_channels=8, kernel_size=3) self.conv5_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv5.weight) self.conv6 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv6_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv6.weight) self.pool4 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Apply max-pooling with a [3x3] kernel using tiling (*NO SLIDING WINDOW*) self.conv7 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv7_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv7.weight) self.conv8 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv8_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv8.weight) self.pool5 = nn.MaxPool2d(kernel_size=4, stride=4) # Define 2 fully connected layers: #TODO: fc1 self.fc1 = nn.Linear(in_features=122*122*8, out_features=512) self.fc1_normed = nn.BatchNorm1d(512) torch_init.xavier_normal_(self.fc1.weight) #TODO: fc2 self.fc2 = nn.Linear(in_features=512, out_features=128) self.fc2_normed = nn.BatchNorm1d(128) torch_init.xavier_normal_(self.fc2.weight) #TODO: fc3 self.fc3 = nn.Linear(in_features=128, out_features=14) torch_init.xavier_normal_(self.fc3.weight) #TODO: Output layer: what should out_features be? self.out_features = 14 def forward(self, batch): """Pass the batch of images through each layer of the network, applying non-linearities after each layer. Note that this function *needs* to be called "forward" for PyTorch to automagically perform the forward pass. Params: ------- - batch: (Tensor) An input batch of images Returns: -------- - logits: (Variable) The output of the network """ # Apply first convolution, followed by ReLU non-linearity; # use batch-normalization on its outputs batch = func.rrelu(self.conv1_normed(self.conv1(batch))) batch = self.pool1(batch) # Apply conv2 and conv3 similarly batch = func.rrelu(self.conv2_normed(self.conv2(batch))) batch = self.pool2(batch) batch = func.rrelu(self.conv3_normed(self.conv3(batch))) batch = func.rrelu(self.conv4_normed(self.conv4(batch))) batch = self.pool3(batch) batch = func.rrelu(self.conv5_normed(self.conv5(batch))) batch = func.rrelu(self.conv6_normed(self.conv6(batch))) # Pass the output of conv3 to the pooling layer batch = self.pool4(batch) batch = func.rrelu(self.conv7_normed(self.conv7(batch))) batch = func.rrelu(self.conv8_normed(self.conv8(batch))) # Pass the output of conv3 to the pooling layer batch = self.pool5(batch) # Reshape the output of the conv3 to pass to fully-connected layer batch = batch.view(-1, self.num_flat_features(batch)) # Connect the reshaped features of the pooled conv3 to fc1 batch = func.rrelu(self.fc1_normed(self.fc1(batch))) batch = func.rrelu(self.fc2_normed(self.fc2(batch))) # Connect fc1 to fc2 - this layer is slightly different than the rest (why?) batch = self.fc3(batch) # Return the class predictions #TODO: apply an activition function to 'batch' #batch = func.sigmoid(batch) return batch def num_flat_features(self, inputs): # Get the dimensions of the layers excluding the inputs size = inputs.size()[1:] # Track the number of features num_features = 1 for s in size: num_features *= s return num_features
2.4375
2
scraping/faqscraper.py
ednihs-yahska/unibrowser
0
242
import re import httplib2 from bs4 import BeautifulSoup from scraping.faqscrapperutil import stripExtra, removeDuplicates, removeBlackListedQuestions, getBlackListedQuestions, convertToJsonList, saveToMongo from scraping.Constants import ENABLE_CUSTOM_QUESTIONS_FILTER, FAQ_LINKS, COLLECTION_NAME def cleanQuestions(questions): questionList = [] for question in questions: questionList.append(stripExtra(question.lstrip().rstrip())) return removeDuplicates(questionList) def getLastAnswer(question, bodyText): start = bodyText.index(question) + len(question) text = bodyText[start : -1].lstrip() # print(text.lstrip()) whitespaceCount = 0 # print(answerLength) for i in range(0, len(text)): # print(answer[i], ' isSpace : ', answer[i].isspace()) if text[i].isspace(): whitespaceCount = whitespaceCount + 1 if whitespaceCount >= 3: # print(0 + i - 3) # print(text[0 : 0 + i - 2]) return text[0 : 0 + i - 2] else : if whitespaceCount != 0: whitespaceCount = 0 def cleanAnswer(answer): answerLength = len(answer) whitespaceCount = 0 # print(answerLength) for i in range(0, answerLength): # print(answer[i], ' isSpace : ', answer[i].isspace()) if answer[i].isspace(): whitespaceCount = whitespaceCount + 1 if whitespaceCount >= 3: # print(0 + i - 3) return answer[0 : 0 + i - 2].lstrip() else : if whitespaceCount != 0: whitespaceCount = 0 return answer.rstrip() def getAnswers(body, questions): bodyText = body.getText() # answerTag = getAnswerTag(body, bodyText, questions) # print(bodyText) questionCount = len(questions) answerList = [] for i in range(0, questionCount): print('Q: ', questions[i]) if i == questionCount - 1: #Last element answer = getLastAnswer(questions[i], bodyText) else : start = bodyText.index(questions[i]) + len(questions[i]) end = bodyText.index(questions[i + 1], start, -1) print("Start : ", start , " End : ", end) soup1 = BeautifulSoup(bodyText[start : end], 'html.parser') # print(soup1) answer = soup1.getText().lstrip() answer = cleanAnswer(answer) answerList.append(answer) print('A: ', answer) return answerList def processWithCustomQuestions(questions): # isCustomQuestionsEnabled = checkConfigForFlag(ENABLE_CUSTOM_QUESTIONS_FILTER) # print("isCustomQuestionsEnabled : ", isCustomQuestionsEnabled) if ENABLE_CUSTOM_QUESTIONS_FILTER == False: return blackListedQuestions = getBlackListedQuestions() removeBlackListedQuestions(questions, blackListedQuestions) print(questions) def getFaqOfLink(link): # print("LINK : ", link) http = httplib2.Http() status, html = http.request(link) soup = BeautifulSoup(html, 'html.parser') body = soup.body questions = cleanQuestions(soup(text=re.compile(r'\s*((?:how|How|Can|can|what|What|where|Where|describe|Describe|Who|who|When|when|Why|why|Should|should|is|Is|I|Do|do|Are|are|Will|will)[^.<>?]*?\s*\?)'))) # print(questions) processWithCustomQuestions(questions) answerList = getAnswers(body, questions) return questions, answerList # link = "https://transportation.oregonstate.edu/aabc/frequently-asked-questions" # questions, answerList = getFaqOfLink(link) if __name__== "__main__": with open(FAQ_LINKS, 'r') as myfile: FAQ_LINKS = myfile.read().split('\n') faqJsonList = [] for i in range(0, len(FAQ_LINKS)): link = FAQ_LINKS[i] questions, answerList = getFaqOfLink(link) jsonList = convertToJsonList(link, questions, answerList) faqJsonList.extend(jsonList) # saveJsonToFile(faqJsonList, "output.txt") saveToMongo(faqJsonList, COLLECTION_NAME)
2.015625
2
src/pyrqlite/connections.py
zmedico/pyrqlite
2
250
from __future__ import unicode_literals import codecs import logging try: from http.client import HTTPConnection, HTTPSConnection except ImportError: # pylint: disable=import-error from httplib import HTTPConnection, HTTPSConnection try: from urllib.parse import urlparse except ImportError: # pylint: disable=import-error from urlparse import urlparse from .constants import ( UNLIMITED_REDIRECTS, ) from .cursors import Cursor from ._ephemeral import EphemeralRqlited as _EphemeralRqlited from .extensions import PARSE_DECLTYPES, PARSE_COLNAMES class Connection(object): from .exceptions import ( Warning, Error, InterfaceError, DatabaseError, DataError, OperationalError, IntegrityError, InternalError, ProgrammingError, NotSupportedError, ) def __init__(self, scheme='http', host='localhost', port=4001, user=None, password=<PASSWORD>, connect_timeout=None, detect_types=0, max_redirects=UNLIMITED_REDIRECTS): self.messages = [] self.scheme = scheme self.host = host self.port = port self._headers = {} if not (user is None or password is None): self._headers['Authorization'] = 'Basic ' + \ codecs.encode('{}:{}'.format(user, password).encode('utf-8'), 'base64').decode('utf-8').rstrip('\n') self.connect_timeout = connect_timeout self.max_redirects = max_redirects self.detect_types = detect_types self.parse_decltypes = detect_types & PARSE_DECLTYPES self.parse_colnames = detect_types & PARSE_COLNAMES self._ephemeral = None if scheme == ':memory:': self._ephemeral = _EphemeralRqlited().__enter__() self.host, self.port = self._ephemeral.http self._connection = self._init_connection() def _init_connection(self): if self.scheme in ('http', ':memory:'): cls = HTTPConnection elif self.scheme == 'https': cls = HTTPSConnection else: raise Connection.ProgrammingError('Unsupported scheme %r' % self.scheme) return cls(self.host, port=self.port, timeout=None if self.connect_timeout is None else float(self.connect_timeout)) def _retry_request(self, method, uri, body=None, headers={}): tries = 10 while tries: tries -= 1 try: self._connection.request(method, uri, body=body, headers=dict(self._headers, **headers)) return self._connection.getresponse() except Exception: if not tries: raise self._connection.close() self._connection = self._init_connection() def _fetch_response(self, method, uri, body=None, headers={}): """ Fetch a response, handling redirection. """ response = self._retry_request(method, uri, body=body, headers=headers) redirects = 0 while response.status == 301 and \ response.getheader('Location') is not None and \ (self.max_redirects == UNLIMITED_REDIRECTS or redirects < self.max_redirects): redirects += 1 uri = response.getheader('Location') location = urlparse(uri) logging.getLogger(__name__).debug("status: %s reason: '%s' location: '%s'", response.status, response.reason, uri) if self.host != location.hostname or self.port != location.port: self._connection.close() self.host = location.hostname self.port = location.port self._connection = self._init_connection() response = self._retry_request(method, uri, body=body, headers=headers) return response def close(self): """Close the connection now (rather than whenever .__del__() is called). The connection will be unusable from this point forward; an Error (or subclass) exception will be raised if any operation is attempted with the connection. The same applies to all cursor objects trying to use the connection. Note that closing a connection without committing the changes first will cause an implicit rollback to be performed.""" self._connection.close() if self._ephemeral is not None: self._ephemeral.__exit__(None, None, None) self._ephemeral = None def __del__(self): self.close() def commit(self): """Database modules that do not support transactions should implement this method with void functionality.""" pass def rollback(self): """This method is optional since not all databases provide transaction support. """ pass def cursor(self, factory=None): """Return a new Cursor Object using the connection.""" if factory: return factory(self) else: return Cursor(self) def execute(self, *args, **kwargs): return self.cursor().execute(*args, **kwargs)
1.484375
1
dataset_specifications/swirls.py
joeloskarsson/CGAN-regression
12
258
import numpy as np import math from dataset_specifications.dataset import Dataset class SwirlsSet(Dataset): def __init__(self): super().__init__() self.name = "swirls" self.n_samples = { "train": 2000, "val": 1000, "test": 1000, } self.y_dim = 2 # 2D heteroskedastic Gaussian mixture model with 2 components def sample_ys(self, xs): n = xs.shape[0] components = np.random.randint(2, size=n) # uniform 0,1 angles = math.pi*components + (math.pi/2.)*xs[:,0] # Angles to centers means = np.stack((np.cos(angles), np.sin(angles)), axis=1) noise = np.random.randn(n, 2) # samples form 2d gaussian std = 0.3 - 0.2*np.abs(xs-1.) ys = means + std*noise return ys def sample(self, n): xs = np.random.uniform(low=0., high=2., size=(n,1)) ys = self.sample_ys(xs) return np.concatenate((xs, ys), axis=1)
2.1875
2
ceilometer/data_processing/notifications.py
vmturbo/ceilometer
0
266
# Copyright (c) 2014 Mirantis Inc. # # 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. from oslo.config import cfg import oslo.messaging from ceilometer import plugin from ceilometer import sample OPTS = [ cfg.StrOpt('sahara_control_exchange', default='sahara', help="Exchange name for Data Processing notifications."), ] cfg.CONF.register_opts(OPTS) SERVICE = 'sahara' class DataProcessing(plugin.NotificationBase): resource_name = '%s.cluster' % SERVICE @property def event_types(self): return [ '%s.create' % self.resource_name, '%s.update' % self.resource_name, '%s.delete' % self.resource_name, ] @staticmethod def get_targets(conf): """Return a sequence of oslo.messaging.Target It is defining the exchange and topics to be connected for this plugin. """ return [oslo.messaging.Target(topic=topic, exchange=conf.sahara_control_exchange) for topic in conf.notification_topics] def process_notification(self, message): name = message['event_type'].replace(self.resource_name, 'cluster') project_id = message['payload']['project_id'] user_id = message['_context_user_id'] yield sample.Sample.from_notification( name=name, type=sample.TYPE_DELTA, unit='cluster', volume=1, resource_id=message['payload']['cluster_id'], user_id=user_id, project_id=project_id, message=message)
1.429688
1
TWLight/applications/management/commands/send_coordinator_reminders.py
nicole331/TWLight
67
274
import logging from collections import Counter from django.core.management.base import BaseCommand from django.db.models import Q from TWLight.applications.models import Application from TWLight.resources.models import Partner from TWLight.applications.signals import Reminder from TWLight.users.models import Editor logger = logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args, **options): # This is not DRY. Originally, this pulled the queryset from # TWLight.applications.views.ListApplicationsView.get_queryset(). # But that now expects a request object. So, we did a copy/paste. # We're actually getting apps with a status of PENDING or QUESTION # or APPROVED, and their corresponding user preferences being True # for partners with a status of AVAILABLE. all_apps = ( Application.objects.filter( Q( partner__coordinator__editor__user__userprofile__pending_app_reminders=True ) & Q(status=Application.PENDING) | Q( partner__coordinator__editor__user__userprofile__discussion_app_reminders=True ) & Q(status=Application.QUESTION) | Q( partner__coordinator__editor__user__userprofile__approved_app_reminders=True ) & Q(status=Application.APPROVED), partner__status__in=[Partner.AVAILABLE], editor__isnull=False, ) .exclude(editor__user__groups__name="restricted") .order_by("status", "partner", "date_created") ) # A deduplicated dict of coordinators from the pending app queryset, along # with a count of how many total pending apps they have coordinators = Counter( all_apps.values_list( "partner__coordinator__editor", "partner__coordinator__email", "partner__coordinator__editor__user__userprofile__lang", ) ) for coordinator, count in list(coordinators.items()): try: # We create a dictionary with the three status codes # we'd want to send emails for, and their corresponding # counts. app_status_and_count = { Application.PENDING: all_apps.filter( status=Application.PENDING, partner__coordinator__editor=coordinator[0], ).count(), Application.QUESTION: all_apps.filter( status=Application.QUESTION, partner__coordinator__editor=coordinator[0], ).count(), Application.APPROVED: all_apps.filter( status=Application.APPROVED, partner__coordinator__editor=coordinator[0], ).count(), } editor = Editor.objects.get(id=coordinator[0]) except Editor.DoesNotExist: logger.info( "Editor {} does not exist; skipping.".format(coordinator[0]) ) break # Only bother with the signal if we have a coordinator email. if coordinator[1]: Reminder.coordinator_reminder.send( sender=self.__class__, app_status_and_count=app_status_and_count, coordinator_wp_username=editor.wp_username, coordinator_email=coordinator[1], coordinator_lang=coordinator[2], )
1.429688
1
survey/api/matrix.py
djaodjin/djaodjin-survey
15
282
# 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. import logging, re from collections import OrderedDict from django.db.models import F from django.http import Http404 from django.shortcuts import get_object_or_404 from extra_views.contrib.mixins import SearchableListMixin from rest_framework import generics from rest_framework.pagination import PageNumberPagination from rest_framework import response as http from ..compat import reverse from ..mixins import MatrixMixin from ..models import Answer, Matrix, EditableFilter from ..utils import (get_account_model, get_account_serializer, get_question_serializer) from .serializers import EditableFilterSerializer, MatrixSerializer LOGGER = logging.getLogger(__name__) class MatrixCreateAPIView(generics.ListCreateAPIView): """ Filtered list of ``Question``. **Examples**: .. code-block:: http GET /api/matrix/ Response: { "slug": "all", "title": "All accounts against all questions", "metric": { "slug": "all-questions", "title": "All questions", "predicates": [] }, "cohorts": [{ "slug": "all-accounts", "title": "All accounts", "predicates": [] }] } .. code-block:: http POST /api/matrix/ { "slug": "all", "title": "All accounts against all questions", "metric": { "slug": "all-questions", "title": "All questions", "predicates": [] }, "cohorts": [{ "slug": "all-accounts", "title": "All accounts", "predicates": [] }] } Response: 201 CREATED { "slug": "all", "title": "All accounts against all questions", "metric": { "slug": "all-questions", "title": "All questions", "predicates": [] }, "cohorts": [{ "slug": "all-accounts", "title": "All accounts", "predicates": [] }] } """ serializer_class = MatrixSerializer def get_queryset(self): return Matrix.objects.all() class MatrixDetailAPIView(MatrixMixin, generics.RetrieveUpdateDestroyAPIView): """ A table of scores for cohorts aganist a metric. **Examples**: .. code-block:: http GET /api/matrix/languages Response: [{ "slug": "languages", "title": "All cohorts for all questions" "scores":{ "portfolio-a": "0.1", "portfolio-b": "0.5", } }] """ serializer_class = MatrixSerializer lookup_field = 'slug' lookup_url_kwarg = 'path' question_model = get_question_serializer().Meta.model def aggregate_scores(self, metric, cohorts, cut=None, accounts=None): #pylint:disable=unused-argument,too-many-locals if accounts is None: accounts = get_account_model().objects.all() scores = {} if metric: assert 'metric' in metric.tags, \ "filter '%s' is not tagged as a metric" % str(metric) includes, excludes = metric.as_kwargs() questions = self.question_model.objects.filter( **includes).exclude(**excludes) nb_questions = len(questions) if nb_questions > 0: for cohort in cohorts: if isinstance(cohort, EditableFilter): includes, excludes = cohort.as_kwargs() qs_accounts = accounts.filter( **includes).exclude(**excludes) else: # If `matrix.cohorts is None`, the `cohorts` argument # will be a list of single account objects. qs_accounts = [cohort] nb_accounts = len(qs_accounts) if nb_accounts > 0: nb_correct_answers = Answer.objects.filter( question__in=questions, sample__account__in=qs_accounts).filter( measured=F('question__correct_answer')).count() score = nb_correct_answers * 100 / ( nb_questions * nb_accounts) LOGGER.debug("score for '%s' = (%d * 100) "\ "/ (%d * %d) = %f", str(cohort), nb_correct_answers, nb_questions, nb_accounts, score) assert score <= 100 scores.update({str(cohort): score}) return {"scores": scores} @property def matrix(self): if not hasattr(self, '_matrix'): self._matrix = Matrix.objects.filter( slug=self.kwargs.get(self.matrix_url_kwarg)).first() return self._matrix def get_accounts(self): #pylint:disable=unused-argument,no-self-use return get_account_model().objects.all() def get_likely_metric(self, cohort_slug): """ Returns a URL to a ``Matrix`` derived from *cohort*. Many times people will use the same name to either mean a cohort or a metric and expect the system will magically switch between both meaning. This is an attempt at magic. """ likely_metric = None look = re.match(r"(\S+)(-\d+)", cohort_slug) if look: try: likely_metric = self.request.build_absolute_uri( reverse('matrix_chart', args=( EditableFilter.objects.get(slug=look.group(1)).slug,))) except EditableFilter.DoesNotExist: pass return likely_metric def get(self, request, *args, **kwargs): #pylint:disable=unused-argument,too-many-locals matrix = self.matrix if matrix: metric = self.matrix.metric else: parts = self.kwargs.get(self.matrix_url_kwarg).split('/') metric = get_object_or_404(EditableFilter, slug=parts[-1]) matrix = Matrix.objects.filter(slug=parts[0]).first() if not matrix: raise Http404() cohort_serializer = EditableFilterSerializer cohorts = matrix.cohorts.exclude(tags__contains='aggregate') public_cohorts = matrix.cohorts.filter(tags__contains='aggregate') cut = matrix.cut if not cohorts: # We don't have any cohorts, let's show individual accounts instead. if cut: includes, excludes = cut.as_kwargs() accounts = self.get_accounts().filter( **includes).exclude(**excludes) else: accounts = self.get_accounts() cohort_serializer = get_account_serializer() # Implementation Note: switch cohorts from an queryset # of `EditableFilter` to a queryset of `Account` ... cohorts = accounts result = [] scores = {} val = { 'slug': metric.slug, 'title': metric.title, 'metric': EditableFilterSerializer().to_representation(metric), 'cut': EditableFilterSerializer().to_representation(cut), 'cohorts': cohort_serializer(many=True).to_representation(cohorts)} # In some case, a metric and cohort have a connection # and could have the same name. for cohort in val['cohorts']: likely_metric = self.get_likely_metric(cohort['slug']) if likely_metric: cohort['likely_metric'] = likely_metric scores.update(val) scores.update({"values": self.aggregate_scores( metric, cohorts, cut, accounts=self.get_accounts())}) result += [scores] if public_cohorts: public_scores = {} public_scores.update(val) public_scores.update( {"cohorts": EditableFilterSerializer( public_cohorts, many=True).data, "values": self.aggregate_scores(metric, public_cohorts)}) result += [public_scores] return http.Response(result) class EditableFilterQuerysetMixin(object): @staticmethod def get_queryset(): return EditableFilter.objects.all() class EditableFilterListAPIView(SearchableListMixin, EditableFilterQuerysetMixin, generics.ListCreateAPIView): """ List fitlers **Tags**: survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json { "count": 2, previous: null, next: null, results: [ { "slug": "all", "title": "All", "tags": "", "predicates": [ "rank": 1, "operator": "", "operand": "", "field": "", "selector": "" ], "likely_metric": "" }, { "slug": "none", "title": "None", "tags": "", "predicates": [ "rank": 1, "operator": "", "operand": "", "field": "", "selector": "" ], "likely_metric": "" } ] } """ search_fields = ['tags'] serializer_class = EditableFilterSerializer def post(self, request, *args, **kwargs): """ Create a fitler **Tags**: survey **Examples** .. code-block:: http POST /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json { "count": 2, previous: null, next: null, results: [ { "slug": "all", "title": "All", "tags": "", "predicates": [ "rank": 1, "operator": "", "operand": "", "field": "", "selector": "" ], "likely_metric": "" }, { "slug": "none", "title": "None", "tags": "", "predicates": [ "rank": 1, "operator": "", "operand": "", "field": "", "selector": "" ], "likely_metric": "" } ] } """ #pylint:disable=useless-super-delegation return super(EditableFilterListAPIView, self).post( request, *args, **kwargs) class EditableFilterDetailAPIView(generics.RetrieveUpdateDestroyAPIView): """ Retrieve a fitler **Tags**: survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/all/ HTTP/1.1 responds .. code-block:: json { "slug": "all", "title": "All", "tags": "", "predicates": [ "rank": 1, "operator": "", "operand": "", "field": "", "selector": "" ], "likely_metric": "" } """ serializer_class = EditableFilterSerializer lookup_field = 'slug' lookup_url_kwarg = 'editable_filter' def get_queryset(self): return EditableFilter.objects.all() def put(self, request, *args, **kwargs): """ Updates a fitler **Tags**: survey **Examples** .. code-block:: http PUT /api/xia/matrix/filters/all/ HTTP/1.1 .. code-block:: json { "slug": "all", "title": "All", "tags": "", "predicates": [ "rank": 1, "operator": "", "operand": "", "field": "", "selector": "" ], "likely_metric": "" } responds .. code-block:: json { "slug": "all", "title": "All", "tags": "", "predicates": [ "rank": 1, "operator": "", "operand": "", "field": "", "selector": "" ], "likely_metric": "" } """ #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).put( request, *args, **kwargs) def delete(self, request, *args, **kwargs): """ Deletes a fitler **Tags**: survey **Examples** .. code-block:: http DELETE /api/xia/matrix/filters/all/ HTTP/1.1 """ #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).delete( request, *args, **kwargs) class EditableFilterPagination(PageNumberPagination): def paginate_queryset(self, queryset, request, view=None): self.editable_filter = view.editable_filter return super(EditableFilterPagination, self).paginate_queryset( queryset, request, view=view) def get_paginated_response(self, data): return http.Response(OrderedDict([ ('editable_filter', EditableFilterSerializer().to_representation( self.editable_filter)), ('count', self.page.paginator.count), ('next', self.get_next_link()), ('previous', self.get_previous_link()), ('results', data) ])) class EditableFilterObjectsAPIView(generics.ListAPIView): """ List filter objects **Tags**: survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json { "created_at": "2020-01-01T00:00:00Z", "measured": 12 } """ pagination_class = EditableFilterPagination serializer_class = None # override in subclasses lookup_field = 'slug' lookup_url_kwarg = 'editable_filter' def get_queryset(self): return self.get_serializer_class().Meta.model.objects.all() def get(self, request, *args, **kwargs): #pylint: disable=unused-argument self.editable_filter = generics.get_object_or_404( EditableFilter.objects.all(), slug=self.kwargs[self.lookup_url_kwarg]) return super(EditableFilterObjectsAPIView, self).get( request, *args, **kwargs) class AccountListAPIView(EditableFilterObjectsAPIView): """ Filtered list of ``EditableFilter``. **Examples**: .. code-block:: http GET /api/questions/languages Response: { "slug": "languages", "title": "All questions related to languages" "predicates":[{ "operator": "contains", "operand": "language", "field": "text", "selector":"keepmatching" }] } """ serializer_class = get_account_serializer() class QuestionListAPIView(EditableFilterObjectsAPIView): """ Filtered list of ``Question``. **Examples**: .. code-block:: http GET /api/questions/languages Response: { "slug": "languages", "title": "All questions related to languages" "predicates":[{ "operator": "contains", "operand": "language", "field": "text", "selector":"keepmatching" }] } """ serializer_class = get_question_serializer()
1.375
1
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
4,611
Edit dataset card