id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
1690712
<filename>tests/domain/test_Track_group.py import pytest from tloen.domain import Application, Track @pytest.mark.asyncio async def test_1(): track_a = Track() track_b = Track() group_track = await Track.group([track_a, track_b]) assert isinstance(group_track, Track) assert list(group_track.track...
StarcoderdataPython
3216377
<reponame>rowanv/django-blog-zinnia # coding=utf-8 """Test cases for Zinnia's admin""" from __future__ import unicode_literals from django.contrib.admin.sites import AdminSite from django.contrib.auth.models import User from django.contrib.sites.models import Site from django.test import RequestFactory from django.tes...
StarcoderdataPython
4840930
<gh_stars>1-10 ''' Given an array of integers nums and an integer k, return the total number of continuous subarrays whose sum equals to k. Example 1: Input: nums = [1,1,1], k = 2 Output: 2 Example 2: Input: nums = [1,2,3], k = 3 Output: 2 Constraints: 1 <= nums.length <= 2 * 10^4 -1000 <= nums[i] <= 10...
StarcoderdataPython
21207
import json from PIL import Image with open('/home/tianpei.qian/workspace/data_local/sl4_front_1.0/sl4_side_val_1.7.json') as f: val_1_7 = json.load(f) with open('sl4_side_val_1.7/results.json') as f: new_1_8 = json.load(f) ROOT = '/home/tianpei.qian/workspace/data_local/sl4_front_1.0/' for old, new in zip(...
StarcoderdataPython
3323920
<gh_stars>1-10 import requests import csv from time import time baseURL = "https://sisu-api.apps.mec.gov.br/api/v1/oferta/" filename = "all_courses" t0 = time() print("Will write to file '{}.csv'.".format(filename)) csvFile = open(filename + ".csv", "w+", encoding="UTF-8") csvFileWriter = csv.writer(csvFile, deli...
StarcoderdataPython
1615469
import os PROJECT_PATH = os.path.abspath(os.getcwd()) DEBUG = False TEMPLATE_DEBUG = DEBUG ADMINS = ( ('<NAME>', '<EMAIL>'), ('<NAME>', '<EMAIL>'), ) MANAGERS = ADMINS ALLOWED_HOSTS = [ '127.0.0.1', ] TIME_ZONE = 'Europe/Istanbul' LANGUAGE_CODE = 'TR-tr' SITE_ID = 1 USE_I18N = True USE_L10N = True USE_...
StarcoderdataPython
3379840
import math def older(person): print() print('Person ', person, ' is older') def main(): # compiling the bday for person 1 print('please input birthday of 1st person') p1_year = int(input('\tyear: ')) * math.pow(10, 4) p1_month = 0 while p1_month > 12 or p1_month == ...
StarcoderdataPython
6814
<reponame>sbarguil/Testing-framework<filename>AutomationFramework/tests/interfaces/test_if_subif.py import pytest from AutomationFramework.page_objects.interfaces.interfaces import Interfaces from AutomationFramework.tests.base_test import BaseTest class TestInterfacesSubInterfaces(BaseTest): test_case_file = 'if...
StarcoderdataPython
3392633
<filename>pettygram/views.py #django from django.http import HttpResponse #utilities from datetime import datetime import json def hello_world(request): return HttpResponse("oh, hi! , Current server time is {now}".format( now= datetime.now().strftime('%b %dth, %y - %H:%M hrs') )) def sorted_i...
StarcoderdataPython
120688
# Testing serial ports # https://faradayrf.com/unit-testing-pyserial-code/ # Import modules import serial class SerialTestClass(object): """A mock serial port test class""" def __init__(self): """Creates a mock serial port which is a loopback object""" self.device = "test" self._port...
StarcoderdataPython
3343552
#!/usr/bin/env python """An implementation of an in-memory data store for testing.""" from __future__ import print_function import sys import threading import time from future.utils import iteritems from grr_response_core.lib import rdfvalue from grr_response_core.lib import utils from grr_response_server import af...
StarcoderdataPython
1766927
<filename>src/ext/confirmer.py import discord class ConfirmerSession: """Class that interactively paginates a set of embed using reactions.""" def __init__(self, page, color=discord.Color.green(), footer=''): """Confirmer, for confirming things obv duh.""" super().__init__() self....
StarcoderdataPython
1654458
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Author: <NAME> # Description: # mrc_ner_data_processor.py import os from mrc_utils import read_mrc_ner_examples class QueryNERProcessor(object): # processor for the query-based ner dataset def get_examples(self, data_dir, data_sign): data = re...
StarcoderdataPython
1646231
<reponame>mo-cmyk/wbgapi '''Access information about World Bank lending groups. This works best with the WDI (source=2) and other databases that share the same list of economies. It will probably not work well with subnational databases or region-specific ones. ''' import wbgapi as w from . import utils import builtin...
StarcoderdataPython
53115
import pytest from pynetworking.Device import Device def setup_dut(dut): dut.reset() dut.add_cmd({'cmd': 'show version', 'state': -1, 'action': 'PRINT', 'args': [""" AlliedWare Plus (TM) 5.4.2 09/25/13 12:57:26 Build name : x600-5.4.2-3.14.rel Build date : Wed Sep 25 12:57:26 NZST 2013 Build type : RELEASE ...
StarcoderdataPython
3388685
<reponame>sinahmr/parted-vae import json import torch from partedvae.models import VAE def load(path, img_size, disc_priors, device): path_to_specs = path + 'specs.json' path_to_model = path + 'model.pt' with open(path_to_specs) as specs_file: specs = json.load(specs_file) latent_spec = spe...
StarcoderdataPython
195721
import os import numpy as np import cv2 import csv import utils output_dir = "./multipleBackgroundsCorners" if (not os.path.isdir(output_dir)): os.mkdir(output_dir) dir = "../data1" import csv with open(output_dir+"/gt.csv", 'a') as csvfile: spamwriter_1 = csv.writer(csvfile, delimiter=',', ...
StarcoderdataPython
1668209
<reponame>adrienbrunet/mixt # coding: mixt """Ensure that the space before the ``/`` character is not mandatory""" from mixt import html from mixt.element import Element def test_normal_tag_without_props(): assert str(<button />) == '<button></button>' assert str(<button/>) == '<button></button>' def test...
StarcoderdataPython
138331
<gh_stars>0 import random import numpy as np import pandas as pd import tqdm as tqdm import matplotlib.pyplot as plt # Initialize and create dataframe headers = ['Particle_X', 'Particle_Y', 'q1', 'q2', 'q3', 'q4', 'q5', 'q6', 'Velocity_X', 'Velocity_Y'] dataset = pd.DataFrame(columns=headers) # ...
StarcoderdataPython
1619419
#!/usr/bin/env python """ This is a script to automatically tag repos on GitHub. Sample usage: * To create a tag: $ python tagz.py -r mozilla/fireplace -c create -t 2014.02.11 NOTE: annotated tags are used by default (-a). If you want lightweight tags, you can pass -l: $ python tagz.py -l -r mozilla/...
StarcoderdataPython
1650740
from __future__ import unicode_literals from rest_framework import serializers from rest_framework.response import Response from rest_framework.decorators import detail_route from django.db.models import Q from onadata.apps.fieldsight.models import Site # from onadata.apps.main.models.meta_data import MetaData from on...
StarcoderdataPython
3212413
#!/usr/bin/env python # Author: cptx032 # Mail-me: <EMAIL> from Tkinter import * top = Tk() SEC = 0 HOUR = 0 MIN = 0 PAUSED = True MINIMIZED = False top.withdraw() top.config(bg="#333") top.overrideredirect(1) top.attributes("-alpha",0.9, "-topmost",1) top.geometry("%dx%d+%d+0" % (200, top.winfo_screenheight(), top.win...
StarcoderdataPython
3227915
""" A script to embed every phrase in a dataset as a dense vector, then to find the top-k neighbors of each phrase according to cosine similarity. 1. Install missing dependencies. # More details: https://github.com/facebookresearch/faiss/blob/master/INSTALL.md conda install faiss-cpu -c pytorch 2. Prepare da...
StarcoderdataPython
1601582
<filename>app/schemas.py from typing import List from pydantic import BaseModel # the orm model tells the Pydantic model to read the data even it it # is not a dict, but an ORM model (or any other arbitrary object with attributes). class MarketBase(BaseModel): id: int market_name: str country_code: str ...
StarcoderdataPython
48703
## ACL Import Module # ACL CSV Import # Version 5 # 2015-10-30 # we only need the datetime class & the static function strptime from datetime module from datetime import datetime import re import sys import os import logging # best postgresql module so far, install it "yum install python-psycopg2" import psycopg2 im...
StarcoderdataPython
170911
from typing import overload from UdonPie import System from UdonPie import UnityEngine from UdonPie.Undefined import * class Canvas: def __new__(cls, arg1=None): ''' :returns: Canvas :rtype: UnityEngine.Canvas ''' pass @staticmethod def op_Implicit(arg1): ...
StarcoderdataPython
3284583
# -*- coding: utf-8 -*- from django.conf import settings from django.http.response import Http404 def restrict_for_museum(func): def view(request, *args, **kwargs): if request.user.is_authenticated() and request.user.profile.is_museum: raise Http404() return func(request, *args, **kw...
StarcoderdataPython
4805830
<filename>backend/app/schemas/chat/messages.py """Message schemas.""" from datetime import datetime from pydantic import BaseModel, Field from ..base import MongoModel, MongoId class Message(BaseModel): """Base Message schema.""" text: str class MessageIn(Message): """Input Message schema.""" class...
StarcoderdataPython
60216
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any...
StarcoderdataPython
1700097
# Copyright (c) 2012 <NAME>, Hupfeldt IT # All rights reserved. This work is under a BSD license, see LICENSE.TXT. from multiconf.repeatable import Repeatable from multiconf import ConfigItem, ConfigBuilder def check_containment(start_item, level=0, prefix=" "): for key, item in start_item.iteritems(): ...
StarcoderdataPython
99900
#stupid hacky stuff logging = 0 exec(open("./wordle-evaluator.py").read()) hardMode = False def load_freq(): with open('unigram_freq.csv') as f: freq = {} f.readline() for line in f: freq[line.split(',')[0].strip().upper()] = int(line.split(',')[1]) return freq def ad...
StarcoderdataPython
3285913
import json from . import geo, date, data, calc geo = geo date = date data = data calc = calc # Outputs JSON for the given dictionary or list to the given path. def save_json(x, path, quiet=False): # pragma: no cover with open(path, 'w+') as output_file: output_file.write(json.dumps(x, separators=(',', ':...
StarcoderdataPython
64048
<gh_stars>0 # -*- coding: utf-8 -*- """Demo236_House_Preprocessed.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1D-6jwkEPkq3S7AiHnSH2SYp6FJPGArlF """ import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns f...
StarcoderdataPython
1681404
class Solution: def countVowelStrings(self, n: int) -> int: dp = [[i for i in range(5,0,-1)] for _ in range(n)] for i in range(1,n): for j in range(3,-1,-1): dp[i][j] = dp[i - 1][j] + dp[i][j + 1] return dp[n-1][0]
StarcoderdataPython
1629092
import sys import argparse import pandas as pd import numpy as np parser = argparse.ArgumentParser(description='Create dummy reference data.') parser.add_argument('--items', help='Input cscv with items. default: %(default)s', metavar='<name>', default='items...
StarcoderdataPython
109565
import math def buildSparseTable(arr, n): for i in range(0, n): lookup[i][0] = arr[i] j = 1 while (1 << j) <= n: i = 0 while (i + (1 << j) - 1) < n: if (lookup[i][j - 1] < lookup[i + (1 << (j - 1))][j - 1]): lookup[i][j] = lookup[i][j - 1] else: lookup[i][j] = lookup[i + (1 << (...
StarcoderdataPython
74694
""" Project Euler Problem 174: https://projecteuler.net/problem=174 We shall define a square lamina to be a square outline with a square "hole" so that the shape possesses vertical and horizontal symmetry. Given eight tiles it is possible to form a lamina in only one way: 3x3 square with a 1x1 hole in the midd...
StarcoderdataPython
3336475
<gh_stars>0 import click @click.command() @click.option('--name', default="world", help="Name to use when printing 'hello'") def main(name): click.echo("Hello %s" % name) if __name__ == "__main__": main()
StarcoderdataPython
13544
# created by <NAME> # 7/8/16 import classes as c def printIntro(): print 'Welcome to the\n' print '''__/\\\\\\\\\\\\\\\\\\\\\\\\_________________________________________________\ __________________________\n _\\/\\\\\\////////\\\\\\___________________________________\ ______________________________________\...
StarcoderdataPython
3277816
<reponame>LourencoFernando/SMS-Project """ Quoting the PDF spec: > PDF’s logical _structure facilities_ provide a mechanism for incorporating > structural information about a document’s content into a PDF file. > The logical structure of a document is described by a hierarchy of objects called > the _structure hierarc...
StarcoderdataPython
3217197
#!/usr/bin/env python3 ############### # Author: Paresh # Purpose: Simulation to Real Implementation on Kinova # Summer 2020 ############### import numpy as np import math import matplotlib.pyplot as plt import time import os, sys from scipy.spatial.transform import Rotation as R import random import pickle import pd...
StarcoderdataPython
1650510
<reponame>linkolearn/linkolearn from shopyo.api.module import ModuleHelp from flask import render_template from flask import url_for from flask import redirect from flask import flash from flask import request from flask import jsonify # from shopyo.api.html import notify_success # from shopyo.api.forms import flash_...
StarcoderdataPython
155313
<filename>fdm-devito-notebooks/01_vib/exer-vib/vib_conv_rate.py import numpy as np import matplotlib.pyplot as plt from vib_verify_mms import solver def u_exact(t, I, V, A, f, c, m): """Found by solving mu'' + cu = F in Wolfram alpha.""" k_1 = I k_2 = (V - A*2*np.pi*f/(c - 4*np.pi**2*f**2*m))*\ ...
StarcoderdataPython
1693483
<gh_stars>100-1000 import pytest def test_upgrade_chip_replication_quality_metric_1_2(upgrader, chip_replication_quality_metric_1): value = upgrader.upgrade( "chip_replication_quality_metric", chip_replication_quality_metric_1, current_version="1", target_version="2", ) ass...
StarcoderdataPython
3201177
<filename>tests/snapshots/snap_test_holidata/test_holidata_produces_holidays_for_locale_and_year[hu_HU-2019] 1.py<gh_stars>10-100 [ { 'date': '2019-01-01', 'description': 'Újév', 'locale': 'hu-HU', 'notes': '', 'region': '', 'type': 'NF' }, { 'date': '...
StarcoderdataPython
34082
# Copyright (c) 2021 PaddlePaddle 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 appli...
StarcoderdataPython
1662162
<reponame>mporcheron/pyfeedbacker # -*- coding: utf-8 -*- from collections import OrderedDict import abc class AbstractModelContainer(OrderedDict): def __init__(self, root_model, child_data_type = None, parent_data_id = None): """Base class for storing...
StarcoderdataPython
3278298
<filename>djangorestframework_hal/parsers.py<gh_stars>0 from .renderers import HalJSONRenderer from .settings import api_settings from .utils import parse_from_hal class HalJSONParser(api_settings.PARSER_CLASS): media_type = "application/hal+json" renderer_class = HalJSONRenderer def parse(self, stream, ...
StarcoderdataPython
35063
#!/usr/bin/env python3 import sys import os.path import re from datetime import date, datetime, time, timedelta # helper def is_timeformat(s): p = re.compile('^[0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3}$') if p.match(s) is None: return False else: return True def is_time_line(l): p = re.c...
StarcoderdataPython
74915
import os import random import time import torch import torch.nn.functional as F import torch.nn as nn import numpy as np import scipy.io.wavfile as wavfile import matplotlib from mir_eval.separation import bss_eval_sources from arguments import ArgParser from dataset import MUSICMixDataset from models import ModelBu...
StarcoderdataPython
166596
<reponame>softwarefactory-project/sf-conf # 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
120751
<reponame>continual-ml/forgetful-networks<filename>model.py<gh_stars>0 import torch import torch.nn as nn def make_processor(in_dim: int, out_dim: int) -> nn.Module: return nn.Sequential( nn.Linear(in_dim, 128), nn.LeakyReLU(0.2), nn.Linear(128, 32), nn.LeakyReLU(0.2), nn.L...
StarcoderdataPython
3250386
""" Gestion de fichiers """ from log_generator.exit_program import exitProgram from zipfile import ZipFile import os.path import shutil # Verification de la presence du fichier def file_exist_check(file_with_path:str): status:bool = False try: status = os.path.exists(file_with_path) except OSError...
StarcoderdataPython
29255
<filename>test/test_document.py # test utilities import unittest from decimal import Decimal # tested module import madseq class Test_Document(unittest.TestCase): def test_parse_line(self): parse = madseq.Document.parse_line Element = madseq.Element self.assertEqual(list(parse(' \t ')...
StarcoderdataPython
1777390
# <NAME> # 10/15/2017 # Tested and Developed on Python 2.7 and 3.5 / Configured for Windows, Linux, and Mac # Strictly For Educational/Ethical Pen Testing Purposes ONLY. I condone no illegal activities with this script # Use of this code for unlawful purposes is wrong in every sense of the word, a crime, and strictly ...
StarcoderdataPython
93440
# coding:utf-8 from django.db import models # isbn13:9787111013853 class Comment(models.Model): """ 评论模型 """ isbn13 = models.CharField(max_length=200,default=None) author = models.CharField(max_length=200,null=True,blank=True,default=None) time = models.CharField(max_length=200,null=True,blan...
StarcoderdataPython
3274905
#!/usr/bin/env python import urllib import urllib2 import hashlib import hmac import time import json import sys import os.path class poloniex(object): _trade_api_url = 'https://poloniex.com/tradingApi' _public_api_url = 'https://poloniex.com/public' _dump_file_prefix = 'dump_polo_' def __...
StarcoderdataPython
1674271
import unittest from tests import StockMapStub from stockpy.metrics.finance import roe from stockpy import expr from stockpy.filter import horse class RoeTest(unittest.TestCase): @classmethod def setUpClass(cls): data = { 'n_income_attr_p': { 2019: { 1:...
StarcoderdataPython
3289706
<reponame>serrabaum/Python-Baseball import pytest import matplotlib matplotlib.use('Agg') from .utils import get_assignments, get_calls from stats import offense @pytest.mark.test_select_all_plays_module4 def test_select_all_plays_module4(): assert 'games' in dir(offense), 'Have you imported `games` from `data`?'...
StarcoderdataPython
1638475
def get_config_file(): import os path = os.path.abspath(__file__) f = os.path.join(os.path.dirname(path), 'setup.cfg.tpl') return open(f).read()
StarcoderdataPython
3264852
<reponame>figtools/figgy-cli<filename>src/figcli/extras/key_utils.py import re from typing import Set, Dict from figcli.config import * class KeyUtils(object): @staticmethod def find_all_expected_names(config_keys: set, shared_names: set, merge_conf: dict, repl_conf: dict, rep...
StarcoderdataPython
3381939
<filename>src/analyticViz/viz.py import plotly.express as px import plotly.figure_factory as ff """ This is a script that contains functions needed for plotting various visualizations using plotly The various viz includes; * Bar Chart (Horizontal) * Bar Chart (Vertical) * Stacked bar chart * Clustered bar...
StarcoderdataPython
3270810
def parse_relationship(string): """Parses relationship from string of format A)B where A is the parent and B is the child. Args: original string Returns: Parent, Child: string, string """ parsed = string.strip().split(')') return parsed[0], parsed[1] def get_input_str(fil...
StarcoderdataPython
3392859
# coding: utf-8 # How to use: # type 'ipython' at the terminal to get to the Interactive Python (IPython) environments # Type: # %run batch_replace_rmd.py import re methods = 'facs', 'droplet' for method in methods: rmds = get_ipython().getoutput(f'ls *{method}.Rmd') for rmd in rmds: backup = rmd...
StarcoderdataPython
3223573
<reponame>borisz264/mono_seq import os import operator import itertools import gzip import numpy as np from scipy import stats def old_chris_formula(R, k, read_len): """ Implements the formula Chris burge derived """ return (4 ** k -1) * ( R * (read_len - k + 1) - (read_len - k) ) / (4 ** k + read_len...
StarcoderdataPython
4835289
# Copyright (c) 2021 PaddlePaddle 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 app...
StarcoderdataPython
3287655
<filename>catatom2osm/hgwnames.py<gh_stars>0 """Parsing of highway names.""" import re from fuzzywuzzy import fuzz, process from catatom2osm import config MATCH_THR = 60 def normalize(text): return re.sub(r" *\(.*\)", "", text.lower().strip()) def parse(name): """Transform the name of a street from Cadas...
StarcoderdataPython
3363787
f = open('text.txt') text = f.read() #Словарь import pymorphy2 morph = pymorphy2.MorphAnalyzer() def LEG (word): p = morph.parse(word)[0] pp = p.normal_form return pp #print(LEG('звери')) LEG ('звери') #e = список знаков препинания формат ,"#знак препинания" e = ",", ".","!","-","?","»","«","—" for i i...
StarcoderdataPython
39280
import sim import utils import numpy as np import matplotlib.pyplot as plt import argparse def main(): my_parser = argparse.ArgumentParser(description='Parameters for Simulation') my_parser.add_argument('-N', '--n_cars', type=int, action='store', help='Number of cars', default = 40) my_parser.add_argumen...
StarcoderdataPython
3285648
import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator import numpy as np from .reference_points import create_references from .clust_color import assign_colors from .misc import process_result_list def parameters(results, ax=None, free_indices_only=True, lb=None, ub=None, size=None,...
StarcoderdataPython
1745982
<gh_stars>0 import tarfile import tempfile import json import shutil import torch import torch.nn as nn class BaseNet(nn.Module, object): def __init__(self, **kwargs): super(BaseNet, self).__init__() # Keep all the __init__parameters for saving/loading self.net_parameters = kwargs ...
StarcoderdataPython
3387169
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT) p = GPIO.PWM(7,50) p.start(7.5) time.sleep(1) p.ChangeDutyCycle(2.5) time.sleep(2) p.ChangeDutyCycle(7.5) except KeyboardInterrupt: GPIO.cleanup() if __name__ == "__main__": import sys fib(int(sys.argv[1]))
StarcoderdataPython
1731441
<filename>gemtown/modelers/migrations/0002_auto_20190420_1510.py # Generated by Django 2.0.13 on 2019-04-20 06:10 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('model...
StarcoderdataPython
3265059
from roamtokenize import WordOnlyTokenizer import re from nltk.tokenize import sent_tokenize normalization_patterns = [ ("long_punctuation_formatting", '(\-{3,}|\.{3,}|\_{3,})',' FORMATTING '), ("de-ids", '(([0-9]+[A-Z]+)+[0-9]*|([A-Z]+[0-9]+)+[A-Z]*)', " DEIDENTIFIED "), ("data_re", r"\*\*DATE...
StarcoderdataPython
103480
# -*- coding: utf-8 -*- """ Created on Sun Nov 14 21:24:02 2021 @author: JOSEP """ import pandas as pd import numpy as np import matplotlib df = pd.read_csv("NFT_Sales.csv") nft_df = df nft_df.head() nft_df["NaN"] = df.apply(lambda x: 1 if x.isna() else 0, axis=1) missing_values = nft_df.isnull() nft_df["NaN"] = mis...
StarcoderdataPython
3334490
<reponame>staguchi0703/ABC164 def resolve(): ''' code here ''' S = input() def chk(num_str): temp = int(num_str) % 2019 if temp == 0: return True else: return False ans_set = [ str((i+1) * 2019) for i in range(2*10**5//2019)] cnt = 0 t...
StarcoderdataPython
1601707
<filename>rpi-rgb-led-matrix-master/matrixtest.py #!/usr/bin/python # Simple RGBMatrix example, using only Clear(), Fill() and SetPixel(). # These functions have an immediate effect on the display; no special # refresh operation needed. # Requires rgbmatrix.so present in the same directory. import time from rgbmatrix...
StarcoderdataPython
1786794
import pandas as pd import matplotlib.pyplot as plt from downloadTabelas import downloadTabela import os datasp = pd.DataFrame(columns=['ano', 'sp', 'sbc', 'g', 'c', 'sjc']) # Downloading files in 'seade.gov.br' downloadTabela() # Excel to Pandas import glob, os os.chdir("C:/Users/Matheus/Documents/PIBbrasil/SeadeFil...
StarcoderdataPython
3229325
from qmctorch.utils import ( plot_energy, plot_data, plot_block, plot_walkers_traj) import matplotlib.pyplot as plt import numpy as np print(r" ____ __ ______________ _") print(r" / __ \ / |/ / ___/_ __/__ ________/ / ") print(r"/ /_/ / / /|_/ / /__ / / / _ \/ __/ __/ _ \ ") print(r"\___\_\...
StarcoderdataPython
3202197
<filename>willie/modules/minecraft_logins.py<gh_stars>0 # coding=utf8 """minecraft_logins.py - Willie module to watch for users to go online/offline on a minecraft server Currently gets its data from minecraft dynmap, a bukkit plugin, but bukkit's future is uncertain, so it won't be a good source of info for very long...
StarcoderdataPython
1799107
<reponame>AbdoulayeDiop/Regression-Tree<gh_stars>0 import numpy as np from region import Region1, Region2 class Model(): def __init__(self, minSize, eval, norm, alpha): self.minSize = minSize self.axis = None self.subAxis = None self.root = None self.eval = eval...
StarcoderdataPython
1706908
def test_cli_version(cliapp): from uns import __version__ s, o, e = cliapp() assert e == '' assert s == 0 assert o.startswith('usage: uns [-h] [-v]') s, o, e = cliapp('--version') assert s == 0 assert o.startswith(__version__) s, o, e = cliapp('-v') assert s == 0 assert o....
StarcoderdataPython
79063
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Apr 28 17:57:57 2017 @author: pipolose """ from polyML.plot_overlay import plot_n_save_3plane import matplotlib.pyplot as plt from matplotlib import cm in_dict = {} in_dict['do_save'] = True # True # in_dict['formats_used'] = ['pdf', 'png'] in_dict[...
StarcoderdataPython
3293056
<gh_stars>0 from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^recibidos/listar', views.recibidosListar, name='recibidos-listar'), url(r'^recibidos/facturar', views.recibidosFacturar, name='recibidos-facturar'), url(r'^gastos/', views.gas...
StarcoderdataPython
1704064
<filename>flowtorch/param.py # Copyright (c) FlowTorch Development Team. All Rights Reserved # SPDX-License-Identifier: MIT from typing import Dict, Optional, Sequence, Tuple import torch import torch.nn as nn class ParamsModuleList(torch.nn.Module): params_modules: nn.ModuleList def __init__( self,...
StarcoderdataPython
3375239
<gh_stars>0 #!/usr/bin/env python3 # -*- coding: utf-8 -*- import requests import zlib from literate_banana import Bot LANGUAGES = { 'c': 'c-gcc', 'c#': 'cs-core', 'c++': 'cpp-gcc', 'common lisp': 'clisp', 'groovy': 'groovy', 'go': 'go', 'haskell': 'haskell', 'java': 'java-openjdk9', ...
StarcoderdataPython
56283
#!/usr/bin/python # -*- coding: utf-8 -*- # author arrti from ss_admin import app if __name__ == '__main__': app.run()
StarcoderdataPython
4817957
from django.db import models from accounts.models import CustomUser import datetime class Schedule(models.Model): summary = models.CharField("タイトル ※必須", max_length=25) date = models.DateField("日付 ※必須") place = models.CharField("場所", max_length=20, blank=True) time = models.TimeField("時間", blank=True, ...
StarcoderdataPython
119462
""" Implements the Perception & Adaline Learning Algorithm Author: <NAME> Created: May 18, 2010 """ import numpy as np import matplotlib.pyplot as plt class Perception: """first artifical neural classifier Args: eta: Learning rate (between 0.0 and 1.0) n_iter: pas...
StarcoderdataPython
3289845
<reponame>StardustDL/Game.GoldenNumber def adjustNumberInRange(x: float) -> float: """Adjust number into range (0,100)""" if x <= 0: return 1e-12 if x >= 100: return 100 - 1e-12 return x
StarcoderdataPython
120032
from __future__ import division from datetime import timedelta, datetime, tzinfo if not hasattr(timedelta, 'total_seconds'): def total_seconds(td): "Return the total number of seconds contained in the duration for Python 2.6 and under." return (td.microseconds + (td.seconds + td.days * 86400) * 1e...
StarcoderdataPython
74975
#Execution-3 from fake_news_detection_final_code import * # main function. def main(): Training_Validating('fake_news_dataset',130000,400,100,12,64,'x_test_3','y_test_3','history_3','model_3') Testing('x_test_3','y_test_3','history_3','model_3') ############################################# # uti...
StarcoderdataPython
87258
<reponame>icryrainix/odil<filename>tests/wrappers/webservices/test_message.py import unittest import odil class TestMessage(unittest.TestCase): def test_default_constructor(self): message = odil.webservices.Message() self.assertEqual(dict(message.get_headers()), {}) self.assertEqual(messag...
StarcoderdataPython
3345423
# Copyright 2020 The Cirq Developers # # 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 ...
StarcoderdataPython
136273
<filename>actingweb/__init__.py __all__ = ["actor", "oauth", "auth", "property", "trust", "config"]
StarcoderdataPython
3305884
<reponame>cclauss/4most-4gp-scripts<gh_stars>0 #!../../../../virtualenv/bin/python3 # -*- coding: utf-8 -*- # NB: The shebang line above assumes you've installed a python virtual environment alongside your working copy of the # <4most-4gp-scripts> git repository. It also only works if you invoke this python script fro...
StarcoderdataPython
1766244
#crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos dolares ela pode comprar.$=3,27 Real = float(input('Quanto dinheiro você tem na carteira? R$')) Dolar = Real/3.27 print(f'Com R${Real:.2f} você pode comprar US${Dolar:.2f}')
StarcoderdataPython
136516
<gh_stars>0 from airflow import DAG from airflow.operators.bash_operator import BashOperator from airflow.operators.python_operator import PythonOperator from datetime import datetime, timedelta default_args = { 'owner': 'airflow', 'description': 'Wikipedia assistant', 'depends_on_past': False, 'start_...
StarcoderdataPython
4810811
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-09-12 03:42 from __future__ import unicode_literals import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('swot_item', '0003_auto_20170912_0321'), ] operation...
StarcoderdataPython
73989
<reponame>matheusmiguelsa/Exerc-cios-de-Python<gh_stars>0 v = float(input('Valor da casa a ser comprada: R$')) s = float(input('Salário do comprador: R$')) qa = float(input('Quantos anos irá pagar: ')) print('Para pagar uma casa de R${:.2f} em {:.0f} anos'.format(v, qa), end='') print(' a prestação sera de R${:.2f}'.fo...
StarcoderdataPython