id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
5052695
<filename>month02/day03/exercise01.py """ 练习1: 一次读取5个字符,将file.txt 文件从头到尾读取打印出来,打印 内容与原文件保持一直 """ # 函数 def print_file(filename): # 默认读 file = open(filename) while True: data = file.read(1024) # 读到结尾会data为空 if not data: break # 每次打印不换行 print(data,end="") ...
StarcoderdataPython
9744747
from __future__ import division, absolute_imports, print_function """ openmoltools wrapper for packmol ? https://github.com/choderalab/openmoltools """ def oesolvate(solute, density=1.0, padding_distance=10.0, distance_between_atoms=2.5, solvents='[H]O[H]', molar_fractions='1.0', ...
StarcoderdataPython
1875708
<reponame>mageirakos/rucio #!/usr/bin/env python # Copyright 2012-2018 CERN for the benefit of the ATLAS collaboration. # # 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.apach...
StarcoderdataPython
11350187
import KratosMultiphysics as KM import KratosMultiphysics.KratosUnittest as KratosUnittest from KratosMultiphysics.testing.utilities import GetPython3Command from KratosMultiphysics.CoSimulationApplication.solver_wrappers.kratos_co_sim_io import Create as CreateKratosCoSimIO from KratosMultiphysics.CoSimulationApplica...
StarcoderdataPython
12857810
from .appifaceprog import api from .database import db
StarcoderdataPython
6578875
<gh_stars>0 # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.core.urlresolvers import reverse from django.views.generic import DetailView, ListView, RedirectView, UpdateView from django.contrib.messages.views import SuccessMessageMixin from braces.views import LoginRequired...
StarcoderdataPython
6572198
""" Generate daily, monthly, and yearly rolling stock returns ((Ending Value - Begining Value) / (Ending Value)) based on the basic price data ingestet from the yahoo finance api. To run this program, the stock_price_until_2019_04_03.csv must be in the same working directory. <NAME> 04/25/19 """ import pandas as pd ...
StarcoderdataPython
11324341
<reponame>gnikit/fortls<filename>fortls/regex_patterns.py from __future__ import annotations from dataclasses import dataclass from re import I, compile from typing import Pattern @dataclass(frozen=True) class FortranRegularExpressions: USE: Pattern = compile( r"[ ]*USE([, ]+(?:INTRINSIC|NON_INTRINSIC))?...
StarcoderdataPython
8032802
<reponame>Zhenye-Na/leetcode # # @lc app=leetcode id=1 lang=python3 # # [1] Two Sum # # https://leetcode.com/problems/two-sum/description/ # # algorithms # Easy (46.28%) # Likes: 18950 # Dislikes: 675 # Total Accepted: 3.8M # Total Submissions: 8.2M # Testcase Example: '[2,7,11,15]\n9' # # Given an array of inte...
StarcoderdataPython
1697485
# coding: utf8 import math def rgb_to_xyz(rgb): """ Convert tuple from the sRGB color space to the CIE XYZ color space. The XYZ output is determined using D65 illuminate with a 2° observer angle. https://en.wikipedia.org/wiki/Illuminant_D65 The conversion matrix used was provided by <NAME>: ...
StarcoderdataPython
3540620
import argparse import json import os import spacy from spacy.tokens import Doc from benepar.spacy_plugin import BeneparComponent # Benepar tag set: ['ADJP', 'ADVP', 'CONJP', 'FRAG', 'INTJ', 'LST', 'NAC', 'NP', 'NX', 'PP', 'PRN', 'PRT', 'QP', 'RRC', 'S', 'SBAR', 'SBARQ', 'SINV', 'SQ', 'UCP', 'VP', 'WHADJP', 'WHADVP', ...
StarcoderdataPython
4877358
<reponame>PacktWorkshops/The-Spark-Workshop from utilities01_py.helper_python import * from pyspark.sql import SparkSession from pyspark import RDD from collections import defaultdict from typing import DefaultDict, Tuple import time if __name__ == "__main__": session: SparkSession = create_session(2, "Activity 3...
StarcoderdataPython
5175900
<filename>Lib/site-packages/abf_explorer/plotutils.py<gh_stars>0 # utilities for interacting with pyabf # would like a simpler way to handle IO. So when you select the ABF, we should store the ABF somewhere? or store the path to the ABF somewhere along with something like n_sweeps, n_channels, +metadata? this should be...
StarcoderdataPython
8086818
<reponame>Kalwing/fighting-and-wizardry import colorama colorama.init() class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def print_header(size: int, name: str): ...
StarcoderdataPython
6445734
<filename>utils/base_io.py import joblib import pandas as pd import json import sys import torch import glog from torch.utils.data import DataLoader sys.path.append("../") import xfinai_config from utils import path_wrapper from data_layer.base_dataset import FuturesDatasetRecurrent def load_data(fut...
StarcoderdataPython
6440538
<filename>tests/permission/conftest.py """ Conftest for permission tests """ # pylint: disable=unused-argument import pytest from permissions.models import TestModel PERMISSION_ONE = "can_do_things" PERMISSION_TWO = "can_cook_dinner" PERMISSION_UNUSED = "is_useless" @pytest.fixture def model1(user_char1): """Te...
StarcoderdataPython
5169463
<filename>tests/unit/test_newstools_crawler.py # -*- coding: utf-8 -*- import unittest from dexter.models import db from dexter.models.seeds import seed_db from dexter.processing.crawlers import NewstoolsCrawler class TestNewstoolsCrawler(unittest.TestCase): def setUp(self): self.crawler = NewstoolsCrawl...
StarcoderdataPython
1861296
# At the end couldn't manage to finish on time import yfinance as yf amount = input("Enter the amount you wish to invest: ") risk = input("Enter a number from 1 to 5, indicating the risk level you'd like to take with your investment: "(period="1y") vunHist = yf.Ticker("VUN.TO").history(period="1y") viuHist = yf.Ticker...
StarcoderdataPython
1616117
import boto3, json, pprint, requests, textwrap, time, logging, requests import os from datetime import datetime from typing import Optional, Union sfn_non_terminal_states = {"RUNNING"} sfn_failed_states = {"FAILED", "TIMED_OUT", "ABORTED"} def detect_running_region(): """Dynamically determine the region from a r...
StarcoderdataPython
6690523
import json try: import cympy except: # Only installed on the Cymdist server pass def cymdist(configuration_filename, time, input_voltage_names, input_voltage_values, output_names, input_save_to_file): """Communicate with the FMU to launch a Cymdist simulation Args: configurat...
StarcoderdataPython
3368870
"""Utility classes for saving model checkpoints.""" import os import torch import torch.nn as nn device = torch.device("cuda" if torch.cuda.is_available() else "cpu") class Checkpointer: """A simple `PyTorch` model load/save wrapper.""" def __init__( self, model: nn.Module, ckpt_dir: str, ...
StarcoderdataPython
6565291
#! /usr/bin/env python from Asap import * from Asap.Dynamics.VelocityVerlet import VelocityVerlet from Asap.Dynamics.Langevin import Langevin from Asap.Setup.Lattice.Cubic import FaceCenteredCubic import sys, cPickle, time, commands, os, re import RandomArray from Numeric import * from Asap.testtools import ReportTest...
StarcoderdataPython
1691758
import pyspark.sql.functions as F import pyspark.sql.types as T from typing import Callable from pyspark.sql import SparkSession, DataFrame # helper function for looping def loop(op: Callable[[DataFrame], DataFrame], df: DataFrame = None) -> DataFrame: for _ in range(10): df = op(df) return df class ...
StarcoderdataPython
3531195
<filename>ticket/forms.py from django import forms class TicketForm(forms.Form): title = forms.CharField(max_length=50, label='Título', widget=forms.TextInput(attrs={ 'placeholder': 'Título Mensaje', 'class': 'form-control' })) text = forms.CharField(max_length=2000, label='Texto', widget...
StarcoderdataPython
1918959
<gh_stars>0 # Generated by Django 3.2.5 on 2021-07-24 16:43 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('event', '0018_auto_20200819_1456'), ] operations = [ migrations.AlterField( model_name='racer', name='id...
StarcoderdataPython
3378486
import h5py import matplotlib.pyplot as plt from scipy.interpolate import UnivariateSpline class Signal_Intensity(object): def __init__(self, hdf5_file): self.hdf5_file = hdf5_file with h5py.File(hdf5_file, 'r') as f: for cell in range(0, 100): if cell % 20 == 0: print ("Plot...
StarcoderdataPython
1752996
# test_detects.py # This class tests the detects service class import json import os import sys import pytest # Authentication via the test_authorization.py from tests import test_authorization as Authorization # Import our sibling src folder into the path sys.path.append(os.path.abspath('src')) # Classes to test - man...
StarcoderdataPython
5178685
<reponame>birlrobotics/birl_baxter_tasks<filename>scripts/real_baxter_pick_and_place_task/real_pick_n_place_srv_client.py #!/usr/bin/env python """ pick and place service server """ from arm_move import pick_and_place from birl_baxter_tasks.srv import * import sys import rospy import copy from geometry_msgs.msg impor...
StarcoderdataPython
104565
<filename>anti_lib_progs/geodesic.py #!/usr/bin/env python3 # Copyright (c) 2003-2016 <NAME> <<EMAIL>> # 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 ...
StarcoderdataPython
1646054
<filename>Timecalc/setup.py from setuptools import setup, find_packages classifiers = [ 'Development Status :: 5 - Production/Stable', 'Programming Language :: Python :: 3', 'Operating System :: Microsoft :: Windows :: Windows 10' ] setup( name="timecalculator", version="1.1.9", packages=find_...
StarcoderdataPython
9797382
""" Author: <NAME> and <NAME> DATE: April 2020 Parts of this files are from many github repos @gurkirt mostly from https://github.com/gurkirt/RetinaNet.pytorch.1.x @longcw faster_rcnn_pytorch: https://github.com/longcw/faster_rcnn_pytorch @rbgirshick py-faster-rcnn https://github.com/rbgir...
StarcoderdataPython
1896381
"""Dealing with asset images.""" from PIL import Image, ImageTk from PIL import ImageDraw from os import path as p import os def optimize_image(path_in, path_out, size=800): '''take in an image, resize it, and save it out.''' # If destination directory doesn't exist create it: dst_dir = p.dirname(path_ou...
StarcoderdataPython
1611844
from crontab_tasks.celery import app import os import logging import requests from helpers.operation_with_files import read_service_configuration logger = logging.getLogger() logging.basicConfig( format='%(asctime)s:%(levelname)s:%(message)s', level=logging.INFO ) logger.setLevel(logging.INFO) @app.task(queue='req...
StarcoderdataPython
9719626
"""Add folio number to entity table Revision ID: 09c44f82c03c Revises: 68e2f43b9d22 Create Date: 2020-03-20 10:33:31.402269 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '09c44f82c03c' down_revision = '<KEY>' branch_labels = None depends_on = None def upgra...
StarcoderdataPython
3278121
import warnings from typing import Union import numpy as np import pandas as pd import xarray as xr from regime_switching.generate.base import CanRandomInstance, SeriesGenerator from regime_switching.utils.rng import AnyRandomState class ChainGenerator(SeriesGenerator): """Base object for chain generators.""" ...
StarcoderdataPython
7366
############################################################################## # # Copyright (c) 2004 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOF...
StarcoderdataPython
3402882
<gh_stars>0 from dotenv import load_dotenv from pprint import pprint from newsapi import NewsApiClient import urllib import os from bs4 import BeautifulSoup from readability import Document from find_entity import find_entity import pickle import pandas as pd from mysql_caching import set_cache_entities, get_cached_ent...
StarcoderdataPython
6528494
#!/usr/bin/env python3 # https://codeforces.com/problemset/problem/1169/A # (n+1)余数和保持不变,然后求相等点,再检查相等点是否在两者之间 # (a+b)不够,可能是出现(a+b+n)或(a+b-n)的情况 # 逻辑一大堆,好像还没有暴力法方便? # 重新整理逻辑..之前修修补补太多次了.. # 先算ta和tb; 或者直接算list(暴力法) def f(l): n,a,x,b,y = l al = list(range(a,x+1,+1)) if x>=a else list(range(a,n+1,+1))+list(rang...
StarcoderdataPython
4950395
<reponame>dedol1/verauth_api from django.shortcuts import render, HttpResponse, get_object_or_404 from django.urls import reverse from django.shortcuts import redirect from django.contrib.auth import authenticate, login,logout from django.contrib import messages from django.contrib.auth.models import User from dj...
StarcoderdataPython
11289523
import sys from acom_config import * filename = sys.argv[1] codeBlock = [] actualCode = [] counter = 0 incrementer = 0 # Read in our MD file #with open(base_path + filename, "r") as f: with open(filename, "r") as f: inputLines = f.readlines() # For each line, search for our code block delimiters #...
StarcoderdataPython
4847418
import pandas, sys, json import time, Config import requests, os from selenium import webdriver from dotenv import load_dotenv from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDr...
StarcoderdataPython
8150966
<reponame>joonaskalda/streamlit-heroku<gh_stars>0 import os import streamlit.components.v1 as components import streamlit as st import time import numpy as np import IPython.display as ipd #ipd.Audio(audio, rate=16000) from online_scd.model import SCDModel from online_scd.streaming import StreamingDecoder import time...
StarcoderdataPython
5106020
<reponame>DeflatedPickle/quill<gh_stars>10-100 import quill import tkinter as tk game = quill.Window() def startup(): game.sword_broken = quill.rpg.Item(game, "Broken Sword", {"weapon": {"type": "sword", "damage": 5}}, rarity="Common") game.potion_health_small = quill.rpg.Item(game, "Small Potion of Health",...
StarcoderdataPython
3298098
""" Mock Recommender for tests purposes only. """ from barbante.recommendation.Recommender import Recommender class RecommenderMock(Recommender): """ Returns weird things. """ def __init__(self, session_context): super().__init__(session_context) def get_suffix(self): """ See barbant...
StarcoderdataPython
8141663
<gh_stars>1-10 import os import pytest import responses import shutil import unittest import tempfile from askanna import result as askanna_result from askanna.core import client as askanna_client, exceptions from tests.create_fake_files import create_json_file class TestSDKResult(unittest.TestCase): def setUp(...
StarcoderdataPython
11222711
from django.shortcuts import render from products.models import Product from django.views.generic import ListView # Create your views here. class SearchProductView(ListView): template_name = "search/list.html" def get_context_data(self,*args,**kwargs): context=super(SearchProductView,self).get_context_data(*args,...
StarcoderdataPython
6505903
<reponame>wanjugu96/Blogs-app from flask import render_template from . import main @main.app_errorhandler(404) def fourowfour(error): ''' renders the 404 page ''' return render_template('error.html'),404
StarcoderdataPython
314164
<filename>api/v0/const.py # -*- coding: utf-8 -*- ''' Copyright (c) 2014 @author: <NAME> <<EMAIL>> ''' API_VERSION_V0 = 0 API_VERSION = API_VERSION_V0 bp_name = 'api_v0' api_v0_prefix = '{prefix}/v{version}'.format( prefix='/api', # current_app.config['URL_PREFIX'], version=API_VERSION_V0 )
StarcoderdataPython
1926734
<reponame>ZmeiGorynych/generative_playground import numpy as np import nltk from nltk.grammar import Nonterminal class GrammarMaskGeneratorNew: def __init__(self, MAX_LEN, grammar): self.MAX_LEN = MAX_LEN self.grammar = grammar self.reset() def reset(self): self.S = None ...
StarcoderdataPython
5002083
# Distributed under the Apache License, Version 2.0. # See accompanying NOTICE file for details. import sys import numpy as np from pyproj import Geod from shapely.geometry import Point _wgs84_geod = Geod(ellps='WGS84') class Detection(object): __slots__ = ['frame_number', 'tracking_plane_loc_x'...
StarcoderdataPython
5162313
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals config = { 'alpha': 5e-4, 'randomize': True, 'num_hidden_units': 128, 'emb_size': 50, 'batch_size': 20, 'optimizer_type': 'adam', 'max_cores': 4, 'use_t...
StarcoderdataPython
221213
# # CanvasObject.py -- base class for shapes drawn on ginga canvases. # # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # import numpy as np from collections import namedtuple from ginga.misc import Callback, Bunch from ginga import trcalc, colors from . imp...
StarcoderdataPython
231703
from networkx import strongly_connected_components from LSD.auxiliary_graph import AuxiliaryGraph def get_strongly_connected_component(g): """Create the SCC components.""" sccs = strongly_connected_components(g) dag = AuxiliaryGraph(0) n = 1 non_singelton = [] for scc in sccs: if len(s...
StarcoderdataPython
3245842
<reponame>Kikito07/picoquic import os import sys os.chdir("/home/nikita/memoire/dpdk_picoquic/") nb_of_iteration = int(sys.argv[1]) batching = int(sys.argv[2]) gB = 10**9 size = 20*gB mycommand = ("sudo /home/nikita/memoire/dpdk_picoquic/dpdk_picoquicdemo dpdk -l 0-1 -a 0000:51:00.0 -- -@ {} -A 50:6b:4b:f3:7c:70 -N...
StarcoderdataPython
1882797
<reponame>koraygulcu/bitmovin-python from .dash_manifest import DashManifest from .abstract_adaptation_set import AbstractAdaptationSet from .period import Period from .audio_adaptation_set import AudioAdaptationSet from .subtitle_adaptation_set import SubtitleAdaptationSet from .video_adaptation_set import VideoAdapta...
StarcoderdataPython
1769945
from .chapter_dto import ChapterDTO from .metadata_dto import MetaDataDTO from .novel_dto import NovelDTO from .volume_dto import VolumeDTO
StarcoderdataPython
8076125
from datetime import date nasc = int(input('Digite o ano do nascimento: ')) hoje = date.today().year idade = hoje - nasc print('\n\nA idade do atleta é {}'.format(idade)) if idade <= 9: print('Atleta MIRIM') elif 10 < idade <= 14: print('Atleta INFANTIL') elif 15 < idade <= 19: print('Atleta JUNIOR') e...
StarcoderdataPython
3574448
<gh_stars>0 # coding: utf-8 import matplotlib.pyplot as plt from IPython import display import numpy as np import pandas as pd from scipy.sparse.linalg import svds import itertools import pickle import math import re import sys from bs4 import BeautifulSoup from nltk.corpus import stopwords from gensim.models impor...
StarcoderdataPython
6678211
<reponame>karinnecristina/Case_gamers_club<filename>dags/airflow.py import airflow from airflow import DAG from airflow.operators.python_operator import PythonOperator from pipeline import Pipeline pipeline = Pipeline(["tb_players","tb_players_medalha","tb_lobby_stats_player"]) DEFAULT_ARGS = { 'owner': 'Airflow...
StarcoderdataPython
8022814
<filename>tests/test_env.py import unittest from unittest import mock from modi.module.input_module.env import Env class TestEnv(unittest.TestCase): """Tests for 'Env' class.""" def setUp(self): """Set up test fixtures, if any.""" mock_args = (-1, -1, None) self.env = Env(*mock_args...
StarcoderdataPython
3464134
#PyPDF2 import PyPDF2 with open('./pdfFiles/dummy.pdf', 'rb') as file: #rb -> Converts from a file stream object to a binary mode reader = PyPDF2.PdfFileReader(file) #print(reader.numPages) page = reader.getPage(0) print(page.rotateClockwise(180)) writer = PyPDF2.PdfFileWriter() writer.a...
StarcoderdataPython
6509551
sacar = float(input('Digite quanto deseja sacar: R$')) print(f'{sacar // 50:.0f} nota(s) de R$ 50,00') sacar %= 50 print(f'{sacar // 20:.0f} nota(s) de R$ 20,00') sacar %= 20 print(f'{sacar // 10:.0f} nota(s) de R$ 10,00') sacar %= 10 print(f'{sacar:.0f} nota(s) de R$ 1,00')
StarcoderdataPython
11284997
<reponame>JhonAI13/Curso_python<filename>Curso-em-video/Aula_23.py #Faça um proggrama que leia um numero de 0 a 9999 e mostre cada um dos digitos separados. '''n = input('Digite um numero de 0 a 9999:') print('unidade:',n[3]) print('desena:',n[2]) print('centena:',n[1]) print('milhar:',n[0])''' n = int(input('Digite u...
StarcoderdataPython
6606346
<filename>GetKeys.py import time import os import sys import pygame #print ('Hello World') pygame.init() Running = True screen = pygame.display.set_mode([50,50]) while Running: for event in pygame.event.get(): if event.type == pygame.QUIT: Running = False pygame.quit() ...
StarcoderdataPython
350363
# # Copyright (c) 2015-2016 Pivotal Software, Inc. All Rights Reserved. # import clusterdef import fileinput import json import os import os.path import io import subprocess import sys import tempfile import threading import random def determineExternalHost(ipaddress): #Determine ip address process = subpro...
StarcoderdataPython
4970989
<reponame>Algorithmic-Alignment-Lab/openTAMP<gh_stars>1-10 from opentamp.core.util_classes.common_predicates import ExprPredicate from opentamp.core.util_classes.openrave_body import OpenRAVEBody import opentamp.core.util_classes.transform_utils as T import opentamp.core.util_classes.common_constants as const from open...
StarcoderdataPython
1689628
import test_runner import struct import asyncio import time from fibre.utils import Logger from odrive.enums import * from test_runner import * class TestStepDir(): """ Tests Step/Dir input. Not all possible combinations are tested, but each axis and each GPIO participates in at least one test case....
StarcoderdataPython
1721930
import matplotlib.animation as animation import matplotlib.pyplot as plt from IPython.display import HTML class Swarm: def __init__(self, grid, controller): self.grid = grid self.controller = controller(grid) def run(self): fig, ax = plt.subplots(6, 6) anim = animation.FuncAn...
StarcoderdataPython
142582
''' AudioAvplayer: implementation of Sound using pyobjus / AVFoundation. Works on iOS / OSX. ''' __all__ = ('SoundAvplayer', ) from kivy.core.audio import Sound, SoundLoader from pyobjus import autoclass from pyobjus.dylib_manager import load_framework, INCLUDE load_framework(INCLUDE.AVFoundation) AVAudioPlayer = au...
StarcoderdataPython
6564078
<reponame>revnav/sandbox # coding: utf-8 # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licens...
StarcoderdataPython
1827471
from collections import defaultdict from utils.parsers import line_splitter, scan_line_sections, no_op class Polymerizer(object): def __init__(self): self.polymer_pairs = defaultdict(lambda: 0) self.polymer_counts = defaultdict(lambda: 0) self.rules = {} line_parsers = [ ...
StarcoderdataPython
12812822
#!/usr/bin/env python # # Read or "fix" signature and checksum in MT1939 firmware image. # - <NAME> 2014. This file is released into the public domain. # import struct, sys, os, random class Firmware: def __init__(self, filename=None): if filename: self.open(filename) def open(self, file...
StarcoderdataPython
6519217
# -*- coding: utf-8 -*- # # Tumbleweed Verbs documentation build configuration file, created by # sphinx-quickstart on Wed May 17 10:45:35 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated fi...
StarcoderdataPython
10882
<filename>vmtkScripts/vmtkmeshboundaryinspector.py #!/usr/bin/env python ## Program: VMTK ## Module: $RCSfile: vmtkmeshboundaryinspector.py,v $ ## Language: Python ## Date: $Date: 2006/05/26 12:35:13 $ ## Version: $Revision: 1.3 $ ## Copyright (c) <NAME>, <NAME>. All rights reserved. ## See LICENSE f...
StarcoderdataPython
3558826
<reponame>abhishekyana/SentimenNet-for-Sentiment-Detection import torch import torch.nn as nn import numpy as np import pickle class SentimentNet(torch.nn.Module): def __init__(self,nE=300,nH=512,nL=2): super().__init__() self.rnn = torch.nn.LSTM(nE,nH,nL,batch_first=True) self.fc = torch.n...
StarcoderdataPython
221207
# ============================================================================= # IMPORTS # ============================================================================= import os import hou import inspect from LaidlawFX import log # ============================================================================= # FUNC...
StarcoderdataPython
245771
<gh_stars>0 #!/usr/bin/python # Google Spreadsheet DHT Sensor Data-logging Example # Depends on the 'gspread' package being installed. If you have pip installed # execute: # sudo pip install gspread # Copyright (c) 2014 Adafruit Industries # Author: <NAME> # Permission is hereby granted, free of charge, to any p...
StarcoderdataPython
4994404
<filename>database.py import os import time import sqlite3 as sql from tkinter import messagebox as mbox from utility import Logger, debugger, register_event import utility class Database(object): __instance = None @staticmethod def get_instance(): ''' This static method is used to get ...
StarcoderdataPython
8187256
from modeltranslation.translator import TranslationOptions, translator from .models import BugTrackerProduct, BugTrackerType, BugTrackerTag, BugTrackerPriority, BugTrackerStatus class BugTrackerProductTranslationOptions(TranslationOptions): fields = ('name',) class BugTrackerTypeTranslationOptions(TranslationO...
StarcoderdataPython
3306303
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui_sliceLabels.ui' # # Created by: PyQt5 UI code generator 5.7 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectNa...
StarcoderdataPython
4810292
from . import code from . import rst import functools import inspect MAX_SIGNATURE = 80 def describe(path, value, sections, is_member, doks): section = sections[2 + is_member] def describe(): try: dok = doks[value] except Exception: dok = doks.get(str(path)) ...
StarcoderdataPython
1909533
<filename>src/train.py # 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...
StarcoderdataPython
1941838
import json import dml import prov.model import datetime import uuid import pandas as pd class massValidZipCodes(dml.Algorithm): contributor = 'ashwini_gdukuray_justini_utdesai' reads = [] writes = ['ashwini_gdukuray_justini_utdesai.validZipCodes'] @staticmethod def execute(trial=False): ...
StarcoderdataPython
8151482
<reponame>changgang/steps from .libsteps import pylibsteps from ctypes import c_char_p import platform import os global STEPS_LIB class STEPS(): """ Common usage to build a simulator with STEPS: 1) simulator = STEPS(is_default=True, log_file="") # use default simulator, disable log file and show inform...
StarcoderdataPython
11222356
<reponame>david-sackmary/halo-report-generator #!/usr/bin/python class Server(): def __init__(self, hostname, serverid, serverlabel, servergroupname): self.name = hostname self.id = serverid self.label = serverlabel self.group_name = servergroupname self.issues = ''
StarcoderdataPython
192434
#!/usr/bin/env python import sys, json import netCDF4 as nc import numpy as np import pylab as pl import datetime as dt ############# # Constants # ############# Lv = 2.5E6 Rd = 287 Rv = 461 T0 = 273.15 E0 = 6.11 ###################################### # Data from Materhorn Field Campaign # ###########################...
StarcoderdataPython
9690968
#coding:utf-8 #Python中声明文件编码的注释,编码格式指定为utf-8 from socket import * from time import ctime import binascii import RPi.GPIO as GPIO import time import threading import cv2 import numpy as np print '....WIFIROBOTS START!!!...' global Path_Dect_px Path_Dect_px = 320 GPIO.setmode(GPIO.BCM) GPIO.setwarnings(Fals...
StarcoderdataPython
11242404
import logging import os import unittest import angr l = logging.getLogger("angr.tests") test_location = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', 'binaries', 'tests') class TestRelro(unittest.TestCase): def _run_fauxware_relro(self,arch): p = angr.Project(os.path.join(test_l...
StarcoderdataPython
336601
# This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild from pkg_resources import parse_version from kaitaistruct import __version__ as ks_version, KaitaiStruct, KaitaiStream, BytesIO if parse_version(ks_version) < parse_version('0.7'): raise Exception("Incompatible Kai...
StarcoderdataPython
393635
# -*- coding: UTF-8 -*- from OpenGL.GL import * import numpy as np class Material(object): def __init__(self, ambient, diffuse, specular, shininess): self.__ambient = np.array(ambient, dtype=np.float32) self.__diffuse = np.array(diffuse, dtype=np.float32) self.__specular = np.array(specula...
StarcoderdataPython
4850167
# <NAME> # ADS UNIFIP # REVISÃO DE PYTHON # AULA 21 Funções (Def) 2° parte---> GUSTAVO GUANABARA ''' Faça um Programa que tenha uma função leiaInt() que vai funcionar semelhante à função input() do Python só que fazendo a valiação par aceitar apenas um valor numérico. ex: n = leiaInt ''' print('='*30) print('{:*^30}'...
StarcoderdataPython
6695300
# -*- encoding: utf-8 -*- from ..mandelbrot import * def test_inside(): max_iterations = 100 # (0, 0) and (-1, 0) should be in the set z0, it0 = mandelbrot_iterate( 0 + 0 * 1j, max_iterations) z1, it1 = mandelbrot_iterate(-1 + 0 * 1j, max_iterations) assert it0 == max_iterations assert it1 ==...
StarcoderdataPython
12853682
<filename>MoveRestructure.py import sys import os import SimpleITK as sitk import pydicom from slugify import slugify import shutil import argparse def gen_dcm_identifiers(in_dir): ##Get Absolute Path For Every DCM File Recursively dcms_path_list = [os.path.abspath(os.path.join(dire,dcm)) for dire,sub_dir,dcms...
StarcoderdataPython
3364637
<filename>src/visualization/visualize.py from matplotlib.axes import SubplotBase import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from typing import List def pie_plot(feature_name: str, df: pd.DataFrame, ax: SubplotBase=None, title: str=None): title = title if title is...
StarcoderdataPython
333639
""" Define os verbos REST para Pessoas """ from flasgger import swag_from from flask_restful import Resource from flask_restful.reqparse import Argument from flask.json import jsonify from repositories import PessoaRepository from util import parse_params class PessoaResource(Resource): """ Verbos relacionados ...
StarcoderdataPython
6403982
import sys import readchar program = "" if len(sys.argv) <= 1: filename = "examples/hello_world.bf" else: filename = sys.argv[1] file = open(filename, "r") program = file.read() # Jump table creation to improve loop performance jumpTable = {} openingBrackets = [] cursor = 0 while cursor < len(program): i...
StarcoderdataPython
124767
<reponame>zal/simenvbenchmark<filename>environments/WeBots/controller/__init__.py #!/usr/bin/env python3 from .robot_env import RobotEnv_webots from .nnn_env import nnnEnv_webots from .simulation_interface import WebotsInterface
StarcoderdataPython
45150
#https://www.crummy.com/software/BeautifulSoup/bs4/doc/#strings-and-stripped-strings html_doc = """<html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://exam...
StarcoderdataPython
6661620
<reponame>pauvrepetit/leetcode # 350. 两个数组的交集 II # # 20200811 # huao # 排序比较慢 不排序又不会写... from typing import List class Solution: def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: nums1.sort() nums2.sort() inter = [] i = 0 j = 0 while i < len(nums...
StarcoderdataPython
5198797
<gh_stars>10-100 # Generated by Django 2.2.9 on 2020-02-11 15:14 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('registrations', '0003_auto_20200206_0926'), ] operations = [ migrations.AlterField( model_name='pending', ...
StarcoderdataPython