content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
from Pages import * app = App() app.mainloop()
[ 6738, 28221, 1330, 1635, 198, 198, 1324, 796, 2034, 3419, 198, 1324, 13, 12417, 26268, 3419, 198 ]
2.823529
17
import flask from cauldron.cli.server import run as server_runner from cauldron.ui import arguments from cauldron.ui import statuses
[ 11748, 42903, 198, 198, 6738, 269, 45637, 13, 44506, 13, 15388, 1330, 1057, 355, 4382, 62, 16737, 198, 6738, 269, 45637, 13, 9019, 1330, 7159, 198, 6738, 269, 45637, 13, 9019, 1330, 1185, 2664, 628 ]
3.857143
35
import requests from bs4 import BeautifulSoup import re rq = requests.get("https://play.google.com/store/apps/category/GAME_MUSIC?hl=ko") rqctnt = rq.content soup = BeautifulSoup(rqctnt,"html.parser") soup = soup.find_all(attrs={'class':'title'}) blacklsit = ["","/TV","","","","",""] for link in soup: if link.text.strip() in blacklsit: pass else: print(link.text.strip())
[ 11748, 7007, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 11748, 302, 198, 198, 81, 80, 796, 7007, 13, 1136, 7203, 5450, 1378, 1759, 13, 13297, 13, 785, 14, 8095, 14, 18211, 14, 22872, 14, 47109, 62, 44, 2937, 2149, 30, 18...
2.430303
165
from unittest import TestCase from pyramid import testing
[ 6738, 555, 715, 395, 1330, 6208, 20448, 198, 198, 6738, 27944, 1330, 4856, 628, 198 ]
4.066667
15
#Negative Indexes spam = ['cat', 'bat', 'rat', 'elephant'] spam[-1] # elepant spam[-3] # bat # Getting a List from another List with Slices spam = ['cat', 'bat', 'rat', 'elephant'] spam[0:4] # ['cat', 'bat', 'rat', 'elephant'] spam[1:3] # ['bat', 'rat'] spam[0:-1] # ['cat', 'bat', 'rat'] spam[:2] # ['cat', 'bat'] spam[1:] # ['bat', 'rat', 'elephant'] spam[:] # ['cat', 'bat', 'rat', 'elephant'] # Getting a List's length with the len() Function spam = ['cat', 'dog', 'moose'] len(spam) # 3 # Changing Values in a List with Indexes spam = ['cat', 'bat', 'rat', 'elephant'] spam[1] = 'aardvark' spam # ['cat', 'aardvark', 'rat', 'elephant'] spam[2]=spam[1] spam # ['cat', 'aardvark', 'aardvark', 'elephant'] spam[-1] = 12345 spam # ['cat', 'aardvark', 'aardvark', 12345] # List Concatenation and List Replication [1, 2, 3] + ['A', 'B', 'C'] # [1, 2, 3, 'A', 'B', 'C'] ['X', 'Y', 'Z'] * 3 #['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z'] spam = [1, 2, 3] spam = spam + ['A', 'B', 'C'] # [1, 2, 3, 'A', 'B', 'C'] # Removing Values From Lists with del Statements spam = ['cat', 'bat', 'rat', 'elephant'] del spam[2] spam # ['cat', 'bat', 'elephant'] del spam[2] spam # ['cat', 'bat'] # Using for Loops with Lists for i in range(4): print(i) supplies = ['pens', 'staplers', 'flamethrowers', 'binders'] for i in range(len(supplies)): print('Index ' + str(i) + ' in supplies is: ' + supplies[i]) # The in and not in Operators 'howdy' in ['hello', 'hi', 'howdy', 'heyas'] # True spam = ['hello', 'hi', 'howdy', 'heyas'] 'cat' in spam # False 'howdy' not in spam # False # Type in a pet name and then check wether the name is in a list of pets myPets = ['Zophie', 'Pooka', 'Fat-tail'] print('Enter a pet name:') name = input() if name not in myPets: print('I do not have a pet named ' + name) else: print(name + ' is my pet.') # The Multiple Assignment Trick cat = ['fat', 'gray', 'loud'] size = cat[0] color = cat[1] disposition = cat[2] # type this line cat = ['fat', 'gray', 'loud'] size, color, disposition = cat # Using the enumerate() Function with Lists # enumerate() Function is useful when you need both the item and item's index in loop's block supplies = ['pens', 'staplers', 'flamethrowers', 'binders'] for index, item in enumerate(supplies): print('Index ' + str(index) + ' in supplies is: ' + item) # Using the random.choice() and random.shuffle() Function with Lists import random pets = ['Dog', 'Cat', 'Moose'] random.choice(pets) random.choice(pets) random.choice(pets) # random.choice(someList) to be a shorter form of someList[random.randint(0, len(someList)-1)] import random people = ['Alice', 'Bob', 'Carol', 'David'] random.shuffle(people) people # ['Bob', 'Carol', 'David', 'Alice'] random.shuffle(people) people # random list of people #Augmented Assignment Operators spam += 1 # spam = spam + 1 spam -= 1 # spam = spam - 1 spam *= 1 # spam = spam * 1 spam /= 1 #spam = spam / 1 spam %= 1 #spam = spam % 1
[ 2, 32863, 876, 12901, 274, 198, 2777, 321, 796, 37250, 9246, 3256, 705, 8664, 3256, 705, 10366, 3256, 705, 11129, 33959, 20520, 198, 2777, 321, 58, 12, 16, 60, 1303, 9766, 79, 415, 198, 2777, 321, 58, 12, 18, 60, 1303, 7365, 628, ...
2.495833
1,200
import pandas as pd path = "Resources/cities.csv" data = pd.read_csv(path) data_html = data.to_html("data.html", bold_rows = True)
[ 11748, 19798, 292, 355, 279, 67, 198, 6978, 796, 366, 33236, 14, 66, 871, 13, 40664, 1, 198, 7890, 796, 279, 67, 13, 961, 62, 40664, 7, 6978, 8, 198, 7890, 62, 6494, 796, 1366, 13, 1462, 62, 6494, 7203, 7890, 13, 6494, 1600, 107...
2.6
50
# Copyright (C) 2020 Red Hat Inc. # # Authors: # Eduardo Habkost <ehabkost@redhat.com> # # This work is licensed under the terms of the GNU GPL, version 2. See # the COPYING file in the top-level directory. from tempfile import NamedTemporaryFile from .patching import FileInfo, FileMatch, Patch, FileList from .regexps import * def test_container_match(): of = NamedTemporaryFile('wt') of.writelines(['statement1()\n', 'statement2()\n', 'BEGIN function1\n', ' statement3()\n', ' statement4()\n', 'END\n', 'BEGIN function2\n', ' statement5()\n', ' statement6()\n', 'END\n', 'statement7()\n']) of.flush() files = FileList() f = FileInfo(files, of.name) f.load() assert len(f.matches_of_type(Function)) == 2 print(' '.join(m.name for m in f.matches_of_type(Statement))) assert len(f.matches_of_type(Statement)) == 7 f1 = f.find_match(Function, 'function1') f2 = f.find_match(Function, 'function2') st1 = f.find_match(Statement, 'statement1') st2 = f.find_match(Statement, 'statement2') st3 = f.find_match(Statement, 'statement3') st4 = f.find_match(Statement, 'statement4') st5 = f.find_match(Statement, 'statement5') st6 = f.find_match(Statement, 'statement6') st7 = f.find_match(Statement, 'statement7') assert not f1.contains(st1) assert not f1.contains(st2) assert not f1.contains(st2) assert f1.contains(st3) assert f1.contains(st4) assert not f1.contains(st5) assert not f1.contains(st6) assert not f1.contains(st7) assert not f2.contains(st1) assert not f2.contains(st2) assert not f2.contains(st2) assert not f2.contains(st3) assert not f2.contains(st4) assert f2.contains(st5) assert f2.contains(st6) assert not f2.contains(st7)
[ 2, 15069, 357, 34, 8, 12131, 2297, 10983, 3457, 13, 198, 2, 198, 2, 46665, 25, 198, 2, 220, 40766, 13109, 19654, 74, 455, 1279, 68, 5976, 74, 455, 31, 445, 5183, 13, 785, 29, 198, 2, 198, 2, 770, 670, 318, 11971, 739, 262, 284...
2.151581
917
# # Simple Tuple # fruits = ('Apple', 'Orange', 'Mango') # # Using Constructor # fruits = tuple(('Apple', 'Orange', 'Mango')) # # Getting a Single Value # print(fruits[1]) # Trying to change based on position # fruits[1] = 'Grape' # Tuples with one value should have trailing comma # fruits = ('Apple') # fruits = ('Apple',) # # Getting length of a tupel # print(len(fruits)) # ## Set fruits = {'Apple', 'Orange', 'Mango', 'Apple'} # Checking if in Set print('Apple' in fruits) # Add to Set fruits.add('Grape') # Removing from Set fruits.remove('Grape') # Clearing Set fruits.clear() # Delete set del fruits print(fruits)
[ 2, 1303, 17427, 309, 29291, 198, 2, 15921, 796, 19203, 16108, 3256, 705, 40141, 3256, 705, 44, 14208, 11537, 198, 198, 2, 1303, 8554, 28407, 273, 198, 2, 15921, 796, 46545, 7, 10786, 16108, 3256, 705, 40141, 3256, 705, 44, 14208, 6, ...
2.817778
225
from dataclasses import dataclass from dataclasses import asdict from typing import List, Tuple, Callable import numpy as np from sklearn.metrics import accuracy_score as accuracy_sklearn from sklearn.metrics import precision_score as precision_sklearn from sklearn.metrics import recall_score as recall_sklearn from sklearn.metrics import precision_recall_fscore_support as prf_sklearn from sklearn.exceptions import UndefinedMetricWarning import warnings from seqeval.metrics import precision_score as precision_seqeval from seqeval.metrics import recall_score as recall_seqeval from seqeval.metrics import f1_score as f1_seqeval from seqeval.scheme import IOB2, BILOU from nerblackbox.modules.ner_training.annotation_tags.tags import Tags
[ 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 198, 6738, 4818, 330, 28958, 1330, 355, 11600, 198, 6738, 19720, 1330, 7343, 11, 309, 29291, 11, 4889, 540, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 1341, 35720, 13, 4164, 10466...
3.545024
211
import sys if __name__ == "__main__": data, all_features, labelCount= readInput() results = rankByChiSquared(data, all_features, labelCount)
[ 11748, 25064, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1366, 11, 477, 62, 40890, 11, 6167, 12332, 28, 1100, 20560, 3419, 198, 220, 220, 220, 2482, 796, 4279, 3886, 1925, 72, 22266, 1144, 7, 7...
2.901961
51
# Importamos la librera para leer archivos json import json # Abrimos el archivo master en modo lectura ('r') con todos los id de los archivos descargados with open('master.json', 'r') as f: # Guardamos en la variable lista el contenido de master lista = json.load(f) # En este ejemplo se representa cmo se asignara a la lista archivos especficos #lista = ['2095303', '2169202'] # Abrimos el archivo tryall.json en modo lectura ('w'), si no est creado previamente # se crea en este momento, se puede cambiar nombre a este archivo with open('tryall.json', 'w') as outfile: # Iniciamos un contador para ir marcando cuntos archivos llevamos unidos contador = 0 # Esta variable ayuda a guardar el nombre del archivo anterior para # corroborar si no se est repitiendo con el anterior helper = 0 # Esta variable nos indica que tenemos que escribir dentro del documento lo que hay # dentro del archivo actual update = True # Recorremos toda la lista de archivos descargados for names in lista: # Abrimos cada archivo with open(f'{names}.json') as infile: # Leemos los primeras 3 lneas infile.readline() infile.readline() infile.readline() # Guardamos el contenido de la 4 que tiene el nmero del thread # en una variable temportal temp = infile.readline() # Comprobamos si helper tiene el mismo contenido que temp if helper != temp: # Si es diferente se puede hacer la actualizacin ya que no se va # a tener threads repetidos update = True # asignamos el nuevo contenido a la variable persistente helper = temp # Si tienen el mismo contenido entonces no se hace la actualizacin else: update = False # Abrimos nuevamente el archivo with open(f'{names}.json') as infile: # Si el post no est repetido entra if update == True: # Se escribe el contenido completo del thread en el archivo de salida outfile.write(infile.read()) # Se aumenta el contador ya que se escribi un documento nuevo contador+=1 # Se imporime el contador con el nombre del archivo ledo print(contador, names) # Se pone un salto de pgina para escribir el contenido del archivo siguiente outfile.write("\n")
[ 2, 17267, 321, 418, 8591, 9195, 24420, 31215, 443, 263, 3934, 452, 418, 33918, 198, 11748, 33918, 198, 198, 2, 317, 1671, 320, 418, 1288, 3934, 23593, 4958, 551, 953, 78, 11042, 5330, 19203, 81, 11537, 369, 284, 37427, 22346, 4686, 39...
2.262826
1,111
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file contains the generators and their inverses for common archimedean copulas. """ import numpy as np
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 220, 220, 220, 770, 2393, 4909, 262, 27298, 290, 511, 287, 690, 274, 329, 2219, 3934, 320, 276, 1102...
2.844828
58
""" """ from admin import routes def init_app(app): """ :param app: :return: """ routes.init_app(app)
[ 37811, 198, 198, 37811, 198, 6738, 13169, 1330, 11926, 628, 198, 4299, 2315, 62, 1324, 7, 1324, 2599, 198, 220, 220, 220, 37227, 628, 220, 220, 220, 1058, 17143, 598, 25, 198, 220, 220, 220, 1058, 7783, 25, 198, 220, 220, 220, 37227...
2.25
56
from output.models.nist_data.list_pkg.decimal.schema_instance.nistschema_sv_iv_list_decimal_pattern_2_xsd.nistschema_sv_iv_list_decimal_pattern_2 import NistschemaSvIvListDecimalPattern2 __all__ = [ "NistschemaSvIvListDecimalPattern2", ]
[ 6738, 5072, 13, 27530, 13, 77, 396, 62, 7890, 13, 4868, 62, 35339, 13, 12501, 4402, 13, 15952, 2611, 62, 39098, 13, 77, 1023, 2395, 2611, 62, 21370, 62, 452, 62, 4868, 62, 12501, 4402, 62, 33279, 62, 17, 62, 87, 21282, 13, 77, 1...
2.405941
101
import numpy as np import pyamg from scipy import sparse from scipy.spatial import Delaunay from linsolver import sparse_solver from triangulation.delaunay import delaunay
[ 11748, 299, 32152, 355, 45941, 198, 11748, 12972, 321, 70, 198, 6738, 629, 541, 88, 1330, 29877, 198, 6738, 629, 541, 88, 13, 2777, 34961, 1330, 4216, 1942, 323, 198, 198, 6738, 300, 1040, 14375, 1330, 29877, 62, 82, 14375, 198, 6738,...
3.181818
55
"""Support for Atlantic Electrical Heater IO controller.""" import logging from typing import List from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( HVAC_MODE_HEAT, HVAC_MODE_OFF, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS from ..coordinator import TahomaDataUpdateCoordinator from ..tahoma_entity import TahomaEntity _LOGGER = logging.getLogger(__name__) COMMAND_GET_LEVEL = "getLevel" COMMAND_SET_LEVEL = "setLevel" CORE_LEVEL_STATE = "core:LevelState"
[ 37811, 15514, 329, 10596, 40224, 679, 729, 24418, 10444, 526, 15931, 198, 11748, 18931, 198, 6738, 19720, 1330, 7343, 198, 198, 6738, 1363, 562, 10167, 13, 5589, 3906, 13, 42570, 1330, 13963, 32398, 198, 6738, 1363, 562, 10167, 13, 5589, ...
2.939698
199
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2021-03-02 13:32 from typing import Optional, Union, Dict, Any import torch from torch import nn from transformers import PreTrainedTokenizer from elit.components.mtl.attn.attn import TaskAttention from elit.components.mtl.attn.transformer import JointEncoder from elit.layers.embeddings.contextual_word_embedding import ContextualWordEmbeddingModule, ContextualWordEmbedding from elit.layers.scalar_mix import ScalarMixWithDropoutBuilder from elit.layers.transformers.utils import pick_tensor_for_each_token
[ 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 2, 6434, 25, 289, 962, 6359, 198, 2, 7536, 25, 33448, 12, 3070, 12, 2999, 1511, 25, 2624, 198, 6738, 19720, 1330, 32233, 11, 4479, 11, 360, 713, 11, 4377, 198, 198, 117...
3.048913
184
from sensors.sensors import sense_characteristics, sense_pedestrians
[ 6738, 15736, 13, 82, 641, 669, 1330, 2565, 62, 22769, 3969, 11, 2565, 62, 9124, 395, 19151 ]
4
17
"""Implementations of algorithms for continuous control.""" import functools from typing import Optional, Sequence, Tuple import jax import jax.numpy as jnp import numpy as np import optax from jaxrl.agents.sac import temperature from jaxrl.agents.sac.actor import update as update_actor from jaxrl.agents.sac.critic import target_update from jaxrl.agents.sac_v1.critic import update_q, update_v from jaxrl.datasets import Batch from jaxrl.networks import critic_net, policies from jaxrl.networks.common import InfoDict, Model, PRNGKey
[ 37811, 3546, 26908, 602, 286, 16113, 329, 12948, 1630, 526, 15931, 198, 198, 11748, 1257, 310, 10141, 198, 6738, 19720, 1330, 32233, 11, 45835, 11, 309, 29291, 198, 198, 11748, 474, 897, 198, 11748, 474, 897, 13, 77, 32152, 355, 474, ...
3.220238
168
"""Collections of library function names. """ def drop_suffix(f): s = f.rsplit('.', 1)[-1] if s in ['p0i8', 'f64', 'f32', 'i1', 'i8', 'i16', 'i32', 'i64', 'i128']: f = f[:-len(s)-1] return drop_suffix(f) return f def get_llvm_name(f, prefix='llvm.'): """Return normalized name of a llvm intrinsic name. """ if f.startswith(prefix): return drop_suffix(f[len(prefix):]) return f
[ 37811, 5216, 26448, 286, 5888, 2163, 3891, 13, 198, 37811, 628, 628, 628, 198, 198, 4299, 4268, 62, 37333, 844, 7, 69, 2599, 198, 220, 220, 220, 264, 796, 277, 13, 3808, 489, 270, 10786, 2637, 11, 352, 38381, 12, 16, 60, 198, 220,...
2.110048
209
import pandas as pd print(pd.__version__) city_names = pd.Series(['San Francisco', 'San Jose', 'Sacramento']) population = pd.Series([852469, 1015785, 485199]) #city_population_table = pd.DataFrame(({'City name': city_names, 'Population': population})) california_houseing_dataframe = pd.read_csv("https://storage.googleapis.com/mledu-datasets/california_housing_train.csv", sep=",") california_houseing_dataframe.describe() california_houseing_dataframe.head() #some error #california_houseing_dataframe.hist('housing_median_age') cities = pd.DataFrame({'City name': city_names, 'Population': population}) #print(type(cities['City name'])) #print(cities['City name']) #print(type(cities['City name'][1])) #print(cities['City name'][1]) #print(type(cities[0:2])) #print(cities[0:2]) #print(population / 1000) import numpy as np np.log(population) #print(population.apply(lambda val: val > 10000)) cities['Area square miles'] = pd.Series([46.87, 176.53, 97.92]) #print(cities) cities['Population density'] = cities['Population'] / cities['Area square miles'] #print(cities) print(city_names.index) print(cities.reindex([2, 0, 1])) print(cities)
[ 11748, 19798, 292, 355, 279, 67, 198, 4798, 7, 30094, 13, 834, 9641, 834, 8, 198, 19205, 62, 14933, 796, 279, 67, 13, 27996, 7, 17816, 15017, 6033, 3256, 705, 15017, 5264, 3256, 705, 38318, 15141, 78, 6, 12962, 198, 39748, 796, 279,...
2.741007
417
from helloworld.app import main if True or __name__ == '__main__': main().main_loop()
[ 6738, 5968, 322, 1764, 13, 1324, 1330, 1388, 198, 198, 361, 6407, 393, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 22446, 12417, 62, 26268, 3419, 198 ]
2.757576
33
from fastapi import FastAPI from dotenv import load_dotenv from fastapi.middleware.cors import CORSMiddleware from app.api.api_v1.api import api_router from app.core.config import settings app = FastAPI() load_dotenv() app.include_router(api_router, prefix=settings.API_V1_STR) # Set all CORS enabled origins if settings.BACKEND_CORS_ORIGINS: app.add_middleware( CORSMiddleware, allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) if __name__ == "__main__": # Use this for debugging purposes only # pyright: reportGeneralTypeIssues=false import uvicorn uvicorn.run(app, host="0.0.0.0", port=8001, log_level="debug")
[ 6738, 3049, 15042, 1330, 12549, 17614, 198, 6738, 16605, 24330, 1330, 3440, 62, 26518, 24330, 198, 6738, 3049, 15042, 13, 27171, 1574, 13, 66, 669, 1330, 23929, 12310, 2509, 1574, 198, 6738, 598, 13, 15042, 13, 15042, 62, 85, 16, 13, ...
2.437309
327
"""Example revision Revision ID: fdf0cf6487a3 Revises: Create Date: 2021-08-09 17:55:19.491713 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "fdf0cf6487a3" down_revision = None branch_labels = None depends_on = None
[ 37811, 16281, 18440, 198, 198, 18009, 1166, 4522, 25, 277, 7568, 15, 12993, 2414, 5774, 64, 18, 198, 18009, 2696, 25, 198, 16447, 7536, 25, 33448, 12, 2919, 12, 2931, 1596, 25, 2816, 25, 1129, 13, 2920, 1558, 1485, 198, 198, 37811, ...
2.632075
106
from __future__ import annotations from typing import Optional # Definition for a binary tree node.
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 6738, 19720, 1330, 32233, 198, 198, 2, 30396, 329, 257, 13934, 5509, 10139, 13, 198 ]
4.590909
22
# @lc app=leetcode id=506 lang=python3 # # [506] Relative Ranks # # https://leetcode.com/problems/relative-ranks/description/ # # algorithms # Easy (53.46%) # Likes: 188 # Dislikes: 9 # Total Accepted: 71.1K # Total Submissions: 132.4K # Testcase Example: '[5,4,3,2,1]' # # You are given an integer array score of size n, where score[i] is the score # of the i^th athlete in a competition. All the scores are guaranteed to be # unique. # # The athletes are placed based on their scores, where the 1^st place athlete # has the highest score, the 2^nd place athlete has the 2^nd highest score, and # so on. The placement of each athlete determines their rank: # # # The 1^st place athlete's rank is "Gold Medal". # The 2^nd place athlete's rank is "Silver Medal". # The 3^rd place athlete's rank is "Bronze Medal". # For the 4^th place to the n^th place athlete, their rank is their placement # number (i.e., the x^th place athlete's rank is "x"). # # # Return an array answer of size n where answer[i] is the rank of the i^th # athlete. # # # Example 1: # # # Input: score = [5,4,3,2,1] # Output: ["Gold Medal","Silver Medal","Bronze Medal","4","5"] # Explanation: The placements are [1^st, 2^nd, 3^rd, 4^th, 5^th]. # # Example 2: # # # Input: score = [10,3,8,9,4] # Output: ["Gold Medal","5","Bronze Medal","Silver Medal","4"] # Explanation: The placements are [1^st, 5^th, 3^rd, 2^nd, 4^th]. # # # # # Constraints: # # # n == score.length # 1 <= n <= 10^4 # 0 <= score[i] <= 10^6 # All the values in score are unique. # # # # @lc tags=Unknown # @lc imports=start from imports import * # @lc imports=end # @lc idea=start # # # # @lc idea=end # @lc group= # @lc rank= # @lc code=start # @lc code=end # @lc main=start if __name__ == '__main__': print('Example 1:') print('Input : ') print('score = [5,4,3,2,1]') print('Exception :') print('["Gold Medal","Silver Medal","Bronze Medal","4","5"]') print('Output :') print(str(Solution().findRelativeRanks([5, 4, 3, 2, 1]))) print() print('Example 2:') print('Input : ') print('score = [10,3,8,9,4]') print('Exception :') print('["Gold Medal","5","Bronze Medal","Silver Medal","4"]') print('Output :') print(str(Solution().findRelativeRanks([10, 3, 8, 9, 4]))) print() pass # @lc main=end
[ 2, 2488, 44601, 598, 28, 293, 316, 8189, 4686, 28, 35638, 42392, 28, 29412, 18, 198, 2, 198, 2, 685, 35638, 60, 45344, 371, 2283, 198, 2, 198, 2, 3740, 1378, 293, 316, 8189, 13, 785, 14, 1676, 22143, 14, 43762, 12, 81, 2283, 14,...
2.593296
895
# -*- Python -*- import os # Setup config name. config.name = 'MemorySanitizer' + getattr(config, 'name_suffix', 'default') # Setup source root. config.test_source_root = os.path.dirname(__file__) # Setup default compiler flags used with -fsanitize=memory option. clang_msan_cflags = (["-fsanitize=memory", "-mno-omit-leaf-frame-pointer", "-fno-omit-frame-pointer", "-fno-optimize-sibling-calls"] + [config.target_cflags] + config.debug_info_flags) # Some Msan tests leverage backtrace() which requires libexecinfo on FreeBSD. if config.host_os == 'FreeBSD': clang_msan_cflags += ["-lexecinfo", "-fPIC"] clang_msan_cxxflags = config.cxx_mode_flags + clang_msan_cflags # Flags for KMSAN invocation. This is C-only, we're not interested in C++. clang_kmsan_cflags = (["-fsanitize=kernel-memory"] + [config.target_cflags] + config.debug_info_flags) config.substitutions.append( ("%clang_msan ", build_invocation(clang_msan_cflags)) ) config.substitutions.append( ("%clangxx_msan ", build_invocation(clang_msan_cxxflags)) ) config.substitutions.append( ("%clang_kmsan ", build_invocation(clang_kmsan_cflags)) ) # Default test suffixes. config.suffixes = ['.c', '.cc', '.cpp'] if config.host_os not in ['Linux', 'NetBSD', 'FreeBSD']: config.unsupported = True # For mips64, mips64el we have forced store_context_size to 1 because these # archs use slow unwinder which is not async signal safe. Therefore we only # check the first frame since store_context size is 1. if config.host_arch in ['mips64', 'mips64el']: config.substitutions.append( ('CHECK-%short-stack', 'CHECK-SHORT-STACK')) else: config.substitutions.append( ('CHECK-%short-stack', 'CHECK-FULL-STACK'))
[ 2, 532, 9, 12, 11361, 532, 9, 12, 198, 198, 11748, 28686, 198, 198, 2, 31122, 4566, 1438, 13, 198, 11250, 13, 3672, 796, 705, 30871, 15017, 3029, 263, 6, 1343, 651, 35226, 7, 11250, 11, 705, 3672, 62, 37333, 844, 3256, 705, 12286,...
2.408673
761
# Generated by Django 2.0.6 on 2018-06-17 04:47 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 362, 13, 15, 13, 21, 319, 2864, 12, 3312, 12, 1558, 8702, 25, 2857, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
# # nuna_sql_tools: Copyright 2022 Nuna 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. # """Utilityes for checking and.""" import dataclasses import datetime import decimal from types import ModuleType from typing import NewType, Union # In your data declaration python modules define a JAVA_PACKAGE # variable at top level to specify the corresponding Java package of generated # classes. JAVA_PACKAGE = 'JAVA_PACKAGE' _SCHEMA_ANNOTATIONS = '__schema_annotations__' _EXPECTED_DICT_KEYS = set([ '__module__', '__annotations__', '__doc__', '__dict__', '__weakref__', '__dataclass_params__', '__dataclass_fields__', _SCHEMA_ANNOTATIONS ]) _EXPECTED_FUNCTIONS = ['__init__', '__repr__', '__eq__', '__hash__'] _BASE_TYPES = set([ int, bytes, str, float, bool, datetime.date, datetime.datetime, decimal.Decimal ]) _SCHEMA_ANNOTATIONS = '__schema_annotations__' _CLASS_ID = 0 def _Annotate(cls=None, annotation=None): """Annotates a class or a type. `annotation` should from annotation.py""" if cls is None: return Wrap return Wrap(cls) def Annotate(cls, annotation): """Annotates a field type with the provided annotation.""" return _Annotate(cls, annotation=annotation) def IsAnnotatedType(field_cls: type): """If provided field_cls is an annotated type.""" return hasattr(field_cls, _SCHEMA_ANNOTATIONS) def GetAnnotatedType(field_cls: type): """Returns the original type behind the annotation (if any).""" if IsAnnotatedType(field_cls) and hasattr(field_cls, '__supertype__'): return field_cls.__supertype__ return field_cls def IsOptionalType(field_cls: type): """If the field_cls looks like an Optional[...] type.""" return (hasattr(field_cls, '__origin__') # pylint: disable=comparison-with-callable and field_cls.__origin__ == Union and len(field_cls.__args__) == 2 and field_cls.__args__[1] == type(None)) def GetOptionalType(field_cls: type): """Returns the type of optional & annotation or None if not optional.""" field_cls = GetAnnotatedType(field_cls) if IsOptionalType(field_cls): return field_cls.__args__[0] return None def GetOriginalType(field_cls: type): """Returns the type of field_cls, behind annotations and Optional.""" field_cls = GetAnnotatedType(field_cls) if IsOptionalType(field_cls): return field_cls.__args__[0] return field_cls def GetStructuredTypeName(field_cls: type): """Returns the structure type name for a type, behind annotation.""" field_cls = GetAnnotatedType(field_cls) if not hasattr(field_cls, '__origin__'): return None if field_cls.__origin__ is dict: return 'dict' elif field_cls.__origin__ is list: return 'list' elif field_cls.__origin__ is set: return 'set' return None def IsBasicType(field_cls: type): """If the type field_cls looks like one of the basic field types.""" if GetAnnotatedType(field_cls) in _BASE_TYPES: return True _MAX_DEPTH = 30 def SchemaAnnotations(cls: type): """Returns the schema annotations of a type.""" annotations = [] if hasattr(cls, _SCHEMA_ANNOTATIONS): annotations.extend(cls.__schema_annotations__) return annotations
[ 2, 198, 2, 299, 9613, 62, 25410, 62, 31391, 25, 15069, 33160, 399, 9613, 3457, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, ...
2.718481
1,396
"""HERE are the base Points for all valid Tonnetze Systems. A period of all 12 notes divided by mod 3, mod 4 (always stable) """ # x = 4, y = 3 NotePointsT345 = { 0: (0, 0), 1: (1, 3), 2: (2, 2), 3: (0, 1), 4: (1, 0), 5: (2, 3), 6: (0, 2), 7: (1, 1), 8: (2, 0), 9: (0, 3), 10: (1, 2), 11: (2, 1) } # x = 8, y = 3 NotePointsT138 = { 0: (0, 0), 1: (2, 3), 2: (1, 2), 3: (0, 1), 4: (2, 0), 5: (1, 3), 6: (0, 2), 7: (2, 1), 8: (1, 0), 9: (0, 3), 10: (2, 2), 11: (1, 1) } # x = 2, y = 9 NotePointsT129 = { 0: (0, 0), 1: (2, 1), 2: (1, 0), 3: (0, 3), 4: (2, 0), 5: (1, 3), 6: (0, 2), 7: (2, 3), 8: (1, 2), 9: (0, 1), 10: (2, 2), 11: (1, 1) } # x = 4, y = 1 NotePointsT147 = { 0: (0, 0), 1: (0, 1), 2: (0, 2), 3: (0, 3), 4: (1, 0), 5: (1, 1), 6: (1, 2), 7: (1, 3), 8: (2, 0), 9: (2, 1), 10: (2, 2), 11: (2, 3) } # x = 2, y = 3 NotePointsT237 = { 0: (0, 0), 1: (2, 3), 2: (1, 0), 3: (0, 1), 4: (2, 0), 5: (1, 1), 6: (0, 2), 7: (2, 1), 8: (1, 2), 9: (0, 3), 10: (2, 2), 11: (1, 3) } dictOfTonnetz = { 'T345': NotePointsT345, 'T147': NotePointsT147, 'T138': NotePointsT138, 'T237': NotePointsT237, 'T129': NotePointsT129 } dictOfTonnetze = { 'T129': [1, 2, 9], 'T138': [1, 3, 8], 'T147': [1, 4, 7], 'T156': [1, 5, 6], 'T237': [2, 3, 7], 'T345': [3, 4, 5] }
[ 37811, 39, 9338, 389, 262, 2779, 11045, 329, 477, 4938, 16859, 3262, 2736, 11998, 13, 198, 198, 32, 2278, 286, 477, 1105, 4710, 9086, 416, 953, 513, 11, 953, 604, 357, 33770, 8245, 8, 198, 37811, 198, 198, 2, 2124, 796, 604, 11, 3...
1.591942
968
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from .aws import Action as BaseAction from .aws import BaseARN service_name = "AWS Proton" prefix = "proton" CreateEnvironment = Action("CreateEnvironment") CreateEnvironmentTemplate = Action("CreateEnvironmentTemplate") CreateEnvironmentTemplateMajorVersion = Action("CreateEnvironmentTemplateMajorVersion") CreateEnvironmentTemplateMinorVersion = Action("CreateEnvironmentTemplateMinorVersion") CreateService = Action("CreateService") CreateServiceTemplate = Action("CreateServiceTemplate") CreateServiceTemplateMajorVersion = Action("CreateServiceTemplateMajorVersion") CreateServiceTemplateMinorVersion = Action("CreateServiceTemplateMinorVersion") DeleteAccountRoles = Action("DeleteAccountRoles") DeleteEnvironment = Action("DeleteEnvironment") DeleteEnvironmentTemplate = Action("DeleteEnvironmentTemplate") DeleteEnvironmentTemplateMajorVersion = Action("DeleteEnvironmentTemplateMajorVersion") DeleteEnvironmentTemplateMinorVersion = Action("DeleteEnvironmentTemplateMinorVersion") DeleteService = Action("DeleteService") DeleteServiceTemplate = Action("DeleteServiceTemplate") DeleteServiceTemplateMajorVersion = Action("DeleteServiceTemplateMajorVersion") DeleteServiceTemplateMinorVersion = Action("DeleteServiceTemplateMinorVersion") GetAccountRoles = Action("GetAccountRoles") GetEnvironment = Action("GetEnvironment") GetEnvironmentTemplate = Action("GetEnvironmentTemplate") GetEnvironmentTemplateMajorVersion = Action("GetEnvironmentTemplateMajorVersion") GetEnvironmentTemplateMinorVersion = Action("GetEnvironmentTemplateMinorVersion") GetService = Action("GetService") GetServiceInstance = Action("GetServiceInstance") GetServiceTemplate = Action("GetServiceTemplate") GetServiceTemplateMajorVersion = Action("GetServiceTemplateMajorVersion") GetServiceTemplateMinorVersion = Action("GetServiceTemplateMinorVersion") ListEnvironmentTemplateMajorVersions = Action("ListEnvironmentTemplateMajorVersions") ListEnvironmentTemplateMinorVersions = Action("ListEnvironmentTemplateMinorVersions") ListEnvironmentTemplates = Action("ListEnvironmentTemplates") ListEnvironments = Action("ListEnvironments") ListServiceInstances = Action("ListServiceInstances") ListServiceTemplateMajorVersions = Action("ListServiceTemplateMajorVersions") ListServiceTemplateMinorVersions = Action("ListServiceTemplateMinorVersions") ListServiceTemplates = Action("ListServiceTemplates") ListServices = Action("ListServices") ListTagsForResource = Action("ListTagsForResource") TagResource = Action("TagResource") UntagResource = Action("UntagResource") UpdateAccountRoles = Action("UpdateAccountRoles") UpdateEnvironment = Action("UpdateEnvironment") UpdateEnvironmentTemplate = Action("UpdateEnvironmentTemplate") UpdateEnvironmentTemplateMajorVersion = Action("UpdateEnvironmentTemplateMajorVersion") UpdateEnvironmentTemplateMinorVersion = Action("UpdateEnvironmentTemplateMinorVersion") UpdateService = Action("UpdateService") UpdateServiceInstance = Action("UpdateServiceInstance") UpdateServicePipeline = Action("UpdateServicePipeline") UpdateServiceTemplate = Action("UpdateServiceTemplate") UpdateServiceTemplateMajorVersion = Action("UpdateServiceTemplateMajorVersion") UpdateServiceTemplateMinorVersion = Action("UpdateServiceTemplateMinorVersion")
[ 2, 15069, 357, 66, 8, 2321, 12, 1238, 2481, 11, 2940, 2631, 988, 1279, 4102, 31, 431, 988, 13, 2398, 29, 198, 2, 1439, 2489, 10395, 13, 198, 2, 198, 2, 4091, 38559, 24290, 2393, 329, 1336, 5964, 13, 198, 198, 6738, 764, 8356, 13...
4.772277
707
# Copyright 2020 DeepMind Technologies Limited. 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. # ============================================================================== """Tests for jaxline's utils.""" import functools import itertools as it import time from unittest import mock from absl.testing import absltest from absl.testing import flagsaver import jax import jax.numpy as jnp from jaxline import utils import numpy as np if __name__ == "__main__": absltest.main()
[ 2, 15069, 12131, 10766, 28478, 21852, 15302, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 35...
3.779851
268
#!/usr/bin/python # Classification (U) """Program: slaverep_isslverror.py Description: Unit testing of SlaveRep.is_slv_error in mysql_class.py. Usage: test/unit/mysql_class/slaverep_isslverror.py Arguments: """ # Libraries and Global Variables # Standard import sys import os if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest # Third-party # Local sys.path.append(os.getcwd()) import mysql_class import lib.machine as machine import version __version__ = version.__version__ if __name__ == "__main__": unittest.main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 40984, 357, 52, 8, 198, 198, 37811, 15167, 25, 220, 11778, 7856, 62, 747, 75, 332, 1472, 13, 9078, 628, 220, 220, 220, 12489, 25, 220, 11801, 4856, 286, 38795, 6207, 13, 271, 62, 6649,...
2.653333
225
""" 108. """ from TreeNode import TreeNode t = [-10,-3,0,5,9] obj = Solution() node = obj.sortedArrayToBST(t) node.preorderTraversal()
[ 37811, 198, 15711, 13, 220, 198, 37811, 198, 198, 6738, 12200, 19667, 1330, 12200, 19667, 628, 628, 198, 83, 796, 25915, 940, 12095, 18, 11, 15, 11, 20, 11, 24, 60, 198, 26801, 796, 28186, 3419, 198, 17440, 796, 26181, 13, 82, 9741,...
2.366667
60
## -*- encoding: utf-8 -*- """ This file (./domaines_doctest.sage) was *autogenerated* from ./domaines.tex, with sagetex.sty version 2011/05/27 v2.3.1. It contains the contents of all the sageexample environments from this file. You should be able to doctest this file with: sage -t ./domaines_doctest.sage It is always safe to delete this file; it is not used in typesetting your document. Sage example in ./domaines.tex, line 10:: sage: x = var('x') Sage example in ./domaines.tex, line 69:: sage: o = 12/35 sage: type(o) <... 'sage.rings.rational.Rational'> Sage example in ./domaines.tex, line 82:: sage: type(12/35) <... 'sage.rings.rational.Rational'> Sage example in ./domaines.tex, line 131:: sage: o = 720 sage: o.factor() 2^4 * 3^2 * 5 Sage example in ./domaines.tex, line 142:: sage: type(o).factor(o) 2^4 * 3^2 * 5 Sage example in ./domaines.tex, line 157:: sage: 720.factor() 2^4 * 3^2 * 5 Sage example in ./domaines.tex, line 166:: sage: o = 720 / 133 sage: o.numerator().factor() 2^4 * 3^2 * 5 Sage example in ./domaines.tex, line 253:: sage: 3 * 7 21 Sage example in ./domaines.tex, line 261:: sage: (2/3) * (6/5) 4/5 Sage example in ./domaines.tex, line 267:: sage: (1 + I) * (1 - I) 2 Sage example in ./domaines.tex, line 274:: sage: (x + 2) * (x + 1) (x + 2)*(x + 1) sage: (x + 1) * (x + 2) (x + 2)*(x + 1) Sage example in ./domaines.tex, line 308:: sage: def fourth_power(a): ....: a = a * a ....: a = a * a ....: return a Sage example in ./domaines.tex, line 330:: sage: fourth_power(2) 16 sage: fourth_power(3/2) 81/16 sage: fourth_power(I) 1 sage: fourth_power(x+1) (x + 1)^4 sage: M = matrix([[0,-1],[1,0]]); M [ 0 -1] [ 1 0] sage: fourth_power(M) [1 0] [0 1] Sage example in ./domaines.tex, line 375:: sage: t = type(5/1); t <... 'sage.rings.rational.Rational'> sage: t == type(5) False Sage example in ./domaines.tex, line 476:: sage: a = 5; a 5 sage: a.is_unit() False Sage example in ./domaines.tex, line 484:: sage: a = 5/1; a 5 sage: a.is_unit() True Sage example in ./domaines.tex, line 507:: sage: parent(5) Integer Ring sage: parent(5/1) Rational Field Sage example in ./domaines.tex, line 515:: sage: ZZ Integer Ring sage: QQ Rational Field Sage example in ./domaines.tex, line 525:: sage: QQ(5).parent() Rational Field sage: ZZ(5/1).parent() Integer Ring sage: ZZ(1/5) Traceback (most recent call last): ... TypeError: no conversion of this rational to integer Sage example in ./domaines.tex, line 543:: sage: ZZ(1), QQ(1), RR(1), CC(1) (1, 1, 1.00000000000000, 1.00000000000000) Sage example in ./domaines.tex, line 568:: sage: cartesian_product([QQ, QQ]) The Cartesian product of (Rational Field, Rational Field) Sage example in ./domaines.tex, line 574:: sage: ZZ.fraction_field() Rational Field Sage example in ./domaines.tex, line 580:: sage: ZZ['x'] Univariate Polynomial Ring in x over Integer Ring Sage example in ./domaines.tex, line 591:: sage: Z5 = GF(5); Z5 Finite Field of size 5 sage: P = Z5['x']; P Univariate Polynomial Ring in x over Finite Field of size 5 sage: M = MatrixSpace(P, 3, 3); M Full MatrixSpace of 3 by 3 dense matrices over Univariate Polynomial Ring in x over Finite Field of size 5 Sage example in ./domaines.tex, line 602:: sage: M.random_element() # random [2*x^2 + 3*x + 4 4*x^2 + 2*x + 2 4*x^2 + 2*x] [ 3*x 2*x^2 + x + 3 3*x^2 + 4*x] [ 4*x^2 + 3 3*x^2 + 2*x + 4 2*x + 4] Sage example in ./domaines.tex, line 697:: sage: QQ.category() Join of Category of number fields and Category of quotient fields and Category of metric spaces Sage example in ./domaines.tex, line 704:: sage: QQ in Fields() True Sage example in ./domaines.tex, line 712:: sage: QQ in CommutativeAdditiveGroups() True Sage example in ./domaines.tex, line 718:: sage: QQ['x'] in EuclideanDomains() True Sage example in ./domaines.tex, line 859:: sage: 5.parent() Integer Ring Sage example in ./domaines.tex, line 872:: sage: type(factor(4)) <class 'sage.structure.factorization_integer.IntegerFactorization'> Sage example in ./domaines.tex, line 895:: sage: int(5) 5 sage: type(int(5)) <... 'int'> Sage example in ./domaines.tex, line 909:: sage: Integer(5) 5 sage: type(Integer(5)) <... 'sage.rings.integer.Integer'> Sage example in ./domaines.tex, line 926:: sage: factorial(99) / factorial(100) - 1 / 50 -1/100 Sage example in ./domaines.tex, line 974:: sage: 72/53 - 5/3 * 2.7 -3.14150943396227 Sage example in ./domaines.tex, line 982:: sage: cos(1), cos(1.) (cos(1), 0.540302305868140) Sage example in ./domaines.tex, line 1000:: sage: pi.n(digits=50) # variant: n(pi,digits=50) 3.1415926535897932384626433832795028841971693993751 Sage example in ./domaines.tex, line 1020:: sage: z = CC(1,2); z.arg() 1.10714871779409 Sage example in ./domaines.tex, line 1036:: sage: I.parent() Number Field in I with defining polynomial x^2 + 1 with I = 1*I Sage example in ./domaines.tex, line 1043:: sage: (1.+2.*I).parent() Complex Field with 53 bits of precision sage: (1.+2.*SR(I)).parent() Symbolic Ring Sage example in ./domaines.tex, line 1064:: sage: z = 3 * exp(I*pi/4) sage: z.real(), z.imag(), z.abs().canonicalize_radical() (3/2*sqrt(2), 3/2*sqrt(2), 3) Sage example in ./domaines.tex, line 1094:: sage: a, b, c = 0, 2, 3 sage: a == 1 or (b == 2 and c == 3) True Sage example in ./domaines.tex, line 1147:: sage: x, y = var('x, y') sage: bool( (x-y)*(x+y) == x^2-y^2 ) True Sage example in ./domaines.tex, line 1171:: sage: Z4 = IntegerModRing(4); Z4 Ring of integers modulo 4 sage: m = Z4(7); m 3 Sage example in ./domaines.tex, line 1184:: sage: 3 * m + 1 2 Sage example in ./domaines.tex, line 1191:: sage: Z3 = GF(3); Z3 Finite Field of size 3 Sage example in ./domaines.tex, line 1243:: sage: a = matrix(QQ, [[1,2,3],[2,4,8],[3,9,27]]) sage: (a^2 + 1) * a^(-1) [ -5 13/2 7/3] [ 7 1 25/3] [ 2 19/2 27] Sage example in ./domaines.tex, line 1259:: sage: M = MatrixSpace(QQ,3,3); M Full MatrixSpace of 3 by 3 dense matrices over Rational Field sage: a = M([[1,2,3],[2,4,8],[3,9,27]]) sage: (a^2 + 1) * a^(-1) [ -5 13/2 7/3] [ 7 1 25/3] [ 2 19/2 27] Sage example in ./domaines.tex, line 1283:: sage: P = ZZ['x']; P Univariate Polynomial Ring in x over Integer Ring sage: F = P.fraction_field(); F Fraction Field of Univariate Polynomial Ring in x over Integer Ring sage: p = P(x+1) * P(x); p x^2 + x sage: p + 1/p (x^4 + 2*x^3 + x^2 + 1)/(x^2 + x) sage: parent(p + 1/p) Fraction Field of Univariate Polynomial Ring in x over Integer Ring Sage example in ./domaines.tex, line 1382:: sage: k.<a> = NumberField(x^3 + x + 1); a^3; a^4+3*a -a - 1 -a^2 + 2*a Sage example in ./domaines.tex, line 1416:: sage: parent(sin(x)) Symbolic Ring Sage example in ./domaines.tex, line 1422:: sage: SR Symbolic Ring Sage example in ./domaines.tex, line 1428:: sage: SR.category() Category of fields Sage example in ./domaines.tex, line 1482:: sage: R = QQ['x1,x2,x3,x4']; R Multivariate Polynomial Ring in x1, x2, x3, x4 over Rational Field sage: x1, x2, x3, x4 = R.gens() Sage example in ./domaines.tex, line 1489:: sage: x1 * (x2 - x3) x1*x2 - x1*x3 Sage example in ./domaines.tex, line 1496:: sage: (x1+x2)*(x1-x2) - (x1^2 - x2^2) 0 Sage example in ./domaines.tex, line 1509:: sage: P = prod( (a-b) for (a,b) in Subsets([x1,x2,x3,x4],2) ); P * P.lc() x1^3*x2^2*x3 - x1^2*x2^3*x3 - x1^3*x2*x3^2 + x1*x2^3*x3^2 + x1^2*x2*x3^3 - x1*x2^2*x3^3 - x1^3*x2^2*x4 + x1^2*x2^3*x4 + x1^3*x3^2*x4 - x2^3*x3^2*x4 - x1^2*x3^3*x4 + x2^2*x3^3*x4 + x1^3*x2*x4^2 - x1*x2^3*x4^2 - x1^3*x3*x4^2 + x2^3*x3*x4^2 + x1*x3^3*x4^2 - x2*x3^3*x4^2 - x1^2*x2*x4^3 + x1*x2^2*x4^3 + x1^2*x3*x4^3 - x2^2*x3*x4^3 - x1*x3^2*x4^3 + x2*x3^2*x4^3 Sage example in ./domaines.tex, line 1531:: sage: x1, x2, x3, x4 = SR.var('x1, x2, x3, x4') sage: got = prod( (a-b) for (a,b) in Subsets([x1,x2,x3,x4],2) ) sage: expected1 = -(x1 - x2)*(x1 - x3)*(x1 - x4)*(x2 - x3)*(x2 - x4)*(x3 - x4) sage: expected2 = (x1 - x2)*(x1 - x3)*(x1 - x4)*(x2 - x3)*(x2 - x4)*(x3 - x4) sage: bool(got == expected1 or got == expected2) True Sage example in ./domaines.tex, line 1581:: sage: x = var('x') sage: p = 54*x^4+36*x^3-102*x^2-72*x-12 sage: factor(p) 6*(x^2 - 2)*(3*x + 1)^2 Sage example in ./domaines.tex, line 1616:: sage: R = ZZ['x']; R Univariate Polynomial Ring in x over Integer Ring Sage example in ./domaines.tex, line 1622:: sage: q = R(p); q 54*x^4 + 36*x^3 - 102*x^2 - 72*x - 12 Sage example in ./domaines.tex, line 1629:: sage: parent(q) Univariate Polynomial Ring in x over Integer Ring Sage example in ./domaines.tex, line 1635:: sage: factor(q) 2 * 3 * (3*x + 1)^2 * (x^2 - 2) Sage example in ./domaines.tex, line 1642:: sage: R = QQ['x']; R Univariate Polynomial Ring in x over Rational Field sage: q = R(p); q 54*x^4 + 36*x^3 - 102*x^2 - 72*x - 12 sage: factor(q) (54) * (x + 1/3)^2 * (x^2 - 2) Sage example in ./domaines.tex, line 1665:: sage: R = ComplexField(16)['x']; R Univariate Polynomial Ring in x over Complex Field with 16 bits of precision sage: q = R(p); q 54.00*x^4 + 36.00*x^3 - 102.0*x^2 - 72.00*x - 12.00 sage: factor(q) (54.00) * (x - 1.414) * (x + 0.3333)^2 * (x + 1.414) Sage example in ./domaines.tex, line 1685:: sage: R = QQ[sqrt(2)]['x']; R Univariate Polynomial Ring in x over Number Field in sqrt2 with defining polynomial x^2 - 2 with sqrt2 = 1.414213562373095? sage: q = R(p); q 54*x^4 + 36*x^3 - 102*x^2 - 72*x - 12 sage: factor(q) (54) * (x - sqrt2) * (x + sqrt2) * (x + 1/3)^2 Sage example in ./domaines.tex, line 1698:: sage: R = GF(5)['x']; R Univariate Polynomial Ring in x over Finite Field of size 5 sage: q = R(p); q 4*x^4 + x^3 + 3*x^2 + 3*x + 3 sage: factor(q) (4) * (x + 2)^2 * (x^2 + 3) """
[ 2235, 532, 9, 12, 21004, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 1212, 2393, 357, 19571, 27830, 274, 62, 4598, 310, 395, 13, 82, 496, 8, 373, 1635, 2306, 519, 877, 515, 9, 422, 24457, 27830, 274, 13, 16886, 11, 198, ...
2.237533
4,572
from .Deserializer import Deserializer from .RateLimiter import RateLimiter from .Handlers import ( DeprecationHandler, DeserializerAdapter, DictionaryDeserializer, RateLimiterAdapter, ThrowOnErrorHandler, TypeCorrectorHandler, ) from .Handlers.RateLimit import BasicRateLimiter from ._apis import BaseApi from ._apis.riot import AccountApi
[ 6738, 764, 5960, 48499, 7509, 1330, 2935, 48499, 7509, 198, 6738, 764, 32184, 19352, 2676, 1330, 14806, 19352, 2676, 198, 198, 6738, 764, 12885, 8116, 1330, 357, 198, 220, 220, 220, 2129, 8344, 341, 25060, 11, 198, 220, 220, 220, 2935, ...
3.118644
118
# Copyright 1996-2021 Cyberbotics Ltd. # # 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. """Webots GPS device wrapper for ROS2.""" from rclpy.qos import QoSReliabilityPolicy, qos_profile_sensor_data from std_msgs.msg import Float32 from sensor_msgs.msg import NavSatFix, NavSatStatus from geometry_msgs.msg import PointStamped from .sensor_device import SensorDevice from controller import GPS
[ 2, 15069, 8235, 12, 1238, 2481, 15101, 13645, 873, 12052, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, ...
3.630081
246
setlist = [['a','m','n','s','t','g','q','o','x'],['b','e','c'],['h','k','u','v'], ['d','r','p'],['f'],['l'],['i'],['w'],['y']]
[ 2617, 4868, 796, 16410, 6, 64, 41707, 76, 41707, 77, 41707, 82, 41707, 83, 41707, 70, 41707, 80, 41707, 78, 41707, 87, 6, 4357, 17816, 65, 41707, 68, 41707, 66, 6, 4357, 17816, 71, 41707, 74, 41707, 84, 41707, 85, 6, 4357, 198, 17...
1.763889
72
from .player import Player
[ 6738, 764, 7829, 1330, 7853, 198 ]
4.5
6
#!/usr/bin/env python # Nathan Rhoades 10/13/2017 import serial import serialport import bgapi import gui import digicueblue import traceback import time import threading import sys if sys.version_info[0] < 3: import Tkinter as Tk else: import tkinter as Tk if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 18106, 10323, 1170, 274, 838, 14, 1485, 14, 5539, 198, 198, 11748, 11389, 198, 11748, 11389, 634, 198, 11748, 275, 70, 15042, 198, 11748, 11774, 198, 11748, 3100, 291, 518, 175...
2.704348
115
import requests #newspi key c2d941c74c144421945618d97a458144
[ 11748, 7007, 198, 198, 2, 3605, 2777, 72, 1994, 269, 17, 67, 24, 3901, 66, 4524, 66, 1415, 2598, 28896, 29228, 1507, 67, 5607, 64, 29334, 18444, 628 ]
2.25
28
import logging import os import json from multiprocessing import Process, Queue, Lock import numpy as np from PyMaSC.core.mappability import MappableLengthCalculator from PyMaSC.utils.progress import ProgressHook, MultiLineProgressManager from PyMaSC.utils.compatible import tostr, xrange from PyMaSC.utils.output import prepare_outdir from PyMaSC.utils.calc import exec_worker_pool logger = logging.getLogger(__name__)
[ 11748, 18931, 198, 11748, 28686, 198, 11748, 33918, 198, 6738, 18540, 305, 919, 278, 1330, 10854, 11, 4670, 518, 11, 13656, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 9485, 21467, 6173, 13, 7295, 13, 76, 1324, 1799, 1330, ...
3.3
130
from django.shortcuts import render from django.views import View # Create your views here. # Call this with a parameter number # Using inheritance (extend)
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 42625, 14208, 13, 33571, 1330, 3582, 198, 198, 2, 13610, 534, 5009, 994, 13, 198, 220, 220, 220, 220, 198, 2, 4889, 428, 351, 257, 11507, 1271, 198, 198, 2, 8554, 24155, 3...
3.510638
47
from flask import escape '''with open('ex') as full: for line in full: print(line,end='**') ''' ''' a=[] with open('ex') as full: for line in full: a.append(line.split('|')) print(a) ''' ''' with open('ex') as full: for line in full.readline(): print(line) ''' contents=[] with open('ex') as log: for line in log: #contents.append([]) for item in line.split('|'): contents.append(item) print(contents)
[ 6738, 42903, 1330, 6654, 198, 198, 7061, 6, 4480, 1280, 10786, 1069, 11537, 355, 1336, 25, 198, 220, 220, 220, 329, 1627, 287, 1336, 25, 198, 220, 220, 220, 220, 220, 220, 220, 3601, 7, 1370, 11, 437, 11639, 1174, 11537, 198, 7061, ...
2.168182
220
import requests import jsonpickle from requests_oauthlib import OAuth1 from urllib.parse import parse_qs, urlencode import cherrypy from collections import defaultdict import json import os import re from collections import defaultdict # For readable serializations jsonpickle.set_encoder_options('json', sort_keys=True, indent=4) #Local cache caches tokens for different users local_cache = LocalCache() def strip_html(text): """ Get rid of ugly twitter html """ text = reply_to(text) text = text.replace('@', ' ') return " ".join([token for token in text.split() if ('http:' not in token) and ('https:' not in token)]) def post_tweet(user_id, message, additional_params={}): """ Helper function to post a tweet """ url = "https://api.twitter.com/1.1/statuses/update.json" params = { "status" : message } params.update(additional_params) r = make_twitter_request(url, user_id, params, request_type='POST') print (r.text) return "Successfully posted a tweet {}".format(message) def process_tweets(tweet_list): """ Clean tweets and enumerate, preserving only things that we are interested in """ return [Tweet(tweet) for tweet in tweet_list] def make_twitter_request(url, user_id, params={}, request_type='GET'): """ Generically make a request to twitter API using a particular user's authorization """ if request_type == "GET": return requests.get(url, auth=get_twitter_auth(user_id), params=params) elif request_type == "POST": return requests.post(url, auth=get_twitter_auth(user_id), params=params) def geo_search(user_id, search_location): """ Search for a location - free form """ url = "https://api.twitter.com/1.1/geo/search.json" params = {"query" : search_location } response = make_twitter_request(url, user_id, params).json() return response def read_out_tweets(processed_tweets, speech_convertor=None): """ Input - list of processed 'Tweets' output - list of spoken responses """ return ["tweet number {num} by {user}. {text}.".format(num=index+1, user=user, text=text) for index, (user, text) in enumerate(processed_tweets)] def get_retweets_of_me(user_id, input_params={}): """ returns recently retweeted tweets """ url = "https://api.twitter.com/1.1/statuses/retweets_of_me.json" print ("trying to get retweets") return request_tweet_list(url, user_id) def get_my_favourite_tweets(user_id, input_params = {}): """ Returns a user's favourite tweets """ url = "https://api.twitter.com/1.1/favorites/list.json" return request_tweet_list(url, user_id) def search_for_tweets_about(user_id, params): """ Search twitter API """ url = "https://api.twitter.com/1.1/search/tweets.json" response = make_twitter_request(url, user_id, params) return process_tweets(response.json()["statuses"])
[ 11748, 7007, 198, 11748, 33918, 27729, 293, 198, 6738, 7007, 62, 12162, 1071, 8019, 1330, 440, 30515, 16, 198, 6738, 2956, 297, 571, 13, 29572, 1330, 21136, 62, 48382, 11, 2956, 11925, 8189, 198, 11748, 23612, 9078, 220, 198, 6738, 1726...
2.704238
1,109
import json from enum import Enum from decimal import Decimal def convert_serializable_special_cases(o): """ Convert an object to a type that is fairly generally serializable (e.g. json serializable). This only handles the cases that need converting. The json module handles all the rest. For JSON, with json.dump or json.dumps with argument default=convert_serializable. Example: json.dumps(my_animal, indent=4, default=_convert_serializable) :param o: object to be converted to a type that is serializable :return: a serializable representation """ if isinstance(o, Enum): serializable_representation = o.value elif isinstance(o, Decimal): # decimal.Decimal (e.g. in AWS DynamoDB), both integer and floating point if o % 1 == 0: # if representable with an integer, use an integer serializable_representation = int(o) else: # not representable with an integer so use a float serializable_representation = float(o) else: raise NotImplementedError(f"can not serialize {o} since type={type(o)}") return serializable_representation
[ 11748, 33918, 198, 198, 6738, 33829, 1330, 2039, 388, 198, 6738, 32465, 1330, 4280, 4402, 628, 198, 4299, 10385, 62, 46911, 13821, 62, 20887, 62, 33964, 7, 78, 2599, 628, 220, 220, 220, 37227, 198, 220, 220, 220, 38240, 281, 2134, 284...
2.870732
410
import sys import os import argparse import numpy as np import paddle.v2 as paddle import reader import utils import network import config from utils import logger def show_parameter_init_info(parameters): """ Print the information of initialization mean and standard deviation of parameters :param parameters: the parameters created in a model """ logger.info("Parameter init info:") for p in parameters: p_val = parameters.get(p) logger.info(("%-25s : initial_mean=%-7.4f initial_std=%-7.4f " "actual_mean=%-7.4f actual_std=%-7.4f dims=%s") % (p, parameters.__param_conf__[p].initial_mean, parameters.__param_conf__[p].initial_std, p_val.mean(), p_val.std(), parameters.__param_conf__[p].dims)) logger.info("\n") def show_parameter_status(parameters): """ Print some statistical information of parameters in a network :param parameters: the parameters created in a model """ for p in parameters: abs_val = np.abs(parameters.get(p)) abs_grad = np.abs(parameters.get_grad(p)) logger.info( ("%-25s avg_abs_val=%-10.6f max_val=%-10.6f avg_abs_grad=%-10.6f " "max_grad=%-10.6f min_val=%-10.6f min_grad=%-10.6f") % (p, abs_val.mean(), abs_val.max(), abs_grad.mean(), abs_grad.max(), abs_val.min(), abs_grad.min())) if __name__ == "__main__": main()
[ 11748, 25064, 198, 11748, 28686, 198, 11748, 1822, 29572, 198, 11748, 299, 32152, 355, 45941, 198, 198, 11748, 39517, 13, 85, 17, 355, 39517, 198, 198, 11748, 9173, 198, 11748, 3384, 4487, 198, 11748, 3127, 198, 11748, 4566, 198, 6738, ...
2.289231
650
import subprocess import uuid as uuid_gen import logging from datetime import datetime import os import psutil import warnings import weakref from yggdrasil import backwards, tools, platform, serialize from yggdrasil.languages import get_language_dir from yggdrasil.config import ygg_cfg from yggdrasil.drivers.InterpretedModelDriver import InterpretedModelDriver from yggdrasil.tools import TimeOut, sleep logger = logging.getLogger(__name__) try: # pragma: matlab disable_engine = ygg_cfg.get('matlab', 'disable_engine', 'False').lower() if platform._is_win or (disable_engine == 'true'): _matlab_engine_installed = False if not tools.is_subprocess(): logger.debug("matlab.engine disabled") else: import matlab.engine _matlab_engine_installed = True except ImportError: # pragma: no matlab logger.debug("Could not import matlab.engine. " + "Matlab support for using a sharedEngine will be disabled.") _matlab_engine_installed = False _top_lang_dir = get_language_dir('matlab') _compat_map = { 'R2015b': ['2.7', '3.3', '3.4'], 'R2017a': ['2.7', '3.3', '3.4', '3.5'], 'R2017b': ['2.7', '3.3', '3.4', '3.5', '3.6'], 'R2018b': ['2.7', '3.3', '3.4', '3.5', '3.6']} def kill_all(): r"""Kill all Matlab shared engines.""" if platform._is_win: # pragma: windows os.system(('taskkill /F /IM matlab.engine.shareEngine /T')) else: os.system(('pkill -f matlab.engine.shareEngine')) def locate_matlab_engine_processes(): # pragma: matlab r"""Get all of the active matlab sharedEngine processes. Returns: list: Active matlab sharedEngine processes. """ out = [] for p in psutil.process_iter(): p.info = p.as_dict(attrs=['name', 'pid', 'cmdline']) if (((p.info['name'] == 'MATLAB') and ('matlab.engine.shareEngine' in p.info['cmdline']))): out.append(p) # p.info['pid']) return out def is_matlab_running(): r"""Determine if there is a Matlab engine running. Returns: bool: True if there is a Matlab engine running, False otherwise. """ if not _matlab_engine_installed: # pragma: no matlab out = False else: # pragma: matlab out = (len(matlab.engine.find_matlab()) != 0) return out def locate_matlabroot(): # pragma: matlab r"""Find directory that servers as matlab root. Returns: str: Full path to matlabroot directory. """ return MatlabModelDriver.get_matlab_info()[0] def install_matlab_engine(): # pragma: matlab r"""Install the MATLAB engine API for Python.""" if not _matlab_engine_installed: mtl_root = locate_matlabroot() mtl_setup = os.path.join(mtl_root, 'extern', 'engines', 'python') cmd = 'python setup.py install' result = subprocess.check_output(cmd, cwd=mtl_setup) print(result) def start_matlab_engine(skip_connect=False, timeout=None): # pragma: matlab r"""Start a Matlab shared engine session inside a detached screen session. Args: skip_connect (bool, optional): If True, the engine is not connected. Defaults to False. timeout (int, optional): Time (in seconds) that should be waited for Matlab to start up. Defaults to None and is set from the config option ('matlab', 'startup_waittime_s'). Returns: tuple: Information on the started session including the name of the screen session running matlab, the created engine object, the name of the matlab session, and the matlab engine process. Raises: RuntimeError: If Matlab is not installed. """ if not _matlab_engine_installed: # pragma: no matlab raise RuntimeError("Matlab engine is not installed.") if timeout is None: timeout = float(ygg_cfg.get('matlab', 'startup_waittime_s', 10)) old_process = set(locate_matlab_engine_processes()) old_matlab = set(matlab.engine.find_matlab()) screen_session = str('ygg_matlab' + datetime.today().strftime("%Y%j%H%M%S") + '_%d' % len(old_matlab)) try: args = ['screen', '-dmS', screen_session, '-c', os.path.join(_top_lang_dir, 'matlab_screenrc'), 'matlab', '-nodisplay', '-nosplash', '-nodesktop', '-nojvm', '-r', '"matlab.engine.shareEngine"'] subprocess.call(' '.join(args), shell=True) T = TimeOut(timeout) while ((len(set(matlab.engine.find_matlab()) - old_matlab) == 0) and not T.is_out): logger.debug('Waiting for matlab engine to start') sleep(1) # Usually 3 seconds except KeyboardInterrupt: # pragma: debug args = ['screen', '-X', '-S', screen_session, 'quit'] subprocess.call(' '.join(args), shell=True) raise if (len(set(matlab.engine.find_matlab()) - old_matlab) == 0): # pragma: debug raise Exception("start_matlab timed out at %f s" % T.elapsed) new_matlab = list(set(matlab.engine.find_matlab()) - old_matlab)[0] new_process = list(set(locate_matlab_engine_processes()) - old_process)[0] # Connect to the engine matlab_engine = None if not skip_connect: matlab_engine = connect_matlab_engine(new_matlab, first_connect=True) return screen_session, matlab_engine, new_matlab, new_process def connect_matlab_engine(matlab_session, first_connect=False): # pragma: matlab r"""Connect to Matlab engine. Args: matlab_session (str): Name of the Matlab session that should be connected to. first_connect (bool, optional): If True, this is the first time Python is connecting to the Matlab shared engine and certain environment variables should be set. Defaults to False. Returns: MatlabEngine: Matlab engine that was connected. """ matlab_engine = matlab.engine.connect_matlab(matlab_session) matlab_engine.eval('clear classes;', nargout=0) err = backwards.StringIO() try: matlab_engine.eval("YggInterface('YGG_MSG_MAX');", nargout=0, stderr=err) except BaseException: for x in MatlabModelDriver.paths_to_add: matlab_engine.addpath(x, nargout=0) matlab_engine.eval("os = py.importlib.import_module('os');", nargout=0) if not first_connect: if backwards.PY2: matlab_engine.eval("py.reload(os);", nargout=0) else: # matlab_engine.eval("py.importlib.reload(os);", nargout=0) pass return matlab_engine def stop_matlab_engine(screen_session, matlab_engine, matlab_session, matlab_process, keep_engine=False): # pragma: matlab r"""Stop a Matlab shared engine session running inside a detached screen session. Args: screen_session (str): Name of the screen session that the shared Matlab session was started in. matlab_engine (MatlabEngine): Matlab engine that should be stopped. matlab_session (str): Name of Matlab session that the Matlab engine is connected to. matlab_process (psutil.Process): Process running the Matlab shared engine. keep_engine (bool, optional): If True, the references to the engine will be removed so it is not deleted. Defaults to False. Raises: RuntimeError: If Matlab is not installed. """ if not _matlab_engine_installed: # pragma: no matlab raise RuntimeError("Matlab engine is not installed.") if keep_engine and (matlab_engine is not None): if '_matlab' in matlab_engine.__dict__: matlab_engine.quit() return # Remove weakrefs to engine to prevent stopping engine more than once if matlab_engine is not None: # Remove weak references so engine not deleted on exit eng_ref = weakref.getweakrefs(matlab_engine) for x in eng_ref: if x in matlab.engine._engines: matlab.engine._engines.remove(x) # Either exit the engine or remove its reference if matlab_session in matlab.engine.find_matlab(): try: matlab_engine.eval('exit', nargout=0) except BaseException: pass else: # pragma: no cover matlab_engine.__dict__.pop('_matlab', None) # Stop the screen session containing the Matlab shared session if screen_session is not None: if matlab_session in matlab.engine.find_matlab(): os.system(('screen -X -S %s quit') % screen_session) T = TimeOut(5) while ((matlab_session in matlab.engine.find_matlab()) and not T.is_out): logger.debug("Waiting for matlab engine to exit") sleep(1) if (matlab_session in matlab.engine.find_matlab()): # pragma: debug if matlab_process is not None: matlab_process.terminate() logger.error("stop_matlab_engine timed out at %f s. " % T.elapsed + "Killed Matlab sharedEngine process.") def start(self): r"""Start asychronous call.""" self.future = self.target(*self.args, **self.kwargs) def is_started(self): r"""bool: Has start been called.""" return (self.future is not None) def is_cancelled(self): r"""bool: Was the async call cancelled or not.""" if self.is_started(): try: return self.future.cancelled() except matlab.engine.EngineError: self.on_matlab_error() return True except BaseException: return True return False def is_done(self): r"""bool: Is the async call still running.""" if self.is_started(): try: return self.future.done() or self.is_cancelled() except matlab.engine.EngineError: self.on_matlab_error() return True except BaseException: return True return False def is_alive(self): r"""bool: Is the async call funning.""" if self.is_started(): return (not self.is_done()) return False def kill(self, *args, **kwargs): r"""Cancel the async call.""" if self.is_alive(): try: out = self.future.cancel() self.debug("Result of cancelling Matlab call?: %s", out) except matlab.engine.EngineError as e: self.debug('Matlab Engine Error: %s' % e) self.on_matlab_error() except BaseException as e: self.debug('Other error on kill: %s' % e) self.print_output() if self.is_alive(): self.info('Error killing Matlab script.') self.matlab_engine.quit() self.future = None self._returncode = -1 assert(not self.is_alive()) def on_matlab_error(self): r"""Actions performed on error in Matlab engine.""" # self.print_output() self.debug('') if self.matlab_engine is not None: try: self.matlab_engine.eval('exception = MException.last;', nargout=0) self.matlab_engine.eval('getReport(exception)') except matlab.engine.EngineError: pass class MatlabModelDriver(InterpretedModelDriver): # pragma: matlab r"""Base class for running Matlab models. Args: name (str): Driver name. args (str or list): Argument(s) for running the model in matlab. Generally, this should be the full path to a Matlab script. **kwargs: Additional keyword arguments are passed to parent class's __init__ method. Attributes: started_matlab (bool): True if the driver had to start a new matlab engine. False otherwise. screen_session (str): Screen session that Matlab was started in. mlengine (object): Matlab engine used to run script. mlsession (str): Name of the Matlab session that was started. Raises: RuntimeError: If Matlab is not installed. .. note:: Matlab models that call exit will shut down the shared engine. """ _schema_subtype_description = ('Model is written in Matlab.') language = 'matlab' language_ext = '.m' base_languages = ['python'] default_interpreter_flags = ['-nodisplay', '-nosplash', '-nodesktop', '-nojvm', '-batch'] version_flags = ["fprintf('R%s', version('-release')); exit();"] path_env_variable = 'MATLABPATH' comm_linger = (os.environ.get('YGG_MATLAB_ENGINE', '').lower() == 'true') send_converters = {'pandas': serialize.consolidate_array, 'table': serialize.consolidate_array} recv_converters = {'pandas': 'array'} type_map = { 'int': 'intX', 'float': 'single, double', 'string': 'char', 'array': 'cell', 'object': 'containers.Map', 'boolean': 'logical', 'null': 'NaN', 'uint': 'uintX', 'complex': 'complex', 'bytes': 'char (utf-8)', 'unicode': 'char', '1darray': 'mat', 'ndarray': 'mat', 'ply': 'containers.Map', 'obj': 'containers.Map', 'schema': 'containers.Map'} function_param = { 'input': '{channel} = YggInterface(\'YggInput\', \'{channel_name}\');', 'output': '{channel} = YggInterface(\'YggOutput\', \'{channel_name}\');', 'recv': '[{flag_var}, {recv_var}] = {channel}.recv();', 'send': '{flag_var} = {channel}.send({send_var});', 'function_call': '{output_var} = {function_name}({input_var});', 'define': '{variable} = {value};', 'comment': '%', 'true': 'true', 'not': 'not', 'indent': 2 * ' ', 'quote': '\'', 'print': 'disp(\'{message}\');', 'fprintf': 'fprintf(\'{message}\', {variables});', 'error': 'error(\'{error_msg}\');', 'block_end': 'end;', 'if_begin': 'if ({cond})', 'for_begin': 'for {iter_var} = {iter_begin}:{iter_end}', 'while_begin': 'while ({cond})', 'break': 'break;', 'try_begin': 'try', 'try_except': 'catch {error_var}', 'assign': '{name} = {value};'} def parse_arguments(self, args): r"""Sort model arguments to determine which one is the executable and which ones are arguments. Args: args (list): List of arguments provided. """ super(MatlabModelDriver, self).parse_arguments(args) model_base, model_ext = os.path.splitext(os.path.basename(self.model_file)) wrap_base = 'wrapped_%s_%s' % (model_base, self.uuid.replace('-', '_')) # Matlab has a variable name limit of 62 wrap_base = wrap_base[:min(len(wrap_base), 60)] self.model_wrapper = os.path.join(self.model_dir, wrap_base + model_ext) self.wrapper_products.append(self.model_wrapper) def start_matlab_engine(self): r"""Start matlab session and connect to it.""" ml_attr = ['screen_session', 'mlengine', 'mlsession', 'mlprocess'] attempt_connect = (len(matlab.engine.find_matlab()) != 0) # Connect to matlab if a session exists if attempt_connect: for mlsession in matlab.engine.find_matlab(): try: self.debug("Trying to connect to session %s", mlsession) self.mlengine = connect_matlab_engine(mlsession) self.mlsession = mlsession self.debug("Connected to existing shared engine: %s", self.mlsession) break except matlab.engine.EngineError: pass # Start if not running or connect failed if self.mlengine is None: if attempt_connect: self.debug("Starting a matlab shared engine (connect failed)") else: self.debug("Starting a matlab shared engine (none existing)") out = start_matlab_engine() for i, attr in enumerate(ml_attr): setattr(self, attr, out[i]) self.started_matlab = True # Add things to Matlab environment self.mlengine.addpath(self.model_dir, nargout=0) self.debug("Connected to matlab session '%s'" % self.mlsession) def before_start(self): r"""Actions to perform before the run loop.""" kwargs = dict(fname_wrapper=self.model_wrapper) if self.using_matlab_engine: self.start_matlab_engine() kwargs.update(matlab_engine=self.mlengine, no_queue_thread=True) else: kwargs.update(working_dir=self.model_dir) with self.lock: if self.using_matlab_engine and (self.mlengine is None): # pragma: debug self.debug('Matlab engine not set. Stopping') return super(MatlabModelDriver, self).before_start(**kwargs) def run_loop(self): r"""Loop to check if model is still running and forward output.""" if self.using_matlab_engine: self.model_process.print_output() self.periodic_debug('matlab loop', period=100)('Looping') if self.model_process.is_done(): self.model_process.print_output() self.set_break_flag() try: self.model_process.future.result() self.model_process.print_output() except matlab.engine.EngineError: self.model_process.print_output() except BaseException: self.model_process.print_output() self.exception("Error running model.") else: self.sleep() else: super(MatlabModelDriver, self).run_loop() def after_loop(self): r"""Actions to perform after run_loop has finished. Mainly checking if there was an error and then handling it.""" if self.using_matlab_engine: if (self.model_process is not None) and self.model_process.is_alive(): self.info("Model process thread still alive") self.kill_process() return super(MatlabModelDriver, self).after_loop() if self.using_matlab_engine: with self.lock: self.cleanup() def cleanup(self): r"""Close the Matlab session and engine.""" if self.using_matlab_engine: try: stop_matlab_engine(self.screen_session, self.mlengine, self.mlsession, self.mlprocess, keep_engine=(not self.started_matlab)) except (SystemError, Exception) as e: # pragma: debug self.error('Failed to exit matlab engine') self.raise_error(e) self.debug('Stopped Matlab') self.screen_session = None self.mlsession = None self.started_matlab = False self.mlengine = None self.mlprocess = None super(MatlabModelDriver, self).cleanup() def check_exits(self): r"""Check to make sure the program dosn't contain any exits as exits will shut down the Matlab engine as well as the program. Raises: RuntimeError: If there are any exit calls in the file. """ has_exit = False with open(self.raw_model_file, 'r') as fd: for i, line in enumerate(fd): if line.strip().startswith('exit'): has_exit = True break if self.using_matlab_engine and has_exit: warnings.warn( "Line %d in '%s' contains an " % ( i, self.raw_model_file) + "'exit' call which will exit the MATLAB engine " + "such that it cannot be reused. Please replace 'exit' " + "with a return or error.") def set_env(self): r"""Get environment variables that should be set for the model process. Returns: dict: Environment variables for the model process. """ out = super(MatlabModelDriver, self).set_env() if self.using_matlab_engine: out['YGG_MATLAB_ENGINE'] = 'True' # TODO: Move the following to InterpretedModelDriver once another # language sets path_env_variable path_list = [] prev_path = out.pop(self.path_env_variable, '') if prev_path: path_list.append(prev_path) if isinstance(self.paths_to_add, list): for x in self.paths_to_add: if x not in prev_path: path_list.append(x) path_list.append(self.model_dir) if path_list: out[self.path_env_variable] = os.pathsep.join(path_list) return out
[ 11748, 850, 14681, 198, 11748, 334, 27112, 355, 334, 27112, 62, 5235, 198, 11748, 18931, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 11748, 28686, 198, 11748, 26692, 22602, 198, 11748, 14601, 198, 11748, 4939, 5420, 198, 6738, 331, 1130...
2.210165
9,621
# Generated by Django 3.1.3 on 2021-04-09 04:03 import django.db.models.deletion from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 18, 319, 33448, 12, 3023, 12, 2931, 8702, 25, 3070, 198, 198, 11748, 42625, 14208, 13, 9945, 13, 27530, 13, 2934, 1616, 295, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, ...
2.818182
44
import pathlib from typing import Iterator import pandas as pd from ted_sws.resources.prefixes import PREFIXES_DEFINITIONS import re CONCEPTUAL_MAPPINGS_RULES_SHEET_NAME = "Rules" RULES_SF_FIELD_ID = 'Standard Form Field ID (M)' RULES_SF_FIELD_NAME = 'Standard Form Field Name (M)' RULES_E_FORM_BT_ID = 'eForm BT-ID (O)' RULES_E_FORM_BT_NAME = 'eForm BT Name (O)' RULES_BASE_XPATH = 'Base XPath (for anchoring) (M)' RULES_FIELD_XPATH = 'Field XPath (M)' RULES_CLASS_PATH = 'Class path (M)' RULES_PROPERTY_PATH = 'Property path (M)' DEFAULT_RQ_NAME = 'sparql_query_' SPARQL_PREFIX_PATTERN = re.compile('(?:\\s+|^)(\\w+)?:') SPARQL_PREFIX_LINE = 'PREFIX {prefix}: <{value}>' def mapping_suite_processor_generate_sparql_queries(conceptual_mappings_file_path: pathlib.Path, output_sparql_queries_folder_path: pathlib.Path, rq_name: str = DEFAULT_RQ_NAME): """ This function reads data from conceptual_mappings.xlsx and generates SPARQL validation queries in provided package. :param conceptual_mappings_file_path: :param output_sparql_queries_folder_path: :param rq_name: :return: """ with open(conceptual_mappings_file_path, 'rb') as excel_file: conceptual_mappings_rules_df = pd.read_excel(excel_file, sheet_name=CONCEPTUAL_MAPPINGS_RULES_SHEET_NAME) conceptual_mappings_rules_df.columns = conceptual_mappings_rules_df.iloc[0] conceptual_mappings_rules_df = conceptual_mappings_rules_df[1:] conceptual_mappings_rules_df = conceptual_mappings_rules_df[ conceptual_mappings_rules_df[RULES_PROPERTY_PATH].notnull()] sparql_queries = sparql_validation_generator(conceptual_mappings_rules_df) output_sparql_queries_folder_path.mkdir(parents=True, exist_ok=True) for index, sparql_query in enumerate(sparql_queries): output_file_path = output_sparql_queries_folder_path / f"{rq_name}{index}.rq" with open(output_file_path, "w") as output_file: output_file.write(sparql_query)
[ 11748, 3108, 8019, 198, 6738, 19720, 1330, 40806, 1352, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 28501, 62, 2032, 82, 13, 37540, 13, 40290, 274, 1330, 22814, 47084, 1546, 62, 7206, 20032, 2043, 11053, 198, 11748, 302, 198, 198, ...
2.261853
928
import sys from os.path import dirname, abspath, join cur_folder = dirname(abspath(__file__)) sys.path.insert(0, join(dirname(cur_folder), 'src')) sys.path.insert(0, dirname(cur_folder)) print(cur_folder)
[ 11748, 25064, 198, 6738, 28686, 13, 6978, 1330, 26672, 3672, 11, 2352, 6978, 11, 4654, 198, 198, 22019, 62, 43551, 796, 26672, 3672, 7, 397, 2777, 776, 7, 834, 7753, 834, 4008, 198, 17597, 13, 6978, 13, 28463, 7, 15, 11, 4654, 7, ...
2.662338
77
# https://stackoverflow.com/questions/3300464/how-can-i-get-dict-from-sqlite-query # from flask import Flask from flask_restful import Resource, reqparse from src.model.serie import SerieModel from src.server.instance import server from db import db # books_db = [{"id": 0, "title": "War and Peace"}, {"id": 1, "title": "Clean Code"}] api = server.api
[ 2, 3740, 1378, 25558, 2502, 11125, 13, 785, 14, 6138, 507, 14, 2091, 22914, 2414, 14, 4919, 12, 5171, 12, 72, 12, 1136, 12, 11600, 12, 6738, 12, 25410, 578, 12, 22766, 198, 198, 2, 422, 42903, 1330, 46947, 198, 6738, 42903, 62, 21...
3.033898
118
import copy import pickle import tcod
[ 11748, 4866, 198, 11748, 2298, 293, 198, 198, 11748, 256, 19815, 628, 628 ]
3.230769
13
############################################################################## # # Copyright (c) 2006 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Viewlet. """ import os import zope.viewlet.viewlet from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile def SimpleViewletClass(template, bases=(), attributes=None, name=''): """A function that can be used to generate a viewlet from a set of information. """ # Create the base class hierarchy bases += (simple, ViewletBase) attrs = {'index': ViewPageTemplateFile(template), '__name__': name} if attributes: attrs.update(attributes) # Generate a derived view class. class_ = type("SimpleViewletClass from %s" % template, bases, attrs) return class_ def JavaScriptViewlet(path): """Create a viewlet that can simply insert a javascript link.""" src = os.path.join(os.path.dirname(__file__), 'javascript_viewlet.pt') klass = type('JavaScriptViewlet', (ResourceViewletBase, ViewletBase), {'index': ViewPageTemplateFile(src), '_path': path}) return klass def CSSViewlet(path, media="all", rel="stylesheet"): """Create a viewlet that can simply insert a javascript link.""" src = os.path.join(os.path.dirname(__file__), 'css_viewlet.pt') klass = type('CSSViewlet', (CSSResourceViewletBase, ViewletBase), {'index': ViewPageTemplateFile(src), '_path': path, '_media': media, '_rel': rel}) return klass
[ 29113, 29113, 7804, 4242, 2235, 198, 2, 198, 2, 15069, 357, 66, 8, 4793, 1168, 3008, 5693, 290, 25767, 669, 13, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 770, 3788, 318, 2426, 284, 262, 8617, 286, 262, 1168, 3008, 5094, 13789...
2.849727
732
#Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). #If d(a) = b and d(b) = a, where a b, then a and b are an amicable pair and each of a and b are called amicable numbers. #For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. #Evaluate the sum of all the amicable numbers under 10000. import euler print euler.get_divisors(284) print sum(euler.get_divisors(284)) limit=10000 perc=5 step=perc*limit/100 cp=0 a=1 amics=[] print "Starting..." for a in range(1,limit+1): b=d(a) if a==d(b) and a!=b: print "Pair:" + str(a) + " and " + str(b) if (a not in amics): amics.append(a) if (b not in amics): amics.append(b) print "Sum of amicables:" print sum(amics)
[ 2, 5756, 288, 7, 77, 8, 307, 5447, 355, 262, 2160, 286, 1774, 2659, 271, 669, 286, 299, 357, 77, 17024, 1342, 621, 299, 543, 14083, 21894, 656, 299, 737, 198, 2, 1532, 288, 7, 64, 8, 796, 275, 290, 288, 7, 65, 8, 796, 257, 1...
2.401099
364
#!/usr/bin/env python3 """Unpack a MIME message into a directory of files.""" import os import email import mimetypes from email.policy import default from argparse import ArgumentParser if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 37811, 3118, 8002, 257, 337, 12789, 3275, 656, 257, 8619, 286, 3696, 526, 15931, 198, 198, 11748, 28686, 198, 11748, 3053, 198, 11748, 17007, 2963, 12272, 198, 198, 6738, 3053, ...
3.178082
73
import sys, os import logging import datetime module_name = 'Streetview_Module' debug_mode = True
[ 11748, 25064, 11, 28686, 198, 11748, 18931, 198, 11748, 4818, 8079, 198, 198, 21412, 62, 3672, 796, 705, 34356, 1177, 62, 26796, 6, 198, 24442, 62, 14171, 796, 6407, 198 ]
3.3
30
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' from tkinter import * root = Tk() root.title('Chess board') canvas = Canvas(root, width=700, height=700, bg='#fff') canvas.pack() fill = '#fff' outline = '#000' size = 88 for i in range(8): for j in range(8): x1, y1, x2, y2 = i * size, j * size, i * size + size, j * size + size canvas.create_rectangle(x1, y1, x2, y2, fill=fill, outline=outline) fill, outline = outline, fill fill, outline = outline, fill root.mainloop()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 834, 9800, 834, 796, 705, 541, 21879, 1077, 6, 628, 198, 6738, 256, 74, 3849, 1330, 1635, 198, 198, 15763, ...
2.261603
237
# asandbox.py # # Authors: # - Coumes Quentin <coumes.quentin@gmail.com> """An asynchronous implementation of the Sandbox API.""" import io import json import os from contextlib import AbstractAsyncContextManager from typing import BinaryIO, Optional, Union import aiohttp from .exceptions import status_exceptions from .utils import ENDPOINTS
[ 2, 355, 392, 3524, 13, 9078, 198, 2, 198, 2, 46665, 25, 198, 2, 220, 220, 532, 15062, 6880, 42447, 1279, 66, 280, 6880, 13, 421, 31371, 31, 14816, 13, 785, 29, 628, 198, 37811, 2025, 39354, 7822, 286, 262, 3837, 3524, 7824, 526, ...
3.45098
102
import datetime from uuid import UUID from api.actions import storage from fastapi import HTTPException from api.models.usuario import Usuario from starlette.requests import Request from api.dependencies import validar_email, validar_formato_fecha,validar_edad FORMATO_FECHA = "%Y-%m-%d" EDAD_MINIMA = 18 EDAD_MAXIMA = 100
[ 11748, 4818, 8079, 198, 6738, 334, 27112, 1330, 471, 27586, 198, 6738, 40391, 13, 4658, 1330, 6143, 198, 6738, 3049, 15042, 1330, 14626, 16922, 198, 6738, 40391, 13, 27530, 13, 385, 84, 4982, 1330, 471, 2385, 4982, 198, 6738, 3491, 2134...
2.936364
110
import os import logging import dateutil import pickle from six.moves.urllib.parse import urlparse from libtaxii import get_message_from_http_response, VID_TAXII_XML_11 from libtaxii.messages_11 import PollRequest, PollFulfillmentRequest from libtaxii.messages_11 import PollResponse, generate_message_id from libtaxii.clients import HttpClient from certau import version_string def poll(self, poll_url, collection, subscription_id=None, begin_timestamp=None, end_timestamp=None, state_file=None): """Send the TAXII poll request to the server using the given URL.""" # Parse the poll_url to get the parts required by libtaxii url_parts = urlparse(poll_url) # Allow credentials to be provided in poll_url if url_parts.username and url_parts.password: self.username = url_parts.username self.password = url_parts.password self._logger.debug('updating username and password from poll_url') if url_parts.scheme not in ['http', 'https']: raise Exception('invalid scheme in poll_url (%s); expected ' '"http" or "https"', poll_url) use_ssl = True if url_parts.scheme == 'https' else False # Initialise the authentication settings self.setup_authentication(use_ssl) if state_file and not begin_timestamp: begin_timestamp = self.get_poll_time( filename=state_file, poll_url=poll_url, collection=collection, ) request = self.create_poll_request( collection=collection, subscription_id=subscription_id, begin_timestamp=begin_timestamp, end_timestamp=end_timestamp, ) self._logger.debug('sending poll request (url=%s, collection=%s)', poll_url, collection) response = self.send_taxii_message( request=request, host=url_parts.hostname, path=url_parts.path, port=url_parts.port, ) first = True poll_end_time = None while True: if not isinstance(response, PollResponse): raise Exception('didn\'t get a poll response') self._logger.debug('received poll response ' '(content_blocks=%d, result_id=%s, more=%s)', len(response.content_blocks), response.result_id, 'True' if response.more else 'False') # Save end timestamp from first PollResponse if first: poll_end_time = response.inclusive_end_timestamp_label if len(response.content_blocks) == 0: if first: self._logger.info('poll response contained ' 'no content blocks') break for content_block in response.content_blocks: yield content_block if not response.more: break # Send a fulfilment request if first: # Initialise fulfilment request values part_number = response.result_part_number result_id = response.result_id first = False part_number += 1 request = self.create_fulfillment_request( collection=collection, result_id=result_id, part_number=part_number, ) self._logger.debug('sending fulfilment request ' '(result_id=%s, part_number=%d)', result_id, part_number) response = self.send_taxii_message( request=request, host=url_parts.hostname, path=url_parts.path, port=url_parts.port, ) # Update the timestamp for the latest poll if state_file and poll_end_time: self.save_poll_time( filename=state_file, poll_url=poll_url, collection=collection, timestamp=poll_end_time, )
[ 11748, 28686, 198, 11748, 18931, 198, 11748, 3128, 22602, 198, 11748, 2298, 293, 198, 198, 6738, 2237, 13, 76, 5241, 13, 333, 297, 571, 13, 29572, 1330, 19016, 29572, 198, 198, 6738, 9195, 19290, 4178, 1330, 651, 62, 20500, 62, 6738, ...
2.027053
2,107
import os import zipfile import requests DATA_PATH = './data' RESULT_PATH = './result' if not os.path.exists(DATA_PATH): os.makedirs(DATA_PATH) print('Downloading and extracting data...') url = 'https://weisslab.cs.ucl.ac.uk/WEISSTeaching/datasets/-/archive/hn2dct/datasets-hn2dct.zip' r = requests.get(url,allow_redirects=True) temp_file = 'temp.zip' _ = open(temp_file,'wb').write(r.content) with zipfile.ZipFile(temp_file,'r') as zip_obj: zip_obj.extractall(DATA_PATH) os.remove(temp_file) print('Done.') print('Head-neck 2D CT data downloaded: %s' % os.path.abspath(os.path.join(DATA_PATH,'datasets-hn2dct'))) if not os.path.exists(RESULT_PATH): os.makedirs(RESULT_PATH) print('Result directory created: %s' % os.path.abspath(RESULT_PATH))
[ 198, 11748, 28686, 198, 11748, 19974, 7753, 198, 11748, 7007, 628, 198, 26947, 62, 34219, 796, 705, 19571, 7890, 6, 198, 19535, 16724, 62, 34219, 796, 705, 19571, 20274, 6, 198, 198, 361, 407, 28686, 13, 6978, 13, 1069, 1023, 7, 26947...
2.43038
316
import doctest from insights.parsers import freeipa_healthcheck_log from insights.parsers.freeipa_healthcheck_log import FreeIPAHealthCheckLog from insights.tests import context_wrap LONG_FREEIPA_HEALTHCHECK_LOG_OK = """ [{"source": "ipahealthcheck.ipa.roles", "check": "IPACRLManagerCheck", "result": "SUCCESS", "uuid": "1f4177a4-0ddb-4e4d-8258-a5cd5f4638fc", "when": "20191203122317Z", "duration": "0.002254", "kw": {"key": "crl_manager", "crlgen_enabled": true}}] """.strip() LONG_FREEIPA_HEALTHCHECK_LOG_FAILURES = """ [{"source": "ipahealthcheck.system.filesystemspace", "check": "FileSystemSpaceCheck", "result": "ERROR", "uuid": "90ed8765-6ad7-425c-abbd-b07a652649cb", "when": "20191203122221Z", "duration": "0.000474", "kw": { "msg": "/var/log/audit/: free space under threshold: 14 MiB < 512 MiB", "store": "/var/log/audit/", "free_space": 14, "threshold": 512}}] """.strip() FREEIPA_HEALTHCHECK_LOG_DOCS_EXAMPLE = ''' [ { "source": "ipahealthcheck.ipa.roles", "check": "IPACRLManagerCheck", "result": "SUCCESS", "uuid": "1f4177a4-0ddb-4e4d-8258-a5cd5f4638fc", "when": "20191203122317Z", "duration": "0.002254", "kw": { "key": "crl_manager", "crlgen_enabled": true } }, { "source": "ipahealthcheck.ipa.roles", "check": "IPARenewalMasterCheck", "result": "SUCCESS", "uuid": "1feb7f99-2e98-4e37-bb52-686896972022", "when": "20191203122317Z", "duration": "0.018330", "kw": { "key": "renewal_master", "master": true } }, { "source": "ipahealthcheck.system.filesystemspace", "check": "FileSystemSpaceCheck", "result": "ERROR", "uuid": "90ed8765-6ad7-425c-abbd-b07a652649cb", "when": "20191203122221Z", "duration": "0.000474", "kw": { "msg": "/var/log/audit/: free space under threshold: 14 MiB < 512 MiB", "store": "/var/log/audit/", "free_space": 14, "threshold": 512 } } ] '''.strip() FREEIPA_HEALTHCHECK_LOG_OK = "".join(LONG_FREEIPA_HEALTHCHECK_LOG_OK.splitlines()) FREEIPA_HEALTHCHECK_LOG_FAILURES = "".join(LONG_FREEIPA_HEALTHCHECK_LOG_FAILURES.splitlines())
[ 11748, 10412, 395, 198, 6738, 17218, 13, 79, 945, 364, 1330, 1479, 541, 64, 62, 13948, 9122, 62, 6404, 198, 6738, 17218, 13, 79, 945, 364, 13, 5787, 541, 64, 62, 13948, 9122, 62, 6404, 1330, 3232, 4061, 32, 18081, 9787, 11187, 198, ...
2.027361
1,133
# Copyright 2021 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. from recipe_engine import post_process from PB.recipes.infra.windows_image_builder import windows_image_builder as wib from PB.recipes.infra.windows_image_builder import actions from PB.recipes.infra.windows_image_builder import sources from recipe_engine.post_process import DropExpectation, StatusSuccess from RECIPE_MODULES.infra.windows_scripts_executor import test_helper as t DEPS = [ 'depot_tools/gitiles', 'recipe_engine/platform', 'recipe_engine/properties', 'recipe_engine/raw_io', 'recipe_engine/json', 'windows_adk', 'windows_scripts_executor', ] PYTHON_VERSION_COMPATIBILITY = 'PY3' PROPERTIES = wib.Image def RunSteps(api, image): """ This recipe executes offline_winpe_customization.""" if not api.platform.is_win: raise AssertionError('This recipe can only run on windows') # this recipe will only execute the offline winpe customizations for cust in image.customizations: assert (cust.WhichOneof('customization') == 'offline_winpe_customization') # initialize the image to scripts executor api.windows_scripts_executor.init() custs = api.windows_scripts_executor.init_customizations(image) # pinning all the refs and generating unique keys custs = api.windows_scripts_executor.process_customizations(custs) # download all the required refs api.windows_scripts_executor.download_all_packages(custs) # download and install the windows ADK and WinPE packages api.windows_adk.ensure() # execute the customizations given api.windows_scripts_executor.execute_customizations(custs) wpe_image = 'wpe_image' wpe_cust = 'generic' arch = 'x86' key = '9055a3e678be47d58bb860d27b85adbea41fd2ef3e22c5b7cb3180edf358de90'
[ 2, 15069, 33448, 383, 18255, 1505, 46665, 13, 1439, 2489, 10395, 13, 198, 2, 5765, 286, 428, 2723, 2438, 318, 21825, 416, 257, 347, 10305, 12, 7635, 5964, 326, 460, 307, 198, 2, 1043, 287, 262, 38559, 24290, 2393, 13, 198, 198, 6738...
3.004823
622
from lollangCompiler.compiler import Compiler import argparse if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--file", required=True, help=" .") parser.add_argument("--out", default="out.py", help=" ") args = parser.parse_args() cmp = Compiler() cmp.compileFile(args.file, args.out)
[ 6738, 300, 692, 648, 7293, 5329, 13, 5589, 5329, 1330, 3082, 5329, 198, 11748, 1822, 29572, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 30751, 796, 1822, 29572, 13, 28100, 1713, 46677, 3419, ...
2.674419
129
import logging import subprocess import xml.etree.ElementTree as ET from tqdm import tqdm logger = logging.getLogger('root') POST_TYPE_QUESTION = '1' POST_TYPE_ANSWER = '2'
[ 11748, 18931, 198, 11748, 850, 14681, 198, 11748, 35555, 13, 316, 631, 13, 20180, 27660, 355, 12152, 198, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 628, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 10786, 15763, 11537, 198...
2.78125
64
# -*- coding: utf-8 -*- # Copyright 2020 Green Valley Belgium NV # # 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. # # @@license_version:1.7@@ from google.appengine.api import users as gusers from mcfw.cache import CachedModelMixIn from mcfw.consts import MISSING from mcfw.restapi import register_postcall_hook, INJECTED_FUNCTIONS from mcfw.rpc import serialize_value, get_type_details from rogerthat.rpc import users from rogerthat.utils import OFFLOAD_TYPE_WEB, offload from rogerthat.utils.transactions import on_trans_committed dummy = lambda: None register_postcall_hook(log_restapi_call_result) INJECTED_FUNCTIONS.get_current_session = users.get_current_session del log_restapi_call_result CachedModelMixIn.on_trans_committed = lambda self, f, *args, **kwargs: on_trans_committed(f, *args, **kwargs)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 12131, 3469, 6916, 15664, 23973, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, ...
3.22113
407
""" This script adds tables needed for Galaxy cloud functionality. """ from __future__ import print_function import datetime import logging from sqlalchemy import Boolean, Column, DateTime, ForeignKey, Integer, MetaData, Table, TEXT now = datetime.datetime.utcnow log = logging.getLogger( __name__ ) metadata = MetaData() CloudImage_table = Table( "cloud_image", metadata, Column( "id", Integer, primary_key=True ), Column( "create_time", DateTime, default=now ), Column( "update_time", DateTime, default=now, onupdate=now ), Column( "provider_type", TEXT ), Column( "image_id", TEXT, nullable=False ), Column( "manifest", TEXT ), Column( "state", TEXT ), Column( "architecture", TEXT ), Column( "deleted", Boolean, default=False ) ) """ UserConfiguredInstance (UCI) table """ UCI_table = Table( "cloud_uci", metadata, Column( "id", Integer, primary_key=True ), Column( "create_time", DateTime, default=now ), Column( "update_time", DateTime, default=now, onupdate=now ), Column( "user_id", Integer, ForeignKey( "galaxy_user.id" ), index=True, nullable=False ), Column( "credentials_id", Integer, ForeignKey( "cloud_user_credentials.id" ), index=True ), Column( "key_pair_name", TEXT ), Column( "key_pair_material", TEXT ), Column( "name", TEXT ), Column( "state", TEXT ), Column( "error", TEXT ), Column( "total_size", Integer ), Column( "launch_time", DateTime ), Column( "deleted", Boolean, default=False ) ) CloudInstance_table = Table( "cloud_instance", metadata, Column( "id", Integer, primary_key=True ), Column( "create_time", DateTime, default=now ), Column( "update_time", DateTime, default=now, onupdate=now ), Column( "launch_time", DateTime ), Column( "stop_time", DateTime ), Column( "user_id", Integer, ForeignKey( "galaxy_user.id" ), index=True, nullable=False ), Column( "uci_id", Integer, ForeignKey( "cloud_uci.id" ), index=True ), Column( "type", TEXT ), Column( "reservation_id", TEXT ), Column( "instance_id", TEXT ), Column( "mi_id", Integer, ForeignKey( "cloud_image.id" ), index=True ), Column( "state", TEXT ), Column( "error", TEXT ), Column( "public_dns", TEXT ), Column( "private_dns", TEXT ), Column( "security_group", TEXT ), Column( "availability_zone", TEXT ) ) CloudStore_table = Table( "cloud_store", metadata, Column( "id", Integer, primary_key=True ), Column( "create_time", DateTime, default=now ), Column( "update_time", DateTime, default=now, onupdate=now ), Column( "attach_time", DateTime ), Column( "user_id", Integer, ForeignKey( "galaxy_user.id" ), index=True, nullable=False ), Column( "uci_id", Integer, ForeignKey( "cloud_uci.id" ), index=True, nullable=False ), Column( "volume_id", TEXT ), Column( "size", Integer, nullable=False ), Column( "availability_zone", TEXT ), Column( "inst_id", Integer, ForeignKey( "cloud_instance.id" ) ), Column( "status", TEXT ), Column( "device", TEXT ), Column( "space_consumed", Integer ), Column( "error", TEXT ), Column( "deleted", Boolean, default=False ) ) CloudSnapshot_table = Table( "cloud_snapshot", metadata, Column( "id", Integer, primary_key=True ), Column( "create_time", DateTime, default=now ), Column( "update_time", DateTime, default=now, onupdate=now ), Column( "user_id", Integer, ForeignKey( "galaxy_user.id" ), index=True, nullable=False ), Column( "uci_id", Integer, ForeignKey( "cloud_uci.id" ), index=True ), Column( "store_id", Integer, ForeignKey( "cloud_store.id" ), index=True, nullable=False ), Column( "snapshot_id", TEXT ), Column( "status", TEXT ), Column( "description", TEXT ), Column( "error", TEXT ), Column( "deleted", Boolean, default=False ) ) CloudUserCredentials_table = Table( "cloud_user_credentials", metadata, Column( "id", Integer, primary_key=True ), Column( "create_time", DateTime, default=now ), Column( "update_time", DateTime, default=now, onupdate=now ), Column( "user_id", Integer, ForeignKey( "galaxy_user.id" ), index=True, nullable=False ), Column( "provider_id", Integer, ForeignKey( "cloud_provider.id" ), index=True, nullable=False ), Column( "name", TEXT ), Column( "access_key", TEXT ), Column( "secret_key", TEXT ), Column( "deleted", Boolean, default=False ) ) CloudProvider_table = Table( "cloud_provider", metadata, Column( "id", Integer, primary_key=True ), Column( "create_time", DateTime, default=now ), Column( "update_time", DateTime, default=now, onupdate=now ), Column( "user_id", Integer, ForeignKey( "galaxy_user.id" ), index=True, nullable=False ), Column( "type", TEXT, nullable=False ), Column( "name", TEXT ), Column( "region_connection", TEXT ), Column( "region_name", TEXT ), Column( "region_endpoint", TEXT ), Column( "is_secure", Boolean ), Column( "host", TEXT ), Column( "port", Integer ), Column( "proxy", TEXT ), Column( "proxy_port", TEXT ), Column( "proxy_user", TEXT ), Column( "proxy_pass", TEXT ), Column( "debug", Integer ), Column( "https_connection_factory", TEXT ), Column( "path", TEXT ), Column( "deleted", Boolean, default=False ) )
[ 37811, 198, 1212, 4226, 6673, 8893, 2622, 329, 9252, 6279, 11244, 13, 198, 37811, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 4818, 8079, 198, 11748, 18931, 198, 198, 6738, 44161, 282, 26599, 1330, 41146, 11, 29...
1.846645
4,069
# -*- encoding: utf-8 -*- """ Copyright (c) 2021 ronyman.com """ from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from apps.user import views as user_views from.views import EditProfilePage urlpatterns = [ #User path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('login/', auth_views.LoginView.as_view(template_name='registration/login.html'), name='login'), path('profile/', user_views.profile, name='profile'), path('edit_profile/', user_views.edit_profile, name='edit_profile'), path("myprofile/", user_views.myprofile, name="Myprofile"), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), #path('tinymce/', include('tinymce.urls')), path('edit_profile_page/', user_views.EditProfilePage.as_view(template_name='registration/edit_profile_page.html'), name='edit_profile_page'), # For PasswordPresset path('admin/password_reset/',auth_views.PasswordResetView.as_view(),name='admin_password_reset',), path('admin/password_reset/done/',auth_views.PasswordResetDoneView.as_view(),name='password_reset_done',), path('reset/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(),name='password_reset_confirm',), path('reset/done/',auth_views.PasswordResetCompleteView.as_view(),name='password_reset_complete',), ]
[ 2, 532, 9, 12, 21004, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 15269, 357, 66, 8, 33448, 374, 1647, 805, 13, 785, 198, 37811, 198, 198, 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 42625, 14208, 13, 3642, ...
2.913958
523
# Generated by Django 2.0.3 on 2018-09-14 12:42 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 362, 13, 15, 13, 18, 319, 2864, 12, 2931, 12, 1415, 1105, 25, 3682, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
#! /usr/bin/env python import cv2 import matplotlib.pyplot as plt import skimage import skimage.io from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure from matplotlib.pyplot import cm from mpl_toolkits.axes_grid1 import make_axes_locatable from numpy import arange, array, newaxis, tile, linspace, pad, expand_dims, \ fromstring, ceil, dtype, float32, sqrt, dot, zeros from misc import WithTimer def norm01c(arr, center): '''Maps the input range to [0,1] such that the center value maps to .5''' arr = arr.copy() arr -= center arr /= max(2 * arr.max(), -2 * arr.min()) + 1e-10 arr += .5 assert arr.min() >= 0 assert arr.max() <= 1 return arr def norm0255(arr): '''Maps the input range to [0,255] as dtype uint8''' arr = arr.copy() arr -= arr.min() arr *= 255.0 / (arr.max() + 1e-10) arr = array(arr, 'uint8') return arr def cv2_read_file_rgb(filename): '''Reads an image from file. Always returns (x,y,3)''' im = cv2.imread(filename) if len(im.shape) == 2: # Upconvert single channel grayscale to color im = im[:, :, newaxis] if im.shape[2] == 1: im = tile(im, (1, 1, 3)) if im.shape[2] > 3: # Chop off transparency im = im[:, :, :3] return cv2.cvtColor(im, cv2.COLOR_BGR2RGB) # Convert native OpenCV BGR -> RGB def caffe_load_image(filename, color=True, as_uint=False): ''' Copied from Caffe to simplify potential import problems. Load an image converting from grayscale or alpha as needed. Take filename: string color: flag for color format. True (default) loads as RGB while False loads as intensity (if image is already grayscale). Give image: an image with type float32 in range [0, 1] of size (H x W x 3) in RGB or of size (H x W x 1) in grayscale. ''' with WithTimer('imread', quiet=True): if as_uint: img = skimage.io.imread(filename) else: img = skimage.img_as_float(skimage.io.imread(filename)).astype(float32) if img.ndim == 2: img = img[:, :, newaxis] if color: img = tile(img, (1, 1, 3)) elif img.shape[2] == 4: img = img[:, :, :3] return img def get_tiles_height_width(n_tiles, desired_width=None): '''Get a height x width size that will fit n_tiles tiles.''' if desired_width == None: # square width = int(ceil(sqrt(n_tiles))) height = width else: assert isinstance(desired_width, int) width = desired_width height = int(ceil(float(n_tiles) / width)) return height, width def get_tiles_height_width_ratio(n_tiles, width_ratio=1.0): '''Get a height x width size that will fit n_tiles tiles.''' width = int(ceil(sqrt(n_tiles * width_ratio))) return get_tiles_height_width(n_tiles, desired_width=width) def to_255(vals_01): '''Convert vals in [0,1] to [0,255]''' try: ret = [v * 255 for v in vals_01] if type(vals_01) is tuple: return tuple(ret) else: return ret except TypeError: # Not iterable (single int or float) return vals_01 * 255 def ensure_uint255(arr): '''If data is float, multiply by 255 and convert to uint8. Else leave as uint8.''' if arr.dtype == 'uint8': return arr elif arr.dtype in ('float32', 'float64'): # print 'extra check...' # assert arr.max() <= 1.1 return array(arr * 255, dtype='uint8') else: raise Exception('ensure_uint255 expects uint8 or float input but got %s with range [%g,%g,].' % ( arr.dtype, arr.min(), arr.max())) def ensure_float01(arr, dtype_preference='float32'): '''If data is uint, convert to float and divide by 255. Else leave at float.''' if arr.dtype == 'uint8': # print 'extra check...' # assert arr.max() <= 256 return array(arr, dtype=dtype_preference) / 255 elif arr.dtype in ('float32', 'float64'): return arr else: raise Exception('ensure_float01 expects uint8 or float input but got %s with range [%g,%g,].' % ( arr.dtype, arr.min(), arr.max())) def resize_to_fit(img, out_max_shape, dtype_out=None, shrink_interpolation=cv2.INTER_LINEAR, grow_interpolation=cv2.INTER_NEAREST): '''Resizes to fit within out_max_shape. If ratio is different, returns an image that fits but is smaller along one of the two dimensions. If one of the out_max_shape dimensions is None, then use only the other dimension to perform resizing. Timing info on MBP Retina with OpenBlas: - conclusion: uint8 is always tied or faster. float64 is slower. Scaling down: In [79]: timeit.Timer('resize_to_fit(aa, (200,200))', setup='from kerasvis.app import resize_to_fit; import numpy as np; aa = array(np.random.uniform(0,255,(1000,1000,3)), dtype="uint8")').timeit(100) Out[79]: 0.04950380325317383 In [77]: timeit.Timer('resize_to_fit(aa, (200,200))', setup='from kerasvis.app import resize_to_fit; import numpy as np; aa = array(np.random.uniform(0,255,(1000,1000,3)), dtype="float32")').timeit(100) Out[77]: 0.049156904220581055 In [76]: timeit.Timer('resize_to_fit(aa, (200,200))', setup='from kerasvis.app import resize_to_fit; import numpy as np; aa = array(np.random.uniform(0,255,(1000,1000,3)), dtype="float64")').timeit(100) Out[76]: 0.11808204650878906 Scaling up: In [68]: timeit.Timer('resize_to_fit(aa, (2000,2000))', setup='from kerasvis.app import resize_to_fit; import numpy as np; aa = array(np.random.uniform(0,255,(1000,1000,3)), dtype="uint8")').timeit(100) Out[68]: 0.4357950687408447 In [70]: timeit.Timer('resize_to_fit(aa, (2000,2000))', setup='from kerasvis.app import resize_to_fit; import numpy as np; aa = array(np.random.uniform(0,255,(1000,1000,3)), dtype="float32")').timeit(100) Out[70]: 1.3411099910736084 In [73]: timeit.Timer('resize_to_fit(aa, (2000,2000))', setup='from kerasvis.app import resize_to_fit; import numpy as np; aa = array(np.random.uniform(0,255,(1000,1000,3)), dtype="float64")').timeit(100) Out[73]: 2.6078310012817383 ''' if dtype_out is not None and img.dtype != dtype_out: dtype_in_size = img.dtype.itemsize dtype_out_size = dtype(dtype_out).itemsize convert_early = (dtype_out_size < dtype_in_size) convert_late = not convert_early else: convert_early = False convert_late = False if img.shape[0] == 0 and img.shape[1] == 0: scale = 1 elif out_max_shape[0] is None or img.shape[0] == 0: scale = float(out_max_shape[1]) / img.shape[1] elif out_max_shape[1] is None or img.shape[1] == 0: scale = float(out_max_shape[0]) / img.shape[0] else: scale = min(float(out_max_shape[0]) / img.shape[0], float(out_max_shape[1]) / img.shape[1]) if convert_early: img = array(img, dtype=dtype_out) out = cv2.resize(img, (int(img.shape[1] * scale), int(img.shape[0] * scale)), # in (c,r) order interpolation=grow_interpolation if scale > 1 else shrink_interpolation) if convert_late: out = array(out, dtype=dtype_out) return out def cv2_typeset_text(data, lines, loc, between=' ', string_spacing=0, line_spacing=0, wrap=False): '''Typesets mutliple strings on multiple lines of text, where each string may have its own formatting. Given: data: as in cv2.putText loc: as in cv2.putText lines: list of lists of FormattedString objects, may be modified by this function! between: what to insert between each string on each line, ala str.join string_spacing: extra spacing to insert between strings on a line line_spacing: extra spacing to insert between lines wrap: if true, wraps words to next line Returns: locy: new y location = loc[1] + y-offset resulting from lines of text ''' data_width = data.shape[1] # lines_modified = False # lines = lines_in # will be deepcopied if modification is needed later if isinstance(lines, FormattedString): lines = [lines] assert isinstance(lines, list), 'lines must be a list of lines or list of FormattedString objects or a single FormattedString object' if len(lines) == 0: return loc[1] if not isinstance(lines[0], list): # If a single line of text is given as a list of strings, convert to multiline format lines = [lines] locy = loc[1] line_num = 0 while line_num < len(lines): line = lines[line_num] maxy = 0 locx = loc[0] for ii, fs in enumerate(line): last_on_line = (ii == len(line) - 1) if not last_on_line: fs.string += between boxsize, _ = cv2.getTextSize(fs.string, fs.face, fs.fsize, fs.thick) if fs.width is not None: if fs.align == 'right': locx += fs.width - boxsize[0] elif fs.align == 'center': locx += (fs.width - boxsize[0]) / 2 # print 'right boundary is', locx + boxsize[0], '(%s)' % fs.string # print 'HERE' right_edge = locx + boxsize[0] if wrap and ii > 0 and right_edge > data_width: # Wrap rest of line to the next line # if not lines_modified: # lines = deepcopy(lines_in) # lines_modified = True new_this_line = line[:ii] new_next_line = line[ii:] lines[line_num] = new_this_line lines.insert(line_num + 1, new_next_line) break ###line_num += 1 ###continue cv2.putText(data, fs.string, (locx, locy), fs.face, fs.fsize, fs.clr, fs.thick) maxy = max(maxy, boxsize[1]) if fs.width is not None: if fs.align == 'right': locx += boxsize[0] elif fs.align == 'left': locx += fs.width elif fs.align == 'center': locx += fs.width - (fs.width - boxsize[0]) / 2 else: locx += boxsize[0] locx += string_spacing line_num += 1 locy += maxy + line_spacing return locy def saveimage(filename, im): '''Saves an image with pixel values in [0,1]''' # matplotlib.image.imsave(filename, im) if len(im.shape) == 3: # Reverse RGB to OpenCV BGR order for color images cv2.imwrite(filename, 255 * im[:, :, ::-1]) else: cv2.imwrite(filename, 255 * im)
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 269, 85, 17, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 1341, 9060, 198, 11748, 1341, 9060, 13, 952, 198, 6738, 2603, 29487, 8019, 13, 18...
2.224531
4,908
import pygame.font import copy
[ 11748, 12972, 6057, 13, 10331, 198, 11748, 4866, 628 ]
3.555556
9
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import os import pytest from selenium.common.exceptions import WebDriverException from selenium.webdriver.support.wait import WebDriverWait # @pytest.mark.xfail_ie # @pytest.mark.xfail_chromiumedge(reason="Fails on Travis") # @pytest.mark.xfail_firefox(reason="Fails on Travis") # @pytest.mark.xfail_remote(reason="Fails on Travis") # def testShouldMaximizeTheWindow(driver): # resize_timeout = 5 # wait = WebDriverWait(driver, resize_timeout) # old_size = driver.get_window_size() # driver.set_window_size(200, 200) # wait.until( # lambda dr: dr.get_window_size() != old_size if old_size["width"] != 200 and old_size["height"] != 200 else True) # size = driver.get_window_size() # driver.maximize_window() # wait.until(lambda dr: dr.get_window_size() != size) # new_size = driver.get_window_size() # assert new_size["width"] > size["width"] # assert new_size["height"] > size["height"] # @pytest.mark.xfail_safari(raises=WebDriverException, # reason='Fullscreen command not implemented') # @pytest.mark.skipif(os.environ.get('TRAVIS') == 'true', # reason='Fullscreen command causes Travis to hang') # @pytest.mark.no_driver_after_test # def test_should_fullscreen_the_current_window(driver): # start_width = driver.execute_script('return window.innerWidth;') # start_height = driver.execute_script('return window.innerHeight;') # driver.fullscreen_window() # WebDriverWait(driver, 2)\ # .until(lambda d: driver.execute_script('return window.innerWidth;') > start_width) # end_width = driver.execute_script('return window.innerWidth;') # end_height = driver.execute_script('return window.innerHeight;') # driver.quit() # Kill driver so we aren't running fullscreen after # assert end_width > start_width # assert end_height > start_height # @pytest.mark.xfail_safari(raises=WebDriverException, # reason='Minimize command not implemented') # @pytest.mark.skipif(os.environ.get('TRAVIS') == 'true', # reason='Minimize command causes Travis to hang') # @pytest.mark.no_driver_after_test # def test_should_minimize_the_current_window(driver): # driver.minimize_window() # minimized = driver.execute_script('return document.hidden;') # driver.quit() # Kill driver so we aren't running minimized after # assert minimized is True
[ 2, 49962, 284, 262, 10442, 10204, 7162, 3883, 357, 50, 4851, 8, 739, 530, 198, 2, 393, 517, 18920, 5964, 11704, 13, 220, 4091, 262, 28536, 2393, 198, 2, 9387, 351, 428, 670, 329, 3224, 1321, 198, 2, 5115, 6634, 9238, 13, 220, 383,...
2.885816
1,121
# coding: utf-8 # # a Geometry class contains the list of patches and additional information about # the topology i.e. connectivity, boundaries # For the moment, it is used as a container, that can be loaded from a file # (hdf5) from itertools import product from collections import abc import numpy as np import string import random import h5py import yaml import os import string import random from mpi4py import MPI from psydac.fem.splines import SplineSpace from psydac.fem.tensor import TensorFemSpace from psydac.mapping.discrete import SplineMapping, NurbsMapping from sympde.topology import Domain, Line, Square, Cube, NCubeInterior from sympde.topology.basic import Union #============================================================================== def export( self, filename ): """ Parameters ---------- filename : str Name of HDF5 output file. """ # ... comm = self.comm # ... # Create dictionary with geometry metadata yml = {} yml['ldim'] = self.ldim yml['pdim'] = self.pdim # ... information about the patches if not( self.mappings ): raise ValueError('No mappings were found') patches_info = [] i_mapping = 0 for patch_name, mapping in self.mappings.items(): name = '{}'.format( patch_name ) mapping_id = 'mapping_{}'.format( i_mapping ) dtype = '{}'.format( type( mapping ).__name__ ) patches_info += [{'name': name, 'mapping_id': mapping_id, 'type': dtype}] i_mapping += 1 yml['patches'] = patches_info # ... # ... topology topo_yml = self.domain.todict() # ... # Create HDF5 file (in parallel mode if MPI communicator size > 1) if not(comm is None) and comm.size > 1: kwargs = dict( driver='mpio', comm=comm ) else: kwargs = {} h5 = h5py.File( filename, mode='w', **kwargs ) # ... # Dump geometry metadata to string in YAML file format geo = yaml.dump( data = yml, sort_keys=False) # Write geometry metadata as fixed-length array of ASCII characters h5['geometry.yml'] = np.array( geo, dtype='S' ) # ... # ... # Dump geometry metadata to string in YAML file format geo = yaml.dump( data = topo_yml, sort_keys=False) # Write topology metadata as fixed-length array of ASCII characters h5['topology.yml'] = np.array( geo, dtype='S' ) # ... i_mapping = 0 for patch_name, mapping in self.mappings.items(): space = mapping.space # Create group for patch 0 group = h5.create_group( yml['patches'][i_mapping]['mapping_id'] ) group.attrs['shape' ] = space.vector_space.npts group.attrs['degree' ] = space.degree group.attrs['rational' ] = False # TODO remove group.attrs['periodic' ] = space.periodic for d in range( self.ldim ): group['knots_{}'.format( d )] = space.spaces[d].knots # Collective: create dataset for control points shape = [n for n in space.vector_space.npts] + [self.pdim] dtype = space.vector_space.dtype dset = group.create_dataset( 'points', shape=shape, dtype=dtype ) # Independent: write control points to dataset starts = space.vector_space.starts ends = space.vector_space.ends index = [slice(s, e+1) for s, e in zip(starts, ends)] + [slice(None)] index = tuple( index ) dset[index] = mapping.control_points[index] # case of NURBS if isinstance(mapping, NurbsMapping): # Collective: create dataset for weights shape = [n for n in space.vector_space.npts] dtype = space.vector_space.dtype dset = group.create_dataset( 'weights', shape=shape, dtype=dtype ) # Independent: write weights to dataset starts = space.vector_space.starts ends = space.vector_space.ends index = [slice(s, e+1) for s, e in zip(starts, ends)] index = tuple( index ) dset[index] = mapping.weights[index] i_mapping += 1 # Close HDF5 file h5.close() #============================================================================== def export_nurbs_to_hdf5(filename, nurbs, periodic=None, comm=None ): """ Export a single-patch igakit NURBS object to a Psydac geometry file in HDF5 format Parameters ---------- filename : <str> Name of output geometry file, e.g. 'geo.h5' nurbs : <igakit.nurbs.NURBS> igakit geometry nurbs object comm : <MPI.COMM> mpi communicator """ import os.path import igakit assert isinstance(nurbs, igakit.nurbs.NURBS) extension = os.path.splitext(filename)[-1] if not extension == '.h5': raise ValueError('> Only h5 extension is allowed for filename') yml = {} yml['ldim'] = nurbs.dim yml['pdim'] = nurbs.dim patches_info = [] i_mapping = 0 i = 0 rational = not abs(nurbs.weights-1).sum()<1e-15 patch_name = 'patch_{}'.format(i) name = '{}'.format( patch_name ) mapping_id = 'mapping_{}'.format( i_mapping ) dtype = 'NurbsMapping' if rational else 'SplineMapping' patches_info += [{'name': name , 'mapping_id':mapping_id, 'type':dtype}] yml['patches'] = patches_info # ... # Create HDF5 file (in parallel mode if MPI communicator size > 1) if not(comm is None) and comm.size > 1: kwargs = dict( driver='mpio', comm=comm ) else: kwargs = {} h5 = h5py.File( filename, mode='w', **kwargs ) # ... # Dump geometry metadata to string in YAML file format geom = yaml.dump( data = yml, sort_keys=False) # Write geometry metadata as fixed-length array of ASCII characters h5['geometry.yml'] = np.array( geom, dtype='S' ) # ... # ... topology if nurbs.dim == 1: bounds1 = (float(nurbs.breaks(0)[0]), float(nurbs.breaks(0)[-1])) domain = Line(patch_name, bounds1=bounds1) elif nurbs.dim == 2: bounds1 = (float(nurbs.breaks(0)[0]), float(nurbs.breaks(0)[-1])) bounds2 = (float(nurbs.breaks(1)[0]), float(nurbs.breaks(1)[-1])) domain = Square(patch_name, bounds1=bounds1, bounds2=bounds2) elif nurbs.dim == 3: bounds1 = (float(nurbs.breaks(0)[0]), float(nurbs.breaks(0)[-1])) bounds2 = (float(nurbs.breaks(1)[0]), float(nurbs.breaks(1)[-1])) bounds3 = (float(nurbs.breaks(2)[0]), float(nurbs.breaks(2)[-1])) domain = Cube(patch_name, bounds1=bounds1, bounds2=bounds2, bounds3=bounds3) topo_yml = domain.todict() # Dump geometry metadata to string in YAML file format geom = yaml.dump( data = topo_yml, sort_keys=False) # Write topology metadata as fixed-length array of ASCII characters h5['topology.yml'] = np.array( geom, dtype='S' ) group = h5.create_group( yml['patches'][i]['mapping_id'] ) group.attrs['degree' ] = nurbs.degree group.attrs['rational' ] = rational group.attrs['periodic' ] = tuple( False for d in range( nurbs.dim ) ) if periodic is None else periodic for d in range( nurbs.dim ): group['knots_{}'.format( d )] = nurbs.knots[d] group['points'] = nurbs.points[...,:nurbs.dim] if rational: group['weights'] = nurbs.weights h5.close() #============================================================================== def refine_nurbs(nrb, ncells=None, degree=None, multiplicity=None, tol=1e-9): """ This function refines the nurbs object. It contructs a new grid based on the new number of cells, and it adds the new break points to the nrb grid, such that the total number of cells is equal to the new number of cells. We use knot insertion to construct the new knot sequence , so the geometry is identical to the previous one. It also elevates the degree of the nrb object based on the new degree. Parameters ---------- nrb : <igakit.nurbs.NURBS> geometry nurbs object ncells : <list> total number of cells in each direction degree : <list> degree in each direction multiplicity : <list> multiplicity of each knot in the knot sequence in each direction tol : <float> Minimum distance between two break points. Returns ------- nrb : <igakit.nurbs.NURBS> the refined geometry nurbs object """ if multiplicity is None: multiplicity = [1]*nrb.dim nrb = nrb.clone() if ncells is not None: for axis in range(0,nrb.dim): ub = nrb.breaks(axis)[0] ue = nrb.breaks(axis)[-1] knots = np.linspace(ub,ue,ncells[axis]+1) index = nrb.knots[axis].searchsorted(knots) nrb_knots = nrb.knots[axis][index] for m,(nrb_k, k) in enumerate(zip(nrb_knots, knots)): if abs(k-nrb_k)<tol: knots[m] = np.nan knots = knots[~np.isnan(knots)] indices = np.round(np.linspace(0, len(knots) - 1, ncells[axis]+1-len(nrb.breaks(axis)))).astype(int) knots = knots[indices] if len(knots)>0: nrb.refine(axis, knots) if degree is not None: for axis in range(0,nrb.dim): d = degree[axis] - nrb.degree[axis] if d<0: raise ValueError('The degree {} must be >= {}'.format(degree, nrb.degree)) nrb.elevate(axis, times=d) for axis in range(nrb.dim): decimals = abs(np.floor(np.log10(np.abs(tol))).astype(int)) knots, counts = np.unique(nrb.knots[axis].round(decimals=decimals), return_counts=True) counts = multiplicity[axis] - counts counts[counts<0] = 0 knots = np.repeat(knots, counts) nrb = nrb.refine(axis, knots) return nrb def refine_knots(knots, ncells, degree, multiplicity=None, tol=1e-9): """ This function refines the knot sequence. It contructs a new grid based on the new number of cells, and it adds the new break points to the nrb grid, such that the total number of cells is equal to the new number of cells. We use knot insertion to construct the new knot sequence , so the geometry is identical to the previous one. It also elevates the degree of the nrb object based on the new degree. Parameters ---------- knots : <list> list of knot sequences in each direction ncells : <list> total number of cells in each direction degree : <list> degree in each direction multiplicity : <list> multiplicity of each knot in the knot sequence in each direction tol : <float> Minimum distance between two break points. Returns ------- knots : <list> the refined knot sequences in each direction """ from igakit.nurbs import NURBS dim = len(ncells) if multiplicity is None: multiplicity = [1]*dim assert len(knots) == dim nrb = NURBS(knots) for axis in range(dim): ub = nrb.breaks(axis)[0] ue = nrb.breaks(axis)[-1] knots = np.linspace(ub,ue,ncells[axis]+1) index = nrb.knots[axis].searchsorted(knots) nrb_knots = nrb.knots[axis][index] for m,(nrb_k, k) in enumerate(zip(nrb_knots, knots)): if abs(k-nrb_k)<tol: knots[m] = np.nan knots = knots[~np.isnan(knots)] indices = np.round(np.linspace(0, len(knots) - 1, ncells[axis]+1-len(nrb.breaks(axis)))).astype(int) knots = knots[indices] if len(knots)>0: nrb.refine(axis, knots) for axis in range(dim): d = degree[axis] - nrb.degree[axis] if d<0: raise ValueError('The degree {} must be >= {}'.format(degree, nrb.degree)) nrb.elevate(axis, times=d) for axis in range(dim): decimals = abs(np.floor(np.log10(np.abs(tol))).astype(int)) knots, counts = np.unique(nrb.knots[axis].round(decimals=decimals), return_counts=True) counts = multiplicity[axis] - counts counts[counts<0] = 0 knots = np.repeat(knots, counts) nrb = nrb.refine(axis, knots) return nrb.knots #============================================================================== def import_geopdes_to_nurbs(filename): """ This function reads a geopdes geometry file and convert it to igakit nurbs object Parameters ---------- filename : <str> the filename of the geometry file Returns ------- nrb : <igakit.nurbs.NURBS> the geometry nurbs object """ extension = os.path.splitext(filename)[-1] if not extension == '.txt': raise ValueError('> Expected .txt extension') f = open(filename) lines = f.readlines() f.close() lines = [line for line in lines if line[0].strip() != "#"] data = _read_header(lines[0]) n_dim = data[0] r_dim = data[1] n_patchs = data[2] n_lines_per_patch = 3*n_dim + 1 list_begin_line = _get_begin_line(lines, n_patchs) nrb = _read_patch(lines, 1, n_lines_per_patch, list_begin_line) return nrb
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 2, 198, 2, 257, 2269, 15748, 1398, 4909, 262, 1351, 286, 16082, 290, 3224, 1321, 546, 198, 2, 262, 1353, 1435, 1312, 13, 68, 13, 19843, 11, 13215, 198, 2, 1114, 262, 2589, 11, 340, 318, 973, ...
2.261936
6,032
__author__ = 'Jiri Fajtl' __email__ = 'ok1zjf@gmail.com' __version__= '2.2' __status__ = "Research" __date__ = "28/1/2018" __license__= "MIT License" import os import numpy as np import glob import subprocess import platform import sys import pkg_resources import torch import PIL as Image try: import cv2 except: print("WARNING: Could not load OpenCV python package. Some functionality may not be available.") if __name__ == "__main__": print_pkg_versions() split_files = get_split_files('datasets/lamem', 'splits', 'test_*.txt') print(split_files) weight_files = get_weight_files(split_files, experiment_name='lamem_ResNet50FC_lstm3_last', max_rc_checkpoints=True) # weight_files = get_weight_files(split_files, experiment_name='lamem_ResNet50FC_lstm3') print(weight_files)
[ 834, 9800, 834, 796, 705, 41, 14783, 376, 1228, 28781, 6, 198, 834, 12888, 834, 796, 705, 482, 16, 89, 73, 69, 31, 14816, 13, 785, 6, 198, 834, 9641, 834, 28, 705, 17, 13, 17, 6, 198, 834, 13376, 834, 796, 366, 25104, 1, 198, ...
2.721854
302
# automatically generated by the FlatBuffers compiler, do not modify # namespace: aghast_generated import flatbuffers
[ 2, 6338, 7560, 416, 262, 21939, 36474, 364, 17050, 11, 466, 407, 13096, 198, 198, 2, 25745, 25, 257, 456, 459, 62, 27568, 198, 198, 11748, 6228, 36873, 364, 628, 198 ]
3.935484
31
import axelrod as axl from .test_player import TestPlayer C, D = axl.Action.C, axl.Action.D
[ 11748, 7877, 417, 14892, 355, 7877, 75, 198, 198, 6738, 764, 9288, 62, 7829, 1330, 6208, 14140, 198, 198, 34, 11, 360, 796, 7877, 75, 13, 12502, 13, 34, 11, 7877, 75, 13, 12502, 13, 35, 198 ]
2.540541
37
#FILE NAME: BannerTool.py #created by: Ciro Veneruso #purpose: banner localization #last edited by: Ciro Veneruso #INSTALL: BeautifulSoup #TODO: this code is a blob, must be refactorized!!!! import re import mechanize import socket import urllib from tools import BaseTool from bs4 import BeautifulSoup from pprint import pprint from ipwhois import IPWhois, WhoisLookupError from tld import get_tld import urlparse from tld.exceptions import TldIOError, TldDomainNotFound, TldBadUrl from tools import ToolException
[ 2, 25664, 36751, 25, 27414, 25391, 13, 9078, 198, 2, 25598, 416, 25, 327, 7058, 569, 877, 385, 78, 198, 2, 29983, 25, 17625, 42842, 198, 2, 12957, 13012, 416, 25, 327, 7058, 569, 877, 385, 78, 198, 198, 2, 38604, 7036, 25, 23762, ...
3.223602
161
from .ise import ISE from .vivado import Vivado
[ 198, 6738, 764, 786, 1330, 3180, 36, 198, 6738, 764, 85, 452, 4533, 1330, 25313, 4533, 198 ]
2.882353
17
# Copyright 2020 EraO Prosopagnosia Helper Dev Team, Liren Pan, Yixiao Hong, Hongzheng Xu, Stephen Huang, Tiancong Wang # # Supervised by Prof. Steve Mann (http://www.eecg.toronto.edu/~mann/) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import datetime import mysql.connector import re import time from app.sql.config.DbConfig import db_config from flask import render_template, redirect, url_for, request, g, session from flask_bcrypt import Bcrypt from app import EmailSender as email_confirmation from app import webapp validUsernameChar = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" # The function used to establish connection to sql database def connect_to_database(): ''' Function used to connect to database :return: ''' return mysql.connector.connect(user=db_config['user'], password=db_config['password'], host=db_config['host'], database=db_config['database'], use_pure=True) def get_database(): ''' function used to get database :return: ''' db = getattr(g, '_database', None) if db is None: db = g._database = connect_to_database() return db """ ############################################################# Login Settings ############################################################ """ """ ############################################################# Sign up Settings ############################################################ """ # Display an empty HTML form that allows users to fill the info and sign up. # Create a new account and save them in the database. """ ############################################################# Secure Index ############################################################ """ """ ############################################################# Send Email ############################################################ """ # Create a new account and save them in the database.
[ 2, 220, 15069, 12131, 25466, 46, 27631, 404, 4660, 418, 544, 5053, 525, 6245, 4816, 11, 406, 24080, 5961, 11, 575, 844, 13481, 9764, 11, 9764, 89, 31753, 33591, 11, 7970, 31663, 11, 20834, 36801, 15233, 198, 2, 198, 2, 220, 3115, 16...
3.582003
689
import math from point2d import Point2D
[ 11748, 10688, 198, 198, 6738, 966, 17, 67, 1330, 6252, 17, 35, 628, 198 ]
3.071429
14
import concurrent import os import re import shutil import xml.etree.ElementTree as ET # TODO do we have this as requirement? from concurrent.futures import as_completed from concurrent.futures._base import as_completed from pathlib import Path import ffmpeg import pandas as pd import webrtcvad from audio_korpora_pipeline.baseobjects import FileHandlingObject from audio_korpora_pipeline.inputadapter.audiosplit.splitter import Splitter from audio_korpora_pipeline.metamodel.mediasession import MediaAnnotationBundle, \ MediaAnnotationBundleWithoutTranscription, WrittenResource, MediaFile, \ MediaSessionActor, Sex, \ MediaSessionActors, MediaSession
[ 11748, 24580, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 4423, 346, 198, 11748, 35555, 13, 316, 631, 13, 20180, 27660, 355, 12152, 220, 1303, 16926, 46, 466, 356, 423, 428, 355, 9079, 30, 198, 6738, 24580, 13, 69, 315, 942, 1330,...
3.361809
199
import matplotlib.pyplot as plt import math import shutil import torch from accelerate import Accelerator from tensorboardX import SummaryWriter from cli import parse_args from dataset import SvbrdfDataset from losses import MixedLoss, MixedLoss2, MixedLoss3 from models import MultiViewModel, SingleViewModel from pathlib import Path from persistence import Checkpoint from renderers import LocalRenderer, RednerRenderer import utils import environment as env import numpy as np import sys from PIL import Image args = parse_args() clean_training = args.mode == 'train' and args.retrain # Load the checkpoint checkpoint_dir = Path(args.model_dir) checkpoint = Checkpoint() if not clean_training: checkpoint = Checkpoint.load(checkpoint_dir) # Immediatly restore the arguments if we have a valid checkpoint if checkpoint.is_valid(): args = checkpoint.restore_args(args) # Make the result reproducible utils.enable_deterministic_random_engine() # Determine the device accelerator = Accelerator() device = accelerator.device # Create the model model = MultiViewModel(use_coords=args.use_coords).to(device) if checkpoint.is_valid(): model = checkpoint.restore_model_state(model) elif args.mode == 'test': print("No model found in the model directory but it is required for testing.") exit(1) # TODO: Choose a random number for the used input image count if we are training and we don't request it to be fix (see fixImageNb for reference) data = SvbrdfDataset(data_directory=args.input_dir, image_size=args.image_size, scale_mode=args.scale_mode, input_image_count=args.image_count, used_input_image_count=args.used_image_count, use_augmentation=True, mix_materials=args.mode == 'train', no_svbrdf=args.no_svbrdf_input, is_linear=args.linear_input) epoch_start = 0 # model.generator.delete() # model = torch.nn.Sequential( # *list(model.children())[:-8], # ) # print(*list(model.parameters())) if args.mode == 'train': validation_split = 0.01 print("Using {:.2f} % of the data for validation".format( round(validation_split * 100.0, 2))) training_data, validation_data = torch.utils.data.random_split(data, [int(math.ceil( len(data) * (1.0 - validation_split))), int(math.floor(len(data) * validation_split))]) print("Training samples: {:d}.".format(len(training_data))) print("Validation samples: {:d}.".format(len(validation_data))) training_dataloader = torch.utils.data.DataLoader( training_data, batch_size=8, pin_memory=True, shuffle=True) validation_dataloader = torch.utils.data.DataLoader( validation_data, batch_size=8, pin_memory=True, shuffle=False) batch_count = int(math.ceil(len(training_data) / training_dataloader.batch_size)) # Train as many epochs as specified epoch_end = args.epochs print("Training from epoch {:d} to {:d}".format(epoch_start, epoch_end)) # Set up the optimizer # TODO: Use betas=(0.5, 0.999) L = torch.FloatTensor(5, 3).uniform_(0.2, 1.0) L = L / torch.linalg.norm(L, ord=2, dim=-1, keepdim=True) L[:, :2] = 2.0 * L[:, :2] - 1.0 V = torch.FloatTensor(1, 3).uniform_(0.2, 1.0) V = V / torch.linalg.norm(V, ord=2, dim=-1, keepdim=True) V[:, :2] = 2.0 * V[:, :2] - 1.0 scenes = env.generate_specific_scenes(5, L, L) L.requires_grad = True VIP = [L] # V.requires_grad = True optimizer = torch.optim.Adam(VIP, lr=0.1) model, optimizer, training_dataloader, validation_dataloader = accelerator.prepare( model, optimizer, training_dataloader, validation_dataloader) # print("scene", scene.camera) # TODO: Use scheduler if necessary #scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min') # Set up the loss loss_renderer = LocalRenderer() loss_function = MixedLoss2(loss_renderer, scenes) # Setup statistics stuff statistics_dir = checkpoint_dir / "logs" if clean_training and statistics_dir.exists(): # Nuke the stats dir shutil.rmtree(statistics_dir) statistics_dir.mkdir(parents=True, exist_ok=True) writer = SummaryWriter(str(statistics_dir.absolute())) last_batch_inputs = None # Clear checkpoint in order to free up some memory checkpoint.purge() lights = [] losses = [] for epoch in range(epoch_start, epoch_end): for i, batch in enumerate(training_dataloader): # Unique index of this batch print("Ldet", (L.detach().numpy())[0]) lights.append(((L.detach().numpy())[0]).tolist()) scenes = env.generate_specific_scenes(5, L, L) print("L", L) # if(epoch_end - epoch < 3): loss_function = MixedLoss2(loss_renderer, scenes) # else: # loss_function = MixedLoss2(loss_renderer, scene[0]) batch_index = epoch * batch_count + i # Construct inputs batch_inputs = batch["inputs"].to(device) batch_svbrdf = batch["svbrdf"].to(device) # Perform a step optimizer.zero_grad() outputs = model(batch_inputs) print("batch_inputs", batch_inputs.size()) print("batch_svbrdfs", batch_svbrdf.size()) print("batch_outputs", outputs.size()) loss = loss_function(outputs, batch_svbrdf) accelerator.backward(loss) optimizer.step() print("Epoch {:d}, Batch {:d}, loss: {:f}".format( epoch, i + 1, loss.item())) losses.append((epoch, loss.item())) # Statistics writer.add_scalar("loss", loss.item(), batch_index) last_batch_inputs = batch_inputs lights.append(((L.detach().numpy())[0]).tolist()) with open('/content/experiment1/losses/loss.txt', "w") as text_file: text_file.write(str(losses)) print("lights1", lights) # print(len(lights)) lights2 = [] for j in range(len(lights)): if j%10 == 0: lights2.append(lights[j]) # print("lights2", lights) # l=np.array(lights) l = np.array(lights2) renderer = LocalRenderer() rendered_scene = env.generate_specific_scenes(1, L.detach(), L.detach()) img = renderer.render(rendered_scene[0], batch_svbrdf[0]) fig = plt.figure(frameon=False) # fig.set_size_inches(w,h) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) # print("shape", img.size()) ax.imshow(img[0].detach().permute(1,2,0), aspect='auto') fig.savefig('/content/experiment1/figures/render1.png') img = renderer.render(rendered_scene[0], outputs[0]) fig = plt.figure(frameon=False) # fig.set_size_inches(w,h) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) # print("shape", img.size()) ax.imshow(img[0].detach().permute(1,2,0), aspect='auto') fig.savefig('/content/experiment1/figures/render2.png') # print("size", batch_inputs.size()) torch.add(L, 5) print("L", L) rendered_scene = env.generate_specific_scenes(1, L, L) img = renderer.render(rendered_scene[0], batch_svbrdf[0]) fig = plt.figure(frameon=False) # fig.set_size_inches(w,h) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) # print("shape", img.size()) ax.imshow(img[0].detach().permute(1,2,0), aspect='auto') fig.savefig('/content/experiment1/figures/render3.png') print("size", batch_inputs[0][0].size()) img = batch_inputs[0][0] fig = plt.figure(frameon=False) # fig.set_size_inches(w,h) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) # print("shape", img.size()) ax.imshow(img.detach().permute(1,2,0), aspect='auto') fig.savefig('/content/experiment1/figures/render4.png') print("size", batch_inputs[0][0].size()) normals, diffuse, roughness, specular = utils.unpack_svbrdf(outputs[0]) img = normals fig = plt.figure(frameon=False) # fig.set_size_inches(w,h) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) # print("shape", img.size()) ax.imshow(img.detach().permute(1,2,0), aspect='auto') fig.savefig('/content/experiment1/figures/output_normal.png') img = diffuse fig = plt.figure(frameon=False) # fig.set_size_inches(w,h) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) # print("shape", img.size()) ax.imshow(img.detach().permute(1,2,0), aspect='auto') fig.savefig('/content/experiment1/figures/output_diffuse.png') img = roughness fig = plt.figure(frameon=False) # fig.set_size_inches(w,h) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) # print("shape", img.size()) ax.imshow(img.detach().permute(1,2,0), aspect='auto') fig.savefig('/content/experiment1/figures/output_roughness.png') img = specular fig = plt.figure(frameon=False) # fig.set_size_inches(w,h) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) # print("shape", img.size()) ax.imshow(img.detach().permute(1,2,0), aspect='auto') fig.savefig('/content/experiment1/figures/output_specular.png') print("size", batch_inputs[0][0].size()) normals, diffuse, roughness, specular = utils.unpack_svbrdf(batch_svbrdf[0]) img = normals fig = plt.figure(frameon=False) # fig.set_size_inches(w,h) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) # print("shape", img.size()) ax.imshow(img.detach().permute(1,2,0), aspect='auto') fig.savefig('/content/experiment1/figures/target_normal.png') img = diffuse fig = plt.figure(frameon=False) # fig.set_size_inches(w,h) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) # print("shape", img.size()) ax.imshow(img.detach().permute(1,2,0), aspect='auto') fig.savefig('/content/experiment1/figures/target_diffuse.png') img = roughness fig = plt.figure(frameon=False) # fig.set_size_inches(w,h) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) # print("shape", img.size()) ax.imshow(img.detach().permute(1,2,0), aspect='auto') fig.savefig('/content/experiment1/figures/target_roughness.png') img = specular fig = plt.figure(frameon=False) # fig.set_size_inches(w,h) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) # print("shape", img.size()) ax.imshow(img.detach().permute(1,2,0), aspect='auto') fig.savefig('/content/experiment1/figures/target_specular.png') images = [Image.open(x) for x in ['/content/experiment1/figures/target_normal.png', '/content/experiment1/figures/target_diffuse.png', '/content/experiment1/figures/target_roughness.png', '/content/experiment1/figures/target_specular.png']] widths, heights = zip(*(i.size for i in images)) total_width = sum(widths) max_height = max(heights) new_im = Image.new('RGB', (total_width, max_height)) x_offset = 0 for im in images: new_im.paste(im, (x_offset,0)) x_offset += im.size[0] new_im.save('/content/experiment1/figures/target_svbrdf.png') images = [Image.open(x) for x in ['/content/experiment1/figures/output_normal.png', '/content/experiment1/figures/output_diffuse.png', '/content/experiment1/figures/output_roughness.png', '/content/experiment1/figures/output_specular.png']] widths, heights = zip(*(i.size for i in images)) total_width = sum(widths) max_height = max(heights) new_im = Image.new('RGB', (total_width, max_height)) x_offset = 0 for im in images: new_im.paste(im, (x_offset,0)) x_offset += im.size[0] new_im.save('/content/experiment1/figures/output_svbrdf.png') print("size", batch_inputs[0][0].size()) normals, diffuse, roughness, specular = utils.unpack_svbrdf(outputs[0]) img = normals fig = plt.figure(frameon=False) # fig.set_size_inches(w,h) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) # print("shape", img.size()) ax.imshow(img.detach().permute(1,2,0), aspect='auto') fig.savefig('/content/experiment1/figures/output_normal.png') print("lights3", l) fig = plt.figure() ax = fig.add_subplot(projection='3d') ax.scatter([0.0], [0.0], [0.0], marker='o', c='r') # v = V.detach().numpy() ax.scatter(l[:,0], l[:,1], l[:,2], marker='.', c='g') # ax.scatter(v[:,0], v[:,1], v[:,2], marker='^', c='b') ax.set_xlim(-8, 8) ax.set_ylim(-8, 8) ax.set_zlim(-8., 8.) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') # plt.show() plt.savefig('/content/experiment1/figures/light.png') plt.show() # if epoch % args.save_frequency == 0: # Checkpoint.save(checkpoint_dir, args, model, optimizer, epoch) # if epoch % args.validation_frequency == 0 and len(validation_data) > 0: # model.eval() # val_loss = 0.0 # batch_count_val = 0 # for batch in validation_dataloader: # # Construct inputs # batch_inputs = batch["inputs"].to(device) # batch_svbrdf = batch["svbrdf"].to(device) # outputs = model(batch_inputs) # val_loss += loss_function(outputs, batch_svbrdf).item() # batch_count_val += 1 # val_loss /= batch_count_val # print("Epoch {:d}, validation loss: {:f}".format(epoch, val_loss)) # writer.add_scalar("val_loss", val_loss, epoch * batch_count) # model.train()
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 10688, 198, 11748, 4423, 346, 198, 11748, 28034, 198, 6738, 22636, 1330, 29805, 1352, 198, 6738, 11192, 273, 3526, 55, 1330, 21293, 34379, 198, 6738, 537, 72, 1330, 21...
2.258713
6,169
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 from .engines import do_train, do_inference from .lstr.lstr_trainer import * from .lstr.lstr_inference import *
[ 2, 15069, 6186, 13, 785, 11, 3457, 13, 393, 663, 29116, 13, 1439, 6923, 33876, 13, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 198, 6738, 764, 1516, 1127, 1330, 466, 62, 27432, 11, 466, 62, 259...
3.013699
73
# Copyright 2017 NOKIA # All Rights Reserved. from netaddr import IPNetwork import testtools from tempest.common import waiters from tempest.lib import exceptions from tempest.scenario import manager from tempest.test import decorators from nuage_tempest_plugin.lib.test.nuage_test import NuageAdminNetworksTest from nuage_tempest_plugin.lib.test.nuage_test import NuageBaseTest from nuage_tempest_plugin.lib.topology import Topology from nuage_tempest_plugin.lib.utils import constants from nuage_tempest_plugin.services.nuage_client import NuageRestClient CONF = Topology.get_conf() LOG = Topology.get_logger(__name__)
[ 2, 15069, 2177, 8005, 42, 3539, 198, 2, 1439, 6923, 33876, 13, 198, 198, 6738, 2010, 29851, 1330, 6101, 26245, 198, 11748, 1332, 31391, 198, 198, 6738, 20218, 395, 13, 11321, 1330, 4043, 364, 198, 6738, 20218, 395, 13, 8019, 1330, 132...
3.294737
190
''' Advent of code 2019 Day 11 - Space police ''' from typing import NamedTuple from enum import Enum INPUT_FILE=__file__.replace('.py', '.dat') def run_robot(code: dict, start_on_white: bool = False) -> int: DIRECTIONS_COUNT = 4 direction = Direction.UP panels = {} seen = set() color = [] position = Point(0, 0) if start_on_white: panels[position] = 1 finished = False brain = run_program(code, color) while True: try: # Sense the color on the point. Default is black (0). if position in panels: color.append(panels[position]) else: color.append(0) paint = next(brain) rotation = next(brain) if paint == "" or rotation == "": raise RuntimeError(f"Failed to read paint: {paint}, rotation: {rotation}") # Paints the panel. panels[position] = paint # Keeps track of all visited points. seen.add(position) # Turn left (0) or right (1). if rotation == 0: direction = Direction((direction.value + 1) % DIRECTIONS_COUNT) elif rotation == 1: direction = Direction((direction.value - 1) % DIRECTIONS_COUNT) # Move a step forward. if direction == Direction.UP: position = Point(position.X, position.Y - 1) elif direction == Direction.LEFT: position = Point(position.X - 1, position.Y) elif direction == Direction.DOWN: position = Point(position.X, position.Y + 1) elif direction == Direction.RIGHT: position = Point(position.X + 1, position.Y) else: raise RuntimeError(f"Wrong direction: {direction}") except StopIteration: return panels # Read the input with open(INPUT_FILE) as f: input_dict = get_dict(list(map(int, f.read().strip().split(',')))) # Part 1 solution panels_count = len(run_robot(input_dict)) print(f"Part 1: {panels_count}") # Part 2 solution panels = run_robot(input_dict, True) print(f"Part 2:") print_panels(panels)
[ 7061, 6, 33732, 286, 2438, 13130, 3596, 1367, 532, 4687, 1644, 220, 705, 7061, 201, 198, 201, 198, 6738, 19720, 1330, 34441, 51, 29291, 201, 198, 6738, 33829, 1330, 2039, 388, 201, 198, 201, 198, 1268, 30076, 62, 25664, 28, 834, 7753,...
2.073214
1,120
description = 'Mezei spin flipper using TTI power supply' group = 'optional' tango_base = 'tango://miractrl.mira.frm2:10000/mira/' devices = dict( dct1 = device('nicos.devices.entangle.PowerSupply', description = 'current in first channel of supply (flipper current)', tangodevice = tango_base + 'tti1/out1', timeout = 1, precision = 0.01, ), dct2 = device('nicos.devices.entangle.PowerSupply', description = 'current in second channel of supply (compensation current)', tangodevice = tango_base + 'tti1/out2', timeout = 1, precision = 0.01, ), flip = device('nicos.devices.polarized.MezeiFlipper', description = 'Mezei flipper before sample (in shielding table)', flip = 'dct1', corr = 'dct2', ), )
[ 11213, 796, 705, 5308, 2736, 72, 7906, 781, 14710, 1262, 309, 25621, 1176, 5127, 6, 198, 8094, 796, 705, 25968, 6, 198, 198, 83, 14208, 62, 8692, 796, 705, 83, 14208, 1378, 10793, 529, 45895, 13, 76, 8704, 13, 8310, 76, 17, 25, 49...
2.380117
342
# Copyright 1999-2021 Alibaba Group Holding Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np from ... import opcodes from ... import tensor as mt from ...core import OutputType, recursive_tile from ...core.operand import OperandStage from ...serialization.serializables import KeyField, Int32Field from ...tensor.array_utils import as_same_device, device from ...tensor.core import TensorOrder from ...tensor.random import RandomStateField from ...utils import has_unknown_shape from ..metrics import euclidean_distances from ..operands import LearnOperand, LearnOperandMixin ############################################################################### # Initialization heuristic def _k_init(X, n_clusters, x_squared_norms, random_state, n_local_trials=None): """Init n_clusters seeds according to k-means++ Parameters ---------- X : array or sparse matrix, shape (n_samples, n_features) The data to pick seeds for. To avoid memory copy, the input data should be double precision (dtype=np.float64). n_clusters : integer The number of seeds to choose x_squared_norms : array, shape (n_samples,) Squared Euclidean norm of each data point. random_state : int, RandomState instance The generator used to initialize the centers. Use an int to make the randomness deterministic. See :term:`Glossary <random_state>`. n_local_trials : integer, optional The number of seeding trials for each center (except the first), of which the one reducing inertia the most is greedily chosen. Set to None to make the number of trials depend logarithmically on the number of seeds (2+log(k)); this is the default. Notes ----- Selects initial cluster centers for k-mean clustering in a smart way to speed up convergence. see: Arthur, D. and Vassilvitskii, S. "k-means++: the advantages of careful seeding". ACM-SIAM symposium on Discrete algorithms. 2007 Version ported from http://www.stanford.edu/~darthur/kMeansppTest.zip, which is the implementation used in the aforementioned paper. """ op = KMeansPlusPlusInit(x=X, n_clusters=n_clusters, x_squared_norms=x_squared_norms, state=random_state, n_local_trials=n_local_trials) return op()
[ 2, 15069, 7358, 12, 1238, 2481, 41992, 4912, 31703, 12052, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, ...
3.128289
912
import re from wikipedia_parser.infobox import clean_text as clean_help from wikipedia_parser.infobox import wikitext_helpers as wtext_help from wikipedia_parser.third_party_adapters import parserfromhell_adapter as adapter __author__ = 'oswaldjones'
[ 11748, 302, 198, 198, 6738, 47145, 11151, 62, 48610, 13, 10745, 672, 1140, 1330, 3424, 62, 5239, 355, 3424, 62, 16794, 198, 6738, 47145, 11151, 62, 48610, 13, 10745, 672, 1140, 1330, 47145, 578, 742, 62, 16794, 364, 355, 266, 5239, 62...
3.225
80
from .GraphQLClient import GraphQLClient from Jumpscale import j JSConfigs = j.baseclasses.object_config_collection
[ 6738, 764, 37065, 9711, 11792, 1330, 29681, 9711, 11792, 198, 6738, 449, 8142, 38765, 1330, 474, 628, 198, 20120, 16934, 82, 796, 474, 13, 8692, 37724, 13, 15252, 62, 11250, 62, 43681, 628 ]
3.606061
33
from os import getenv as e from kombu import Queue CELERY_APP_NAME = 'video_transcoding' VIDEO_TRANSCODING_CELERY_CONF = { 'broker_url': e('VIDEO_TRANSCODING_CELERY_BROKER_URL', 'amqp://guest:guest@rabbitmq:5672/'), 'result_backend': e('VIDEO_TRANSCODING_CELERY_RESULT_BACKEND', None), 'task_default_exchange': CELERY_APP_NAME, 'task_default_exchange_type': 'topic', 'task_default_queue': CELERY_APP_NAME, 'worker_prefetch_multiplier': 1, 'worker_concurrency': e('VIDEO_TRANSCODING_CELERY_CONCURRENCY'), 'task_acks_late': True, 'task_reject_on_worker_lost': True, 'task_queues': [ Queue(CELERY_APP_NAME, routing_key=CELERY_APP_NAME), ] } # Directory for large output files VIDEO_TEMP_DIR = '/tmp' # Download source before processing VIDEO_DOWNLOAD_SOURCE = bool(int(e('VIDEO_DOWNLOAD_SOURCE', 0))) # A list of WebDAV endpoints for storing video results VIDEO_ORIGINS = e('VIDEO_ORIGINS', 'http://storage.localhost:8080/videos/').split(',') # Video streamer public urls (comma-separated) VIDEO_EDGES = e('VIDEO_EDGES', 'http://storage.localhost:8080/').split(',') # Edge video manifest url template VIDEO_URL = '{edge}/hls/{filename}1080p.mp4/index.m3u8' # Output source files checksum CHECKSUM_SOURCE = bool(int(e('CHECKSUM_SOURCE', 0)))
[ 6738, 28686, 1330, 651, 24330, 355, 304, 198, 198, 6738, 479, 2381, 84, 1330, 4670, 518, 628, 198, 34, 3698, 19664, 62, 24805, 62, 20608, 796, 705, 15588, 62, 7645, 66, 7656, 6, 628, 198, 42937, 62, 5446, 1565, 6173, 3727, 2751, 62,...
2.395349
559
from collections import defaultdict from nltk.tokenize import sent_tokenize from nltk.corpus import wordnet as wn from nltk.corpus import semcor as sc from nltk.corpus import stopwords import mywordtokenizer """=================================================================== Place all function calls below the following conditional so that they are called only if this module is called with `python ling278_assign02.py` No functions should execute if it is instead imported with import ling278_assign02 in the interactive shell. """ if __name__ == '__main__': pass
[ 6738, 17268, 1330, 4277, 11600, 198, 6738, 299, 2528, 74, 13, 30001, 1096, 1330, 1908, 62, 30001, 1096, 198, 6738, 299, 2528, 74, 13, 10215, 79, 385, 1330, 1573, 3262, 355, 266, 77, 198, 6738, 299, 2528, 74, 13, 10215, 79, 385, 1330...
3.79085
153
import decimal from unittest import mock from django.conf import settings from django.test import modify_settings from rest_framework import test from rest_framework.reverse import reverse import stripe from restshop import serializers from restshop.models import Order from paymentmethods.stripejs.models import StripeInvoice import restshop.exceptions from restshop.tests.test_product import products_and_price
[ 11748, 32465, 198, 6738, 555, 715, 395, 1330, 15290, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 9288, 1330, 13096, 62, 33692, 198, 6738, 1334, 62, 30604, 1330, 1332, 198, 6738, 1334, 62, 30604, 13,...
4.038835
103
from tnnt.settings import UNIQUE_DEATH_REJECTIONS, UNIQUE_DEATH_NORMALIZATIONS import re # post 2021 TODO: showing unique deaths of a player or clan: # 1. list(Game.objects.values_list('death', 'player__name', 'endtime')) # 2. iterate through list, filtering any death for which reject is True, and # normalizing all death strings. # 3. sort by first death, then endtime. # 4. filter again by taking only the first player/endtime for each death and # ignoring later ones.
[ 6738, 256, 77, 429, 13, 33692, 1330, 4725, 33866, 8924, 62, 7206, 12599, 62, 2200, 23680, 11053, 11, 4725, 33866, 8924, 62, 7206, 12599, 62, 35510, 42126, 14887, 18421, 198, 11748, 302, 198, 198, 2, 1281, 33448, 16926, 46, 25, 4478, 3...
3.258503
147
# This file is part of QuTiP: Quantum Toolbox in Python. # # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. # 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. # # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names # of its contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # 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. ############################################################################### """ This module contains a collection of graph theory routines used mainly to reorder matrices for iterative steady state solvers. """ __all__ = ['graph_degree', 'column_permutation', 'breadth_first_search', 'reverse_cuthill_mckee', 'maximum_bipartite_matching', 'weighted_bipartite_matching'] import numpy as np import scipy.sparse as sp from qutip.cy.graph_utils import ( _breadth_first_search, _node_degrees, _reverse_cuthill_mckee, _maximum_bipartite_matching, _weighted_bipartite_matching) def graph_degree(A): """ Returns the degree for the nodes (rows) of a symmetric graph in sparse CSR or CSC format, or a qobj. Parameters ---------- A : qobj, csr_matrix, csc_matrix Input quantum object or csr_matrix. Returns ------- degree : array Array of integers giving the degree for each node (row). """ if not (sp.isspmatrix_csc(A) or sp.isspmatrix_csr(A)): raise TypeError('Input must be CSC or CSR sparse matrix.') return _node_degrees(A.indices, A.indptr, A.shape[0]) def breadth_first_search(A, start): """ Breadth-First-Search (BFS) of a graph in CSR or CSC matrix format starting from a given node (row). Takes Qobjs and CSR or CSC matrices as inputs. This function requires a matrix with symmetric structure. Use A+trans(A) if original matrix is not symmetric or not sure. Parameters ---------- A : csc_matrix, csr_matrix Input graph in CSC or CSR matrix format start : int Staring node for BFS traversal. Returns ------- order : array Order in which nodes are traversed from starting node. levels : array Level of the nodes in the order that they are traversed. """ if not (sp.isspmatrix_csc(A) or sp.isspmatrix_csr(A)): raise TypeError('Input must be CSC or CSR sparse matrix.') num_rows = A.shape[0] start = int(start) order, levels = _breadth_first_search(A.indices, A.indptr, num_rows, start) # since maybe not all nodes are in search, check for unused entires in # arrays return order[order != -1], levels[levels != -1] def column_permutation(A): """ Finds the non-symmetric column permutation of A such that the columns are given in ascending order according to the number of nonzero entries. This is sometimes useful for decreasing the fill-in of sparse LU factorization. Parameters ---------- A : csc_matrix Input sparse CSC sparse matrix. Returns ------- perm : array Array of permuted row and column indices. """ if not sp.isspmatrix_csc(A): A = sp.csc_matrix(A) count = np.diff(A.indptr) perm = np.argsort(count) return perm def reverse_cuthill_mckee(A, sym=False): """ Returns the permutation array that orders a sparse CSR or CSC matrix in Reverse-Cuthill McKee ordering. Since the input matrix must be symmetric, this routine works on the matrix A+Trans(A) if the sym flag is set to False (Default). It is assumed by default (*sym=False*) that the input matrix is not symmetric. This is because it is faster to do A+Trans(A) than it is to check for symmetry for a generic matrix. If you are guaranteed that the matrix is symmetric in structure (values of matrix element do not matter) then set *sym=True* Parameters ---------- A : csc_matrix, csr_matrix Input sparse CSC or CSR sparse matrix format. sym : bool {False, True} Flag to set whether input matrix is symmetric. Returns ------- perm : array Array of permuted row and column indices. Notes ----- This routine is used primarily for internal reordering of Lindblad superoperators for use in iterative solver routines. References ---------- E. Cuthill and J. McKee, "Reducing the Bandwidth of Sparse Symmetric Matrices", ACM '69 Proceedings of the 1969 24th national conference, (1969). """ if not (sp.isspmatrix_csc(A) or sp.isspmatrix_csr(A)): raise TypeError('Input must be CSC or CSR sparse matrix.') nrows = A.shape[0] if not sym: A = A + A.transpose() return _reverse_cuthill_mckee(A.indices, A.indptr, nrows) def maximum_bipartite_matching(A, perm_type='row'): """ Returns an array of row or column permutations that removes nonzero elements from the diagonal of a nonsingular square CSC sparse matrix. Such a permutation is always possible provided that the matrix is nonsingular. This function looks at the structure of the matrix only. The input matrix will be converted to CSC matrix format if necessary. Parameters ---------- A : sparse matrix Input matrix perm_type : str {'row', 'column'} Type of permutation to generate. Returns ------- perm : array Array of row or column permutations. Notes ----- This function relies on a maximum cardinality bipartite matching algorithm based on a breadth-first search (BFS) of the underlying graph[1]_. References ---------- I. S. Duff, K. Kaya, and B. Ucar, "Design, Implementation, and Analysis of Maximum Transversal Algorithms", ACM Trans. Math. Softw. 38, no. 2, (2011). """ nrows = A.shape[0] if A.shape[0] != A.shape[1]: raise ValueError( 'Maximum bipartite matching requires a square matrix.') if sp.isspmatrix_csr(A) or sp.isspmatrix_coo(A): A = A.tocsc() elif not sp.isspmatrix_csc(A): raise TypeError("matrix must be in CSC, CSR, or COO format.") if perm_type == 'column': A = A.transpose().tocsc() perm = _maximum_bipartite_matching(A.indices, A.indptr, nrows) if np.any(perm == -1): raise Exception('Possibly singular input matrix.') return perm def weighted_bipartite_matching(A, perm_type='row'): """ Returns an array of row permutations that attempts to maximize the product of the ABS values of the diagonal elements in a nonsingular square CSC sparse matrix. Such a permutation is always possible provided that the matrix is nonsingular. This function looks at both the structure and ABS values of the underlying matrix. Parameters ---------- A : csc_matrix Input matrix perm_type : str {'row', 'column'} Type of permutation to generate. Returns ------- perm : array Array of row or column permutations. Notes ----- This function uses a weighted maximum cardinality bipartite matching algorithm based on breadth-first search (BFS). The columns are weighted according to the element of max ABS value in the associated rows and are traversed in descending order by weight. When performing the BFS traversal, the row associated to a given column is the one with maximum weight. Unlike other techniques[1]_, this algorithm does not guarantee the product of the diagonal is maximized. However, this limitation is offset by the substantially faster runtime of this method. References ---------- I. S. Duff and J. Koster, "The design and use of algorithms for permuting large entries to the diagonal of sparse matrices", SIAM J. Matrix Anal. and Applics. 20, no. 4, 889 (1997). """ nrows = A.shape[0] if A.shape[0] != A.shape[1]: raise ValueError('weighted_bfs_matching requires a square matrix.') if sp.isspmatrix_csr(A) or sp.isspmatrix_coo(A): A = A.tocsc() elif not sp.isspmatrix_csc(A): raise TypeError("matrix must be in CSC, CSR, or COO format.") if perm_type == 'column': A = A.transpose().tocsc() perm = _weighted_bipartite_matching( np.asarray(np.abs(A.data), dtype=float), A.indices, A.indptr, nrows) if np.any(perm == -1): raise Exception('Possibly singular input matrix.') return perm
[ 2, 770, 2393, 318, 636, 286, 2264, 40533, 47, 25, 29082, 16984, 3524, 287, 11361, 13, 198, 2, 198, 2, 220, 220, 220, 15069, 357, 66, 8, 2813, 290, 1568, 11, 3362, 360, 13, 8741, 290, 5199, 449, 13, 16053, 44038, 13, 198, 2, 220,...
2.806415
3,523
# comments------------------ if True: a(10)
[ 2, 3651, 1783, 438, 628, 220, 220, 220, 220, 198, 361, 6407, 25, 198, 220, 220, 220, 257, 7, 940, 8 ]
2.52381
21
""" Hull objects of localization data. Submodules: ----------- .. autosummary:: :toctree: ./ hull alpha_shape """ from locan.data.hulls.alpha_shape import * from locan.data.hulls.hull import * __all__ = [] __all__.extend(hull.__all__) __all__.extend(alpha_shape.__all__)
[ 37811, 198, 39, 724, 5563, 286, 42842, 1366, 13, 198, 198, 7004, 18170, 25, 198, 32284, 198, 198, 492, 44619, 388, 6874, 3712, 198, 220, 220, 1058, 1462, 310, 631, 25, 24457, 628, 220, 220, 23644, 198, 220, 220, 17130, 62, 43358, 19...
2.465517
116
import pytest from daisy.workflow import build_combinations
[ 11748, 12972, 9288, 198, 6738, 12379, 13560, 13, 1818, 11125, 1330, 1382, 62, 24011, 7352, 628, 628, 628, 628, 628, 628, 628 ]
3.318182
22
# class Encoder: # pass # class Decoder: # pass # class VariationAutoEncoder: # pass import os os.environ['CUDA_VISIBLE_DEVICES'] = "0" import pickle import logging from glob import glob import numpy as np from time import time from datetime import datetime from PIL import Image import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import tensorflow as tf import tensorflow.keras.backend as K from tensorflow import keras if not os.path.exists("logs"): os.makedirs("logs") today = datetime.now().strftime('%Y%m%d') logger = logging.getLogger('worldmodels') logger.setLevel(logging.DEBUG) # Create logger logger = logging.getLogger("worldmodels") formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s') logger.setLevel(logging.DEBUG) # Uncomment to enable console logger streamhandler = logging.StreamHandler() streamhandler.setFormatter(formatter) streamhandler.setLevel(logging.DEBUG) logger.addHandler(streamhandler) filehandler = logging.FileHandler(filename='logs/dataset.{}.log'.format(today)) filehandler.setFormatter(formatter) filehandler.setLevel(logging.DEBUG) logger.addHandler(filehandler) AUTOTUNE = tf.data.experimental.AUTOTUNE INPUT_SHAPE = (64,64,3) # INPUT_SHAPE = (128,128,3) LATENT_DIM = 32 encoder_input = keras.Input(shape=(INPUT_SHAPE), name='encoder_input_image') x = keras.layers.Conv2D(32, 4, strides=(2,2), activation='relu', name='conv-1')(encoder_input) x = keras.layers.Conv2D(64, 4, strides=(2,2), activation='relu', name='conv-2')(x) x = keras.layers.Conv2D(128, 4, strides=(2,2), activation='relu', name='conv-3')(x) x = keras.layers.Conv2D(256, 4, strides=(2,2), activation='relu', name='conv-4')(x) # x = keras.layers.Conv2D(512, 4, strides=(2,2), activation='relu', name='conv-5')(x) encoder_last_conv_shape = K.int_shape(x)[1:] logger.info("encoder_last_conv_shape: {}".format(encoder_last_conv_shape)) x = keras.layers.Flatten()(x) mu = keras.layers.Dense(LATENT_DIM, activation='linear', name="mean")(x) logvar = keras.layers.Dense(LATENT_DIM, activation='linear', name="variance")(x) encoder = keras.Model(encoder_input, [mu, logvar], name='encoder') encoder.summary() sampled_latent_vector = keras.layers.Lambda(sample)([mu, logvar]) decoder_input = keras.layers.Input(shape=K.int_shape(sampled_latent_vector)[1:], name='decoder_input') x = keras.layers.Dense(np.prod(encoder_last_conv_shape))(decoder_input) x = keras.layers.Reshape((1,1,np.prod(encoder_last_conv_shape)))(x) x = keras.layers.Conv2DTranspose(128, kernel_size=5, strides=(2,2), activation='relu')(x) x = keras.layers.Conv2DTranspose(64, kernel_size=5, strides=(2,2), activation='relu')(x) x = keras.layers.Conv2DTranspose(32, kernel_size=6, strides=(2,2), activation='relu')(x) # x = keras.layers.Conv2DTranspose(32, kernel_size=4, strides=(2,2), activation='relu')(x) decoder_output = keras.layers.Conv2DTranspose(3, kernel_size=6, strides=(2,2))(x) decoder = keras.Model(decoder_input, decoder_output, name='decoder') decoder.summary() # Taken from tensorflow VAE example def train(fnames, output_dirname="output", epochs=600, save_every_pct=0.3, print_every_pct=0.05): logger.info('Total files: {}'.format(len(fnames))) path_ds = tf.data.Dataset.from_tensor_slices(fnames) image_ds = path_ds.map(load_preprocess_image, num_parallel_calls=AUTOTUNE) # Dataset BATCH_SIZE = 64 SHUFFLE_BUFFER_SIZE = len(fnames) train_dataset = image_ds \ .shuffle(SHUFFLE_BUFFER_SIZE) \ .repeat() \ .batch(BATCH_SIZE) \ .prefetch(buffer_size=AUTOTUNE) if not os.path.exists(output_dirname): os.makedirs('{}/ckpt'.format(output_dirname)) os.makedirs('{}/imgs'.format(output_dirname)) # Number of training epochs # EPOCHS = 600 logger.info('Training epochs: {}'.format(epochs)) # Initialize the Variational Autoencoder model model = VAE(encoder, decoder) # Define optimizer optimizer = keras.optimizers.Adam(1e-4) # keep track of losses losses = [] # How often to print the loss print_every = max(int(print_every_pct * epochs), 1) # Model Checkpoint # Save model and optimizer ckpt = tf.train.Checkpoint(optimizer=optimizer, model=model) # Set save path and how many checkpoints to save checkpoint_path = '{}/ckpt/'.format(output_dirname) logger.info('Checkpoints will be stored at {}'.format(checkpoint_path)) manager = tf.train.CheckpointManager(ckpt, checkpoint_path, max_to_keep=2) # Load the latest checkpoint and restore latest_ckpt = manager.latest_checkpoint ckpt.restore(latest_ckpt) if latest_ckpt: logger.info('Restored from {}'.format(latest_ckpt)) else: logger.info('Training from scratch') # How often to save the checkpoint save_every = max(int(save_every_pct * epochs), 1) # We are now ready to start the training loop elapsed_loop_time = time() for epoch in range(0, epochs): for train_x in train_dataset: loss = train_step(train_x, model, optimizer) losses.append(loss) if epoch % print_every == 0: now = datetime.now().strftime('%Y-%m-%d %H:%M:%S') logger.info('{}:Epoch {}/{}: train loss {} in {} seconds'.format(epoch, epochs, losses[-1], time()-elapsed_loop_time)) elapsed_loop_time = time() if epoch % save_every == 0: save_path = manager.save() logger.info('Saved checkpoint for step {}:{}'.format(epoch, save_path)) # Final Save save_path = manager.save() logger.info('Saved checkpoint for step {}'.format(save_path)) if __name__ == "__main__": # Toons # fnames = glob('{}/*.png'.format("/mnt/bigdrive/datasets/cartoonset/cartoonset10k/")) # train(fnames, output_dirname="toons128") # Car racing fnames = glob('{}/*.png'.format("/mnt/bigdrive/projects/public_repos/world-models/src/imgs/")) train(fnames, output_dirname="car_racing")
[ 2, 1398, 14711, 12342, 25, 198, 2, 220, 220, 220, 220, 1208, 198, 198, 2, 1398, 34580, 25, 198, 2, 220, 220, 220, 220, 1208, 198, 198, 2, 1398, 15965, 341, 27722, 27195, 12342, 25, 198, 2, 220, 220, 220, 220, 1208, 198, 198, 117...
2.460499
2,443
import time from config import get_password, get_username from playwright.sync_api import Page
[ 11748, 640, 198, 6738, 4566, 1330, 651, 62, 28712, 11, 651, 62, 29460, 198, 6738, 711, 29995, 13, 27261, 62, 15042, 1330, 7873, 628, 198 ]
3.88
25