id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
11225260
from django.shortcuts import render, get_object_or_404, redirect from django.urls import reverse, reverse_lazy from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.views.generic.edit import ( CreateView, UpdateView, DeleteView) from django.contrib.aut...
StarcoderdataPython
3324083
#!/usr/bin/python from distutils.core import setup from distutils.core import Command from unittest import TextTestRunner, TestLoader import fnmatch import os, sys import os.path import re, glob from distutils.core import Command from unittest import TextTestRunner, TestLoader from glob import glob from os.path imp...
StarcoderdataPython
30131
<reponame>mnagaku/ParaMol # -*- coding: utf-8 -*- """ Description ----------- This module defines the :obj:`ParaMol.Objective_function.Properties.regularization.Regularization` class, which is a ParaMol representation of the regularization property. """ import numpy as np from .property import * # ----------------...
StarcoderdataPython
9725133
# coding: utf-8 class SinglyLinkedList: def __init__(self): self.head = None def is_empty(self): return self.head == None def length(self): curr = self.head len_ = 0 while curr is not None: curr = curr.next len_ += 1 return len_ ...
StarcoderdataPython
1667220
import unittest from runmd import * class TestCommandBuilder(unittest.TestCase): def test_append(self): self.assertEqual(build_command("test", "name"), "test name") def test_insert(self): self.assertEqual(build_command("test %s t", "name"), "test name t") def test_multi_insert(self): ...
StarcoderdataPython
9671089
<gh_stars>0 import os, sys, glob sys.path.append(os.path.abspath(os.path.join(__file__, "../../../"))) from v2.lib.resource_op import Config import datetime import json import v2.utils.utils as utils from v2.utils.utils import HttpResponseParser from v2.lib.exceptions import TestExecError import v2.lib.manage_data as m...
StarcoderdataPython
6660445
<reponame>autobotasia/autoface<gh_stars>1-10 from django.apps import AppConfig class TaggedImgConfig(AppConfig): name = 'tools'
StarcoderdataPython
5062625
class PopulateStatus: status = False def set_initialized(self): self.status = False def set_populated(self): self.status = True def get_status(self): return self.status
StarcoderdataPython
4929974
import sqlite3 #roll identifiers: 1 - solo roll # 2 - dual roll def get_all_tiers_at_level(level: int, is_fa: bool, roll_identifier: int) -> tuple: # At the specified table, return the entire row at the corresponding level if roll_identifier == 1: db_name = 'solo_values.db'...
StarcoderdataPython
8106274
<gh_stars>0 __copyright__ = 'Copyright(c) <NAME> 2017' """ Facade for a collection of model instances """ import logging from functools import wraps LOG = logging.getLogger(__name__) def chainable(generator_method): """ Decorator for use with Collection class Allows for chained invocation of filter m...
StarcoderdataPython
6545228
<filename>hylfm/metrics/psnr.py from math import log10 import numpy import torch.nn.functional from hylfm.metrics import SimpleSingleValueMetric # class PSNR_SkImage(Metric): # sum_: float # num_examples: int # # def __init__(self, *, data_range=None, **super_kwargs): # super().__init__(**super_...
StarcoderdataPython
8116878
<reponame>Satwaj-Dhavale/Sentiment-Analysis-of-Multimedia from face_detection import create_video_output from face_detection import create_webcam_output from face_detection import create_image_output from tkinter import * from tkinter import filedialog from PIL import Image, ImageTk import os import shutil ro...
StarcoderdataPython
162012
<reponame>mfarthin/PyDMD # Tutorial 3: Multiresolution DMD: different time scales # In this tutorial we will show the possibilities of the multiresolution dynamic modes decomposition (mrDMD) with respect to the classical DMD. We follow a wonderful blog post written by <NAME> [available here](http://www.pyrunner.com/...
StarcoderdataPython
3312953
<gh_stars>1-10 from __future__ import annotations from typing import TYPE_CHECKING, Any, Type, TypeVar, cast, overload from asyncpg import Record from asyncpg.pool import PoolConnectionProxy from attr import dataclass from discord.ext import typed_commands from ..compat import ( AbstractAsyncContextManager, ...
StarcoderdataPython
3512162
<reponame>gabrielkotev/HumanVoiceRecognition # -*- coding: utf-8 -*- """ Created on Mon Sep 4 22:40:25 2017 @author: Gabriel """ from keras.models import Sequential from keras.layers import Conv1D, MaxPool1D, Flatten import numpy as np model.summary() input = np.ones(161 * 5).reshape(1,161, 5) model = Sequential(...
StarcoderdataPython
5199399
<gh_stars>10-100 class Animal: def _init_(self, nombre: str): self.nombre = nombre def get_nombre(self) -> str: pass def sonido(self) -> str: pass # se crean clases para los distintosanimales class Perro(Animal): def sonido(self): return 'guau' class Gato(Animal): ...
StarcoderdataPython
9768589
<filename>exercises/gradient_descent_investigation.py import numpy as np import pandas as pd from typing import Tuple, List, Callable, Type from IMLearn import BaseModule from IMLearn.desent_methods import GradientDescent, FixedLR, ExponentialLR from IMLearn.desent_methods.modules import L1, L2 from IMLearn.learners.c...
StarcoderdataPython
329717
import smbus ADC_ADDR = 0x48 CHN_ADDR = { 'AIN0' : 0x40, 'AIN1' : 0x41, 'AIN2' : 0xA2, 'AIN3' : 0xA3 } class Signal(object): def __init__(self, channel): self.channel_address = CHN_ADDR[channel] self.bus = smbus.SMBus(1) def measure(self): self.bus.write_byte(ADC_AD...
StarcoderdataPython
5177402
# Generated by Django 3.0.6 on 2020-05-20 11:08 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("authentik_sources_oauth", "0001_initial"), ] operations = [ migrations.AlterField( model_name="oauthsource", name="a...
StarcoderdataPython
3494703
<reponame>mrgiser/helloworld-python<gh_stars>0 number = 23 guess = int(input('Enter an integer : ')) if guess == number: # 新块从这里开始 print('Congratulations, you guessed it.') print('(but you do not win any prizes!)') # 新块在这里结束 elif guess < number: # 另一代码块 print('No, it is a little higher than that') #...
StarcoderdataPython
1882841
<reponame>yabirgb/simobility<gh_stars>0 import logging import pandas as pd import numpy as np from datetime import datetime import uuid import random from .itinerary import Itinerary from .vehicle import Vehicle from .booking import Booking from .position import Position def basic_booking_itinerary( current_time:...
StarcoderdataPython
12818179
#!/usr/bin/env python # encoding: utf-8 """ File: userprofile_userid_paidinfo.py Date: 2018/10/01 submit command: submit command: spark-submit --master yarn --deploy-mode client --driver-memory 1g --executor-memory 2g --executor-cores 2 --num-executors 30 userprofile_userid_paidinfo.py start-date A220U...
StarcoderdataPython
11307202
<reponame>aananditadhawan/bcc #!/usr/bin/python # This is an example of a hardware breakpoint on a kernel address. # run in project examples directory with: # sudo ./breakpoint.py" # <0xaddress> <pid> <breakpoint_type> # HW_BREAKPOINT_W = 2 # HW_BREAKPOINT_RW = 3 # You may need to clear the old tracepipe inputs befor...
StarcoderdataPython
107724
import os import sys def main(): # no need for int_* in the variable name start = int(input("Enter the start digit: ")) stop = int(input("Enter the stop number: ")) step = int(input("Enter the step number: ")) print(f"Generated integers: {list(range(start, stop, step))}") return os.EX_OK i...
StarcoderdataPython
3413774
import pygame from .viewport import Viewport class Renderer(object): def __init__(self, viewport: Viewport): self.renderers = [] self.window = pygame.display.set_mode((viewport.width, viewport.height), pygame.HWSURFACE, 32) self.window.fill((0, 0, 0)) self.viewport = viewport ...
StarcoderdataPython
4867317
<reponame>entelecheia/eKorpKit import logging import pandas as pd from .base import BaseSentimentAnalyser log = logging.getLogger(__name__) class HIV4SA(BaseSentimentAnalyser): """ A class for sentiment analysis using the HIV4 lexicon. """ def __init__(self, **kwargs): super().__init__(**kwa...
StarcoderdataPython
3397068
<filename>resources/python/KemendagriKTP/options.py paths = { "xls": "./src/xls", "csv": "./src/csv" } database = { "host":"localhost", "user":"kosan", "pwd":"<PASSWORD>!", "database":"kosan_system", "table":"regions" }
StarcoderdataPython
9715910
<reponame>JinyuanSun/SeqDDG #!/usr/bin/python #By <NAME>, 2021 # use HHblist to search sequences and build a3m file from os import popen import subprocess import time #subprocess.call('a.exe') def hhsearch(seqfilename, iter_num, path_to_database, num_threads): searchcmd = "hhblits -i " + seqfilename + " -o " +...
StarcoderdataPython
9799114
<gh_stars>0 '''ALUMNA: <NAME> EJERCICIO 06: REVIEW OF TIME COMPLEXITY''' '''---------------------------------------------------''' # Q6: What is the time complexity of def sumOfNumbers(n): # IMPRIME LA SUMA DE LOS NUMEROS DE 0 HASTA I p = 0 # O(1) i = 1 # O(1) while(p <= n): p = p +...
StarcoderdataPython
3218958
# Copyright 2022 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
StarcoderdataPython
8174264
<gh_stars>1-10 class TableauServerConnection: def __init__(self, config_json, env='tableau_prod'): """ Initialize the TableauServer object. The config_json parameter requires a valid config file. The env parameter is a string that indicates which env...
StarcoderdataPython
3540533
<gh_stars>1-10 # This file is part of beets. # Copyright 2013, <NAME>. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use,...
StarcoderdataPython
3516119
<filename>beartype_test/a00_unit/a00_util/cache/pool/test_utilcachepoolobjecttyped.py #!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Beartype utility fixed list pool unit tests...
StarcoderdataPython
5096626
from ..utils.importing import import_file class Regressor(object): def __init__(self, workflow_element_names=['regressor']): self.element_names = workflow_element_names # self.name = 'regressor_workflow' # temporary def train_submission(self, module_path, X_array, y_array, train_is=None): ...
StarcoderdataPython
12840755
<reponame>TLasguignes/signal_scope ''' A working example for signals from Anymal Plots x,y,z in position and the yaw angle ''' import numpy import sys sys.argv = ['test'] import tf def getYawDegrees(msg): '''yaw degrees''' quaternion = ( msg.pose.pose.orientation.x, msg.pose.pose.orientati...
StarcoderdataPython
4929638
<gh_stars>1-10 import numpy as np import torch try: import nvidia.dali as dali import nvidia.dali.plugin.pytorch as to_pytorch except ImportError: dali = None if not torch.cuda.is_available(): raise RuntimeError("DALI requires CUDA support.") seed = 1549361629 class _DaliImageDecoderPipeline(dal...
StarcoderdataPython
8189924
<gh_stars>0 #!/usr/bin/python # # Copyright 2018-2020 Polyaxon, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
StarcoderdataPython
187253
<reponame>franziskabraendle/alchemy_empowerment<filename>empowermentexploration/resources/littlealchemy/gametrees.py<gh_stars>0 import json import empowermentexploration.utils.data_handle as data_handle class Gametrees(): """Class functions generate Little Alchemy game trees. """ def __init__(self): ...
StarcoderdataPython
8031600
<gh_stars>1-10 """ Contains functions related to the sparsifying front end. Images are assumed to be in the range [0, 1]. """ import numpy as np import pywt def sp_frontend(images, rho=0.03, wavelet='bior4.4', mode='periodization', max_lev=1): """ Sparsifies input in the wavelet basis (using the PyWavelets package...
StarcoderdataPython
3412616
# Copyright (C) 2020 Amazon.com, Inc. All Rights Reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modif...
StarcoderdataPython
5061407
<reponame>IKrukov-HORIS/lets-plot<gh_stars>100-1000 # Copyright (c) 2020. JetBrains s.r.o. # Use of this source code is governed by the MIT license that can be found in the LICENSE file. import pytest import shapely from shapely.geometry import Point import lets_plot.geo_data as geodata from lets_plot.geo_data impo...
StarcoderdataPython
3595395
#!/usr/local/bin/python # coding=utf-8 from django.conf.urls import url from docs import views urlpatterns = [ url(r'^(?P<doc_name>[A-Za-z0-9\-]+)/$', views.docs_view, name='docs_view'), ]
StarcoderdataPython
11270285
<gh_stars>0 import telegram class BaseTrigger: """ Базовый триггер """ def __init__(self, client: telegram.Bot, user_id, messenger, text, message: telegram.update.Message, user_state): """ Инициализация класса :param client: API для работы и отпаврки сообщений ...
StarcoderdataPython
1824112
<reponame>ivaleriano/ProtoPNet base_architecture = 'densenet169' img_size = 139 prototype_shape = (30, 128, 1, 1) #(2000,128,1,1) num_classes = 2 prototype_activation_function = 'log' add_on_layers_type = 'regular' experiment_run = '001' data_path = '/mnt/nas/Users/Sebastian/adni-mri-pet/classification-nomci/mri-pet'...
StarcoderdataPython
6645160
import numpy as np import pandas as pd genetox = {'Ames': 'bacterial reverse mutation test', 'Ames study' :'bacterial reverse mutation test', 'Ames II' : 'bacterial reverse mutation test', 'bacterial reverse mutation assay (e.g. Ames test)' : 'bacterial reverse mutation test', ...
StarcoderdataPython
6617878
from setuptools import * from os import path this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name = 'pydep-cli', version = '0.1.1', author = '<NAME>', author_ema...
StarcoderdataPython
164415
<gh_stars>0 from dal.test import case, stories from dal_select2.test import Select2Story from .models import TestModel class AdminGenericForeignKeyTestCase(Select2Story, case.AdminMixin, case.ContentTypeOptionMixin, case.AutocompleteTestCase)...
StarcoderdataPython
4913298
<filename>rubik/application/help_functions/help_output.py #!/usr/bin/env python3 # # Copyright 2014 <NAME> # # 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/licens...
StarcoderdataPython
3515809
#!/usr/bin/python import sys, os, subprocess, re import argparse usage = """ JOTTER Jadas Output Tif daTa ExporteR viruszoo.py -s VH-HCF_20kx -f 1 -l 50 eman2 must be in user's path. """ parser = argparse.ArgumentParser(description=usage) # example command #> viruszoo.py Tomogram OR coordmode Inputfile (type?) Box...
StarcoderdataPython
6474938
<gh_stars>0 from twilio.rest import TwilioRestClient #Don't share your secrets! account_sid = "{{ account_sid }}" # Your Account SID from www.twilio.com/console auth_token = "{{ auth_token }}" # Your Auth Token from www.twilio.com/console client = TwilioRestClient(account_sid, auth_token) #Note: The number +1234567...
StarcoderdataPython
11246384
"""Unit tests for Reach Helper.""" import logging import time from typing import Union import numpy as np from robogym.robot.utils import reach_helper from robogym.robot.utils.measurement_units import MeasurementUnit from robogym.robot.utils.reach_helper import ReachHelperDebugRecorder logger = logging.getLogger(__n...
StarcoderdataPython
1724427
#!/usr/bin/env python #import modules import csv import string import time from neutronclient.v2_0 import client as neutronclient from novaclient import client as novaclient #write a new rule with a Cidr block reference def elb_create(credentials, my_csv, external_pool, archi, tags=None): #open csv file and read ...
StarcoderdataPython
4812061
<gh_stars>0 __author__ = 'pulphix'
StarcoderdataPython
4810235
<reponame>tatevm/supermariopy import pytest import numpy as np from supermariopy import plotting from matplotlib import pyplot as plt from sklearn.metrics import confusion_matrix class Test_Plotting: @pytest.mark.mpl_image_compare def test_add_colorbars_to_axes(self): from supermariopy.plotting import...
StarcoderdataPython
6445948
<reponame>ElHombreMorado8/sodp # Generated by Django 3.1.12 on 2021-07-20 15:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('reports', '0005_report_status'), ] operations = [ migrations.AddField( model_name='report', ...
StarcoderdataPython
3346668
<gh_stars>0 """ Current FlexGet version. This is contained in a separate file so that it can be easily read by setup.py, and easily edited and committed by release scripts in continuous integration. Should (almost) never be set manually. The version should always be set to the <next release version>.dev The jenkins re...
StarcoderdataPython
9752495
import csv import datetime import gc import os import numpy as np from benchmark.experiments.credit_scoring_experiment import run_credit_scoring_problem from core.composer.optimisers.crossover import CrossoverTypesEnum from core.composer.optimisers.gp_optimiser import GPChainOptimiserParameters from core.compos...
StarcoderdataPython
3463622
#!/usr/bin/env python # -*- coding: utf8 -*- # Copied and adapted from http://www.eurion.net/python-snippets/snippet/Threaded%20Server.html # GPL license import sys import os import socket from threading import Thread import time import datetime from server import * application = tornado.web.Application([ (r'/ws'...
StarcoderdataPython
1687869
<reponame>AamirAnwar/PythonLab # For n disks, total 2^n – 1 moves are required. def towersOfHanoi(n,from_stack,to_stack,aux_stack): if n == 1: print("Moved disc {} from {} to {}".format(n,from_stack, to_stack)) else: towersOfHanoi(n-1, from_stack, aux_stack, to_stack) print("Moved disc ...
StarcoderdataPython
4823421
""" Uqbar Sphinx API generation extension. Install by adding ``'uqbar.sphinx.api'`` to the ``extensions`` list in your Sphinx configuration. This extension provides the following configuration values which correspond to the initialization arguments to the :py:class:`uqbar.apis.APIBuilder` class. - ``uqbar_api_direct...
StarcoderdataPython
6680375
# Generated by Django 2.1.10 on 2019-07-17 15:04 import SiteSpace.models from django.db import migrations, models import djongo.models.fields class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Category', ...
StarcoderdataPython
3295279
from typing import Sequence from snuba.clickhouse.columns import Column, DateTime, UInt from snuba.clusters.storage_sets import StorageSetKey from snuba.migrations import migration, operations, table_engines from snuba.migrations.columns import MigrationModifiers as Modifiers columns = [ # Kafka topic offset ...
StarcoderdataPython
3203747
# blueberry - Yet another Python web framework. # # http://code.google.com/p/blueberrypy # # Copyright 2009 <NAME> # # Use and distribution licensed under the BSD license. See # the LICENSE file for full text. import sys from webob.exc import HTTPNotFound import blueberry from blueberry import config from blue...
StarcoderdataPython
11369415
<reponame>Ravan339/LeetCode<gh_stars>1-10 # https://leetcode.com/problems/reverse-only-letters/ class Solution: def reverseOnlyLetters(self, S): """ :type S: str :rtype: str """ l, r = 0, len(S) - 1 S = list(S) while l < r: while l < r and not S[...
StarcoderdataPython
98168
<reponame>bramvonk/blind-dialer<filename>src/sound.py import sys import pygame.mixer from pygame.mixer import Sound if sys.platform == "win32": # workaround in windows: windows won't play sounds if pygame.init() has been called (which we need for joystick to # work), but you can work around this bug by openin...
StarcoderdataPython
1796565
# encoding: utf-8 # ____ _ __ ___ _ # / ___|___ _ __ ___ _ __ _ _| |_ ___ _ __ \ \ / (_)___(_) ___ _ __ # | | / _ \| '_ ` _ \| '_ \| | | | __/ _ \ '__| \ \ / /| / __| |/ _ \| '_ \ # | |__| (_) | | | | | | |_) | |_| | || __/ | \ V / | \__ \...
StarcoderdataPython
1612317
<reponame>rg3915/orcamentos # Generated by Django 2.1.3 on 2018-12-14 23:46 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('crm', '0008_companycontact'), ] operations = [ migrations.RemoveField( model_name='employee', na...
StarcoderdataPython
3481249
<reponame>yfsong0709/RA-GCNv1<filename>src/mask.py import torch from torch import nn from torch.nn import functional as F class Mask(nn.Module): def __init__(self, model_stream, module): super(Mask, self).__init__() self.model_stream = model_stream self.module = module def ...
StarcoderdataPython
1956396
<filename>Data Structures and Algorithms/LeetCode Algo Solutions/EASY DIFFICULTY PROBLEMS/DetermineColourOfChessSquare.py # DETERMINE COLOR OF A CHESSBOARD SQUARE LEETCODE SOLUTION: class Solution(object): def squareIsWhite(self, coordinates): # creating a dictionary with the correct amount...
StarcoderdataPython
6624257
""" Maximum Sum BST in Binary Tree Given a binary tree root, return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only n...
StarcoderdataPython
3548889
<reponame>sandernaert/brat #--------------------------------------------------------------- # PyNLPl - FoLiA Format Module # by <NAME>, ILK, Universiteit van Tilburg # http://ilk.uvt.nl/~mvgompel # proycon AT anaproy DOT nl # # Module for reading, editing and writing FoLiA XML # # Licensed under GPLv3 # #----...
StarcoderdataPython
4836960
from subprocess import call from . import Command class RelinkCommand(Command): """%prog [options] path Find and relink entities into the SGFS cache. """ def __init__(self): super(RelinkCommand, self).__init__() self.add_option('-C', '--cache-path') self.add_opt...
StarcoderdataPython
4309
from .utils import get_request, authorized class Hubs: @authorized def getHubs(self): url = self.api_url + '/project/v1/hubs' headers = { 'Authorization': '%s %s' % (self.token_type, self.access_token) } return get_request(url, headers) @authorized def g...
StarcoderdataPython
3303467
<gh_stars>100-1000 from gateware.encoder.core import EncoderDMAReader, EncoderBuffer, Encoder
StarcoderdataPython
8059188
__all__ = [ # env 'get_env_name', # geometry 'CoordSystem', # misc 'property_buffered', 'indicate_last', 'working_dir', 'measure_time', # wrappers 'as_part', ] from .env import get_env_name from .geometry import CoordSystem from .misc import property_buffered from .misc...
StarcoderdataPython
321497
# -*- encoding:utf-8 -*- """Autogenerated file, do not edit. Submit translations on Transifex.""" MESSAGES = { "%d min remaining to read": "残りを読むのに必要な時間は%d分", "(active)": "(有効)", "Also available in:": "他の言語で読む:", "Archive": "文書一覧", "Atom feed": "Atomフィード", "Authors": "著者一覧", "Categories": "...
StarcoderdataPython
1797221
import json import pytest from django.contrib.admin.sites import AdminSite from django.urls import reverse from wazimap_ng.profile.models import ProfileHighlight from wazimap_ng.profile.admin import ProfileHighlightAdmin @pytest.mark.django_db class TestProfileHighlightAdminHistory: def test_change_reason_fiel...
StarcoderdataPython
40638
#!/usr/bin/env python from __future__ import division, unicode_literals import argparse from onmt.translate.Translator import make_translator import onmt.io import onmt.translate import onmt import onmt.ModelConstructor import onmt.modules import onmt.opts import timeit def main(opt): translator = mak...
StarcoderdataPython
11255686
# # Copyright 2015-2020 <NAME> <<EMAIL>> # # 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 ...
StarcoderdataPython
11201970
print('--- Functions ---') def test(): print('oi') def test2(param): print(param) def sum(param, paramb): return param + paramb test() test2('sou um parametro') print(sum(5,4)) print() print('--- Lambda ---') #function normal def quadrado(value): return value**2 print(quadrado(2)) my_lambda = lambda param: ...
StarcoderdataPython
190735
from client_lib.servercall import remote_call _isInitialized = False _productList = None _productNameList = [] _productNumberList = [] def _prodSugInit(): global _isInitialized global _productList global _productNameList global _productNumberList _productList = remote_call('/product/all') # Build product name...
StarcoderdataPython
9651330
# Copyright 2017 - Nokia # # 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...
StarcoderdataPython
6596158
# -*- coding: utf-8 -*- """ File Name: zigzag_conversion Author : jing Date: 2020/3/16 """ class Solution: def convert(self, s: str, numRows: int) -> str: if s is None or len(s) == 0 or numRows < 1: return s else: result = [""] * numRows ...
StarcoderdataPython
312218
''' As Mayavi is a little outdated, and not support wxphoenix So I wrote a simple one, and remove two a, M(a)y(a)vi.self.color = cs if isinstance(cs, tuple) else (0,0,0)self.color = cs if isinstance(cs, tuple) else (0,0,0)self.color = cs if isinstance(cs, tuple) else (0,0,0)self.color = cs if isinstance(cs, tuple) else...
StarcoderdataPython
1602961
import importlib from mu.protogen import stores_pb2 MODULE_NAME_FORMAT = 'mu.protogen.{}_pb2' STORE_TYPE_NAME_FORMAT = 'Mu{}Store' def store_from_name(type_name): type_name = type_name.lower() # get class from module via introspection type_module = importlib.import_module(MODULE_NAME_FORMAT.format(type_...
StarcoderdataPython
1932501
import os class RunlistValidationError(Exception): pass class RunlistParsingError(Exception): pass def parseSectionTag(in_tag): isEnd = False if in_tag[-1] != "]": raise RunlistParsingError("Tag not ended with ]") tag_content = in_tag.strip("][") if tag_content[0] == "/": i...
StarcoderdataPython
50066
import os import platform import sys from os import listdir from pathlib import Path from src.create_dir import create_numbered_dirs, get_parent_dir from src.validate_windows_file_name import is_valid_windows_file_name def get_files_in(dir: str): """Returns a list of absolute paths to files sorted alphabetically...
StarcoderdataPython
9671668
<reponame>ajensen1234/ShapeWorks import os import sys import numpy as np from shapeworks import * success = True # note: we just use numpy arrays for coordinates/indices, points, dimensions, vectors, and matrices def coordTest(): c1 = np.array([1.0, 1.0, 1.0]) c2 = np.array([2.0, 2.0, 1.0]) c2[2] = 2 c3 =...
StarcoderdataPython
3333283
<reponame>Lucas-py/Python-Basico02 ''' Escreva um programa que pergunte a velocidade do carro de um usuário. Caso ultrapasse 80 km/h, exiba uma mensagem dizendo que o usuário foi multado. Nesse caso, exiba o valor da multa, cobrando R$ 5 por km acima de 80 km/h. ''' velocidade = int(input('digite a velcidade do veic...
StarcoderdataPython
3509841
<gh_stars>0 import logging import os def get_logger(name='default', level='INFO', log_path=None, log_format = '%(asctime)s - %(levelname)s - %(pathname)s - Line: %(lineno)d - ', prefix=""): if log_path is None: log_path = os.getenv('LOG_PATH', '/tmp') logger = logging.getLogger(name) formatter = logging.Formatter...
StarcoderdataPython
5098265
import json import os import threading from stock.Stock import Stock global config global userAgents def __init__(): path = os.path.dirname(__file__) print(path) with open("../config/config.json", "r+", encoding="utf-8") as f: global config config = json.loads(f.read()) with open(".....
StarcoderdataPython
11392825
import re import os from io import BytesIO, StringIO from copy import deepcopy import flametree from snapgene_reader import snapgene_file_to_seqrecord from Bio import SeqIO try: # Biopython <1.78 from Bio.Alphabet import DNAAlphabet has_dna_alphabet = True except ImportError: # Biopython >=1.78 ha...
StarcoderdataPython
3566139
<reponame>febalci/DomoticzEarthquake """ <plugin key="SeismicPortal" name="Eartquake EMSC Data" author="febalci" version="1.0.1"> <params> <param field="Mode2" label="Radius1 (km)" width="150px" required="true" default="250"/> <param field="Mode3" label="Radius2 (km)" width="150px" required="tru...
StarcoderdataPython
1937881
import networkx as nx import random import time import tree_traversals import sys # import json sys.setrecursionlimit(10**6) def sort_neighbors(d): new_dict = {} for e in d[1]: sub_dict = d[1][e] for d2 in sub_dict: # print(sub_dict[d2]) new_dict.update({e: sub_dict[d2...
StarcoderdataPython
1687023
<gh_stars>0 # coding: utf-8 """ Производственный календарь. """ import json import os import datetime import requests WORKING_TYPE_WORK = 0 WORKING_TYPE_HOLIDAY = 2 WORKING_TYPE_SHORT = 3 DEFAULT_CACHE_PATH = '/tmp/basicdata_calend.json' def is_working_time(date_time, use_cache=False, cache_path=DEFAULT_CACHE_PATH)...
StarcoderdataPython
11254137
import logbook def test_level_properties(logger): assert logger.level == logbook.NOTSET assert logger.level_name == 'NOTSET' logger.level_name = 'WARNING' assert logger.level == logbook.WARNING logger.level = logbook.ERROR assert logger.level_name == 'ERROR' def test_reflected_properties(log...
StarcoderdataPython
9691135
from flask import Flask, jsonify, make_response, send_from_directory import os from os.path import exists, join from constants import CONSTANTS app = Flask(__name__, static_folder='build') # Catching all routes # This route is used to serve all the routes in the frontend application after deployment. @app.route('/',...
StarcoderdataPython
6483840
<gh_stars>1-10 # What happens when you instantiate a class (a fuller version with a # metaclass). class Meta(type): def __new__(cls, name, bases, dict): print('Meta.__new__()') return super().__new__(cls, name, bases, dict) def __init__(self, name, bases, dict): print('Meta.__init__()'...
StarcoderdataPython
390374
<reponame>justinwp/rules_proto load("//:compile.bzl", "ProtoCompileInfo") RustProtoLibInfo = provider(fields = { "name": "rule name", "lib": "lib.rs file", }) def _basename(f): return f.basename[:-len(f.extension) - 1] def _rust_proto_lib_impl(ctx): """Generate a lib.rs file for the crates.""" co...
StarcoderdataPython
12847654
class HasIdent(object): """ 避免 CfgGenerator 交叉引用所使用的基类 """ def __init__(self, ident: int = 0): self.ident = ident def increase_ident(self): self.ident += 1 def decrease_ident(self): self.ident -= 1 class CfgGeneratorIdent(object): def __init__(self, gen: HasIdent)...
StarcoderdataPython