content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. #You may obtain a copy of the License at # # https://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 tensorflow as tf import numpy as np import ops
[ 2, 15069, 2864, 3012, 11419, 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, 13789, 13, 198, 2, 1639, 743, 733...
4.027933
179
import numpy as np import imageio from evaluation.eval_utils import to_img_padded, format_img, init_evaluation main()
[ 11748, 299, 32152, 355, 45941, 198, 11748, 2939, 952, 198, 198, 6738, 12660, 13, 18206, 62, 26791, 1330, 284, 62, 9600, 62, 79, 29373, 11, 5794, 62, 9600, 11, 2315, 62, 18206, 2288, 628, 628, 198, 12417, 3419, 198 ]
3.153846
39
# # HttpServer.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # Server to implement the http part of the oneM2M Mcx communication interface. # from __future__ import annotations import logging, sys, traceback, urllib3 from copy import deepcopy from typing import Any, Callable, Tuple, cast import flask from flask import Flask, Request, make_response, request from urllib3.exceptions import RequestError from Configuration import Configuration from Constants import Constants as C from Types import ReqResp, ResourceTypes as T, Result, ResponseCode as RC, JSON, Conditions from Types import Operation, CSERequest, RequestHeaders, ContentSerializationType, RequestHandler, Parameters, RequestArguments, FilterUsage, FilterOperation, DesiredIdentifierResultType, ResultContentType, ResponseType import CSE, Utils from Logging import Logging as L, LogLevel from resources.Resource import Resource from werkzeug.wrappers import Response from werkzeug.serving import WSGIRequestHandler from werkzeug.datastructures import MultiDict from webUI import WebUI from helpers.BackgroundWorker import * # # Types definitions for the http server # FlaskHandler = Callable[[str], Response] """ Type definition for flask handler. """ ########################################################################## # # Own request handler. # Actually only to redirect some logging of the http server. # This handler does NOT handle requests. #
[ 2, 198, 2, 197, 43481, 10697, 13, 9078, 198, 2, 198, 2, 197, 7, 66, 8, 12131, 416, 33728, 41828, 198, 2, 197, 34156, 25, 347, 10305, 513, 12, 2601, 682, 13789, 13, 4091, 262, 38559, 24290, 2393, 329, 2252, 3307, 13, 198, 2, 198,...
3.918848
382
""" Tests for the sprockets.mixins.statsd package """ import mock import socket try: import unittest2 as unittest except ImportError: import unittest from tornado import httputil from tornado import web from sprockets.mixins import statsd as statsd
[ 37811, 198, 51, 3558, 329, 262, 599, 10823, 1039, 13, 19816, 1040, 13, 34242, 67, 5301, 198, 198, 37811, 198, 11748, 15290, 198, 11748, 17802, 198, 28311, 25, 198, 220, 220, 220, 1330, 555, 715, 395, 17, 355, 555, 715, 395, 198, 163...
3.117647
85
#!/usr/bin/env python # -*- coding: UTF-8 -*- import os from base import BaseObject from base import CryptoBase from base import FileIO from datadb2.core.dmo import BaseDB2Client def cendant(self) -> BaseDB2Client: """ :return: """ return self._connect(self._values(self._config['cendant'])) if __name__ == "__main__": # BuildDb2Url().wft_dev() # BuildDb2Url().wft_prod() BuildDb2Url().cendant()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 41002, 12, 23, 532, 9, 12, 628, 198, 11748, 28686, 198, 198, 6738, 2779, 1330, 7308, 10267, 198, 6738, 2779, 1330, 36579, 14881, 198, 6738, 2779, 1330, 9220...
2.417112
187
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Deep Clustering modeller class """ from .. import torch_imported if torch_imported: import torch import torch.nn as nn 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, 37811, 198, 29744, 1012, 436, 1586, 953, 12368, 1398, 198, 37811, 198, 198, 6738, 11485, 1330, 28034, 62, 320, 9213, 19...
2.653333
75
""" 67 - Faa um programa que mostre a tabuada de vrios nmeros, um de cada vez, para cada valor digitado pelo usurio. O programa ser interrompido quando o nmero solicitado for negativo. """ while True: n = int(input('Informe um nmero para ver sua tabuada: ')) if n < 0: break print('-' * 13) for m in range(1, 11): print(f'{n} x {m} = {n*m}') print('-' * 13) print('Programa encerrado.')
[ 37811, 8275, 532, 376, 7252, 23781, 1430, 64, 8358, 749, 260, 257, 7400, 84, 4763, 390, 410, 380, 418, 299, 647, 418, 11, 23781, 390, 269, 4763, 1569, 89, 11, 31215, 269, 4763, 1188, 273, 16839, 4533, 16176, 78, 198, 385, 333, 952, ...
2.26738
187
from django.shortcuts import render from django.http import HttpResponse from .models import Image,Category,Location # def delete_image(request, pk): # gallery = get_object_or_404(Cat, pk=pk) # if request.method == 'POST': # gallery.delete() # return redirect('/') # return render(request, 'all-galleries/today-gallery.html', {"gallery": gallery})
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 42625, 14208, 13, 4023, 220, 1330, 367, 29281, 31077, 198, 6738, 764, 27530, 1330, 7412, 11, 27313, 11, 14749, 628, 628, 198, 198, 2, 825, 12233, 62, 9060, 7, 25927, 11, 279...
2.301075
186
from typing import Dict from StructNoSQL import TableDataModel, BaseField, MapModel
[ 6738, 19720, 1330, 360, 713, 198, 6738, 32112, 2949, 17861, 1330, 8655, 6601, 17633, 11, 7308, 15878, 11, 9347, 17633, 628 ]
4.047619
21
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # <pep8-80 compliant> bl_info = { "name": "Blockbuster extended OBJ format", "author": "Campbell Barton, Bastien Montagne, McHorse", "version": (0, 1, 0), "blender": (2, 77, 0), "location": "File > Export", "description": "Export Blockbuster OBJ models (meshes, armatures and keyframes)", "warning": "", "category": "Export" } import bpy from bpy.props import (BoolProperty, FloatProperty, StringProperty, EnumProperty) from bpy_extras.io_utils import (ExportHelper, orientation_helper_factory, path_reference_mode, axis_conversion) IOOBJOrientationHelper = orientation_helper_factory("IOOBJOrientationHelper", axis_forward='Z', axis_up='Y') # Export panel # Register and stuff def menu_func_export(self, context): self.layout.operator(ExportOBJ.bl_idname, text="Blockbuster OBJ (.bobj)") def register(): bpy.utils.register_module(__name__) bpy.types.INFO_MT_file_export.append(menu_func_export) def unregister(): bpy.utils.unregister_module(__name__) bpy.types.INFO_MT_file_export.remove(menu_func_export) if "bpy" in locals(): import importlib if "export_bobj" in locals(): importlib.reload(export_bobj) if __name__ == "__main__": register()
[ 2, 46424, 347, 43312, 38644, 38559, 24290, 9878, 11290, 46424, 198, 2, 198, 2, 220, 770, 1430, 318, 1479, 3788, 26, 345, 460, 17678, 4163, 340, 290, 14, 273, 198, 2, 220, 13096, 340, 739, 262, 2846, 286, 262, 22961, 3611, 5094, 1378...
3.007429
673
# Generated by Django 2.2.5 on 2019-12-14 15:11 import django.utils.timezone from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 362, 13, 17, 13, 20, 319, 13130, 12, 1065, 12, 1415, 1315, 25, 1157, 198, 198, 11748, 42625, 14208, 13, 26791, 13, 2435, 11340, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.926829
41
# -*- coding=utf-8 -*- import pygame from bf_form import BFForm from bf_button import BFButton from globals import LanguageConfigParser, LanguageLib
[ 2, 532, 9, 12, 19617, 28, 40477, 12, 23, 532, 9, 12, 198, 11748, 12972, 6057, 198, 6738, 275, 69, 62, 687, 1330, 347, 5777, 579, 198, 6738, 275, 69, 62, 16539, 1330, 41646, 21864, 198, 6738, 15095, 874, 1330, 15417, 16934, 46677, ...
3.166667
48
# -*- coding: utf-8 -*- """ Created on Thu Oct 4 14:09:44 2018 @author: VeNoMzZxHD """ import tkinter from tkinter.filedialog import askopenfilename from collections import Counter import re import string #Returns string of text file def readFile(): ''' tkinter.Tk().withdraw() inputfilename = askopenfilename() ''' inputfilename = 'big.txt' with open(inputfilename) as inputfile: return inputfile.read() #Returns Counter dictionary containing words and their number of occurences within the input file #Returns list of possible permutations of removing a single char from input word. countDict = countWords(readFile()) while True: inword = input("Type quit to exit, or input word: \n") if inword.lower() == 'quit': break correction = findCorrection(inword) if correction=="": print("No correction found") else: print(correction)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 26223, 2556, 220, 604, 1478, 25, 2931, 25, 2598, 2864, 198, 198, 31, 9800, 25, 8016, 2949, 44, 89, 57, 87, 10227, 198, 37811, 198, 198, 11748, ...
2.817629
329
#!/usr/bin/env python # **************************************** # ############# # IMPORTS # ############# # standard python packages import ConfigParser, copy, inspect, logging, os, sys from Node import Node if not os.path.abspath( __file__ + "/../../../lib/iapyx/src" ) in sys.path : sys.path.append( os.path.abspath( __file__ + "/../../../lib/iapyx/src" ) ) from utils import tools # **************************************** # ######### # EOF # #########
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 41906, 4557, 1303, 198, 198, 7804, 4242, 2, 198, 2, 220, 30023, 33002, 220, 1303, 198, 7804, 4242, 2, 198, 2, 3210, 21015, 10392, 198, 11748, 17056, 46677, 11, 4866, 11, 1010...
3.14
150
from freezegame.sprite import Sprite
[ 6738, 1479, 89, 1533, 480, 13, 34975, 578, 1330, 33132, 628 ]
3.454545
11
from django.db import models from wagtail.admin.edit_handlers import FieldPanel, StreamFieldPanel from wagtail.core.blocks import StructBlock, CharBlock from wagtail.core.fields import StreamField from wagtail.core.models import Page from wagtail.images.edit_handlers import ImageChooserPanel from wagtailmarkdown.blocks import MarkdownBlock from invest.blocks.location import LocationAccordionItemBlock from invest.blocks.markdown import MarkdownAccordionItemBlock
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 266, 363, 13199, 13, 28482, 13, 19312, 62, 4993, 8116, 1330, 7663, 26639, 11, 13860, 15878, 26639, 198, 198, 6738, 266, 363, 13199, 13, 7295, 13, 27372, 1330, 32112, 12235, 11, 3178, ...
3.671875
128
from utility.sweetie import serve serve()
[ 6738, 10361, 13, 34751, 494, 1330, 4691, 201, 198, 201, 198, 2655, 303, 3419 ]
3.142857
14
from dataclasses import dataclass, field from enum import Enum from typing import Optional __NAMESPACE__ = "NISTSchema-SV-IV-atomic-ID-enumeration-5-NS"
[ 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 11, 2214, 198, 6738, 33829, 1330, 2039, 388, 198, 6738, 19720, 1330, 32233, 198, 198, 834, 45, 29559, 47, 11598, 834, 796, 366, 45, 1797, 4694, 2395, 2611, 12, 50, 53, 12, 3824, 12, 47...
2.803571
56
#!/usr/bin/env python3 # pylint: disable=no-self-use """Test unit.""" import unittest if __name__ == "__main__": unittest.main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 279, 2645, 600, 25, 15560, 28, 3919, 12, 944, 12, 1904, 198, 37811, 14402, 4326, 526, 15931, 198, 198, 11748, 555, 715, 395, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, ...
2.362069
58
''' this file creates the objects used to access the scrobbling service api No actual creds should be stored here! This module will be imported and used by the main code ''' import os import sys import pylast try: API_KEY = os.environ["LASTFM_API_KEY"] API_SECRET = os.environ["LASTFM_API_SECRET"] except KeyError: API_KEY = "my_api_key" API_SECRET = "my_apy_secret" try: lastfm_username = os.environ["LASTFM_USERNAME"] lastfm_password_hash = os.environ["LASTFM_PASSWORD_HASH"] print("Environment variables for user OK") except KeyError: # In order to perform a write operation you need to authenticate yourself lastfm_username = "my_username" # You can use either use the password, or find the hash once and use that lastfm_password_hash = pylast.md5("my_password") print(lastfm_password_hash) # lastfm_password_hash = "my_password_hash" print("Environment variables for user missing! So far:") print(f"API_KEY: {API_KEY}") print(f"API_SECRET: {API_SECRET}") print(f"LFM USER: {lastfm_username}") print(f"LPW HASH: {lastfm_password_hash}") lastfm_network = pylast.LastFMNetwork( api_key=API_KEY, api_secret=API_SECRET, username=lastfm_username, password_hash=lastfm_password_hash, ) TRACK_SEPARATOR = " - "
[ 7061, 6, 428, 2393, 8075, 262, 5563, 973, 284, 1895, 262, 629, 22609, 11108, 2139, 40391, 628, 220, 220, 220, 1400, 4036, 2600, 82, 815, 307, 8574, 994, 0, 198, 220, 220, 220, 770, 8265, 481, 307, 17392, 290, 973, 416, 262, 1388, ...
2.602767
506
import os import urwid from .globalBase import * from .urwidHelper import * from .tool import * #import dc from .myutil import *
[ 201, 198, 11748, 28686, 201, 198, 11748, 2956, 28029, 201, 198, 201, 198, 6738, 764, 20541, 14881, 1330, 1635, 201, 198, 201, 198, 6738, 764, 333, 28029, 47429, 1330, 1635, 201, 198, 6738, 764, 25981, 1330, 1635, 201, 198, 201, 198, 2...
2.607143
56
# runs t-tests over the null hypothesis # avg_gini if (priority == "newer") == avg_gini if (priority == "more active") import csv import numpy as np from scipy.stats import ttest_ind from scipy.special import stdtr def readCsvFile(fileName): ''' (string) => list of dicts Read the file called fileName and put its content in computer memory ''' allData = [] # data go here as list of dicts with open(fileName) as csvfile: reader = csv.DictReader(csvfile) for row in reader: allData.append(row) return allData def computeTtests (data): ''' (list of dicts) => list of dicts Execute t-tests on data. Return results in an easy-to-read form, i.e.: [ { 'globalchattiness': value, 'intimacystrength': value, 'randomisedchattiness': value, 'policy': value, 'dropouts': value, 'totalmembershipstrength': value, 'totalcomments': value, 'managementeffort':value', 'ms_gini': value, 'nc_gini': value }, ... ] ''' results = [] # assign the parameter space in which we operate for globChat in [.1, .2, .4]: for intStren in [1, 5, 11]: for randChat in ["true", "false"]: for pol in ["engage", "both"]: # keep track of parameters' values result ={} result['globalchattiness'] = globChat result['intimacystrength'] = intStren result['randomisedchattiness'] = randChat result['policy'] = pol # take care of non-Gini variables first for nonGiniVar in ['dropouts', 'totalmembershipstrength', 'totalcomments', 'mgmteffort']: # accumulate in two lists the values, separated by priority moreActiveArray = [] newerArray = [] # read the data. for row in data: if ( float(row['globalchattiness']) == globChat and int(row['intimacystrength']) == intStren and row['randomisedchattiness'] == randChat and row['policy'] == pol): if row['priority'] == 'newer': newerArray.append(float(row[nonGiniVar])) elif row['priority'] == 'more active': moreActiveArray.append(float(row[nonGiniVar])) # save the means relative to the moreActive and newer cases result[nonGiniVar + '_n_mean'] = float(sum(newerArray))/len(newerArray) result[nonGiniVar + '_ma_mean'] = float(sum(moreActiveArray))/len(moreActiveArray) # compute the t-tests. When T is positive, moreActive > newer thisTest = ttest_ind(moreActiveArray, newerArray, equal_var = 'False') result[nonGiniVar + '_t'] = float(thisTest[0]) result[nonGiniVar + '_pVal'] = float(thisTest[1]) # now the two Ginis for giniVar in ['ms', 'nc']: # no need for lists, I have already calculated means and SEs # read the data. for row in data: if ( float(row['globalchattiness']) == globChat and int(row['intimacystrength']) == intStren and row['randomisedchattiness'] == randChat and row['policy'] == pol): if row['priority'] == 'newer': newerMean = float(row[giniVar + '_avg_gini']) newerSE = float(row[giniVar + '_inblockse']) elif row['priority'] == 'more active': moreActiveMean = float(row[giniVar + '_avg_gini']) moreActiveSE = float(row[giniVar + '_inblockse']) # save mean values result[giniVar + '_gini_n_mean'] = newerMean result[giniVar + '_gini_ma_mean'] = moreActiveMean # compute the t-tests. When T is positive, moreActive > newer tStat = (moreActiveMean - newerMean) / np.sqrt((moreActiveSE**2 + newerSE**2)/24) result[giniVar + '_gini_t'] = tStat dof = (moreActiveSE/24 + newerSE/24)**2 / (moreActiveSE**2/(24**2*23) + newerSE**2/(24**2*23)) result[giniVar + '_gini_pVal'] = 2*stdtr(dof, -np.abs(tStat)) results.append(result) return results def saveCsvFile(data, filename): ''' (list of dicts. str) => NoneType saves list of dicts into a CSV file called filename ''' # get the fieldnames from the data: with open (filename, 'w') as csvfile: fieldnames = sorted(data[0].keys()) writer = csv.DictWriter(csvfile, fieldnames = fieldnames) writer.writeheader() for row in data: writer.writerow(row) def findTrends(data): ''' (list of dicts) => NoneType prints some info to screen ''' moreActiveMoreInclusivity1 = 0 moreActiveMoreInclusivity2 = 0 moreActiveMoreActivity = 0 moreActiveMoreDiversity = 0 moreActiveMoreLoyalty = 0 for row in data: if row['dropouts_t'] < 0 and row['dropouts_pVal'] < .01: moreActiveMoreInclusivity1 += 1 if row['ms_gini_t'] < 0 and row['ms_gini_pVal'] < .01: moreActiveMoreInclusivity2 += 1 if row['totalcomments_t'] > 0 and row['totalcomments_pVal'] < .01: moreActiveMoreActivity += 1 if row['nc_gini_t'] < 0 and row['nc_gini_pVal'] < 0.1: moreActiveMoreDiversity += 1 if row['totalmembershipstrength_t'] > 0 and row['totalmembershipstrength_pVal'] < .01: moreActiveMoreLoyalty += 1 print 'Priority "more active" has FEWER dropouts: ' + str(moreActiveMoreInclusivity1) print 'Priority "more active" has MORE inclusivity (lower Gini on ms): ' + str(moreActiveMoreInclusivity2) print 'Priority "more active" has MORE comments: ' + str(moreActiveMoreActivity) print 'Priority "more active" has MORE diversity (lower gini on nc): ' + str(moreActiveMoreDiversity) print 'Priority "more active" has MORE loyalty (higher total membership strength): ' + str(moreActiveMoreLoyalty) newerMoreInclusivity1 = 0 newerMoreInclusivity2 = 0 newerMoreActivity = 0 newerMoreDiversity = 0 newerMoreLoyalty = 0 for row in data: if row['dropouts_t'] > 0 and row['dropouts_pVal'] < .01: newerMoreInclusivity1 += 1 if row['ms_gini_t'] > 0 and row['ms_gini_pVal'] < .01: newerMoreInclusivity2 += 1 if row['totalcomments_t'] < 0 and row['totalcomments_pVal'] < .01: newerMoreActivity += 1 if row['nc_gini_t'] > 0 and row['nc_gini_pVal'] < 0.1: newerMoreDiversity += 1 if row['totalmembershipstrength_t'] < 0 and row['totalmembershipstrength_pVal'] < .01: newerMoreLoyalty += 1 print 'Priority "newer" has FEWER dropouts: ' + str(newerMoreInclusivity1) print 'Priority "newer" has MORE inclusivity (lower Gini on ms): ' + str(newerMoreInclusivity2) print 'Priority "newer" has MORE comments: ' + str(newerMoreActivity) print 'Priority "newer" has MORE diversity (lower gini on nc): ' + str(newerMoreDiversity) print 'Priority "newer" has MORE loyalty (higher total membership strength): ' + str(newerMoreLoyalty) if __name__ == '__main__': dirPath = '/Users/albertocottica/github/local/community-management-simulator/Data/' allData = readCsvFile(dirPath + 'ready-4-tTest.csv') results = computeTtests(allData) saveCsvFile(results, dirPath + 'tTestsResults.csv') findTrends(results)
[ 2, 4539, 256, 12, 41989, 625, 262, 9242, 14078, 220, 198, 2, 42781, 62, 1655, 72, 611, 357, 49336, 6624, 366, 3605, 263, 4943, 6624, 42781, 62, 1655, 72, 611, 357, 49336, 6624, 366, 3549, 4075, 4943, 198, 198, 11748, 269, 21370, 198...
1.960538
4,384
''' Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]nums[i]). Return the running sum of nums. '''
[ 7061, 6, 198, 15056, 281, 7177, 997, 82, 13, 775, 8160, 257, 2491, 2160, 286, 281, 7177, 355, 2491, 13065, 58, 72, 60, 796, 2160, 7, 77, 5700, 58, 15, 60, 77, 5700, 58, 72, 35944, 198, 198, 13615, 262, 2491, 2160, 286, 997, 82, ...
2.78
50
# -*- coding: utf-8 -*- import imported import foo.bar print(imported.__doc__)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 17392, 198, 11748, 22944, 13, 5657, 198, 198, 4798, 7, 320, 9213, 13, 834, 15390, 834, 8, 198 ]
2.382353
34
# Copyright 2014 Alistair Muldal <alistair.muldal@pharm.ox.ac.uk> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import numpy as np import warnings import datetime import subprocess from matplotlib import pyplot as plt from itertools import izip from sklearn import metrics def adjacency2vec(M): """ Unpack an n-by-n directed adjacency matrix to a 1D vector of connection weights Arguments ---------- M: 2D float array adjacency matrix, where: M[i, j] corresponds to w(i->j) Returns ---------- ij: 2D int array 2-by-npairs array of row/column indices w_ij: 1D int array corresponding weights, i.e. w(i->j) """ ncells = M.shape[0] ij = all_directed_connections(ncells) # sanity check # npairs = ncells * (ncells - 1) # assert ij.shape[1] == npairs i, j = ij w_ij = M[i, j] return ij, w_ij def vec2adjacency(ij, connected): """ Pack a 1D vector of connection weights into an n-by-n directed adjacency matrix Arguments ---------- ij: 2D int array 2-by-npairs array of row/column indices w_ij: 1D int array corresponding weights, i.e. w(i->j) Returns ---------- M: 2D float array adjacency matrix, where: M[i, j] corresponds to w(i->j) M[j, i] corresponds to w(j->i) """ npairs = connected.size # 0 = ncells**2 - ncells -npairs roots = np.roots((1, -1, -npairs)) ncells = int(roots[roots > 0]) M = np.zeros((ncells, ncells), dtype=connected.dtype) for (ii, jj), cc in izip(ij.T, connected): M[ii, jj] = cc return M def real2dense(real_connections, n=None, adj=False): """ The network data provided for the challenge lists connections weighted '-1' (which aren't actually present in the simulation), and does not list any weights for pairs of nodes that are not connected. This function converts the provided data into a more convenient dense vector format compatible with adjacency2vec and roc, where every possible directed pair of nodes has a True/False weight. Arguments: ----------- real_connections: 2D np.ndarray or tables.(C)Array npairs-by-3 array, whose columns represent (i, j, connected(i->j)). i, j are assumed to follow MATLAB indexing convenions (i.e. they start at 1). n: positive int, optional the total number of nodes (cells). if unspecified, this is taken to be the maximum index in the first two columns of real_connections plus 1. Returns: ---------- ij: 2D int array 2-by-npairs array of row/column indices connected: boolean vector, True where i->j is connected """ if n is None: n = int(real_connections[:, :2].max()) if np.any(real_connections[:, :2] > n): raise ValueError('real_connections contains indices > n') # handle CArrays real_connections = real_connections[:] # cast to integers real_connections = real_connections.astype(np.int) # find the indices of the cells that are genuinely connected ('1' means # connection, either '-1', '0' or omission means no connection). ij_con = real_connections[(real_connections[:, 2] == 1), :2].T # we subtract 1 from the indices because MATLAB-style indexing starts at 1, # whereas Python indexing starts at 0 ij_con -= 1 # we'll do this the lazy way - construct an adjacency matrix from the # connected indices ... M = np.zeros((n, n), dtype=np.bool) M[ij_con[0, :], ij_con[1, :]] = True if adj: return M else: # ... then convert this directly to the desired format ij, connected = adjacency2vec(M) return ij, connected def all_directed_connections(n): """ For an n-by-n adjacency matrix, return the indices of the nodes for every possible directed connection, i.e. (i->j) and (j->i), but not (i->i) or (j->j) Arguments: n: int number of nodes Returns: idx: 2D int array [2, n * (n - 1)] array of i, j indices """ # all possible pairs of indices (including repeated indices) all_idx = np.indices((n, n)).T.reshape(-1, 2).T # remove repeated indices repeats = (all_idx[0, :] == all_idx[1, :]) idx = all_idx[:, ~repeats] return idx def roc(weights, ground_truth, nsteps=None, do_plot=False, show_progress=True): """ Compute ROC curve and performance metrics for a given set of posterior connection probabilities and the set of ground-truth connections Arguments: ---------- weights: 1D float array vector of posterior probabilities for each possible pairwise connection ground_truth: 1D bool array vector of ground-truth connections nsteps: int, optional number of linear steps between the minimum and maximum values of weights at which to compute the FPR and TPR. if unspecified, every unique value of weights is used, so that the ROC curve is computed exactly do_plot: bool, optional make a pretty plot show_progress: bool, optional show a pretty progress bar Returns: --------- thresh: 1D float array vector of threshold values used for computing the ROC curve fpr: 1D float array false-positive rate at each threshold value tpr: 1D float array true-positive rate at each threshold value pl10: float 10% performance level (tpr at the threshold value that gives 10% false-positives) auc: float area under the ROC curve """ # make sure we're dealing with 1D arrays weights = weights.ravel() ground_truth = ground_truth.ravel() if weights.size != ground_truth.size: raise ValueError('Input vectors must have the same number of elements') fpr, tpr, thresh = metrics.roc_curve(ground_truth, weights, pos_label=True) auc = metrics.roc_auc_score(ground_truth, weights) # 'performance level' is defined as the fraction of true positives at 10% # false-positives pl10 = tpr[fpr.searchsorted(0.1, side='left')] if do_plot: fig, ax = plt.subplots(1, 1, figsize=(5, 5)) ax.hold(True) ax.set_xlim(0, 1) ax.set_ylim(0, 1) ax.set_aspect('equal') ax.plot(fpr, tpr, '-b', lw=2) ax.set_xlabel('False-positive rate') ax.set_ylabel('True-positive rate') ax.set_title('ROC') bbox_props = dict(boxstyle='round', fc='w', ec='0.5') arrow_props = dict(arrowstyle='->', color='k', linewidth=2) ax.annotate('AUC = %.4g' % auc, xy=(0.9, 0.1), xycoords='axes fraction', ha='right', va='bottom', bbox=bbox_props, fontsize=16) plt.show() return thresh, fpr, tpr, pl10, auc
[ 2, 15069, 1946, 978, 396, 958, 8252, 335, 282, 1279, 49845, 958, 13, 30300, 335, 282, 31, 746, 1670, 13, 1140, 13, 330, 13, 2724, 29, 198, 198, 2, 770, 1430, 318, 1479, 3788, 25, 345, 460, 17678, 4163, 340, 290, 14, 273, 13096, ...
2.477927
3,126
#!/usr/bin/env python3 # by affggh # Apcache 2.0 import os import sys import shutil import zipfile import subprocess import platform import requests if os.name == 'nt': import tkinter as tk if os.name == 'posix': from mttkinter import mtTkinter as tk # While Load some need thread funcion on Linux it will failed # Just use mttkinter replace regular tkinter from tkinter.filedialog import * from tkinter import ttk from tkinter import * #import ttkbootstrap as ttk import time import webbrowser import threading # Hide console , need ```pip install pywin32``` # import win32gui, win32con # the_program_to_hide = win32gui.GetForegroundWindow() # win32gui.ShowWindow(the_program_to_hide, win32con.SW_HIDE) if __name__=='__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 220, 416, 1527, 70, 456, 198, 2, 5949, 23870, 362, 13, 15, 220, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 4423, 346, 198, 11748, 19974, 7753, 198, 11748, 850, 14681, 1...
2.839552
268
from .helpers import * from .decorators import *
[ 6738, 764, 16794, 364, 1330, 1635, 198, 6738, 764, 12501, 273, 2024, 1330, 1635, 198 ]
3.266667
15
import sys sys.path.append("..") from gym_snake.envs.node import Node from gym_snake.envs.snake_env import action_to_vector from gym_snake.envs.snake_env import SnakeAction from gym_snake.envs.snake_env import SnakeCellState from gym_snake.envs.snake_env import rotate_action_clockwise from gym_snake.envs.snake_env import rotate_action_counter_clockwise from gym_snake.envs.snake_env import invert_action from gym_snake.queue import Queue
[ 11748, 25064, 201, 198, 17597, 13, 6978, 13, 33295, 7203, 492, 4943, 201, 198, 201, 198, 6738, 11550, 62, 16184, 539, 13, 268, 14259, 13, 17440, 1330, 19081, 201, 198, 6738, 11550, 62, 16184, 539, 13, 268, 14259, 13, 16184, 539, 62, ...
2.634286
175
import discord from discord.ext import commands import asyncio import logging import sys import requests import datetime from bs4 import BeautifulSoup from util import * from wowapi import WowApi, WowApiException, WowApiConfigException from killpoints import KillPoints from math import ceil base_wow_progress = "http://www.wowprogress.com" base_wow_armory = "http://us.battle.net/wow/en/character/{0}/{1}/advanced" base_wc_logs = "https://www.warcraftlogs.com:443/v1" class_array = [ "Warrior", "Paladin", "Hunter", "Rogue", "Priest", "Death Knight", "Shaman", "Mage", "Warlock", "Monk", "Druid", "Demon Hunter" ] race_map = { 1: "Human", 2: "Orc", 3: "Dwarf", 4: "Night Elf", 5: "Undead", 6: "Tauren", 7: "Gnome", 8: "Troll", 9: "Goblin", 10: "Blood Elf", 11: "Draenei", 22: "Worgen", 24:"Pandaren", 25:"Pandaren", 26:"Pandaren" } artifactLevelCost = { 1: { "cost": 100, "total": 100 }, 2: { "cost": 300, "total": 400 }, 3: { "cost": 325, "total": 725 }, 4: { "cost": 350, "total": 1075 }, 5: { "cost": 375, "total": 1450 }, 6: { "cost": 400, "total": 1850 }, 7: { "cost": 425, "total": 2275 }, 8: { "cost": 450, "total": 3250 }, 9: { "cost": 525, "total": 3875 }, 10: { "cost": 625, "total": 4625 }, 11: { "cost": 750, "total": 4625 }, 12: { "cost": 875, "total": 5500 }, 13: { "cost": 1000, "total": 6500 }, 14: { "cost": 6840, "total": 13340 }, 15: { "cost": 8830, "total": 22170 }, 16: { "cost": 11280, "total": 33450 }, 17: { "cost": 14400, "total": 47850 }, 18: { "cost": 18620, "total": 66470 }, 19: { "cost": 24000, "total": 90470 }, 20: { "cost": 30600, "total": 121070 }, 21: { "cost": 39520, "total": 160590 }, 22: { "cost": 50880, "total": 211470 }, 23: { "cost": 64800, "total": 276270 }, 24: { "cost": 82500, "total": 358770 }, 25: { "cost": 105280, "total": 464050 }, 26: { "cost": 138650, "total": 602700 }, 27: { "cost": 182780, "total": 785480 }, 28: { "cost": 240870, "total": 1026350 }, 29: { "cost": 315520, "total": 1341870 }, 30: { "cost": 417560, "total": 1759430 }, 31: { "cost": 546000, "total": 2305430 }, 32: { "cost": 718200, "total": 3023630 }, 33: { "cost": 946660, "total": 3970290 }, 34: { "cost": 1245840, "total": 5216130 }, 35: { "cost": 1635200, "total": 6851330 }, 36: { "cost": 1915000, "total": 8766330 }, 37: { "cost": 2010000, "total": 10776330 }, 38: { "cost": 2110000, "total": 12886330 }, 39: { "cost": 2215000, "total": 15101330 }, 40: { "cost": 2325000, "total": 17426330 }, 41: { "cost": 2440000, "total": 19866330 }, 42: { "cost": 2560000, "total": 22426330 }, 43: { "cost": 2690000, "total": 25116330 }, 44: { "cost": 2825000, "total": 27941330 }, 45: { "cost": 2965000, "total": 30906330 }, 46: { "cost": 3115000, "total": 34021330 }, 47: { "cost": 3270000, "total": 37291330 }, 48: { "cost": 3435000, "total": 40726330 }, 49: { "cost": 3605000, "total": 44331330 }, 50: { "cost": 3785000, "total": 48116330 }, 51: { "cost": 3975000, "total": 52091330 }, 52: { "cost": 4175000, "total": 56266330 }, 53: { "cost": 4385000, "total": 60651330 }, 54: { "cost": 4605000, "total": 65256330 } } artifactKnowledge = { 0: 1, 1: 1.25, 2: 1.5, 3: 1.9, 4: 2.4, 5: 3, 6: 3.75, 7: 4.75, 8: 6, 9: 7.5, 10: 9.5, 11: 12, 12: 15, 13: 18.75, 14: 23.5, 15: 29.5, 16: 37, 17: 46.5, 18: 58, 19: 73, 20: 91, 21: 114, 22: 143, 23: 179, 24: 224, 25: 250 } apRewards = { "+2-3": 500, "+4-6": 800, "+7-9": 1000, "10+": 1200, } set_wow_api_key() set_wclogs_api_key() # Logger info discord_logger = logging.getLogger('discord') discord_logger.setLevel(logging.CRITICAL) bot = commands.Bot(command_prefix='!', description ='Progress Bot') """ Events Region """ """ Commands Region """ bot.run('MjczNTgyNTAwNTk1MzY3OTM2.C2lq3A.imEczu1BMAqrOYJfZEBTPJavOvc')
[ 11748, 36446, 198, 6738, 36446, 13, 2302, 1330, 9729, 198, 11748, 30351, 952, 198, 11748, 18931, 198, 11748, 25064, 198, 11748, 7007, 198, 11748, 4818, 8079, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 6738, 7736, 1330, 1635, 1...
2.283626
1,710
# -*- coding: utf-8 -*- """Module for reading and parsing values from Fingrid APIs.""" # Copyright (c) TUT Tampere University of Technology 2015-2018. # This software has been developed in Procem-project funded by Business Finland. # This code is licensed under the MIT license. # See the LICENSE.txt in the project root for the license terms. # # Main author(s): Ville Heikkila, Otto Hylli, Pekka Itavuo, # Teemu Laukkarinen ja Ulla-Talvikki Virta import copy import csv import datetime import json import requests import time try: import adapters.common_utils as common_utils import adapters.rest_utils as rest_utils except: # used when running the module directly import common_utils import rest_utils
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 26796, 329, 3555, 290, 32096, 3815, 422, 376, 278, 6058, 23113, 526, 15931, 198, 198, 2, 15069, 357, 66, 8, 309, 3843, 11552, 431, 260, 2059, 286, 8987, 1853, 1...
3.134454
238
# script to generate an overview file of all measurentoverview files import os import sys
[ 2, 4226, 284, 7716, 281, 16700, 2393, 286, 477, 3953, 429, 2502, 1177, 3696, 198, 198, 11748, 28686, 198, 11748, 25064, 198 ]
4.136364
22
#!/usr/bin/env python3 import pytest import autosnapgene as snap
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 12972, 9288, 198, 11748, 44619, 77, 499, 70, 1734, 355, 11495, 198 ]
2.75
24
from typing import Set, List from inspectable import Inspectable from interactable import Interactable from items import Batteries, Hammer from usable import Usable
[ 6738, 19720, 1330, 5345, 11, 7343, 198, 198, 6738, 10104, 540, 1330, 20904, 540, 198, 6738, 9427, 540, 1330, 4225, 529, 540, 198, 6738, 3709, 1330, 347, 1436, 444, 11, 18278, 198, 6738, 24284, 1330, 4021, 540, 628 ]
4.394737
38
print("aprendiendo git") a=12 print("ya qued") print("actualizacion 1") print("catualizacion 2")
[ 4798, 7203, 499, 10920, 72, 31110, 17606, 4943, 198, 64, 28, 1065, 198, 4798, 7203, 3972, 627, 276, 4943, 198, 4798, 7203, 50039, 528, 49443, 352, 4943, 198, 4798, 7203, 9246, 723, 528, 49443, 362, 4943 ]
2.666667
36
import argparse from pathlib import Path if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--frames-path", type=str) parser.add_argument("--output-path", type=str) args = parser.parse_args() frame_paths = [p for p in Path(args.frames_path).iterdir()] with open(args.output_path, "w") as f: for p in sorted(Path(args.frames_path).iterdir()): f.write('{"image_path": "%s"}\n' % str(p))
[ 11748, 1822, 29572, 198, 6738, 3108, 8019, 1330, 10644, 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, 198, 220, 220, 220, 30751, 13, 2860, ...
2.475936
187
import _thread import sqlalchemy from app.document import bp from flask_login import login_required, current_user from flask import render_template, redirect, url_for, request, send_file, flash, jsonify from flask import current_app from app.document.general import create_document, check_and_remove_document, save_image, \ get_collaborators_select_data, save_collaborators, is_document_owner, is_user_owner_or_collaborator,\ remove_image, get_document_images, get_page_layout, get_page_layout_text, update_confidences, is_user_trusted,\ is_granted_acces_for_page, is_granted_acces_for_document, get_line_image_by_id, get_sucpect_lines_ids, \ compute_scores_of_doc, skip_textline, get_line, is_granted_acces_for_line, create_string_response, \ update_baselines, make_image_preview, find_textlines, get_documents_with_granted_acces, \ check_and_change_public_document, is_document_public from werkzeug.exceptions import NotFound from app.db.general import get_requests from app.db.general import get_user_documents, get_document_by_id, get_user_by_email, get_all_documents,\ get_previews_for_documents, get_image_by_id, get_public_documents from app.document.forms import CreateDocumentForm from app.document.annotation_statistics import get_document_annotation_statistics, get_user_annotation_statistics, get_document_annotation_statistics_by_day from io import BytesIO import dateutil.parser import zipfile import time import os import json import re from natsort import natsorted def image_preview(image_id=None, public_access=False): if image_id is None: return send_file('static/img/missing_page.png', cache_timeout=10000000) try: db_image = get_image_by_id(image_id) except (sqlalchemy.exc.StatementError, sqlalchemy.orm.exc.NoResultFound): return "Image does not exist.", 404 document_id = db_image.document_id if public_access: db_document = get_document_by_id(db_image.document_id) if not db_document.is_public: return send_file('static/img/missing_page.png', cache_timeout=10000000) else: if not is_granted_acces_for_document(document_id, current_user): return send_file('static/img/missing_page.png', cache_timeout=10000000) image_preview_path = os.path.join(current_app.config['PREVIEW_IMAGES_FOLDER'], str(document_id), str(image_id) + '.jpg') if not os.path.isfile(image_preview_path): make_image_preview(db_image) return send_file(image_preview_path, cache_timeout=0) def get_image_common(image_id, public=False): try: image_db = get_image_by_id(image_id) except sqlalchemy.exc.StatementError: return "Image does not exist.", 404 if public: if not image_db.document.is_public: return "Image is not public.", 403 elif not is_granted_acces_for_page(image_id, current_user): return "You do not have access to the requested images.", 403 image_path = os.path.join(current_app.config['UPLOADED_IMAGES_FOLDER'], image_db.path) if not os.path.isfile(image_path): print("ERROR: Could not find image on disk. image id: {}, image path: {}.".format(image_id, image_path)) raise NotFound() return send_file(image_path, as_attachment=True, attachment_filename=image_db.filename, cache_timeout=10000000)
[ 11748, 4808, 16663, 198, 11748, 44161, 282, 26599, 198, 6738, 598, 13, 22897, 1330, 275, 79, 198, 6738, 42903, 62, 38235, 1330, 17594, 62, 35827, 11, 1459, 62, 7220, 198, 6738, 42903, 1330, 8543, 62, 28243, 11, 18941, 11, 19016, 62, 1...
2.670837
1,279
""" This module defines a packet structure (composed of: canari, payload, payload_size, and eventually an extra payload). You'll find a 'pack' functions allowing you to create a packet from a payload (btyes object) you want to send, and an 'unpack' function that can extract a payload from a packet (as a bytes object too) after validating the packet structure (canari, checksum, length). packet[64]: abcd abcdefghabcdefghabcd abcdefgh ^ ^ ^ canari[4] checksum[20] payload_size[8] payload_size <-------------------------------------------> abcdefghabcdefghabcdefghabcdefgh [...] ^ ^ payload[32] extra_payload """ import collections import struct import hashlib CANARI = 0xdeadbeef CANARI_SIZE = 4 # unsigned int CHECKSUM_SIZE = 20 # sha1 INT_SIZE = 8 # unsigned long long PAYLOAD_MIN_SIZE = 32 # TODO: tweak me based on DbClient requests size: 256-32 PACKET_MIN_SIZE = ( CANARI_SIZE + CHECKSUM_SIZE + INT_SIZE + PAYLOAD_MIN_SIZE ) # 64 CHECKSUM_OFFSET = CANARI_SIZE + CHECKSUM_SIZE # we'll start hasing from there STRUCT_FORMAT = ( "!" "I" # canari f"{CHECKSUM_SIZE}s" # checksum "Q" # payload_size "{payload_size}s" # payload: complete its size using format ) Packet = collections.namedtuple( "Packet", ["canari", "checksum", "payload_size", "payload"] ) def _checksum(bytes_buf): """Return the sha1 digest of the given 'bytes_buf'.""" return hashlib.sha1(bytes_buf[CHECKSUM_OFFSET:]).digest() def _verify_checksum(ctrl_checksum, bytes_buf): """ Return True if the given 'ctrl_checksum' matches the checksum of 'bytes_buf', otherwise throw a ValueError. """ if ctrl_checksum != _checksum(bytes_buf): raise ValueError("packet: invalid checksum") return True def pack(payload, with_checksum=True): """ Create a packet from the given 'payload' byte object that you want to send. If the 'with_checksum' argument is True, the checksum of the payload will be calculated and inserted in the packet, otherwise the checksum will be set to zeros. Returns a bytes object of the created packet (ready to send). """ packet = Packet( canari=CANARI, checksum=b"\x00" * CHECKSUM_SIZE, payload_size=len(payload), payload=payload.ljust(PAYLOAD_MIN_SIZE, b"\x00") ) payload_size = max(packet.payload_size, PAYLOAD_MIN_SIZE) try: bytes_buf = struct.pack( STRUCT_FORMAT.format(payload_size=payload_size), *packet ) except struct.error as e: raise ValueError(f"packet: {e}") if with_checksum: packet = packet._replace(checksum=_checksum(bytes_buf)) bytes_buf = struct.pack( STRUCT_FORMAT.format(payload_size=payload_size), *packet ) return bytes_buf def unpack(bytes_buf, with_checksum=True): """ Extract the payload (as a bytes object) from the given 'bytes_buf' packet. If the 'with_checksum' argument is True, the checksum in the packet will be checked against a calculated checksum of the packet payload. Otherwise it will just be ignored. Returns a bytes object of the extracted payload. A ValueError will be thrown if an invalid packet is given as 'bytes_buf' (invalid canari, checksum, payload length) """ # first, we try to unpack as if it was a 64 bytes packet try: packet = struct.unpack( STRUCT_FORMAT.format(payload_size=PAYLOAD_MIN_SIZE), bytes_buf[:PACKET_MIN_SIZE] ) except struct.error as e: raise ValueError(f"packet: {e}") packet = Packet(*packet) if packet.canari != CANARI: raise ValueError("packet: the canari is dead") # payload can fit in a 64 bytes packet: just verify checksum, then job done if packet.payload_size <= PAYLOAD_MIN_SIZE: if with_checksum: _verify_checksum(packet.checksum, bytes_buf) packet = packet._replace( payload=packet.payload[:packet.payload_size] ) return packet # packet is actually bigger than 64 bytes (extra_payload) if len(bytes_buf) <= PACKET_MIN_SIZE: return packet # the payload is incomplete, and checksum not verified try: packet = struct.unpack( STRUCT_FORMAT.format(payload_size=packet.payload_size), bytes_buf ) except struct.error as e: raise ValueError(f"packet: {e}") packet = Packet(*packet) if with_checksum: _verify_checksum(packet.checksum, bytes_buf) return packet # complete packet with extra payload
[ 37811, 198, 1212, 8265, 15738, 257, 19638, 4645, 198, 7, 5589, 1335, 286, 25, 460, 2743, 11, 21437, 11, 21437, 62, 7857, 11, 290, 4191, 281, 3131, 21437, 737, 198, 1639, 1183, 1064, 257, 705, 8002, 6, 5499, 5086, 345, 284, 2251, 257...
2.365041
2,071
""" API interfaces for swagger operations. """ from typing import ( Any, Iterable, Mapping, Tuple, ) from marshmallow import Schema from marshmallow.fields import Field from microcosm_flask.swagger.parameters import Parameters from microcosm_flask.swagger.schemas import Schemas def build_schema(schema: Schema, strict_enums: bool = True) -> Mapping[str, Any]: """ Build JSON schema from a marshmallow schema. """ builder = Schemas(build_parameter=build_parameter, strict_enums=strict_enums) return builder.build(schema) def iter_schemas(schema: Schema, strict_enums: bool = True) -> Iterable[Tuple[str, Any]]: """ Build zero or more JSON schemas for a marshmallow schema. Generates: name, schema pairs. """ builder = Schemas(build_parameter=build_parameter, strict_enums=strict_enums) return builder.iter_schemas(schema) def build_parameter(field: Field, **kwargs) -> Mapping[str, Any]: """ Build JSON parameter from a marshmallow field. """ builder = Parameters(**kwargs) return builder.build(field)
[ 37811, 198, 17614, 20314, 329, 1509, 7928, 4560, 13, 198, 198, 37811, 198, 6738, 19720, 1330, 357, 198, 220, 220, 220, 4377, 11, 198, 220, 220, 220, 40806, 540, 11, 198, 220, 220, 220, 337, 5912, 11, 198, 220, 220, 220, 309, 29291, ...
2.822165
388
import sys import struct if(len(sys.argv) != 5): print("Usage: python converter.py <num_pixels_x> <num_pixels_y> <input file> <output file>\n") else: num_pixels_x = int(sys.argv[1]) num_pixels_y = int(sys.argv[2]) print(num_pixels_x) has_alpha_channel = False infile = open(sys.argv[3], "rb") data = infile.read() data_len = len(data) if((data_len != (num_pixels_x * num_pixels_y * 4)) or (data_len != (num_pixels_x * num_pixels_y * 3))): AssertionError( "File size does not match given resolution, or does not use 8bpp.") if(data_len == (num_pixels_x * num_pixels_y * 4)): has_alpha_channel = True outfile = open(sys.argv[4], "wb") infile.seek(0) for y in range(num_pixels_y): for x in range(num_pixels_x): r = (int.from_bytes(infile.read(1), 'little') >> 5) & 0x7 g = (int.from_bytes(infile.read(1), 'little') >> 5) & 0x7 b = (int.from_bytes(infile.read(1), 'little') >> 6) & 0x3 if(has_alpha_channel): # Alpha channel, we don't use this _ = infile.read(1) pixel = (b << 6) | (g << 3) | r outfile.write(pixel.to_bytes(1, 'little')) infile.close() outfile.close()
[ 11748, 25064, 198, 11748, 2878, 198, 198, 361, 7, 11925, 7, 17597, 13, 853, 85, 8, 14512, 642, 2599, 198, 220, 220, 220, 3601, 7203, 28350, 25, 21015, 38394, 13, 9078, 1279, 22510, 62, 79, 14810, 62, 87, 29, 1279, 22510, 62, 79, 1...
2.009375
640
# import require package import os upload_dir = './uploads' remove_content(upload_dir) images_dir = './static/images' remove_content(images_dir)
[ 2, 1330, 2421, 5301, 198, 11748, 28686, 628, 198, 198, 25850, 62, 15908, 796, 705, 19571, 39920, 6, 198, 28956, 62, 11299, 7, 25850, 62, 15908, 8, 198, 198, 17566, 62, 15908, 796, 705, 19571, 12708, 14, 17566, 6, 198, 28956, 62, 112...
3.040816
49
""" Fit step for gross alignment and scale. """ from opencmiss.utils.zinc.field import assignFieldParameters, createFieldsDisplacementGradients from opencmiss.utils.zinc.general import ChangeManager from opencmiss.zinc.field import Field, FieldFindMeshLocation from opencmiss.zinc.optimisation import Optimisation from opencmiss.zinc.result import RESULT_OK from scaffoldfitter.fitterstep import FitterStep
[ 37811, 198, 31805, 2239, 329, 10319, 19114, 290, 5046, 13, 198, 37811, 198, 198, 6738, 1280, 66, 3927, 13, 26791, 13, 89, 1939, 13, 3245, 1330, 8333, 15878, 48944, 11, 2251, 15878, 82, 7279, 489, 5592, 42731, 2334, 198, 6738, 1280, 66...
3.578947
114
from abc import ABCMeta, abstractmethod from typing import Any
[ 6738, 450, 66, 1330, 9738, 48526, 11, 12531, 24396, 198, 6738, 19720, 1330, 4377, 628 ]
4.266667
15
import numpy as np import matplotlib.pyplot as plt import pandas as pd blue = (0, 0, 1.0) green = (0, 0.8, 0) red = (1.0, 0, 0) red_alpha = (1.0, 0, 0, 0.001) gray = (0.7, 0.7, 0.7) results = [[],[], ["RandomForestRegressor-K=1",3.527128,2.820386,0.706743,0.063868,0.009973,0.286104,0.420639], ["RandomForestRegressor-K=2",3.036291,2.333874,0.702417,0.075537,0.011347,0.314841,0.387576], ["RandomForestRegressor-K=3",2.823907,2.109897,0.714009,0.087809,0.012335,0.349486,0.364523], ["RandomForestRegressor-K=4",2.715613,1.979086,0.736527,0.102472,0.014302,0.391750,0.344778], ["RandomForestRegressor-K=5",2.643232,1.887080,0.756151,0.111790,0.015411,0.421380,0.334772], ["RandomForestRegressor-K=6",2.642354,1.851498,0.790856,0.125342,0.016268,0.466556,0.324300], ["RandomForestRegressor-K=7",2.636296,1.822316,0.813980,0.134200,0.017159,0.495746,0.318234], ["RandomForestRegressor-K=8",2.623646,1.784344,0.839303,0.146081,0.018631,0.531100,0.308202], ["RandomForestRegressor-K=9",2.645439,1.780447,0.864992,0.152977,0.019492,0.558601,0.306390], ["RandomForestRegressor-K=10",2.638901,1.753437,0.885464,0.160371,0.020184,0.583494,0.301970], ["ExtraTreesRegressor-K=1",3.376099,2.723586,0.652514,0.051864,0.009532,0.230752,0.421761], ["ExtraTreesRegressor-K=2",2.801100,2.146534,0.654566,0.060858,0.011926,0.258086,0.396480], ["ExtraTreesRegressor-K=3",2.536644,1.886837,0.649807,0.067322,0.012756,0.273424,0.376383], ["ExtraTreesRegressor-K=4",2.409943,1.745583,0.664360,0.076519,0.016511,0.302962,0.361399], ["ExtraTreesRegressor-K=5",2.330165,1.651706,0.678459,0.086137,0.017063,0.331515,0.346944], ["ExtraTreesRegressor-K=6",2.285386,1.597063,0.688323,0.092147,0.019216,0.349667,0.338655], ["ExtraTreesRegressor-K=7",2.263983,1.553772,0.710211,0.100322,0.020510,0.378116,0.332094], ["ExtraTreesRegressor-K=8",2.246997,1.528167,0.718831,0.107167,0.021703,0.396323,0.322507], ["ExtraTreesRegressor-K=9",2.236845,1.495768,0.741077,0.115699,0.023020,0.423894,0.317183], ["ExtraTreesRegressor-K=10",2.232862,1.469781,0.763081,0.123849,0.024420,0.451778,0.311304]] max_features = range(1, 10+1) ax = plt.subplot(1, 2, 1) plt.plot(max_features, [results[1+k][1] for k in max_features], 'o-', color=blue, label='Random Forest') plt.plot(max_features, [results[1+k][2] for k in max_features], 'o--', color=blue) plt.plot(max_features, [results[1+k][3] for k in max_features], 'o:', color=blue) plt.plot(max_features, [results[11+k][1] for k in max_features], 'o-', color=red, label='Extremely Randomized Trees') plt.plot(max_features, [results[11+k][2] for k in max_features], 'o--', color=red) plt.plot(max_features, [results[11+k][3] for k in max_features], 'o:', color=red) plt.legend(loc="best") plt.xlabel("$K$") plt.subplot(1, 2, 2, sharex=ax) plt.plot(max_features, [results[1+k][4] for k in max_features], 'o-', color=blue) plt.plot(max_features, [results[11+k][4] for k in max_features], 'o-', color=red) plt.xlabel("$K$") plt.ylabel("$\\rho$") plt.show()
[ 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 17585, 796, 357, 15, 11, 657, 11, 352, 13, 15, 8, 198, 14809, 796, 357, 15, 11, 657, 13, ...
1.955805
1,516
#!/usr/bin/python # Created by: Jose G. Fernandez Trincado # Date: 2013 June 28 # Program: This program correct the imagen .fit (Science) by Syntethic Flat # 1 m Reflector telescope, National Astronomical Observatory of Venezuela # Mode f/5, 21 arcmin x 21 arcmin # Project: Omega Centauri, Tidal Tails. # The program Astrometry_V1.py defined was developed by J. G. Fernandez Trincado at the Centro de Investigaciones de Astronomia "Francisco J. Duarte". # If you have any problems, please contact J. G. Fernandez Trincado, jfernandez@cida.ve / jfernandezt87@gmail.com import numpy as np import scipy as sc import pyfits import sys, os from pyraf import iraf #run, program. #Example: # Next program: ./Run_Vfree-Synthetic_Flat.py GrupoX.dat # >>> GrupoX.dat/XXX.XX.XXX.XX.XXXX.hlv* location='/home/jfernandez/Escritorio/Tesis_2013-2014_CIDA_ULA/Data_Tesis_2013_2014_CIDA-ULA/Reflector/' if len(sys.argv[:]) < 2.: print '***************************************************' print 'Warning: ./Run_Vfree-Synthetic_Flat.py GrupoX.dat' print '***************************************************' else: #Combine images MEDIAN #TASK IRAF: images.immatch.imcombine #Function to combine images for generates Master Flat data=sc.genfromtxt(sys.argv[1],dtype=str) #Lee lista dentro de los directorios, estas listas contienen la ruta de las imagenes ya clasificadas por filtro y tiempo de exposicion. for i in np.arange(len(data)): temp='/Initial_list_Syntethic_flat_' os.system('ls '+data[i]+temp+'* >temporal_classified.dat') data_clas=sc.genfromtxt('temporal_classified.dat',dtype=str) for j in np.arange(len(data_clas)): if data_clas[j] == data[i]+temp+'I60': os.system('cat '+data[i]+temp+'I60 >> MasterFlat_I60_Good.dat') elif data_clas[j] == data[i]+temp+'I90': os.system('cat '+data[i]+temp+'I90 >> MasterFlat_I90_Good.dat') elif data_clas[j] == data[i]+temp+'V60': os.system('cat '+data[i]+temp+'V60 >> MasterFlat_V60_Good.dat') elif data_clas[j] == data[i]+temp+'V90': os.system('cat '+data[i]+temp+'V90 >> MasterFlat_V90_Good.dat') else: pass os.system('rm temporal_classified.dat') os.system('ls MasterFlat_*_Good.dat >list_temp_gen.dat') data_end=sc.genfromtxt('list_temp_gen.dat',dtype=str) for k in np.arange(len(data_end)): print 'Generating Master Flat: '+data_end[k] print '' Master_combina('@'+data_end[k],data_end[k]+'.fit') print 'End of the process' print '' for h in np.arange(len(data)): os.system('cp '+data_end[k]+'.fit '+data[h]+'/') os.system('rm '+data_end[k]+'.fit') os.system('rm list_temp_gen.dat MasterFlat_*_Good.dat') #END
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 2, 15622, 416, 25, 5264, 402, 13, 39692, 833, 1939, 4533, 198, 2, 7536, 25, 2211, 2795, 2579, 198, 2, 6118, 25, 770, 1430, 3376, 262, 3590, 268, 764, 11147, 357, 26959, 8, 416, 26375...
2.501866
1,072
from typing import TYPE_CHECKING from sqlalchemy import Column, Integer, String, Boolean, DateTime, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.sql import func from abing.db.base_class import Base if TYPE_CHECKING: from .arm import Arm # noqa: F401
[ 6738, 19720, 1330, 41876, 62, 50084, 2751, 198, 198, 6738, 44161, 282, 26599, 1330, 29201, 11, 34142, 11, 10903, 11, 41146, 11, 7536, 7575, 11, 8708, 9218, 198, 6738, 44161, 282, 26599, 13, 579, 1330, 2776, 198, 6738, 44161, 282, 26599,...
3.385542
83
mlevel = 1 elevel = 1 mclass_bonus_a = 20 eclass_bonus_a = 0 mclass_bonus_b = 60 eclass_bonus_b = 0 mclass_power = 3 eclass_power = 2 print(damage_exp()) print(defeat_exp()) print(defeat_exp(2)) print(kill_exp())
[ 76, 5715, 796, 352, 198, 68, 5715, 796, 352, 198, 76, 4871, 62, 4189, 385, 62, 64, 796, 1160, 198, 68, 4871, 62, 4189, 385, 62, 64, 796, 657, 198, 76, 4871, 62, 4189, 385, 62, 65, 796, 3126, 198, 68, 4871, 62, 4189, 385, 62, ...
2.206186
97
import requests import json from pymongo import MongoClient, collection client = MongoClient("mongodb://localhost:27017") database = client["temp"] states_districts = database["states_districts"] states_districts.remove({}) headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36" } response = requests.get( "https://cdn-api.co-vin.in/api/v2/admin/location/states", headers=headers ) states = json.loads(response.text)["states"] custom_state_id=1 for state in states: state_id = state["state_id"] state_name = state["state_name"].strip() print(state_name) response = requests.get( "https://cdn-api.co-vin.in/api/v2/admin/location/districts/" + str(state_id), headers=headers, ) custom_district_id=1 temp=[] districts = json.loads(response.text)["districts"] for district in districts: district_id = district["district_id"] district_name = district["district_name"].strip() data={"state_name":state_name,"custom_state_id":custom_state_id,"district_name":district_name,"custom_district_id":custom_district_id,"actual_district_id":district_id} states_districts.insert_one(data) custom_district_id+=1 custom_state_id+=1
[ 11748, 7007, 198, 11748, 33918, 198, 6738, 279, 4948, 25162, 1330, 42591, 11792, 11, 4947, 198, 16366, 796, 42591, 11792, 7203, 31059, 375, 65, 1378, 36750, 25, 1983, 29326, 4943, 198, 48806, 796, 5456, 14692, 29510, 8973, 198, 27219, 62,...
2.563353
513
import tensorflow as tf
[ 11748, 11192, 273, 11125, 355, 48700, 201, 198, 201, 198, 201, 198, 201, 198, 201, 198, 201, 198, 201, 198 ]
1.85
20
import numpy as np # import matplotlib.pyplot as plt # import pylab import re import itertools import json import collections import multiprocessing as mp import random import sys #sys.path.append("./src/") #from proto import io as protoio #from utils.multiprocessor_cpu import MultiProcessorCPU ''' some general pre/post processing tips: 1. should strip the space at the begining or end 2. consider the influence of punctuation at the end 3. be careful about empty string when using lib re functions ''' def LoadJsonData(filePath): ''' Load the file. @param filePath: filePath string ''' with open(filePath) as dataFile: data = json.load(dataFile) return data def DumpJsonPrediction(filePath, predictions): ''' currently only support top 1 prediction. the output put goes in the following format: {id : answer string} ''' predDict = dict() for title in predictions.keys(): for pred in predictions[title]: if len(pred["prediction"] ) == 0: continue predDict[pred["id"] ] = pred["prediction"][0] with open(filePath, "w") as outFile: json.dump(predDict, outFile) def ParseJsonData(data): ''' @param data is a json object. This is the version before visualization functionality. ''' dataPerArticle = dict() for article in data: text = "" # process articles to a list of sentences represented by list of words for paragraph in article["paragraphs"]: text += paragraph["context"].strip() + " " textInSentences = TextToSentence(text) queries = list() answers = list() qaIds = list() for paragraph in article["paragraphs"]: for qaPair in paragraph["qas"]: # turn everything into lower cases queries.append(StripPunct(qaPair["question"].lower().strip() ) ) answers.append(StripPunct(qaPair["answers"][0]["text"].lower().strip() ) ) qaIds.append(qaPair["id"] ) dataPerArticle[article["title"] ] = { \ "textInSentences": textInSentences, "queries": queries, "answers": answers, "qaIds": qaIds } return dataPerArticle def TextToSentence(text): ''' cut document into sentences with the given delimiters @param delimiters: delimiters to cut doc to sentences as a list of char @return sentences: list of full string of sentences ''' caps = "([A-Z])" prefixes = "(Mr|St|Mrs|Ms|Dr)[.]" suffixes = "(Inc|Ltd|Jr|Sr|Co|Corp)" starters = "(Mr|Mrs|Ms|Dr|He\s|She\s|It\s|They\s|Their\s|Our\s|We\s|But\s|However\s|That\s|This\s|Wherever)" acronyms = "([A-Z][.][A-Z][.](?:[A-Z][.])?)" websites = "[.](com|net|org|io|gov)" numbers = "([-+]?)([0-9]+)(\.)([0-9]+)" text = " " + text + " " text = text.replace("\n"," ") text = re.sub(prefixes,"\\1<prd>",text) text = re.sub(websites,"<prd>\\1",text) if "Ph.D" in text: text = text.replace("Ph.D.","Ph<prd>D<prd>") text = re.sub("\s" + caps + "[.] "," \\1<prd> ",text) text = re.sub(acronyms+" "+starters,"\\1<stop> \\2",text) text = re.sub(caps + "[.]" + caps + "[.]" + caps + "[.]","\\1<prd>\\2<prd>\\3<prd>",text) text = re.sub(caps + "[.]" + caps + "[.]","\\1<prd>\\2<prd>",text) text = re.sub(caps + "[.] " + caps + "[.] " + caps + "[.] ","\\1<prd> \\2<prd> \\3<prd>",text) text = re.sub(caps + "[.] " + caps + "[.] ","\\1<prd> \\2<prd>",text) text = re.sub(" "+suffixes+"[.] "+starters," \\1<stop> \\2",text) text = re.sub(" "+suffixes+"[.]"," \\1<prd>",text) text = re.sub(" " + caps + "[.]"," \\1<prd>",text) text = re.sub(numbers, "\\g<1>\\g<2><prd>\\g<4>", text) # # specific to current SQUAD dataset text = text.lower() suffixesSupp = "(\.)([a-z]+)" text = re.sub(suffixesSupp,"<prd>\\2",text) text = text.replace("...", "<elli>") text = text.replace("i.e.", "i<prd>e<prd>") text = text.replace("etc.", "etc<prd>") text = text.replace("u.s.", "u<prd>s<prd>") text = text.replace("v.s.", "v<prd>s<prd>") text = text.replace("vs.", "vs<prd>") text = text.replace(" v. ", " v<prd> ") text = text.replace("med.sc.d", "med<prd>sc<prd>d") text = text.replace("ecl.", "ecl<prd>") text = text.replace("hma.", "hma<prd>") text = text.replace("(r.", "(r<prd>") # for some year related staff text = text.replace("(d.", "(d<prd>") if "\"" in text: text = text.replace(".\"","\".") if "!" in text: text = text.replace("!\"","\"!") if "?" in text: text = text.replace("?\"","\"?") text = text.replace(".",".<stop>") text = text.replace("?","?<stop>") text = text.replace("!","!<stop>") text = text.replace("<prd>",".") text = text.replace("<elli>", "...") sentences = text.split("<stop>") sentences = [s.strip() \ for s in sentences if s.strip() != ''] return sentences def SentenceToWord(sentences): ''' cut sentences to list of words @param sentences: a list of sentences @return sentencesInWords: a list containing list of words ''' delimiters = "[ ,;\"\n\(\)]+" sentencesInWords = list() for sentence in sentences: sentence = StripPunct(sentence) sentence = sentence.replace("...", " ...") sentencesInWords.append(re.split(delimiters, sentence) ) # omit the empty word produced by re.split sentencesInWords[-1] = [s.strip().lower() for s in sentencesInWords[-1] if s.strip() != ''] return sentencesInWords ############### helper to multiprocess per article task with MultiprocessorCPU def MultipleProcess(agent, titleList, targetFunc, conservative=True, debug=False): ''' target function is the one we want to execute for each article. When conservative == True, the num of threads is equal to the number of cores on the machine ''' procs = [] manager = mp.Manager() returnDict = manager.dict() if debug: for title in titleList: targetFunc(agent, title, returnDict) else: for title in titleList: p = mp.Process(target=targetFunc, args=(agent, title, returnDict) ) procs.append(p) processor = MultiProcessorCPU(procs) processor.run(conservative) return returnDict ################ helpers for protobuf based dataset################# def ReconstructStrFromSpan(tokens, span=None): ''' @param tokens: a protobuf object representing a list of tokens @param span: a pair (beginId, endId). Note endId is excluded. ''' if span is None: span = (0, len(tokens)) string = "" beginId, endId = span for i in range(beginId, endId): string += tokens[i].word + tokens[i].after string = string.strip() return string def GetContextBigram(article): ''' article is an protobuf object for apecific article ''' bigram = [] for paragraph in article.paragraphs: bigramByPara = list() for s in paragraph.context.sentence: bigramByPara.append(GetBigramBySentence(s.token) ) bigram.append(bigramByPara) return bigram def GetBigramBySentence(tokens): ''' tokens is a list of proto message object tokens ''' bigram = [] for i in range(len(tokens) - 1): bigram.append( (tokens[i].word.lower(), tokens[i + 1].word.lower() ) ) return bigram def GetContextConstituentSpan(article): ''' @return span: the spans are organized by the following hierarchy span = [spanByPara1, spanByPara2, ...] Where spanByPara1 = [spanBySentence1, spanBySentence2, ...] spanBySentence1 is a list of spans extracted from the parsing tree ''' span = [] for paragraph in article.paragraphs: spanByPara = list() for s in paragraph.context.sentence: # tokens = [token.word for token in s.token] spanBySentence = GetConstituentSpanBySentence(s.parseTree) spanByPara.append(spanBySentence) span.append(spanByPara) return span def GetConstituentSpanBySentence(parseTree): ''' @param parseTree: a protobuf object extract span represented by nodes in the parsing trees ''' def AddSpanToParseTree(parseTree, nextLeaf): ''' @param parseTree: a protobuf object fill in the yieldBeginIndex and yieldEndIndex fields for parsing trees ''' if len(parseTree.child) == 0: parseTree.yieldBeginIndex = nextLeaf parseTree.yieldEndIndex = nextLeaf + 1 return parseTree, nextLeaf + 1 else: for i in range(len(parseTree.child) ): child, nextLeaf = \ AddSpanToParseTree(parseTree.child[i], nextLeaf) parseTree.child[i].CopyFrom(child) parseTree.yieldBeginIndex = parseTree.child[0].yieldBeginIndex parseTree.yieldEndIndex = parseTree.child[-1].yieldEndIndex return parseTree, nextLeaf parseTree, _ = AddSpanToParseTree(parseTree, nextLeaf=0) spans = list() visitList = list() visitList.append(parseTree) tokenList = list() while len(visitList) != 0: node = visitList.pop(0) spans.append( (node.yieldBeginIndex, node.yieldEndIndex) ) for subTree in node.child: visitList.append(subTree) spansUniq = [] [spansUniq.append(span) for span in spans if span not in spansUniq] return spansUniq # some functions for debug def GetCandidateAnsListInStr(candDataPerArticle, origDataPerArtice, ids, predId): ''' for detailed use browse to prediction function of context rnn ''' ansList = list() for idx in ids: predInfo = candDataPerArticle.candidateAnswers[idx] predParaId = predInfo.paragraphIndex predSenId = predInfo.sentenceIndex predSpanStart = predInfo.spanBeginIndex predSpanEnd = predInfo.spanBeginIndex + predInfo.spanLength tokens = origDataPerArticle.paragraphs[predParaId].context.sentence[predSenId].token[predSpanStart:predSpanEnd] predStr = ReconstructStrFromSpan(tokens, (0, len(tokens) ) ) ansList.append(predStr) return ansList # for serializing complex results # display proto tokens # remove the and . from tokens def UnkrizeData(data, rate, padId, unkId): ''' artificially set non-<pad> tokens to <unk>. The portion of the artificial <unk> is indicated by rate. ''' mask = np.random.uniform(low=0.0, high=1.0, size=data.shape) mask = np.logical_and( (data != padId), (mask >= (1 - rate) ) ) data[mask] = unkId return data
[ 11748, 299, 32152, 355, 45941, 198, 2, 1330, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 2, 1330, 279, 2645, 397, 198, 11748, 302, 198, 11748, 340, 861, 10141, 198, 11748, 33918, 198, 11748, 17268, 198, 11748, 18540, 305, 9...
2.38351
4,524
# print("Hello World!") # sum = 2 + 2 # print(sum) # for i in range(10,-10,-1): # if i % 2 == 0: # print(i) # else: # pass # while(1): # val = input("Enter ") # print(val)
[ 2, 3601, 7203, 15496, 2159, 2474, 8, 198, 2, 2160, 796, 362, 1343, 362, 198, 2, 3601, 7, 16345, 8, 198, 198, 2, 329, 1312, 287, 2837, 7, 940, 12095, 940, 12095, 16, 2599, 198, 2, 220, 220, 220, 220, 611, 1312, 4064, 362, 6624, ...
1.864865
111
# -*- coding: utf-8 -*- """User views.""" from flask import Blueprint, render_template, jsonify from flask_login import login_required from super_nft.extensions import csrf_protect datasprint_bp = Blueprint("datasprint", __name__, url_prefix="/datasprint", static_folder="../static")
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 12982, 5009, 526, 15931, 198, 6738, 42903, 1330, 39932, 11, 8543, 62, 28243, 11, 33918, 1958, 198, 6738, 42903, 62, 38235, 1330, 17594, 62, 35827, 198, 6738, 2208, ...
3.202247
89
''' Escreva um programa que pergunte o salrio de um funcionrio e calcule o valor do seu aumento. Para salrios superiores a R$1.250,00, calcule um aumento de 10% Para os inferiores ou iguais, o aumento de 15%. ''' salario = float(input('Digite o salrio: R$ ')) if salario < 0: print('Valor invlido!') else: if salario <= 1250: print(f'O aumento ser de R${salario*0.15} e passar a ser R${salario + salario*0.15}') else: print(f'O aumento ser de R${salario * 0.10} e passar a ser R${salario + salario * 0.10}')
[ 7061, 6, 198, 47051, 260, 6862, 23781, 1430, 64, 8358, 583, 70, 6311, 267, 3664, 27250, 390, 23781, 25439, 295, 27250, 304, 2386, 23172, 267, 1188, 273, 466, 384, 84, 198, 64, 1713, 78, 13, 198, 47, 3301, 3664, 380, 418, 2208, 72, ...
2.279661
236
cores = {'vermelho': '\033[31m', 'azul': '\033[34m', 'amarelo': '\033[33m', 'branco': '\033[30m', 'roxo': '\033[35m', 'verde': '\033[32m', 'ciano': '\033[36m', 'limpa': '\033[m', 'preto e branco': '\033[7;30;m'} pintar = str(input('Deseja pintar o seu texto com qual cor? ')).lower() while pintar not in cores: pintar = str(input('Erro! Essa cor no existe. Tente novamente: ')) if pintar in cores: break texto = str(input('Digite seu texto: ')) linhas(cor=pintar, txt=texto)
[ 198, 198, 66, 2850, 796, 1391, 6, 332, 17694, 8873, 10354, 705, 59, 44427, 58, 3132, 76, 3256, 198, 220, 220, 220, 220, 220, 220, 220, 220, 705, 1031, 377, 10354, 705, 59, 44427, 58, 2682, 76, 3256, 198, 220, 220, 220, 220, 220, ...
1.865132
304
# Listing_20-2.py # Copyright Warren & Csrter Sande, 2013 # Released under MIT license http://www.opensource.org/licenses/mit-license.php # Version $version ---------------------------- # Adding an event handler for the button import sys from PyQt4 import QtCore, QtGui, uic form_class = uic.loadUiType("MyFirstGui.ui")[0] # Class definition for the main window app = QtGui.QApplication(sys.argv) myWindow = MyWindowClass() myWindow.show() app.exec_()
[ 2, 7343, 278, 62, 1238, 12, 17, 13, 9078, 201, 198, 2, 15069, 11328, 1222, 327, 27891, 353, 3837, 68, 11, 2211, 201, 198, 2, 28728, 739, 17168, 5964, 220, 220, 2638, 1378, 2503, 13, 44813, 1668, 13, 2398, 14, 677, 4541, 14, 2781, ...
2.77907
172
from serial_comminication import * from utils.decorators import Override __author__ = 'Danyang'
[ 6738, 11389, 62, 785, 1084, 3299, 1330, 1635, 198, 6738, 3384, 4487, 13, 12501, 273, 2024, 1330, 3827, 13154, 198, 198, 834, 9800, 834, 796, 705, 35, 1092, 648, 6, 628, 198 ]
3.09375
32
from typing import Dict from botocore.paginate import Paginator
[ 6738, 19720, 1330, 360, 713, 198, 6738, 10214, 420, 382, 13, 79, 363, 4559, 1330, 31525, 20900, 628, 198 ]
3.473684
19
# Best : O(n + k) # Avg : O(n + k) # Worst O(n + k) # Space worst : O(k) - CAN GET VERY BIG BIG # k - range of values in array # Take every number in arr then add += 1 to index of that number in temporary arrays, then # for every index in temporary arrays add to final_arr that amount of that index number of # how big number at that index is - if arr[23] = 3 then add 23 23 23 and same for negatives # 1. The whole thing can get very ineffective if numbers in arr are big # 2. Possibility of sorting negatives greatly increase time/space complexity # create array len of min(to_sort), do the same as positives, then for final result multiply by -1 to get negatives # and reverse them because we were counting them as positive => [1,5,10] => [-1,-5,-10] => [-10,-5,-1] and # add that array at beginning of positive_sorted to_sort = [52, 63, 12, 6, 631, 6, 24, 637, 64, 421, 74, 124, 0, -5, 523, -10, -529] print(counting_sort(to_sort))
[ 2, 6705, 1058, 440, 7, 77, 1343, 479, 8, 198, 2, 33455, 1058, 440, 7, 77, 1343, 479, 8, 198, 2, 33443, 440, 7, 77, 1343, 479, 8, 198, 2, 4687, 5290, 1058, 440, 7, 74, 8, 532, 15628, 17151, 29550, 26746, 26746, 198, 198, 2, 4...
3.047319
317
import os import random import re import numpy as np np.set_printoptions(precision=3, suppress=True) import sys; sys.path.append("../../..") from job_table import JobTable
[ 11748, 28686, 198, 11748, 4738, 198, 11748, 302, 198, 198, 11748, 299, 32152, 355, 45941, 198, 37659, 13, 2617, 62, 4798, 25811, 7, 3866, 16005, 28, 18, 11, 18175, 28, 17821, 8, 198, 198, 11748, 25064, 26, 25064, 13, 6978, 13, 33295, ...
3.125
56
""" Move Zeroes - https://leetcode.com/problems/move-zeroes/ Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array. Example 1: Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0] Example 2: Input: nums = [0] Output: [0] Constraints: 1 <= nums.length <= 104 -231 <= nums[i] <= 231 - 1 Follow up: Could you minimize the total number of operations done? """
[ 37811, 198, 198, 21774, 37028, 3028, 532, 3740, 1378, 293, 316, 8189, 13, 785, 14, 1676, 22143, 14, 21084, 12, 9107, 3028, 14, 198, 220, 198, 15056, 281, 18253, 7177, 997, 82, 11, 1445, 477, 657, 338, 284, 262, 886, 286, 340, 981, ...
2.755435
184
from django.contrib.auth import login as django_login from django.contrib.auth import logout as django_logout from django.http import HttpResponseRedirect from django.shortcuts import resolve_url from django.conf import settings from .backends import StormpathIdSiteBackend ID_SITE_STATUS_AUTHENTICATED = 'AUTHENTICATED' ID_SITE_STATUS_LOGOUT = 'LOGOUT' ID_SITE_STATUS_REGISTERED = 'REGISTERED' ID_SITE_AUTH_BACKEND = 'django_stormpath.backends.StormpathIdSiteBackend' _handle_registered = _handle_authenticated CALLBACK_ACTIONS = { ID_SITE_STATUS_AUTHENTICATED: _handle_authenticated, ID_SITE_STATUS_LOGOUT: _handle_logout, ID_SITE_STATUS_REGISTERED: _handle_registered, }
[ 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 17594, 355, 42625, 14208, 62, 38235, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 2604, 448, 355, 42625, 14208, 62, 6404, 448, 198, 6738, 42625, 14208, 13, 4023, 1330, 367,...
2.705426
258
# https://leetcode.com/problems/perfect-squares/description/ # dp alg, time complexity: O(n^2)
[ 2, 3740, 1378, 293, 316, 8189, 13, 785, 14, 1676, 22143, 14, 25833, 12, 16485, 3565, 14, 11213, 14, 198, 2, 288, 79, 435, 70, 11, 640, 13357, 25, 440, 7, 77, 61, 17, 8, 628 ]
2.666667
36
# Programa para sorteio from tkinter import * '''import PySimpleGUI as sg''' ''' #Layout layout = [ [sg.Text('Nome:'), sg.Input()], [sg.Button('OK')] ] #Janela janela = sg.Window('Janela teste', layout) #Interao eventos, valores = janela.Read() #Mensagem print(f'Ol {valores[0]}, obrigado por usar PySimpleGUI!') #Encerramento da janela janela.close() ''' ''' cont = 0 participantes = dict() for cont in range(0, 2): participantes["nome"] = str(input('Digite o nome do participante: ')) participantes["numero"] = int(input('Digite o nmero do participante: ')) cont += 1 print(f'{cont} pessoas concorrendo ao sorteio!') print(participantes) ''' '''theme_name_list = sg.theme_list() print(theme_name_list)''' # Sempre inicia com: janela = Tk() janela.title('Sorteio T-force') janela.geometry("400x400") # Texto de orientao: texto_de_orientacao = Label(janela, text='Clique no boto para ver as cotaes das moedas') # Posio do texto: texto_de_orientacao.grid(column=0, row=0, padx=10, pady=10) # Boto + funo botao = Button(janela, text="Buscar cotaes Dlar, Euro e BTC", command=pegar_cotacoes) botao.grid(column=0, row=1, padx=10, pady=10) # Texto das cotaes: texto_cotacoes = Label(janela, text="") texto_cotacoes.grid(column=0, row=2, padx=10, pady=10) # Sempre termina com: janela.mainloop()
[ 2, 6118, 64, 31215, 3297, 68, 952, 198, 6738, 256, 74, 3849, 1330, 1635, 198, 7061, 6, 11748, 9485, 26437, 40156, 355, 264, 70, 7061, 6, 198, 7061, 6, 198, 2, 32517, 198, 39786, 796, 685, 198, 220, 220, 220, 685, 45213, 13, 8206, ...
2.367384
558
""" @author: magician @file: __init__.py.py @date: 2020/9/7 """ from flask import Flask from flask_tutorial.flask_sqlite3.flask_sqlite3 import SQLite3 app = Flask(__name__) app.config.from_pyfile('the-config.cfg') db = SQLite3(app)
[ 37811, 198, 31, 9800, 25, 42055, 198, 31, 7753, 25, 220, 220, 11593, 15003, 834, 13, 9078, 13, 9078, 198, 31, 4475, 25, 220, 220, 12131, 14, 24, 14, 22, 198, 37811, 198, 6738, 42903, 1330, 46947, 198, 198, 6738, 42903, 62, 83, 449...
2.438776
98
"""Transformando um string de numeros, em uma lista com conjunto de numeros separads por \n""" matrix = "1 2 3 4\n4 5 6 5\n7 8 9 6\n8 7 6 7" print(matrix) matrix = matrix.split("\n") print(matrix) matrix2 = [] for n in range(len(matrix)): matrix[n] = matrix[n].split() matrix[n] = list(map(int, matrix[n])) # EX: Tranforma a string '1' em um inteiro matrix2.append(matrix[n][0]) # Pegar o primeiro elemento/numero de cada indice for index in range(4): print(matrix[index]) print() print(matrix2)
[ 37811, 41762, 25440, 23781, 4731, 390, 5470, 418, 11, 795, 334, 2611, 1351, 64, 198, 785, 11644, 403, 1462, 390, 5470, 418, 2880, 5643, 16964, 3467, 77, 37811, 198, 198, 6759, 8609, 796, 366, 16, 362, 513, 604, 59, 77, 19, 642, 718,...
2.4
215
from A_1_Add_columns_participant_info_multiprocessing_new import * from A_2_Merge_new_logs import * from B_1_Add_columns_user_performance_multiprocessing_new import * from B_2_Merge_new_logs_with_user_groups import * from C_1_Post_processing_log_new import * from C_2_Merge_new_logs_post_processed import * from D_1_Recalculate_new_levenshtein import * from D_2_Merge_new_logs_new_levenshtein import * from E_1_Correct_ites_new import * from E_2_Merge_new_logs_corrected import * from F_Finalize_dataset_slim import *
[ 6738, 317, 62, 16, 62, 4550, 62, 28665, 82, 62, 48013, 415, 62, 10951, 62, 16680, 541, 305, 919, 278, 62, 3605, 1330, 1635, 198, 6738, 317, 62, 17, 62, 13102, 469, 62, 3605, 62, 6404, 82, 1330, 1635, 198, 6738, 347, 62, 16, 62, ...
2.509709
206
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='xl-helper', version='1.0.5', description='XL Deploy helper', long_description='This tool helps with installation and upgrade of XL Deploy and plugins', author='Mike Kotsur', author_email='mkotsur@xebialabs.com', url='http://xebialabs.com/', packages=find_packages(where=".", exclude=["tests*"]), package_data={'xl_helper': ['deployit.conf', '.xl-helper.defaults']}, include_package_data=True, install_requires=['jenkinsapi', 'argparse', 'pytz'], scripts=['xl-helper'] )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 198, 40406, 7, 198, 220, 220, 220, 1438, 11639, 87, 75, 12, 2978, 525, 3256, 198, 220, 220, 220, 2196, 11639, 16, ...
2.627193
228
# -*- coding: utf-8 -*- from collections import defaultdict from PyPDF2 import PdfFileReader from PyPDF2.pdf import PageObject, ContentStream, TextStringObject, u_, i, b_ PageObject.extractText_with_separator = extractText_with_separator KEYWORDS = ["procesos electorales"] def find_in_pdf(pdf_path, keywords): """ Try to find a word list into pdf file. .. note: The line number is approximately, not exactly. :param pdf_path: path to pdf :type pdf_path: str :param keywords: list of keyword to search :type keywords: list(str) :return: a structure like this: { PAGE_NUM: { LINE_NUM: TEXT_OF_LINE} :rtype: dict(str: dict(int: str)) """ pdf = PdfFileReader(open(pdf_path, 'rb')) matches = defaultdict(dict) for page_no, page in enumerate(pdf.pages, 1): text = page.extractText_with_separator() line_no = 1 # search for keyword in keywords: for line in text.split("\n"): if not line: continue line_no += 1 if keyword in line.lower(): matches["page_%s" % page_no][line_no] = line return matches if __name__ == '__main__': r = find_in_pdf("BOE.pdf", KEYWORDS) print(r)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 17268, 1330, 4277, 11600, 198, 198, 6738, 9485, 20456, 17, 1330, 350, 7568, 8979, 33634, 198, 6738, 9485, 20456, 17, 13, 12315, 1330, 7873, 10267, 11, 14041, 12124, ...
2.673709
426
from setuptools import setup, find_packages setup( name = "django-netpromoterscore", version = '0.0.2', description = "Model, Tests, and API for collecting promoter score from users.", author = "Austin Brennan", author_email = "ab@epantry.com", url = "https://github.com/epantry/django-netpromoterscore", keywords = ["promoter score", "net promoter score", "django"], install_requires = [], packages = find_packages(), include_package_data=True, )
[ 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 628, 198, 40406, 7, 198, 220, 220, 220, 1438, 796, 366, 28241, 14208, 12, 3262, 16963, 26008, 7295, 1600, 198, 220, 220, 220, 2196, 796, 705, 15, 13, 15, 13, 17, 3256, 198, ...
2.91716
169
import flask
[ 11748, 42903, 628, 198 ]
3.75
4
from pynemo.core.base.abstract.property import Property
[ 6738, 279, 2047, 41903, 13, 7295, 13, 8692, 13, 397, 8709, 13, 26745, 1330, 14161, 628 ]
3.5625
16
import logging import sys from pathlib import Path import time from folio_uuid.folio_namespaces import FOLIONamespaces
[ 11748, 18931, 198, 11748, 25064, 198, 6738, 3108, 8019, 1330, 10644, 198, 11748, 640, 198, 198, 6738, 5955, 952, 62, 12303, 312, 13, 13652, 62, 14933, 43076, 1330, 376, 3535, 2849, 1047, 43076, 628, 628 ]
3.514286
35
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://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. """The tree aggregation protocol for noise addition in DP-FTRL.""" import torch from collections import namedtuple from absl import app Element = namedtuple('Element', 'height value') if __name__ == '__main__': app.run(main)
[ 2, 15069, 33448, 3012, 11419, 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, 13789, 13, 198, 2, 921, 743, 733...
3.728111
217
from django.test import TestCase from ladder.models import Player, Result, League, Season from django.db.models import Avg
[ 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 198, 6738, 18002, 13, 27530, 1330, 7853, 11, 25414, 11, 4041, 11, 7369, 198, 6738, 42625, 14208, 13, 9945, 13, 27530, 1330, 33455, 628 ]
3.875
32
"""Google OpenID Connect identity provider.""" from uuid import UUID from fastapi import Depends, status, Request from pydantic import BaseModel from .base import IdPRouter, oauth from ..http import get_edgedb_pool from ..models import IdPClient, Identity as BaseIdentity, Href, User from ..orm import ExtendedComputableProperty, ExclusiveConstraint, with_block idp = IdPRouter("google") class IdentityOut(BaseModel): iss: str # "https://accounts.google.com" hd: str # "edgedb.com" email: str email_verified: bool name: str picture: str # URL given_name: str family_name: str locale: str # "en"
[ 37811, 11708, 4946, 2389, 8113, 5369, 10131, 526, 15931, 198, 198, 6738, 334, 27112, 1330, 471, 27586, 198, 198, 6738, 3049, 15042, 1330, 2129, 2412, 11, 3722, 11, 19390, 198, 6738, 279, 5173, 5109, 1330, 7308, 17633, 198, 198, 6738, 76...
2.941441
222
"""Import processors from 3rd party sources.""" import contextlib import sys import pkg_resources from ._misc import parameters
[ 37811, 20939, 20399, 422, 513, 4372, 2151, 4237, 526, 15931, 198, 198, 11748, 4732, 8019, 198, 11748, 25064, 198, 198, 11748, 279, 10025, 62, 37540, 198, 198, 6738, 47540, 44374, 1330, 10007, 628 ]
4
33
# # @lc app=leetcode.cn id=412 lang=python3 # # [412] Fizz Buzz # # Accepted # 8/8 cases passed (48 ms) # Your runtime beats 76.37 % of python3 submissions # Your memory usage beats 25 % of python3 submissions (14.5 MB) # @lc code=start # @lc code=end
[ 2, 198, 2, 2488, 44601, 598, 28, 293, 316, 8189, 13, 31522, 4686, 28, 39226, 42392, 28, 29412, 18, 198, 2, 198, 2, 685, 39226, 60, 376, 6457, 15753, 198, 2, 198, 198, 2, 21699, 276, 198, 2, 807, 14, 23, 2663, 3804, 357, 2780, ...
2.694737
95
import pandas as pd import numpy as np from sklearn.model_selection import check_cv from sklearn.exceptions import NotFittedError from sklearn.base import clone, is_classifier from robusta.importance import get_importance from robusta.crossval import crossval from .base import _Selector # Original: sklearn.feature_selection.SelectFromModel def _check_max_features(importances, max_features): """Interpret the max_features value""" n_features = len(importances) if max_features is None: max_features = n_features elif isinstance(max_features, int): max_features = min(n_features, max_features) elif isinstance(max_features, float): max_features = int(n_features * max_features) return max_features def _check_threshold(importances, threshold): """Interpret the threshold value""" if threshold is None: threshold = -np.inf elif isinstance(threshold, str): if "*" in threshold: scale, reference = threshold.split("*") scale = float(scale.strip()) reference = reference.strip() if reference == "median": reference = np.median(importances) elif reference == "mean": reference = np.mean(importances) else: raise ValueError("Unknown reference: " + reference) threshold = scale * reference elif threshold == "median": threshold = np.median(importances) elif threshold == "mean": threshold = np.mean(importances) else: raise ValueError("Expected threshold='mean' or threshold='median' " "got %s" % threshold) else: threshold = float(threshold) return threshold
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 1341, 35720, 13, 19849, 62, 49283, 1330, 2198, 62, 33967, 198, 6738, 1341, 35720, 13, 1069, 11755, 1330, 1892, 37, 2175, 12331, 198, 6738, 1341, 35720,...
2.514727
713
import torch import torch.nn as nn import torch_optimizer as optim import pandas as pd # customized libs import criterions import models import datasets
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 62, 40085, 7509, 355, 6436, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 2, 27658, 9195, 82, 198, 11748, 1955, 263, 507, 198, 11748, 4981, 198, 11748, 405...
3.568182
44
import graphene from fuzzywuzzy import process from falmer.search.types import SearchQuery from falmer.search.utils import get_falmer_results_for_term, get_msl_results_for_term, \ SearchTermResponseData
[ 11748, 42463, 198, 6738, 34669, 86, 4715, 88, 1330, 1429, 198, 198, 6738, 24215, 647, 13, 12947, 13, 19199, 1330, 11140, 20746, 198, 6738, 24215, 647, 13, 12947, 13, 26791, 1330, 651, 62, 42932, 647, 62, 43420, 62, 1640, 62, 4354, 11,...
3.296875
64
#Shape of heart: def for_heart(): """printing shape of'heart' using for loop""" for row in range(6): for col in range(7): if row-col==2 or row+col==8 or col%3!=0 and row==0 or col%3==0 and row==1: print("*",end=" ") else: print(" ",end=" ") print() def while_heart(): """printing shape of'heart' using while loop""" i=0 while i<6: j=0 while j<7: if i-j==2 or i+j==8 or j%3!=0 and i==0 or j%3==0 and i==1: print("*",end=" ") else: print(" ",end=" ") j+=1 print() i+=1
[ 2, 33383, 286, 2612, 25, 201, 198, 4299, 329, 62, 11499, 33529, 201, 198, 220, 220, 220, 37227, 4798, 278, 220, 5485, 286, 6, 11499, 6, 1262, 329, 9052, 37811, 201, 198, 220, 220, 220, 329, 5752, 287, 2837, 7, 21, 2599, 201, 198, ...
1.678657
417
from core import add from core import sub def test_add(): """Check that `add()` works as expected""" assert add(2, 3) == 5 def test_add_z(): """Check that `add()` works as expected""" assert add(2, 3, 1) == 6 def test_sub(): """Check that `sub()` works as expected""" assert sub(3, 1) == 2
[ 6738, 4755, 1330, 751, 198, 6738, 4755, 1330, 850, 628, 198, 4299, 1332, 62, 2860, 33529, 198, 220, 220, 220, 37227, 9787, 326, 4600, 2860, 3419, 63, 2499, 355, 2938, 37811, 198, 220, 220, 220, 220, 198, 220, 220, 220, 6818, 751, 7,...
2.449275
138
from __future__ import annotations from setuptools import setup setup()
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 40406, 3419, 198 ]
4.055556
18
#9. Faaumam funo que receba a altura e o raio de um cilindro circular e retorne o volume #do cilindro. O volume de um cilindro circular calculado por meio da seguinte frmula: #V =pi*raio^2 x altura, onde pi = 3.141592. r=float(input("Informe o raio do cilindro: ")) alt=float(input("Informe a altura do cilindro: ")) volume=volCilindro(3,2) print(volume)
[ 2, 24, 13, 376, 7252, 388, 321, 1257, 78, 8358, 1407, 7012, 257, 5988, 5330, 304, 267, 2179, 952, 390, 23781, 269, 346, 521, 305, 18620, 304, 1005, 8553, 267, 6115, 198, 2, 4598, 269, 346, 521, 305, 13, 440, 6115, 390, 23781, 269,...
2.405405
148
import requests from bs4 import BeautifulSoup from sachima import conf
[ 11748, 7007, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 198, 6738, 264, 620, 8083, 1330, 1013, 628 ]
3.65
20
import tkinter if __name__ == '__main__': application = tkinter.Tk() application.title("Mediator Sample") window = Main(application) application.protocol("WM_DELETE_WINDOW", window.quit) application.mainloop()
[ 11748, 256, 74, 3849, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 3586, 796, 256, 74, 3849, 13, 51, 74, 3419, 198, 220, 220, 220, 3586, 13, 7839, 7203, 9921, 38585, 27565, 4943, 198, ...
2.77381
84
# !/usr/bin/env python # -*- coding: utf-8 -*- import sys urlpatterns = [ ] DEFAULT_SETTINGS = dict( INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sites', 'statictemplate', ], DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3' } }, LANGUAGES=( ('en-us', 'English'), ('it', 'Italian'), ), ROOT_URLCONF='runtests', SITE_ID=1, MIDDLEWARE_CLASSES=[ 'django.middleware.http.ConditionalGetMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ], ) if __name__ == '__main__': runtests()
[ 2, 5145, 14, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 25064, 198, 198, 6371, 33279, 82, 796, 685, 198, 60, 198, 198, 7206, 38865, 62, 28480, 51, 20754, 796,...
2.07839
472
x = input() z = input() splitter = [x[i:] for i in range(len(x))] found_splitter = False next_z = "" for i in range(1, len(x) + 1): if z[:i] in splitter: found_splitter = True next_z = z[i:] if next_z[: len(x)] == x: break if i == len(z): break if next_z == "": if found_splitter is False: print(z) else: if found_splitter is True: while True: if next_z[0 : len(x)] == x: next_z = next_z.replace(x, "", 1) else: print(next_z) break
[ 87, 796, 5128, 3419, 198, 89, 796, 5128, 3419, 628, 198, 22018, 1967, 796, 685, 87, 58, 72, 47715, 329, 1312, 287, 2837, 7, 11925, 7, 87, 4008, 60, 198, 9275, 62, 22018, 1967, 796, 10352, 198, 19545, 62, 89, 796, 13538, 198, 1640,...
1.794479
326
import urllib.request url = "https://google.com" data = urllib.request.urlopen(url) print(data) print(data.read())
[ 11748, 2956, 297, 571, 13, 25927, 198, 198, 6371, 796, 366, 5450, 1378, 13297, 13, 785, 1, 198, 198, 7890, 796, 2956, 297, 571, 13, 25927, 13, 6371, 9654, 7, 6371, 8, 198, 4798, 7, 7890, 8, 198, 4798, 7, 7890, 13, 961, 28955, 19...
2.6
45
from django.conf.urls.defaults import patterns, url from datawinners.blue import view from datawinners.blue.view import new_xform_submission_post, edit_xform_submission_post, get_attachment, attachment_download, guest_survey, public_survey from datawinners.blue.view import ProjectUpload, ProjectUpdate from datawinners.blue.view import new_xform_submission_get from datawinners.project.views.submission_views import edit_xform_submission_get urlpatterns = patterns('', url(r'^guest_survey/(?P<link_uid>.+?)/$', guest_survey, name='guest_survey'), url(r'^survey/(?P<org_id>.+?)/(?P<anonymous_link_id>.+?)/*$', public_survey, name='public_survey'), url(r'^xlsform/upload/$', ProjectUpload.as_view(), name="import_project"), url(r'^xlsform/download/$', view.project_download), url(r'^xlsform/upload/update/(?P<project_id>\w+?)/$', ProjectUpdate.as_view(), name="update_project"), url(r'^xlsform/(?P<project_id>.+?)/web_submission/(?P<survey_response_id>[^\\/]+?)/$', edit_xform_submission_get, name="edit_xform_submission"), url(r'^xlsform/(?P<project_id>\w+?)/web_submission/$', new_xform_submission_get, name="xform_web_questionnaire"), url(r'^xlsform/web_submission/(?P<survey_response_id>.+?)/$', edit_xform_submission_post, name="update_web_submission"), url(r'^xlsform/web_submission/$', new_xform_submission_post, name="new_web_submission"), url(r'^attachment/(?P<document_id>.+?)/(?P<attachment_name>[^\\/]+?)/$', get_attachment), url(r'^download/attachment/(?P<document_id>.+?)/(?P<attachment_name>[^\\/]+?)/$', attachment_download) )
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 13, 12286, 82, 1330, 7572, 11, 19016, 198, 6738, 4818, 707, 259, 2741, 13, 17585, 1330, 1570, 198, 6738, 4818, 707, 259, 2741, 13, 17585, 13, 1177, 1330, 649, 62, 87, 687, 62, 7266, 3411,...
2.567742
620
print('hello man') print('hello man') print('hello man') print('hello man') print('hello man')
[ 4798, 10786, 31373, 582, 11537, 198, 4798, 10786, 31373, 582, 11537, 198, 4798, 10786, 31373, 582, 11537, 198, 4798, 10786, 31373, 582, 11537, 198, 4798, 10786, 31373, 582, 11537, 198 ]
3.166667
30
# # Copyright (c) 2020, NVIDIA CORPORATION. # # 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 glob import os import cudf import numpy as np import pyarrow.parquet as pq try: import cupy as cp except ImportError: import numpy as cp
[ 2, 198, 2, 15069, 357, 66, 8, 12131, 11, 15127, 23929, 44680, 6234, 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, ...
3.467593
216
ROUTE = '/push' PORT = 4242 IMAGE_NAME = 'globidocker/github-hook' import docker cli = docker.Client() from lib.git import clone_tmp
[ 49, 2606, 9328, 796, 31051, 14689, 6, 198, 15490, 796, 604, 27877, 198, 198, 3955, 11879, 62, 20608, 796, 705, 4743, 672, 312, 12721, 14, 12567, 12, 25480, 6, 198, 198, 11748, 36253, 198, 198, 44506, 796, 36253, 13, 11792, 3419, 198, ...
2.634615
52
#!/usr/bin/env python3 # Solver test suite runner script, used for # * regression tests (default) # * test-init runs (with --test-init option) # * performance evaluation (with --performance option) # # 1. Regression tests (the default) # - runs set of projects and compares physical results and solver stats # - meant to be run with either sequential or parallel solver # - performance is monitored, but not so important (very short tests!) # - expects jobs to have reference result directory, otherwise warning is issued # and simulation is skipped (with --run-always option all simulations are done even without # reference result dirs) # - result of script: # for each job show old/new stats and metrics # show summary table with timings for all successful jobs # # 2. Initialization tests # - checks if solver can initialize set of project files # - script parses directory structure, generates list of test-init jobs # and executes test initialization # - result of script: # for each job result status and time needed for test init (only for information) # # 3. Performance tests # - collects list of jobs, runs each job 3 times and stores timings for all cases # - result of script: # for each job print individual timings and best evalualtion time in a table # # License: # BSD License # # Authors: # Andreas Nicolai <andreas.nicolai@tu-dresden.de> # # Syntax: # > python run_tests.py --path <path/to/testsuite> --solver <path/to/solver/binary> --extension <project file extension> # # Example: # > python run_tests.py --path ../../data/tests --solver ./DelphinSolver --extension d6p # > python run_tests.py -p ../../data/tests -s ./DelphinSolver -e d6p # # Returns: # 0 - if all tests could be simulated successfully and if all solver results/metrics match those of reference results # 1 - if anything failed # # Note: if run with --run-all option, test cases without reference results will always be accepted. # import subprocess # import the module for calling external programs (creating subprocesses) import sys import os import os.path import shutil import filecmp # for result file comparison import argparse import platform # to detect current OS from colorama import * from SolverStats import * from print_funcs import * from config import USE_COLORS def configCommandLineArguments(): """ This method sets the available input parameters and parses them. Returns a configured argparse.ArgumentParser object. """ parser = argparse.ArgumentParser("run_tests.py") parser.description = ''' Runs the regression test suite. Can be used for init-tests (--test-init) or performance evaluation (--performance) as well.''' parser.add_argument('-p', '--path', dest='path', required=True, type=str, help='Path to test suite root directory.') parser.add_argument('-s', '--solver', dest='solver', required=True, type=str, help='Path to solver binary.') parser.add_argument('-e', '--extension', dest="extension", required=True, type=str, help='Project file extension.') parser.add_argument('--no-colors', dest="no_colors", action='store_true', help='Disables colored console output.') parser.add_argument('--test-init', dest="test_init", action='store_true', help='Enables test-initialization mode (runs solvers with --test-init argument and ' 'skips result evaluation).') parser.add_argument('--performance', dest="performance", action='store_true', help='Enables performance evaluation mode (runs solvers three times ' 'without result evaluation and dumps timings of all cases and best-of-three timings).') parser.add_argument('--run-all', dest="run_all", action='store_true', help='If set (in regression test mode), also the test cases without reference results ' 'are simulated (can be used to generate reference results for all cases).') return parser.parse_args() def checkResults(dir1, dir2, evalTimes): """ Compares two result directories for equal contents. Compared are: - physical results - solver counters (/log/summary.txt) This function uses IBK.SolverStats Arguments: * dir1 (reference results) and dir2 (computed results) * evalTimes is a dictionary with filepath (key) and wall clock time (value), new entries are always added to the dictionary Returns: True on success, False on error """ try: # open stat files and compare them stats1 = SolverStats() if not stats1.read(dir1 + "/log/summary.txt"): return False stats2 = SolverStats() if not stats2.read(dir2 + "/log/summary.txt"): return False if not SolverStats.compareStats(stats1, stats2, []): printError("Mismatching statistics.") return False # compare all result files (d60, tsv), if any reference result files exist if os.path.exists(dir1 + "/results"): if not SolverStats.compareResults(dir1 + "/results", dir2 + "/results"): printError("Mismatching values.") return False evalTimes[dir2] = stats2.timers['WallClockTime'] except Exception as e: printError("Error comparing simulation results, error: {}".format(e)) return True # *** main script *** args = configCommandLineArguments() if not args.no_colors: init() # init ANSI code filtering for windows config.USE_COLORS = True printNotification("Enabling colored console output") if args.test_init and args.performance: printError("Either use --test-init or --performance, but not both together.") exit(1) # process all directories under test suite directory currentOS = platform.system() compilerID = None if currentOS == "Linux" : compilerID = "gcc_linux" elif currentOS == "Windows" : compilerID = "VC14_win64" elif currentOS == "Darwin" : compilerID = "gcc_mac" if compilerID == None: printError("Unknown/unsupported platform") exit(1) else: print("Compiler ID : " + compilerID) print("Test suite : " + args.path) print("Solver : " + args.solver) print("Project file extension : " + args.extension) # walk all subdirectories (except .svn) within testsuite and collect project file names projects = [] for root, dirs, files in os.walk(args.path, topdown=False): for name in files: if name.endswith('.'+args.extension): projectFilePath = os.path.join(root, name) projects.append(projectFilePath) projects.sort() print("Number of projects : {}\n".format(len(projects))) # performance tests? if args.performance: res = run_performance_evaluation(args, projects) exit(res) failed_projects = [] eval_times = dict() # key - file path to project, value - eval time in [s] for project in projects: print(project) path, fname = os.path.split(project) #print("Path : " + path) #print ("Project : " + fname) # compose path of result folder resultsFolder = project[:-(1+len(args.extension))] # remove entire directory with previous results if os.path.exists(resultsFolder): shutil.rmtree(resultsFolder) cmdline = [args.solver, project] # if in test-init mode, append --test-init to command line if args.test_init: cmdline.append("--test-init") skipResultCheck = True args.run_all = True else: skipResultCheck = False referenceFolder = resultsFolder + "." + compilerID if not os.path.exists(referenceFolder): if not args.run_all: failed_projects.append(project) printError("Missing reference data directory '{}'".format(os.path.split(referenceFolder)[1])) continue else: skipResultCheck = True try: # run solver FNULL = open(os.devnull, 'w') if platform.system() == "Windows": cmdline.append("-x") cmdline.append("--verbosity-level=0") retcode = subprocess.call(cmdline, creationflags=subprocess.CREATE_NEW_CONSOLE) else: if args.test_init: # in test-init mode we want to see the output retcode = subprocess.call(cmdline) else: retcode = subprocess.call(cmdline, stdout=FNULL, stderr=subprocess.STDOUT) # check return code if retcode == 0: # successful run if not skipResultCheck: # now check against reference results if not checkResults(referenceFolder, resultsFolder, eval_times): if not project in failed_projects: failed_projects.append(project) # mark as failed printError("Mismatching results.") else: # mark project as failed failed_projects.append(project) # and print error message printError("Simulation failed, see screenlog file {}".format(os.path.join(os.getcwd(), resultsFolder+"/log/screenlog.txt" ) ) ) except OSError as e: printError("Error starting solver executable '{}', error: {}".format(args.solver, e)) exit(1) print("\nSuccessful projects:\n") print("{:80s} {}".format("Project path", "Wall clock time [s]")) filenames = eval_times.keys() filenames = sorted(filenames) for filename in filenames: fname = os.path.basename(filename) onedir = os.path.join(os.path.basename(os.path.dirname(filename)), os.path.basename(filename)) printNotification("{:80s} {:>10.3f}".format(onedir, eval_times[filename])) if len(failed_projects) > 0: print("\nFailed projects:") for p in failed_projects: printError(p) print("\n") printError("*** Failure ***") exit(1) printNotification("*** Success ***") exit(0)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 2, 4294, 332, 1332, 18389, 17490, 4226, 11, 973, 329, 198, 2, 1635, 20683, 5254, 357, 12286, 8, 198, 2, 1635, 1332, 12, 15003, 4539, 357, 4480, 1377, 9288, 12, 15003, 3038, ...
2.913932
3,230
from torch.utils.data import Dataset
[ 6738, 28034, 13, 26791, 13, 7890, 1330, 16092, 292, 316, 628, 198 ]
3.25
12
import logging import datetime import pathlib import pytz import requests import pandas as pd DATA_ROOT = pathlib.Path(__file__).parent.parent / "data" _logger = logging.getLogger(__name__) if __name__ == "__main__": logging.basicConfig(level=logging.INFO) CovidTrackingDataUpdater().update()
[ 11748, 18931, 198, 11748, 4818, 8079, 198, 11748, 3108, 8019, 198, 11748, 12972, 22877, 198, 11748, 7007, 198, 11748, 19798, 292, 355, 279, 67, 198, 26947, 62, 13252, 2394, 796, 3108, 8019, 13, 15235, 7, 834, 7753, 834, 737, 8000, 13, ...
2.867925
106
from chatty import utils from aiohttp import web from chatty.auth.models import User
[ 6738, 8537, 774, 1330, 3384, 4487, 198, 6738, 257, 952, 4023, 1330, 3992, 198, 198, 6738, 8537, 774, 13, 18439, 13, 27530, 1330, 11787, 628, 198 ]
3.384615
26
import os, sys import imp from authorizenet import apicontractsv1 from authorizenet.apicontrollers import * constants = imp.load_source('modulename', 'constants.py') if(os.path.basename(__file__) == os.path.basename(sys.argv[0])): delete_customer_profile(constants.customerProfileId)
[ 11748, 28686, 11, 25064, 198, 11748, 848, 198, 198, 6738, 1772, 33977, 316, 1330, 2471, 291, 756, 974, 21370, 16, 198, 6738, 1772, 33977, 316, 13, 499, 291, 756, 36667, 1330, 1635, 198, 9979, 1187, 796, 848, 13, 2220, 62, 10459, 10786...
2.815534
103
# Copyright 2021 IBM Corp. # SPDX-License-Identifier: Apache-2.0 from pyspark.sql.dataframe import DataFrame from py4j.java_collections import MapConverter
[ 2, 15069, 33448, 19764, 11421, 13, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 198, 6738, 279, 893, 20928, 13, 25410, 13, 7890, 14535, 1330, 6060, 19778, 198, 6738, 12972, 19, 73, 13, 12355, 62, ...
3.078431
51
from kafka.consumer import KafkaConsumer from json import loads from mongoengine import * from matilda.data_pipeline import object_model consumer = KafkaConsumer( 'numtest', # kafka topic bootstrap_servers=['localhost:9092'], # same as our producer # It handles where the consumer restarts reading after breaking down or being turned off and can be set either # to earliest or latest. When set to latest, the consumer starts reading at the end of the log. # When set to earliest, the consumer starts reading at the latest committed offset. auto_offset_reset='earliest', enable_auto_commit=True, # makes sure the consumer commits its read offset every interval. # join a consumer group for dynamic partition assignment and offset commits # a consumer needs to be part of a consumer group to make the auto commit work. # otherwise, need to do it manually i.e. consumer.assign([TopicPartition('foobar', 2)]); msg = next(consumer) group_id='my-group', # deserialize encoded values value_deserializer=lambda x: loads(x.decode('utf-8'))) atlas_url = get_atlas_db_url(username='AlainDaccache', password='qwerty98', dbname='matilda-db') db = connect(host=atlas_url) # The consumer iterator returns ConsumerRecords, which are simple namedtuples # that expose basic message attributes: topic, partition, offset, key, and value: for message in consumer: message = message.value print(message) object_model.Test(number=message['number']).save() print('{} added to db'.format(message)) # # Then to check whats in it: # for doc in object_model.Test.objects: # print(doc._data)
[ 6738, 479, 1878, 4914, 13, 49827, 1330, 46906, 49106, 198, 6738, 33918, 1330, 15989, 198, 6738, 285, 25162, 18392, 1330, 1635, 198, 198, 6738, 2603, 27281, 13, 7890, 62, 79, 541, 4470, 1330, 2134, 62, 19849, 628, 198, 49827, 796, 46906,...
3.331984
494
from graph import Graph
[ 6738, 4823, 1330, 29681, 201, 198, 201, 198 ]
3.375
8