index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
8,700
9c29f04746de6847ad1bbdf08964d14e6c3766db
from modeltranslation.translator import register, TranslationOptions from .models import * @register(PageTitleModel) class TitleTranslationOptions(TranslationOptions): fields = ( 'name', ) @register(NewsModel) class ProjectTranslationOptions(TranslationOptions): fields = ( 'name', ...
8,701
3dc4e10145ad42c0168fec3462da0f87c1e661a5
class Image: def __init__(self, **kwargs): self.ClientID = kwargs['ClientID'] self.DealerID = kwargs['DealerID'] self.VIN = kwargs['VIN'] self.UrlVdp = None self.PhotoURL = kwargs['PhotoURL'] self.VdpActive = None def __repr__(self): return f"{se...
8,702
e8f090a02bfd5ee8a6832351357594af2d6692f9
import calendar import json from datetime import datetime from datapoller.download import download from datapoller.settings import * from messaging.Messaging import sendMessage from messaging.settings import RABBIT_NOTIFY_QUEUE from sessioncontroller.utils import is_level_interesting_for_kp __author__ = 'arik' shared...
8,703
e38be2890526c640ba8d9db5a376ff57ba9e0aa2
import azure.functions as func import json from ..common import cosmos_client def main(req: func.HttpRequest) -> func.HttpResponse: return func.HttpResponse( body = json.dumps(cosmos_client.DB.Goals), mimetype="application/json", charset="utf-8" ) # [ # {'amoun...
8,704
254afebcc909c805d1e4972a0910eb4451d1e64e
"""Copied from http://svn.sourceforge.jp/svnroot/slothlib/CSharp/Version1/SlothLib/NLP/Filter/StopWord/word/Japanese.txt""" STOP_WORDS = set( """ あそこ あたり あちら あっち あと あな あなた あれ いくつ いつ いま いや いろいろ うち おおまか おまえ おれ がい かく かたち かやの から がら きた くせ ここ こっち こと ごと こちら ごっちゃ これ これら ごろ さまざま さらい さん しかた しよう すか ずつ すね すべて ぜんぶ そう そこ そちら そっち...
8,705
ceb714e949a72f621aec8b8728fbd1201e22afd1
""" Copyright (c) Facebook, Inc. and its affiliates. """ # fmt: off """ Every template contains an ordered list of TemplateObjects. TemplateObject is defined in template_objects.py GetMemory templates are written for filters and have an answer_type They represent the action of fetching from the memory using the filte...
8,706
022c8d6c31ad5494b03bfe93d17396eac25b011e
''' This program will simulate leveling a DnD character, showing their ending HP, and stats. ''' import argparse import csv import json import re import time from openpyxl import load_workbook from pandas import DataFrame from src import classes, util def import_race_data(file_path): ''' This method imports d...
8,707
2294dc21ede759e755e51471705fa8ef784528a7
import requests import json import datetime from bs4 import BeautifulSoup from pymongo import MongoClient, UpdateOne import sys #usage: python freesound_crawler.py [from_page] [to_page] SOUND_URL = "https://freesound.org/apiv2/sounds/" SEARCH_URL = "https://freesound.org/apiv2/search/text/" AUTORIZE_URL = "https://fr...
8,708
45335fa5d4773bdd0ef3e6c340fe06e84169be5e
from flask import Flask, send_file import StringIO app = Flask(__name__) @app.route('/') def index(): strIO = StringIO.StringIO() strIO.write('Hello from Dan Jacob and Stephane Wirtel !') strIO.seek(0) return send_file(strIO, attachment_filename="testing.txt", ...
8,709
11984027baf6d4c97b2976e4ac49a0e8ec62f893
from math import sqrt from numpy import concatenate from matplotlib import pyplot from pandas import read_csv from pandas import DataFrame from pandas import concat from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import LabelEncoder from sklearn.metrics import mean_squared_error from tensorflo...
8,710
077c596f71aae22e85589fdaf78d5cdae8085443
from django.conf.urls import url from . import views from .import admin urlpatterns = [ url(r'^$', views.showberanda, name='showberanda'), url(r'^sentimenanalisis/$', views.showsentimenanalisis, name='showsentimenanalisis'), url(r'^bantuan/$', views.showbantuan, name='showbantuan'), url(r'^tweets/', vi...
8,711
294b0dc7587ecd37887591da5a1afe96a4349f6b
# ????? c=0 for i in range(12): if 'r' in input(): c+=1 # ?? print(c)
8,712
1ab690b0f9c34b1886320e1dfe8b54a5ec6cd4d1
"""Support for Deebot Vaccums.""" import logging from typing import Any, Mapping, Optional import voluptuous as vol from deebot_client.commands import ( Charge, Clean, FanSpeedLevel, PlaySound, SetFanSpeed, SetRelocationState, SetWaterInfo, ) from deebot_client.commands.clean import CleanAc...
8,713
b5dba7c1566721f8bb4ec99bc2f13cae4ade4f0a
#!/usr/bin/python3 -S # -*- coding: utf-8 -*- import netaddr from cargo.fields import MacAddress from unit_tests.fields.Field import TestField from unit_tests import configure class TestMacAddress(configure.NetTestCase, TestField): @property def base(self): return self.orm.mac def test___call__...
8,714
5869669f1e3f648c0ddc68683f0b1d2754b40169
import discord from collections import Counter from db import readDB, writeDB INFO_DB_SUCCESS = 'Database updated successfully!' ERROR_DB_ERROR = 'Error: Unable to open database for writing' ERROR_DB_NOT_FOUND = 'Error: Database for specified game does not exist. Check your spelling or use !addgame first.' ERROR_PLA...
8,715
7c3798aa9cc5424656572dfaa87f7acb961613eb
#!/usr/bin/python # -*- coding: UTF-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import os import unittest import logging from collections import Counter from utility import token_util class TestFileReadingFunctions(unittest.TestCase)...
8,716
50c274e0365f2556a46eb58edcd1f0a7301e89db
# -*- coding: utf-8 -*- # # RPi.Spark KeyButton Demo # # Author: Kunpeng Zhang # 2018.6.6 # # See LICENSE for details. from time import sleep import RPi.GPIO as GPIO from JMRPiSpark.Drives.Key.RPiKeyButtons import RPiKeyButtons from JMRPiSpark.Drives.Key.RPiKeyButtons import DEF_BOUNCE_TIME_SHORT_MON from JMRPiSpark....
8,717
1a6f84835ec2f5fbbb064aef2cd872c24eb3839d
prompt = "Enter a message and I will repeat it to you: " message = " " while message != 'quit': message = input(prompt) if message != 'quit': print(message) # using the 'flag' variable prompt = "Enter a message and I will repeat it to you: " # active is the variable used in this case as flag activ...
8,718
6645887b25d75f4657fb231b80d8ebdec2bac7c9
from django.shortcuts import render from django.views.generic import TemplateView from django.conf import settings import os, csv class InflationView(TemplateView): template_name = 'inflation.html' def get(self, request, *args, **kwargs): # чтение csv-файла и заполнение контекста context = {}...
8,719
e0fc7e5771f6cb8e0638bc8c9549cfe1a92d3d82
from django.urls import path from redjit.post.views import MyPost, PostView urlpatterns = [ path('newpost/', MyPost.as_view(), name='newpost') path('subredjit/<subredjit>/<post_id>/', PostView.as_view(), name='post') ]
8,720
f971302f39149bcdcbe4237cc71219572db600d4
import numpy as np from nn.feedforward_nn import Feed_Forward class RMSprop(object): def __init__(self,n_in,n_hid,n_out,regularization_coe): self.nn = Feed_Forward(n_in,n_hid,n_out,regularization_coe) def set_param(self,param): if 'learning_rate' in param.keys(): self.learning_rat...
8,721
c060cdb7730ba5c4d2240b65331f5010cac222fa
import copy import sys import os from datetime import datetime,timedelta from dateutil.relativedelta import relativedelta import numpy as np import pandas import tsprocClass as tc import pestUtil as pu #update parameter values and fixed/unfixed #--since Joe is so pro-America... tc.DATE_FMT = '%m/%d/%Y' #--build ...
8,722
0bce5d590b96e434cd8aee7531a321bc648c1981
#!/usr/bin/python try: from Queue import Queue except ImportError: # Python 3 from queue import Queue class BFSWithQueue: """Breadth-First Search. Attributes ---------- graph : input graph color : dict with nodes, private distance : dict with nodes (distances to source node) ...
8,723
96a4659f03879e051af95b5aa9c1e1364015fb86
#coding=utf-8 import requests,sys result_url=[] def main(): counts=open(sys.argv[1]).readlines() for line in open(sys.argv[1]): line=line.strip("\n") url=line try: #url="http://s6000.sgcc.com.cn/WebContent/s6000/main/index.jsp#no-back" r=requests.get(u...
8,724
3989b4c2a15fa8cd54fef86f9d7150fbd0fb74cf
import os import sys import shutil import re dl_dir = '/home/acarnec/Downloads/' college_dir = '/home/acarnec/Documents/3rdYear' latex_dir = '/home/acarnec/Documents/Latex/' modules = ['mta', 'ana', 'met', 'log', 'mat', 'lin', 'min', 'pol', 'mic', 'mte'] michaelmas = ['mta', 'ana', 'met', 'log', 'mat']...
8,725
1508697f93114d7f20182a3e9c1df5617904529a
# import libraries import pandas as pd import matplotlib.pyplot as plt import numpy as np import warnings import pickle from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score from sklearn.metrics import mean_squared_error impor...
8,726
de77fa677b3b200a41083e609d4da697f9e77f21
def printall(s): for i in s: print i n=str(raw_input("Enter Word:- ")) printall(n)
8,727
7ff029e2f0054146e438f4e4f13269e83e28c469
import pytest import kdlc from shutil import rmtree import os # from .context import kdlc test_generated_dir = os.path.dirname(__file__) + "/generated/" @pytest.fixture(scope="session") def my_setup(request): print("\nDoing setup") def fin(): print("\nDoing teardown") if os.path.exists(tes...
8,728
2e5d66033c2a049ba2423d01792a629bf4b8176d
# -*- coding: utf-8 -*- # This file is auto-generated, don't edit it. Thanks. from typing import Dict from Tea.core import TeaCore from alibabacloud_tea_openapi.client import Client as OpenApiClient from alibabacloud_tea_openapi import models as open_api_models from alibabacloud_tea_util.client import Client as UtilCl...
8,729
2c8b8e9767ac8400fb6390e0851d9df10df7cd8c
import os import torch from collections import OrderedDict from PIL import Image import numpy as np from matplotlib import pyplot as plt from matplotlib import image as mplimg from torch.nn.functional import upsample import networks.deeplab_resnet as resnet from mypath import Path from dataloaders import helpers as h...
8,730
5848273a76995825f01df53d6beed534e6f9f9fe
############################################################################# ## Crytek Source File ## Copyright (C) 2013, Crytek Studios ## ## Creator: Christopher Bolte ## Date: Oct 31, 2013 ## Description: WAF based build system ############################################################################# from wafl...
8,731
7571e86be1077ae0f7ae542824cfcaaa2949dc83
import numpy as np from scipy.stats import loguniform import sys def generate_parameters(seed): np.random.seed(seed) out={} out['nfeatures'] = np.random.randint(3, 25) out['lr'] = float(loguniform.rvs(0.001, 0.01, size=1)) out['gamma'] = np.random.uniform(0.75, 0.05) out['penalty'] = float(logu...
8,732
fe1a9804862942491b11b9baceecd37bf628fbb8
# addtwo_run-py """ Train and test a TCN on the add two dataset. Trying to reproduce https://arxiv.org/abs/1803.01271. """ print('Importing modules') import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.utils.tensorboard import SummaryWriter from torch.uti...
8,733
6f216420f641c042bb2772b79c10f904ffa21938
import pygame from random import randint, choice BLACK = (0,0,0) #---------------------------------------------------------- class Ball(pygame.sprite.Sprite): #------------------------------------------------------ def __init__(self, color, width, height): # Initialize as a Sprite super(...
8,734
a0310b1bab339064c36ff0fe92d275db7a6c5ba9
from _math import Vector2, Vector3, Quaternion, Transform, Vector3Immutable, QuaternionImmutable, minimum_distance from _math import mod_2pi from math import pi as PI, sqrt, fmod, floor, atan2, acos, asin, ceil, pi, e import operator from sims4.repr_utils import standard_repr import enum import native.animation import ...
8,735
923a2979df3c37583eec712880ad821541bd898b
import numpy as np import matplotlib.pyplot as plt conf_arr = [[ 2987, 58, 955, 832, 1991, 181, 986], [ 142, 218, 195, 44, 235, 11, 27], [ 524, 8, 3482, 478, 2406, 708, 588], [ 140, 0, 386, 12491, 793, 182, 438], [ 368, 15, 883, 635, 6331, 71, ...
8,736
c664257d64b269002964ce95c05f132e563a65d4
from __future__ import division rates = { "GBP-EUR":1.10, "EUR-USD":1.11, "GBP-USD":1.22, "GBP-YEN": 129.36 } def find(rates, fx): try: return rates[fx] except: return -1 def getInputs(): amount = raw_input("Enter amount: ") firstCurrency = raw_input("Enter Currency To Convert From: ") secCurrency = raw_in...
8,737
1dd5c25cd3b7bc933ba0b63d9a42fdddc92b8531
import os import lasagne import theano import theano.tensor as T import numpy as np from lasagne.layers import Conv2DLayer,\ MaxPool2DLayer,\ InputLayer from lasagne.nonlinearities import elu, sigmoid, rectify from lasagne.regularization import l2, regularize_layer_...
8,738
70f2fc6873a78305c74e3c3ad04cb24d72019d56
i = 0 real_value = 8 while i <= 3: guess = int(input('Guess: ')) if guess == real_value: print('You Win!') break else: print('You lose')
8,739
876e9f03c908338a247b6bf1f23011e609bbc2a5
#!/usr/bin/python __author__ = "morganlnance" ''' Analysis functions using PyRosetta4 ''' def get_sequence(pose, res_nums=None): # type: (Pose, list) -> str """ Return the sequence of the <pose>, or, return the sequence listed in <res_nums> :param pose: Pose :param res_nums: list() of Pose residu...
8,740
a9e5d4d48f96974da772f47a4c20ebc96bc31d85
#! /usr/bin/env python import os import glob import math from array import array import sys import time import subprocess import ROOT mass=[600,700,800,900,1000] cprime=[01,02,03,05,07,10] BRnew=[00,01,02,03,04,05] for i in range(len(mass)): for j in range(len(cprime)): for k in range(len(BRnew)): ...
8,741
8b7894e274647e48e3a1fe12473937bd6c62e943
from torch.utils.data import DataLoader from config import Config from torchnet import meter import numpy as np import torch from torch import nn from tensorboardX import SummaryWriter from Funcs import MAvgMeter from vae.base_vae import VAE from vae.data_util import Zinc_dataset import time import torch.optim class ...
8,742
4e86dd74374297c3b0ce8fea93910003dac7d5d7
import random from PyQt4.QtGui import ( QWidget, QHBoxLayout, QPushButton, QMainWindow, QIcon, QAction, QShortcut, QKeySequence, QFileDialog, QMessageBox) from PyQt4 import QtCore class Controls(QWidget): def __init__(self, parent): super(Controls, self).__init__(parent) ...
8,743
c7768e44464703552f579a1ec68b58fd9746a381
# -*- coding: utf-8 -*- """ Created on Tue Apr 24 18:50:16 2018 @author: User """ # -*- coding: utf-8 -*- """ Created on Mon Apr 23 19:05:42 2018 @author: User """ from bs4 import BeautifulSoup import pandas as pd import numpy as np import lxml import html5lib import csv path = 'E:/Data Scienc...
8,744
aa24442624aebeb2777f16a826cf59859d7870ba
import torch.nn as nn from torch.autograd import Variable import torch import string all_letters = string.ascii_letters + " .,;'" n_letters = len(all_letters) #Find letter index from all_letters, e.g. "a" = 0 def letterToIndex(letter): return all_letters.find(letter) #Only for demonstation def letterToTensor(let...
8,745
7057b882ca1ce2c08e9ba7add5f115636b9b319e
import easyocr import cv2 import json import numpy as np import os import os.path import glob def convert(o): if isinstance(o, np.generic): return o.item() raise TypeError readers = [ easyocr.Reader(['la', 'en', 'de', 'fr', 'es', 'cs', 'is'], gpu = False), #easyocr.Reader(['ch_tra'], g...
8,746
c645461effe288a1959b783473d62ff99ca29547
def test_logsources_model(self): """ Comprobacion de que el modelo de la fuente de seguridad coincide con su asociado Returns: """ log_source = LogSources.objects.get(Model="iptables v1.4.21") self.assertEqual(log_source.get_model(), "iptables v1.4.21")
8,747
061a78650e2abf6a9d1e4796dd349174a8df5cb8
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # Copyright © YXC # CreateTime: 2016-03-09 10:06:02 """ Example of functions with arbitrary number arguments """ def optional_argument_func(arg1='', arg2=''): """ Function with two optional arguments """ print("arg1:{0}".format(arg1)) ...
8,748
1f4d9f5406b91fd687c0ace8ed29e3c4dfb4d3d2
n=int(input("val : ")) def fact(n): c=1; for i in range(1,n+1): c*=i; return c; print(fact(n));
8,749
21d2de5719fafd94605f31bc07231644f4be18c5
from datetime import datetime from unittest import TestCase from vpnmupd import versions class TestClass01(TestCase): """Software dependency versions compared""" def setUp(self) -> None: super().setUp() self.any_string = "Some string containing v1.1.1" def test_case01(self): """...
8,750
603d904404ace88205a524d8bfbe3e621b65f425
#!/usr/bin/python import os from subprocess import Popen, PIPE, STDOUT import time import re import telnetlib from get_sys_info import get_node_list, get_spec_node_list, get_active_tcu, get_ru_list, is_active_ru g_rg_list = [ '/SGWNetMgr', '/SS7SGU', '/MGW_CMRG', '/MGW_OMURG', '/Directory', ] status_dic...
8,751
57972e6368aa5749edeab94e45d84f7897ca14ab
""" @file @brief Various function to clean files. """ from __future__ import print_function import os import re def clean_exts(folder=".", fLOG=print, exts=None, fclean=None): """ Cleans files in a folder and subfolders with a given extensions. @param folder folder to clean @param fLOG...
8,752
ce5f91aa04065aac4d4bc7bdbaab3b74c5a85a93
import unittest2 as unittest from zope.component import getUtility from plone.registry.interfaces import IRegistry from plone.testing.z2 import Browser from plone.app.testing import SITE_OWNER_NAME, SITE_OWNER_PASSWORD from openmultimedia.imagewatchdog.configlet import IImageWatchDogSettings from openmultimedia.image...
8,753
67380fb8b1557b0ed6779009e5f9ae93fd81aedd
#!/usr/bin/python3 """ module that has fucntions that shows attributes """ def lookup(obj): """ function that returns attributes and methods of an object """ return(dir(obj))
8,754
28a920072bad1b411d71f7f70cd991cb7dfbeb8c
# -*- coding:utf-8 -*- import time class Base: def getTime(self): ''' 获取时间戳 :return: ''' return str(time.time()).split('.')[0]
8,755
df317e914073f5b236f73b616b87f86ae378ef38
#This is just a test print("this is something new") for a in range(10): print(sum(a)) print("the loop worked")
8,756
b1ae3abb6decf4d70bc2372e70cf4f5b868e805d
# coding: utf-8 # 2019/11/27 @ tongshiwei import pytest def test_api(env): assert set(env.parameters.keys()) == {"knowledge_structure", "action_space", "learning_item_base"} @pytest.mark.parametrize("n_step", [True, False]) def test_env(env, tmp_path, n_step): from EduSim.Envs.KSS import kss_train_eval, KS...
8,757
93953f025fed2bcabf29433591689c0a7adf9569
#!/usr/bin/python #encoding=utf-8 import os, sys rules = { 'E': ['A'], 'A': ['A+M', 'M'], 'M': ['M*P', 'P'], 'P': ['(E)', 'N'], 'N': [str(i) for i in range(10)], } #st为要扫描的字符串 #target为终止状态,即最后的可接受状态 def back(st, target): reduced_sets = set() #cur为当前规约后的字符串,hist为记录的规约规则 def _back(cur, ...
8,758
6726c8f1b3ef9a0df74c25c1921203af3aaacb12
#------------------------------------------------------------------------ # # @Author : EV2 CHEVALLIER # # @Date : 16.09.20 # @Location : École Navale / Chaire de Cyberdéfense des systèmes navals # @Project : Projet de Fin d'Études # @Subject : # Real time detection of cyber anomalies upon a NMEA network by using mach...
8,759
bb3c4039ff224c0ca0305778b938ef969c196033
from app import app from flask import render_template, request from app.models import model, formopener @app.route('/', methods=['GET', 'POST']) @app.route('/index') def index(): return render_template("index.html") @app.route('/personality', methods=['GET', 'POST']) def personfont(): user_input=dict(request....
8,760
48369e1ed826a9a50c0fd9f63b7cc10b8225ce2b
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Implements the webservice calls of the command like rest apis or other network related methods """
8,761
6b32f829648b92da4b638ffd79692ffb86be80fe
import cv2 import os import numpy as np import sys from os.path import expanduser np.random.seed(0) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description='Generate artificial videos with one subject in Casia-B') parser.add_argument('--dataset', type=str, required=False...
8,762
e375501e6b815530e61af9181d4cade83d4588ca
#a list of functions/Classes to be inported when a user imports * from swarmpose __all__ = ['Swarmpose']
8,763
c327f8f7aece1a9c25079613809df52e9a8e7a52
from rdflib import Graph from rdflib.plugins.sparql import prepareQuery def is_file_ontology(file_path): """ Method that, given a file, returns its URI. This method is in a separate file in case we want to extract additional metadata if required Parameters ---------- @param file_path: path of ...
8,764
f98f2ef0d94839711b473ad1ca32b85645d4014e
"""A lightweight Python wrapper of SoX's effects.""" import shlex from io import BufferedReader, BufferedWriter from subprocess import PIPE, Popen import numpy as np from .sndfiles import ( FileBufferInput, FileBufferOutput, FilePathInput, FilePathOutput, NumpyArrayInput, NumpyArrayOutput, ...
8,765
b08cface601ee07125090f3ae03a3120974688f2
from PyQt5.QtWidgets import * import sys import math Data = '' class Button: def __init__(self, text, results): self.b = QPushButton(str(text)) self.text = text self.results = results self.b.clicked.connect(lambda: self.handleInput( self.text)) # Important because we ...
8,766
d111f93144a1d2790470365d0ca31bcea17713d7
import json # No llego a solucionarlo entero. #Aparcamientos que estan cubiertos en el centro de deportes . from pprint import pprint with open('Aparcamientos.json') as data_file: data = json.load(data_file) for x in data['docs']: if x['TIPOLOGIA'] == 'Cubierto': print(x['NOMBRE']) elif x['TIPOLOGIA'] == '...
8,767
1f6176e9285d810934ae745cf8759b5cd6f408c8
import typing from pydantic import AnyUrl from .base import FBObject class MediaPayload(FBObject): url: AnyUrl class Coors(FBObject): lat: float long: float class LocationPayload(FBObject): coordinates: Coors class AttachmentFallback(FBObject): title: str url: AnyUrl payload: typin...
8,768
69e8601a387d0987fbb6d1da5ac0f9412fffc63d
import sys num = int(input()) odd_sum = 0 even_sum = 0 odd_smallest = sys.maxsize even_smallest = sys.maxsize odd_biggest = -sys.maxsize even_biggest = -sys.maxsize for i in range(0, num): element = float(input()) if i % 2 != 0: even_sum += element if element <= even_smallest: even_s...
8,769
192c44540018b9e1ab857bdbfba6fdb39bb74431
# -*- coding: utf-8 -*- import json import os import io import shutil import pytest from chi_annotator.algo_factory.common import TrainingData from chi_annotator.task_center.config import AnnotatorConfig from chi_annotator.task_center.data_loader import load_local_data from chi_annotator.task_center.model import Inte...
8,770
a9efa258c223460b2b79861acdde89161706ad9a
''' Given an infinite sorted array (or an array with unknown size), find if a given number ‘key’ is present in the array. Write a function to return the index of the ‘key’ if it is present in the array, otherwise return -1. Since it is not possible to define an array with infinite (unknown) size, you will be provided ...
8,771
821e89730fde2e12b24b52b04701c1f3501e0d57
from flask import abort from flask_restx import Resource, Namespace, Model, fields, reqparse from infraestructura.lineas_repo import LineasRepo from infraestructura.equipos_repo import EquiposRepo from infraestructura.clientes_lep_repo import ClientesLepRepo from infraestructura.lineaequipoplan_repo import LineaEquipoP...
8,772
e4bc2e97b70e2dc91dc86457866ec6b3531ef803
from pyspark.sql import SQLContext, Row from pyspark import SparkContext, SparkConf from pyspark.sql.functions import col import collections # Create a Spark Session (the config bit is only for windows) #conf = SparkConf().setAppName("SQL App").setMaster("local") sc = SparkContext() sqlCtx = SQLContext(sc) def mapp...
8,773
933f74e4fda0b30bdf70ff3f3dbde2383b10c694
# -*- coding:utf-8 -*- ''' Created on 2018/2/23 @author : xxfore ''' import time import sys import re sys.dont_write_bytecode = True class TimeUtils(object): @staticmethod def convert_timestamp_to_date(timestamp): time_local = time.localtime(timestamp) dt = time.strftime("%Y-%m-%d %H:%M:%S",t...
8,774
ca0616694b30f69263db48282bf8b8c130de0fbb
/home/co/Documents/ImageClassifier/tensorflow/tensorflow/contrib/tfprof/__init__.py
8,775
9f34f94422f4847859e9111f34ade2e1274cb543
"""Visit module to add odoo checks """ import os import re import astroid import isort from pylint.checkers import utils from six import string_types from .. import misc, settings ODOO_MSGS = { # C->convention R->refactor W->warning E->error F->fatal # Visit odoo module with settings.BASE_OMODULE_ID 'C...
8,776
05e57ed95427f0de74ea5b0589c5cd56e4a96f73
# https://github.com/openai/gym/blob/master/gym/envs/__init__.py#L449 import gym import numpy as np from rl_main.conf.names import EnvironmentName, DeepLearningModelName from rl_main.environments.environment import Environment from rl_main.main_constants import DEEP_LEARNING_MODEL class BreakoutDeterministic_v4(Envi...
8,777
b54f47de85fe95d47a1b1be921997ad86d7b450d
# nomer7 import no2_modul2 # Atau apapun file-nya yang kamu buat tadi class MhsTIF(no2_modul2.Mahasiswa): # perhatikan class induknya : Mahasiswa """Class MhsTIF yang dibangun dari class Mahasiswa""" def kataKanPy(self): print('Python is cool.') "Apakah metode / state itu berasal ...
8,778
e08820ff4fb35a3770fcb110ef7181aad1abbae5
from django.conf.urls import url from django.contrib import admin from comments.api.views import CommentListAPIView, CommentDetailAPIView urlpatterns = [ url(r'^$', CommentListAPIView.as_view(), name='list'), url(r'^(?P<pk>\d+)/$', CommentDetailAPIView, name='detail'), ]
8,779
00312f57e8a78444937f46cecb62a2b684b4fc91
a = int(input("Enter no. of over: ")) print("total ball:",a*6 ) import random comp_runs = random.randint(0,36) print("computer's run:" ,comp_runs) comp_runs = comp_runs+1 print("runs need to win:",comp_runs) chances_1 = a*6 no_of_chances_1 = 0 your_runs = 0 print("-----------------------------------------...
8,780
2d4187ab5d178efa4920110ccef61c608fdb14c0
""" # System of national accounts (SNA) This is an end-to-end example of national accounts sequence, from output to net lending. It is based on Russian Federation data for 2014-2018. Below is a python session transcript with comments. You can fork [a github repo](https://github.com/epogrebnyak/sna-ru) to replica...
8,781
d1ce6c081dce2e4bdb6087cd61d7f857dbb1348d
a=float.input('Valor da conta') print('Valor da conta com 10%: R$',(a))
8,782
a92384a6abee9e231092ee0e4dbdb60bafcc9979
import glob import csv import math import pandas # this is used to train the model, try different model, generate the csv file of the result import pandas import pandas as pd import pickle from sklearn.linear_model import LogisticRegression from sklearn import metrics from sklearn import datasets from sklearn.prepro...
8,783
2cbdb828ab6e0ad44154f0c5b2a1d807fd0d2520
from redis_db import RedisClient from setting import TEST_URL import requests class Test_Proxy(): def __init__(self): self.db=RedisClient() def proxy_test(self, proxy): url = TEST_URL proxies={ "http":proxy, "https":proxy } # print("{}(测试中)".form...
8,784
2b746d89d34435eb5f3a5b04da61c5cc88178852
__author__ = 'simsun'
8,785
afb09f9d5860994f38e8553b19e7ebc339cc2df6
""" These are data input download and prep scripts. They download and massage the data for the UBM calculations (calc.py) """ from __future__ import absolute_import, division, print_function, unicode_literals import time import urllib try: # For Python 3.0 and later import urllib.request except ImportError: ...
8,786
4927a440093e822250af25dfd6a2ce62d7cc099e
input = open('input').read() stacks_input, instructions = input.split('\n\n') stacks_input_lines = stacks_input.split('\n') stack_numbers = map(int, stacks_input_lines[-1].split()) stacks = [] for _ in stack_numbers: stacks.append([]) for line in stacks_input_lines[:-1]: for stack_index, i in enumerate(range(1...
8,787
c7ecf8ada74b3e401c2144457d4fa1050f598727
from collections import deque for case in xrange(input()): cards = input() indexes = map(int, raw_input().split()) deck = [0 for i in xrange(cards)] index = -1 for i in xrange(1, cards + 1): while True: index = (index + 1)%cards if deck[index] == 0: break for j in xrange(i - 1): ...
8,788
e1c902ef340a0a5538b41a03cc93686e0dd31672
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from prettytable import PrettyTable from time import sleep from customization import * import urllib.request,json chrome_options=webdriver.ChromeOptions() chrome_options.add_argument("--headless") chrome_options.add_argument("--inco...
8,789
315fed1806999fed7cf1366ef0772318a0baa84d
# settings import config # various modules import sys import time import multiprocessing import threading from queue import Queue import time import os import signal import db import time from random import randint # telepot's msg loop & Bot from telepot.loop import MessageLoop from telepot import Bot import asyncio...
8,790
68904be892968d4a1d82a59a31b95a8133a30832
''' * @Author: Mohammad Fatha. * @Date: 2021-09-17 19:50 * @Last Modified by: Mohammad Fatha * @Last Modified time: 2021-09-17 19:55 * @Title: Gambler Game ''' import random def gamblerProblem(): """ Description: This function Simulates a gambler who start with stake and place fair 1 bets until ...
8,791
0f55b598058b65c9dbf9cd4761d1ff6fc7091b19
__author__ = 'NikolaiEgorov' def Lad(a1, a2, b1, b2): if (a1 == b1) | (a2 == b2): return 'YES' else: return 'NO' a1 = int(input()) a2 = int(input()) b1 = int(input()) b2 = int(input()) print(Lad(a1,a2,b1,b2))
8,792
5493887e32dbe7ae27eca79d28da8488183b37a3
import string fhand = open("romeo-full.txt") counts = dict() for line in fhand: line.tranc
8,793
707c83bc83f606b570af973094574e6675cfc83f
# Copyright (c) 2011-2014 by California Institute of Technology # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice,...
8,794
43b5936ca9368dcae8d41b44fd9dc927fe18c9bc
from django.db import transaction from django.contrib.auth.models import Group from drf_yasg import openapi from drf_yasg.utils import swagger_auto_schema from rest_framework import status, mixins from rest_framework.decorators import action from rest_framework.response import Response from rest_framework.viewsets imp...
8,795
d70f77713abf4b35db9de72c1edbf4bf4580b2a4
from random import shuffle, choice from typing import Dict, List, Tuple note_to_midi: Dict[int, int] = { 1: 0, 2: 2, 3: 4, 4: 5, 5: 7, 6: 9, 7: 11, } midi_to_note: Dict[int, int] = { 0: 1, 2: 2, 4: 3, 5: 4, 7: 5, 9: 6, 11: 7, } class Note: num: int @c...
8,796
a70dae504a4dfa3997a11e4c605accfab0024318
from ttkwidgets import CheckboxTreeview from tkinter import * from tkinter.ttk import * from tkinter import messagebox import json import os from DbDataloader import * class DataLoader(): def __init__(self,master): self.anne={} self.master=Toplevel(master) master.wait_visibility(self.master)...
8,797
b2d5b16c287dc76a088f6e20eca4a16dd0aad00f
from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): help = 'Closes the specified poll for voting' def add_arguments(self, parser): # Positional arguments parser.add_argument('poll_id', nargs='+', type=int) # Named (optional arguments) ...
8,798
a995305cb5589fa0cbb246ae3ca6337f4f2c3ca1
from django.apps import AppConfig class ClassromConfig(AppConfig): name = 'classrom'
8,799
8e74bd0c051b672bf22c2c8dfb03760805b105c5
"""Tests for Node objects.""" import numpy as np import unittest import optimus.core as core import optimus.nodes as nodes import optimus.util as util def __relu__(x): "Numpy Rectified Linear Unit." return 0.5 * (np.abs(x) + x) class NodeTests(unittest.TestCase): def setUp(self): pass de...