id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
1676720
import numpy as np from sklearn.metrics.pairwise import euclidean_distances def gradient_descent(D, x0, loss_f, grad_f, lr, tol, max_iter): losses = np.zeros(max_iter) y_old = x0 y = x0 for i in range(max_iter): g = grad_f(D, y) y = y_old - lr * g stress = loss_f(D, y) ...
StarcoderdataPython
36700
<filename>slack_sdk/scim/v1/user.py from typing import Optional, Any, List, Dict, Union from .default_arg import DefaultArg, NotGiven from .internal_utils import _to_dict_without_not_given, _is_iterable from .types import TypeAndValue class UserAddress: country: Union[Optional[str], DefaultArg] locality: Uni...
StarcoderdataPython
8130
def insert_metatable(): """SQL query to insert records from table insert into a table on a DB """ return """ INSERT INTO TABLE {{ params.target_schema }}.{{ params.target_table }} VALUES ('{{ params.schema }}', '{{ params.table }}', {{ ti.xcom_pull(key='hive_res', task_ids=params.count_inserts)[0...
StarcoderdataPython
44973
#!/usr/bin/env python """ nearest_cloud.py - Version 1.0 2013-07-28 Compute the COG of the nearest object in x-y-z space and publish as a PoseStamped message. Relies on PCL ROS nodelets in the launch file to pre-filter the cloud on the x, y and z dimensions. Based on the follower app...
StarcoderdataPython
112998
import colorsys import numpy as np def random_colors(N, bright=True): brightness = 1.0 if bright else 0.7 hsv = [(i / N, 1, brightness) for i in range(N)] colors = list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv)) return colors def apply_mask(image, mask, color, alpha=0.5): for i in range(3): ...
StarcoderdataPython
153905
<gh_stars>1-10 t = int(input()) for _ in range(t) : n, k = map(int, input().split()) arr = list(map(int, input().split())) arr.sort() if(k > arr[0]) : print(abs(k-arr[0])) else : print(0)
StarcoderdataPython
1687686
<reponame>Oumourin/Book-Manager-System from . import Book from . import Order from .. import db class OrderItem(db.Model): __tablename__ = 'order_item' id = db.Column(db.Integer, primary_key=True, autoincrement=True, nullable=False, index=True) order_id = db.Column(db.Integer, db.ForeignKey(Order.id), nul...
StarcoderdataPython
196536
<reponame>Costopoulos/DeliveryApp<filename>src/store/forms.py from driver.models import order from django import forms from datetimewidget.widgets import DateTimeWidget class OrderForm(forms.ModelForm): time_to_pickup = forms.CharField(label='Ημερομηνία και ώρα παράδοσης', wid...
StarcoderdataPython
3264545
import unittest from uvm.base.uvm_report_object import UVMReportObject from uvm.base.uvm_object_globals import ( UVM_INFO, UVM_ERROR, UVM_LOG, UVM_DISPLAY, UVM_COUNT, UVM_MEDIUM, UVM_HIGH) class TestUVMReportObject(unittest.TestCase): """ Unit tests for UVMReportObject """ def test_verbosity(self): ...
StarcoderdataPython
4805850
#!/usr/bin/env python3 from distutils.core import setup setup(name='Pyromania', version='0.1', description='Python facade for a variety of tree models from R', url='https://github.com/trygvebw/pyromania', packages=['pyromania'], install_requires=[ 'pandas', 'numpy', 'scipy', 'rpy2', 'scikit-learn', ],...
StarcoderdataPython
1679740
<filename>backend/bugs/models.py from django.db import models from django.contrib.auth.models import User class Bug(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) description = models.TextField() ...
StarcoderdataPython
3367599
<reponame>mrTavas/owasp-fstm-auto #!/usr/bin/env python3 # # Cross Platform and Multi Architecture Advanced Binary Emulation Framework # from qiling.os.const import * from ..const import * from ..fncc import * from ..ProcessorBind import * from ..UefiBaseType import * # @file: MdePkg\Include\Protocol\SmmSwDispatch2....
StarcoderdataPython
1753318
#encoding=utf-8 import numpy as np; import tensorflow as tf import util; from dataset_utils import int64_feature, float_feature, bytes_feature, convert_to_example # encoding = utf-8 import numpy as np import time import config import util class SynthTextDataFetcher(): def __init__(self, mat_path, root_path...
StarcoderdataPython
1777476
from Chef import Chef from ChineseChef import ChineseChef myChef = Chef() myChef.make_special_dish() myChineseChef = ChineseChef() myChineseChef.make_fried_rice()
StarcoderdataPython
136986
# %% import sys sys.path.append("..") from data import handling as dth import pandas as pd import numpy as np from pathlib import Path %matplotlib inline import quantstats as qs import bar_chart_race as bcr import seaborn as sns # extend pandas functionality with metrics, etc. qs.extend_pandas() # %% ###### # SETUP ###...
StarcoderdataPython
3326700
<filename>web/addons/website_hr/__openerp__.py { 'name': 'Team Page', 'category': 'Website', 'summary': 'Present Your Team', 'version': '1.0', 'description': """ Our Team Page ============= """, 'author': 'OpenERP SA', 'depends': ['website', 'hr'], 'demo': [ 'data/websit...
StarcoderdataPython
1603436
class TestInit(object): def test_init(self): assert 1 == True
StarcoderdataPython
1649813
from hallo.inc.input_parser import InputParser def test_no_args(): p = InputParser("blah blah") assert p.remaining_text == "blah blah" assert len(p.args_dict) == 0 def test_multiple_simple_args(): p = InputParser("blah blah arg1=val1 arg2=val2 arg3=val3") assert p.remaining_text == "blah blah" ...
StarcoderdataPython
1792296
from antarest.study.storage.rawstudy.model.filesystem.config.model import ( FileStudyTreeConfig, ) from antarest.study.storage.rawstudy.model.filesystem.folder_node import ( FolderNode, ) from antarest.study.storage.rawstudy.model.filesystem.inode import TREE from antarest.study.storage.rawstudy.model.filesyste...
StarcoderdataPython
27020
<reponame>mingyuexc/huluxia_woman_meitui<filename>tmp/keyword_get.py #!/usr/bin/python3 # coding = utf-8 """ @author:m1n9yu3 @file:keyword_get.py @time:2021/01/13 """ from get_data import * import threading from urllib import parse def multi_thread(idlist, path): """线程控制 , 一次跑 1000 个线程""" # for i in range(st...
StarcoderdataPython
1703263
# Generated by Django 2.0.5 on 2018-09-27 03:39 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('notes', '0001_initial'),...
StarcoderdataPython
1758405
<gh_stars>1-10 # Imports from nltk.corpus.reader.wordnet import WordNetError from nltk.corpus import wordnet from sqlalchemy import create_engine, Table, Column, BigInteger, Integer, String, Text, DateTime, MetaData, ForeignKey from sqlalchemy.orm.session import sessionmaker from sqlalchemy.schema import UniqueConstrai...
StarcoderdataPython
168174
<gh_stars>1-10 # Generated by Django 2.2 on 2019-04-24 14:09 import DjangoUeditor.models import datetime from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('shop', '0001_initial'), ] operations =...
StarcoderdataPython
1769606
<filename>test/sp_layers_test.py import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import utils from sp_layers import SPLayer def fbank_test(): conf = { "feature_type": "fbank", "sample_rate": 16000, "num_mel_bins": 40, "use_energy": False ...
StarcoderdataPython
4822659
<gh_stars>0 from unittest import TestCase from readconfig import ReadConfig class TestReadConfig(TestCase): def test_ReadConfig_with_file(self): file = "config.yml" cf = ReadConfig(file) assert cf.file == file def test_ReadConfig_with_None(self): file = "./config/config.yml" ...
StarcoderdataPython
1634157
<reponame>sheriffbarrow/production-ecommerce from django.shortcuts import render, HttpResponseRedirect, redirect, HttpResponse from django.contrib.auth.models import User, auth from django.views import generic from django.conf import settings from django.contrib.auth.forms import UserCreationForm from django.core.excep...
StarcoderdataPython
3364687
import asyncio import serial_asyncio import itertools import logging from xml.etree import ElementTree from serial import SerialException from . import emu2_entities _LOGGER = logging.getLogger(__name__) class Emu2: def __init__( self, device ): self._device = device self._c...
StarcoderdataPython
3332534
<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- """ models ---------------------------------- The basic models """ import os class Concentration(object): """ the model holding the charge balance input values """ chemical_amount = None def __init__(self): super(Concentration,...
StarcoderdataPython
1722779
<gh_stars>1-10 """Checkers list.""" from padpo.checkers.empty import EmptyChecker from padpo.checkers.fuzzy import FuzzyChecker from padpo.checkers.glossary import GlossaryChecker from padpo.checkers.grammalecte import GrammalecteChecker from padpo.checkers.linelength import LineLengthChecker from padpo.checkers.nbsp i...
StarcoderdataPython
3362342
<gh_stars>1-10 # Copyright (c) 2018 Dolphin Emulator Website Contributors # SPDX-License-Identifier: MIT from django.conf import settings from django.db import models class NewsArticle(models.Model): """A news article which can be linked to a forum post for comments""" title = models.CharField(max_length=64)...
StarcoderdataPython
1745410
from django.core.management.base import NoArgsCommand from django.db import connection from django.core.management import call_command class Command(NoArgsCommand): help = "Deletes all tables in the 'default' database." option_list = NoArgsCommand.option_list + tuple() def handle_noargs(self, **options):...
StarcoderdataPython
4822353
class Solution: def isPalindrome(self, s): """ :type s: str :rtype: bool """ if s is None or len(s) < 2: return True i, j = 0, len(s) - 1 while True: while i < len(s) and not self.isAlpha(s[i]): i += 1 while ...
StarcoderdataPython
3292292
from nose2.tests._common import FunctionalTestCase class TestDunderTestPlugin(FunctionalTestCase): def test_dunder(self): proc = self.runIn( 'scenario/dundertest_attribute', '-v') self.assertTestRunOutputMatches(proc, stderr='Ran 0 tests')
StarcoderdataPython
46332
# -*- coding: utf-8 -*- # Copyright (c) 2016, KOL # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list o...
StarcoderdataPython
51785
<reponame>andreasala98/pykeen # -*- coding: utf-8 -*- """Inductive models in PyKEEN."""
StarcoderdataPython
28696
<reponame>chelunike/trust_me_i_am_an_engineer # -*- encoding:utf-8 -*- impar = lambda n : 2 * n - 1 header = """ Demostrar que es cierto: 1 + 3 + 5 + ... + (2*n)-1 = n ^ 2 Luego con este programa se busca probar dicha afirmacion. """ def suma_impares(n): suma = 0 for i in range(1, n+1): suma += impar(i) ...
StarcoderdataPython
1655425
import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms import numpy as np import matplotlib.pyplot as plt # Hyper parameters n_epochs = 5 num_classes = 10 batch_size = 100 learning_rate = 0.001 interval = 100 # MNIST dataset train_dataset = torchvision.datasets.MNIST(root=...
StarcoderdataPython
169358
# -*- coding: utf-8 -*- # Visigoth: A lightweight Python3 library for rendering data visualizations in SVG # Copyright (C) 2020-2021 Visigoth Developers # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software # and associated documentation files (the "Software"), to...
StarcoderdataPython
144562
<filename>tronn/interpretation/inference.py<gh_stars>1-10 """description: wrappers for inference runs """ import os import h5py import json from tronn.datalayer import setup_data_loader from tronn.models import setup_model_manager from tronn.util.utils import DataKeys def _setup_input_skip_keys(args): """reduce...
StarcoderdataPython
1784705
<gh_stars>1-10 from intake.tests.base_testcases import ( IntakeDataTestCase, ALL_APPLICATION_FIXTURES) from user_accounts import models, exceptions from user_accounts.tests import mock class TestOrganization(IntakeDataTestCase): fixtures = ALL_APPLICATION_FIXTURES def test_has_a_pdf(self): self....
StarcoderdataPython
4837545
import logging import re from copy import copy from typing import Optional import xlsxwriter from RISparser import readris from RISparser.config import TAG_KEY_MAPPING from . import utils class RisImporter: @classmethod def get_mapping(cls): mapping = copy(TAG_KEY_MAPPING) mapping.update( ...
StarcoderdataPython
1604884
<reponame>AsM0DeUz/leapp-repository import os import shutil import sys from leapp.libraries.common.utils import makedirs from leapp.libraries.stdlib import api LEAPP_HOME = '/root/tmp_leapp_py3' def _get_python_dirname(): # NOTE: I thought about the static value: python2.7 for el7, python3.6 for # el8; but ...
StarcoderdataPython
1669714
import numpy as np import gym import cv2 from baselines.common.atari_wrappers import FrameStack from retro_contest.local import make as make_local cv2.ocl.setUseOpenCL(False) # No GPU use class PreprocessFrame(gym.ObservationWrapper): """ Grayscales and resizes Frame """ def __init__(self, en...
StarcoderdataPython
3387061
<filename>ktane/vanilla.py<gh_stars>1-10 "Solver scripts for all vanilla modules." from typing import Final, List, NamedTuple, Tuple, Dict, Counter from ktane.directors import ModuleSolver, EdgeFlag, Port from ktane.ask import talk from ktane import ask from ktane.solverutils import morse, maze, grid # MorseCode, M...
StarcoderdataPython
100244
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 import math import numpy as np import states.area import states.face import states.fail import states.success from challenge import Challenge class NoseState: MAXIMUM_DURATION_IN_SECONDS = 10 AREA_BOX_T...
StarcoderdataPython
3354080
import datetime import decimal import uuid from dateutil.relativedelta import relativedelta from django.db import transaction from django.db.models import Sum from django.http import HttpResponse from django.utils.translation import ugettext_lazy as _ from django_filters.rest_framework import DjangoFilterBackend from ...
StarcoderdataPython
36431
<filename>setup.py # -*- coding: utf-8 -*- from setuptools import setup, find_packages with open('README.md') as f: readme = f.read() with open('LICENSE') as f: license = f.read() setup( name='vindinium-client', version='0.1.0', description='Client for Vindinium.org', long_description=readm...
StarcoderdataPython
3371488
import swap #import compare_SWAP_GZ2 as utils from simulation import Simulation import os, sys, subprocess, getopt from argparse import ArgumentParser from astropy.table import Table import pdb import datetime as dt import numpy as np import cPickle def MachineShop(args): # Buh. I never built in the ability to ...
StarcoderdataPython
3296605
<gh_stars>100-1000 #!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging from parlai.mturk.core.agents import MTurkAgent, TIMEOUT_MESSAGE from parlai.mturk.co...
StarcoderdataPython
3363734
<gh_stars>10-100 #!/usr/bin/env python '''Provision Static Routes''' # # Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. # __version__ = '1.0' import re import sys import time import os.path import logging import platform import argparse import socket import struct import subprocess from netaddr import...
StarcoderdataPython
3295323
#!/usr/bin/env python #from distutils.core import setup from setuptools import setup, find_packages setup(name='Fraunhofer', version='1.0.0', description='Generic Steller Abundance Determination Software', author='<NAME>', author_email='<EMAIL>', url='https://github.com/dnidever/fraunhof...
StarcoderdataPython
3215254
pg_schema_sql = ''' CREATE TABLE male( id serial PRIMARY KEY, name text ); CREATE TABLE female( id serial PRIMARY KEY, name text, husband integer UNIQUE DEFERRABLE REFERENCES male(id) DEFERRABLE ); CREATE TABLE child( id serial PRIMARY KEY, name text, father in...
StarcoderdataPython
198438
<reponame>eeshashetty/VisualCryptography import cv2 import numpy as np from watermark_generator import wm_gen import argparse parser = argparse.ArgumentParser() parser.add_argument('--image') parser.add_argument('--watermark') parser.add_argument('--owner') args = parser.parse_args() template = cv2.imread(args.water...
StarcoderdataPython
3395462
from flash.text.seq2seq.translation.data import TranslationData # noqa: F401 from flash.text.seq2seq.translation.model import TranslationTask # noqa: F401
StarcoderdataPython
3347677
import numpy as np import pandas as pd def growth_event_annotate(df, threshold=0.5): '''This function adds a "divison event" column to the passed DataFrame and fills it based on the change in the areas between the previous and the next index in the data frame. If that change is above a certain th...
StarcoderdataPython
1777751
"""Module with implementation of the Data class.""" import os import string import random import shutil import numpy import dask.array as dsarray import pyarrow import zarr import cbox.lib.boost as cbox class Data(cbox.create.Data): """Default class to store data""" type_ = "default" def __init__(self...
StarcoderdataPython
3350213
<filename>sessions/migrations/0003_alter_session_public_key.py # Generated by Django 3.2.8 on 2021-10-13 01:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sessions', '0002_auto_20211011_1511'), ] operations = [ migrations.AlterField...
StarcoderdataPython
3380155
<filename>scripts/gatherResults_kASA.py import os, sys path = sys.argv[1] numberOfTools = 1 numberOfMuts = int(sys.argv[2]) outfilePath = sys.argv[3] resultMatrixSens = [[""] * (numberOfMuts + 1) for i in range(numberOfTools + 1)] resultMatrixPrec = [[""] * (numberOfMuts + 1) for i in range(numberOfTools + 1)] result...
StarcoderdataPython
4841796
<filename>0-encapsulation/python/main.py # loose control of object attributes class Without: def __init__(self): self.age = 0 print("Without object is created") # get control of object attributes class With: def __init__(self): self.__age = 0 print("With object is created") ...
StarcoderdataPython
171558
<reponame>simmsbra/quickcell from random import randrange, Random from card import Card from cell import Cell from cascade import Cascade, get_dependent_cards, is_dependent_card_of from foundation import Foundation from game_exception import EmptyOriginException, FullDestinationException, CompatibilityException, TooFe...
StarcoderdataPython
1670873
#!/usr/bin/env python # -*- coding: utf-8 -*- # ============================================================================= # Copyright Ostap developers # ============================================================================= # 1.5.99.0 (Sep 13, 2020, 13:46 [UTC]) # .ooooo...
StarcoderdataPython
10620
#! /usr/bin/env python from __future__ import print_function import pandas as pd import numpy as np import argparse def generate_csv(start_index, fname): cols = [ str('A' + str(i)) for i in range(start_index, NUM_COLS + start_index) ] data = [] for i in range(NUM_ROWS): vals = (np.ra...
StarcoderdataPython
82154
<filename>wagtail/wagtailimages/api/admin/serializers.py from __future__ import absolute_import, unicode_literals from ..fields import ImageRenditionField from ..v2.serializers import ImageSerializer class AdminImageSerializer(ImageSerializer): thumbnail = ImageRenditionField('max-165x165', source='*', read_only...
StarcoderdataPython
1700037
<filename>68-text-justification/text-justification.py # -*- coding: utf-8 -*- """ Created on Sat Jan 23 23:52:34 2021 @author: nacer """ """ Problem link : https://leetcode.com/problems/text-justification/ """ class Solution: def fullJustify(self, words: List[str], maxWidth: int) -> List[str]: o...
StarcoderdataPython
1659966
import pandas as pd import numpy as np import nltk import collections import pickle import pyhanlp from collections import Iterable from collections import Counter from pandas import DataFrame from sklearn.decomposition import PCA from pyhanlp import * """ 一、加载数据: 1.加载问答对 2.加载预训练的词向量模型 二、问题的向量化...
StarcoderdataPython
4818988
<gh_stars>10-100 import random import queue import csv import os from sklearn.model_selection import ParameterGrid def average(lst): return sum(lst) / float(len(lst)) # --- Hyperparameters based off of assumptions --- # # Assume reviewers have an independent 75% probability of choosing the better application ...
StarcoderdataPython
3319429
# 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, ...
StarcoderdataPython
3384158
<gh_stars>100-1000 import unittest from main import * class ConditionalsTests(unittest.TestCase): def test_main(self): self.assertIsInstance(value, str) self.assertIs(value, 'y', "program must print 'yes'")
StarcoderdataPython
1766878
#!/usr/bin/env python from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains from pytesseract import image_to_string from urllib.request import urlretrieve from PIL import Image from io import BytesIO from getpass import getpass i...
StarcoderdataPython
1717054
#!/usr/bin/env python # bcast2.py from mpi4py import MPI comm = MPI.COMM_WORLD rank = comm.Get_rank() if rank == 0: data = {'key1' : [7, 2.72, 2+3j], 'key2' : ( 'abc', 'xyz')} else: data = None data = comm.bcast(data, root=0) print ("process %s" % (rank)) print (rank,data)
StarcoderdataPython
3289408
#!/usr/bin/env python """Parsers for Linux PAM configuration files.""" import os import re from builtins import zip # pylint: disable=redefined-builtin from grr_response_core.lib import parser from grr_response_core.lib.parsers import config_file from grr_response_core.lib.rdfvalues import config_file as rdf_config...
StarcoderdataPython
3276534
<filename>apps/menuplans/dbaccess.py import datetime from uuid import uuid4 import xml.etree.ElementTree as et from basex.basex import recipe_db from recipes.dbaccess import get_random_recipes GET_MENUPLANS_QUERY = ''' import module namespace paging="custom/pagination"; declare variable $query as xs:string extern...
StarcoderdataPython
4822309
<reponame>citReyJoshua/supplie<gh_stars>0 from django.contrib import admin from backend.product.models import Product, ProductImage admin.site.register(Product) admin.site.register(ProductImage)
StarcoderdataPython
92113
# -*- coding: utf-8 -*- """ @date: 2021/5/4 下午7:11 @file: torchvision_resnet_to_zcls_resnet.py @author: zj @description: Transform torchvision pretrained model into zcls format """ import os from torchvision.models.resnet import resnet18, resnet34, resnet50, resnet101, resnet152, resnext50_32x4d, \ resnext101_32x...
StarcoderdataPython
3229719
<filename>foo.py # -*- coding: utf-8 -*- """ Created on Wed Jun 15 09:15:09 2016 @author: ericgrimson """ x = 6 if x != 5: print('i am here') else: print('no I am not')
StarcoderdataPython
1704650
<filename>tests/v1/test_organizations_api.py # coding: utf-8 # Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. # This product includes software developed at Datadog (https://www.datadoghq.com/). # Copyright 2019-Present Datadog, Inc. from __future__ import a...
StarcoderdataPython
1632817
<reponame>ATrain951/01.python-com_Qproject """ # Sample code to perform I/O: name = input() # Reading input from STDIN print('Hi, %s.' % name) # Writing output to STDOUT # Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail """ # Write your code here ...
StarcoderdataPython
1703042
<filename>MyTools/lightup.py import sys import Image import colorsys import ImageDraw import math def convert(img): rgb_img = img.convert('RGBA') img = Image.new('RGBA', rgb_img.size, (0x00,0x00,0x00,0xff)) draw = ImageDraw.Draw(img) x,y = rgb_img.size for i in range(0,x): for j in range(0...
StarcoderdataPython
4805565
# -*- coding: utf-8 -*- import scrapy from scrapy.contrib.spiders import CrawlSpider from scrapy.http import Request from scrapy.selector import Selector from douban.items import DoubanItem class Douban(CrawlSpider): name = "douban" redis_key = 'douban:start_urls' start_urls = ['http://movie.douban.com/top250'] u...
StarcoderdataPython
3347180
# Generated by Django 2.0.6 on 2018-08-24 13:48 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('prod...
StarcoderdataPython
3322274
from pyderman.util import downloader import re import json def get_url(version='latest', _os=None, _os_bit=None): beta = True pattern = version bit = '' if not version or version == 'latest': beta = False pattern = '' if _os == 'linux': bit = '64' if _os_bit == '64' else 'i686' for release in _releases():...
StarcoderdataPython
3392911
""" test_QuerySet """ from AzureODM.QuerySet import ( QuerySet, obj_to_query_value, Q, QCombination, AndOperator, OrOperator) from AzureODM.Entity import Entity from AzureODM.Fields import GenericField, FloatField, KeyField import pytest import re from datetime import datetime, timezone regex = re.compile(Query...
StarcoderdataPython
3205478
#!/usr/bin/env python """ Python implementation of vic2nc This module facilitates the conversion of ascii VIC output files into 3 or 4 dimenstional netcdf files. References: - VIC: http://www.hydro.washington.edu/Lettenmaier/Models/VIC/index.shtml - netCDF: http://www.unidata.ucar.edu/software/netcdf/ - Python net...
StarcoderdataPython
3291543
# exercise 43 was sort of a demonstration of how he created his own game
StarcoderdataPython
1628454
#!/usr/bin/python # _*_ coding:utf-8 _*_ import flickrapi import json import time import os statei = os.path.isfile("done_time_ids.txt") statef = os.path.isfile("raw_time_data.csv") if statei == False: stateicreate = open("done_time_ids.txt", "w") stateicreate.close() else: pass if stat...
StarcoderdataPython
3264362
# -*- coding: utf-8 -*- # visigoth: A lightweight Python3 library for rendering data visualizations in SVG # Copyright (C) 2020 Visigoth Developers # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software # and associated documentation files (the "Software"), to deal...
StarcoderdataPython
1631437
from dataclasses import dataclass from .. import Command, ParsedCommand, Parser from ...nodes import PositionNode from ...parser_types import Position @dataclass() class ParsedSetworldspawnCommand(ParsedCommand): command: str position: PositionNode = None def __str__(self): if self.position is...
StarcoderdataPython
72897
<reponame>Alejandro-sin/Learning_Notebooks ''' Voy a tratar de atrapar diferentes errores con try except. El try captura un error especifico en el ejemplo un Type Error y retorna un mensaje predeterminado. Try solo funciona con Type Errrors. ''' def palindrome(word): if word == word[::-1]: return prin...
StarcoderdataPython
3221499
<filename>systemrdl/core/value_normalization.py import hashlib from typing import Any, Optional, Union, List from .. import rdltypes from .. import node def normalize(value: Any, owner_node: Optional[node.Node]=None) -> str: """ Flatten an RDL value into a unique string that is used for type normalization...
StarcoderdataPython
1654412
number = int(input('how much number of element you want to sum : ')) lst = [] for i in range(number): element = int(input('enter your number : ')) #123 lst.append(element) print('sum of element is = ' , sum(lst)) print('max number of element is = ' , max(lst))
StarcoderdataPython
73482
# -*- coding: utf-8 -*- from functools import partial s_open = partial(open, mode='r')
StarcoderdataPython
1610996
<filename>carsus/io/tests/test_ionization.py<gh_stars>10-100 import pytest import pandas as pd from pandas.util.testing import assert_series_equal from numpy.testing import assert_almost_equal from sqlalchemy.orm import joinedload from carsus.model import Ion from carsus.io.nist.ionization import (NISTIonizationEnerg...
StarcoderdataPython
1631195
<filename>test/unit/factories/NetworkFactoryTest.py import os import unittest from typing import Any from src.shapeandshare.dicebox.config.dicebox_config import DiceboxConfig from src.shapeandshare.dicebox.factories.network_factory import NetworkFactory from src.shapeandshare.dicebox.models.network import Network from...
StarcoderdataPython
3257608
<filename>blackbook/models/transaction.py from django.db import models from django.utils import timezone from django.utils.functional import cached_property from djmoney.models.fields import MoneyField from djmoney.money import Money from .base import get_default_currency from .account import Account from .category i...
StarcoderdataPython
1637667
<gh_stars>0 # Generated by Django 2.2 on 2020-09-20 00:18 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0002_auto_20200919_2337'), ] operations = [ migrations.AddField( model_name='machines', name='ins...
StarcoderdataPython
15534
def lcs(x, y): """ Longest Common Subsequence """ n = len(x) + 1 m = len(y) + 1 table = [ [0]*m for i in range(n) ] for i in range(n): for j in range(m): # If either string is empty, then lcs = 0 if i == 0 or j == 0: table[i][j] = 0 elif x[i - 1] == y[j - 1]: table[i][j] = 1 + table[i-1]...
StarcoderdataPython
81043
# # @lc app=leetcode id=4 lang=python3 # # [4] Median of Two Sorted Arrays # # https://leetcode.com/problems/median-of-two-sorted-arrays/description/ # # algorithms # Hard (30.86%) # Likes: 9316 # Dislikes: 1441 # Total Accepted: 872.2K # Total Submissions: 2.8M # Testcase Example: '[1,3]\n[2]' # # Given two sor...
StarcoderdataPython
1732204
import logging from typing import List from opyoid.bindings import Binding, BindingToProviderAdapter, ClassBindingToProviderAdapter, \ InstanceBindingToProviderAdapter, MultiBindingToProviderAdapter, ProviderBindingToProviderAdapter, \ SelfBindingToProviderAdapter from opyoid.bindings.registered_binding import...
StarcoderdataPython
1776199
<filename>Modulo1/script/hola.py # control + s -> guardar cambios # control + n -> crear nuevo archivo nombre = input("Introduce tu nombre: ") num = int(input("Ingrese un numero entero: ")) # print("valor de numero es: " + num) print("Hola de nuevo {} de edad {}".format(nombre, num)) print(f"Hola por tercera vez {no...
StarcoderdataPython
1684857
<filename>pysaint/api.py """ End User를 위한 간단한 api """ from .constants import Line from .saint import Saint import copy from tqdm import tqdm from datetime import datetime def get(course_type, year_range, semesters, line=Line.FIVE_HUNDRED, **kwargs): """ THIS IS THE END POINT OF pysaint API USAGE:: ...
StarcoderdataPython