uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a01b1f7c0992b90de248c151 | train | function | @pytest.mark.parametrize("database_url", DATABASE_URLS)
@mysql_versions
@async_adapter
async def test_transaction_rollback(database_url):
"""
Ensure that transaction rollback is supported.
"""
async with Database(database_url) as database:
async with database.transaction(force_rollback=True):
... | @pytest.mark.parametrize("database_url", DATABASE_URLS)
@mysql_versions
@async_adapter
async def test_transaction_rollback(database_url):
| """
Ensure that transaction rollback is supported.
"""
async with Database(database_url) as database:
async with database.transaction(force_rollback=True):
try:
async with database.transaction():
query = notes.insert().values(text="example1", comp... | insert_independently()
query = notes.select()
results = await database.fetch_all(query=query)
assert len(results) == 0
delete_independently()
@pytest.mark.parametrize("database_url", DATABASE_URLS)
@mysql_versions
@async_adapter
async def test_transaction_rollback(data... | 64 | 64 | 128 | 28 | 36 | irulast/databases | tests/test_databases.py | Python | test_transaction_rollback | test_transaction_rollback | 558 | 578 | 558 | 561 | 9da5e35226095713b6faa26b3c62074ff71c0cf4 | bigcode/the-stack | train |
37625c23325d8cd4de4b69a3 | train | function | @pytest.mark.parametrize("database_url", DATABASE_URLS)
@mysql_versions
@async_adapter
async def test_rollback_isolation(database_url):
"""
Ensure that `database.transaction(force_rollback=True)` provides strict isolation.
"""
async with Database(database_url) as database:
# Perform some INSERT... | @pytest.mark.parametrize("database_url", DATABASE_URLS)
@mysql_versions
@async_adapter
async def test_rollback_isolation(database_url):
| """
Ensure that `database.transaction(force_rollback=True)` provides strict isolation.
"""
async with Database(database_url) as database:
# Perform some INSERT operations on the database.
async with database.transaction(force_rollback=True):
query = notes.insert().values(tex... | (notes.c.id == pk)
result = await database.fetch_one(query)
assert result["text"] == "example1"
assert result["completed"] == True
@pytest.mark.parametrize("database_url", DATABASE_URLS)
@mysql_versions
@async_adapter
async def test_rollback_isolation(database_url):
| 64 | 64 | 134 | 29 | 34 | irulast/databases | tests/test_databases.py | Python | test_rollback_isolation | test_rollback_isolation | 452 | 469 | 452 | 455 | f920388256edef47f7182f4fa5e9ab2d657b3507 | bigcode/the-stack | train |
c11948f51fbbaaeee2255a11 | train | class | class MyEpochType(sqlalchemy.types.TypeDecorator):
impl = sqlalchemy.Integer
epoch = datetime.date(1970, 1, 1)
def process_bind_param(self, value, dialect):
return (value - self.epoch).days
def process_result_value(self, value, dialect):
return self.epoch + datetime.timedelta(days=val... | class MyEpochType(sqlalchemy.types.TypeDecorator):
| impl = sqlalchemy.Integer
epoch = datetime.date(1970, 1, 1)
def process_bind_param(self, value, dialect):
return (value - self.epoch).days
def process_result_value(self, value, dialect):
return self.epoch + datetime.timedelta(days=value)
| and higher")
return wrapped_func(*args, **kwargs)
return check
class AsyncMock(MagicMock):
async def __call__(self, *args, **kwargs):
return super(AsyncMock, self).__call__(*args, **kwargs)
class MyEpochType(sqlalchemy.types.TypeDecorator):
| 64 | 64 | 75 | 10 | 54 | irulast/databases | tests/test_databases.py | Python | MyEpochType | MyEpochType | 43 | 52 | 43 | 43 | 14ef8acba7fe178e3be45046ce570a4cc07da9d9 | bigcode/the-stack | train |
373ac64406432e9aea0da944 | train | function | @pytest.mark.parametrize("database_url", DATABASE_URLS)
@mysql_versions
@async_adapter
async def test_result_values_allow_duplicate_names(database_url):
"""
The values of a result should respect when two columns are selected
with the same name.
"""
async with Database(database_url) as database:
... | @pytest.mark.parametrize("database_url", DATABASE_URLS)
@mysql_versions
@async_adapter
async def test_result_values_allow_duplicate_names(database_url):
| """
The values of a result should respect when two columns are selected
with the same name.
"""
async with Database(database_url) as database:
async with database.transaction(force_rollback=True):
query = "SELECT 1 AS id, 2 AS id"
row = await database.fetch_one(query=... |
assert results[0][custom_date.c.title] == "Hello, world Custom"
assert results[0][custom_date.c.published] == today
@pytest.mark.parametrize("database_url", DATABASE_URLS)
@mysql_versions
@async_adapter
async def test_result_values_allow_duplicate_names(database_url):
| 64 | 64 | 129 | 30 | 33 | irulast/databases | tests/test_databases.py | Python | test_result_values_allow_duplicate_names | test_result_values_allow_duplicate_names | 393 | 407 | 393 | 396 | eac143da6677332619e6b5867ac7642e522613dd | bigcode/the-stack | train |
5748b2e55228cc25e8f83406 | train | function | def async_adapter(wrapped_func):
"""
Decorator used to run async test cases.
"""
@functools.wraps(wrapped_func)
def run_sync(*args, **kwargs):
loop = asyncio.new_event_loop()
task = wrapped_func(*args, **kwargs)
return loop.run_until_complete(task)
return run_sync
| def async_adapter(wrapped_func):
| """
Decorator used to run async test cases.
"""
@functools.wraps(wrapped_func)
def run_sync(*args, **kwargs):
loop = asyncio.new_event_loop()
task = wrapped_func(*args, **kwargs)
return loop.run_until_complete(task)
return run_sync
| _url.scheme in [
"postgresql+aiopg",
"sqlite+aiosqlite",
"postgresql+asyncpg",
]:
url = str(database_url.replace(driver=None))
engine = sqlalchemy.create_engine(url)
metadata.drop_all(engine)
def async_adapter(wrapped_func):
| 64 | 64 | 74 | 7 | 57 | irulast/databases | tests/test_databases.py | Python | async_adapter | async_adapter | 134 | 145 | 134 | 134 | e8a99e4b5dcce9e1da30b904bcc745db98fa6a52 | bigcode/the-stack | train |
ea26a20dd2b5cc58ce5e693e | train | function | @pytest.mark.parametrize("database_url", DATABASE_URLS)
@mysql_versions
@async_adapter
async def test_fetch_one_returning_no_results(database_url):
"""
fetch_one should return `None` when no results match.
"""
async with Database(database_url) as database:
async with database.transaction(force_r... | @pytest.mark.parametrize("database_url", DATABASE_URLS)
@mysql_versions
@async_adapter
async def test_fetch_one_returning_no_results(database_url):
| """
fetch_one should return `None` when no results match.
"""
async with Database(database_url) as database:
async with database.transaction(force_rollback=True):
# fetch_all()
query = notes.select()
result = await database.fetch_one(query=query)
a... | (query=query)
assert list(row._mapping.keys()) == ["id", "id"]
assert list(row._mapping.values()) == [1, 2]
@pytest.mark.parametrize("database_url", DATABASE_URLS)
@mysql_versions
@async_adapter
async def test_fetch_one_returning_no_results(database_url):
| 64 | 64 | 95 | 31 | 33 | irulast/databases | tests/test_databases.py | Python | test_fetch_one_returning_no_results | test_fetch_one_returning_no_results | 410 | 422 | 410 | 413 | de90ffec160b00bad6087909745bf3f91019387f | bigcode/the-stack | train |
c8135312e6533fa9f993bcbc | train | function | @pytest.mark.parametrize("database_url", DATABASE_URLS)
@mysql_versions
@async_adapter
async def test_queries_raw(database_url):
"""
Test that the basic `execute()`, `execute_many()`, `fetch_all()``, and
`fetch_one()` interfaces are all supported (raw queries).
"""
async with Database(database_url) ... | @pytest.mark.parametrize("database_url", DATABASE_URLS)
@mysql_versions
@async_adapter
async def test_queries_raw(database_url):
| """
Test that the basic `execute()`, `execute_many()`, `fetch_all()``, and
`fetch_one()` interfaces are all supported (raw queries).
"""
async with Database(database_url) as database:
async with database.transaction(force_rollback=True):
# execute()
query = "INSERT IN... | text"] == "example1"
assert result[0] == "example1"
# iterate()
query = notes.select()
iterate_results = []
async for result in database.iterate(query=query):
iterate_results.append(result)
assert len(iterate_results) == 3
... | 166 | 166 | 554 | 27 | 138 | irulast/databases | tests/test_databases.py | Python | test_queries_raw | test_queries_raw | 226 | 285 | 226 | 229 | 1ff9b304cb83fd232519a3f90dbd037f1f49d3fe | bigcode/the-stack | train |
29c4227a72b90c93bf8a2e2a | train | class | class AsyncMock(MagicMock):
async def __call__(self, *args, **kwargs):
return super(AsyncMock, self).__call__(*args, **kwargs)
| class AsyncMock(MagicMock):
| async def __call__(self, *args, **kwargs):
return super(AsyncMock, self).__call__(*args, **kwargs)
| 3.9 and lower")
if url.scheme == "mysql+asyncmy" and sys.version_info < (3, 7):
pytest.skip("asyncmy supports python 3.7 and higher")
return wrapped_func(*args, **kwargs)
return check
class AsyncMock(MagicMock):
| 64 | 64 | 37 | 7 | 56 | irulast/databases | tests/test_databases.py | Python | AsyncMock | AsyncMock | 38 | 40 | 38 | 38 | c3ae1af0c4e0aaebab8702e0518f7c4c2fe97d47 | bigcode/the-stack | train |
53b0fe964bc6509c51e2983f | train | function | @pytest.mark.parametrize("database_url", DATABASE_URLS)
@mysql_versions
@async_adapter
async def test_results_support_column_reference(database_url):
"""
Casting results to a dict should work, since the interface defines them
as supporting the mapping interface.
"""
async with Database(database_url)... | @pytest.mark.parametrize("database_url", DATABASE_URLS)
@mysql_versions
@async_adapter
async def test_results_support_column_reference(database_url):
| """
Casting results to a dict should work, since the interface defines them
as supporting the mapping interface.
"""
async with Database(database_url) as database:
async with database.transaction(force_rollback=True):
now = datetime.datetime.now().replace(microsecond=0)
... | ]) == 3
assert isinstance(results_as_dicts[0]["id"], int)
assert results_as_dicts[0]["text"] == "example1"
assert results_as_dicts[0]["completed"] == True
@pytest.mark.parametrize("database_url", DATABASE_URLS)
@mysql_versions
@async_adapter
async def test_results_support_column_ref... | 78 | 78 | 262 | 29 | 48 | irulast/databases | tests/test_databases.py | Python | test_results_support_column_reference | test_results_support_column_reference | 361 | 390 | 361 | 364 | 0f87cc7232c96b6b1b29a5502de923379a0b6526 | bigcode/the-stack | train |
861bec2282c2fb1cbf87992f | train | function | @pytest.mark.parametrize("database_url", DATABASE_URLS)
def test_global_connection_is_initialized_lazily(database_url):
"""
Ensure that global connection is initialized at latest possible time
so it's _query_lock will belong to same event loop that async_adapter has
initialized.
See https://github.... | @pytest.mark.parametrize("database_url", DATABASE_URLS)
def test_global_connection_is_initialized_lazily(database_url):
| """
Ensure that global connection is initialized at latest possible time
so it's _query_lock will belong to same event loop that async_adapter has
initialized.
See https://github.com/encode/databases/issues/157 for more context.
"""
database_url = DatabaseURL(database_url)
if database_... | (database_url, force_rollback=True) as database:
async def db_lookup():
await database.fetch_one("SELECT pg_sleep(1)")
await asyncio.gather(db_lookup(), db_lookup())
@pytest.mark.parametrize("database_url", DATABASE_URLS)
def test_global_connection_is_initialized_lazily(database_url):
| 64 | 64 | 171 | 23 | 41 | irulast/databases | tests/test_databases.py | Python | test_global_connection_is_initialized_lazily | test_global_connection_is_initialized_lazily | 1,025 | 1,050 | 1,025 | 1,026 | 73fa0cf844f77e3f80e3ca88d6c580f9858bc0dd | bigcode/the-stack | train |
ea32926af6e1b9b6165f65d8 | train | function | @pytest.mark.parametrize("database_url", DATABASE_URLS)
@async_adapter
async def test_iterate_outside_transaction_with_values(database_url):
"""
Ensure `iterate()` works even without a transaction on all drivers.
The asyncpg driver relies on server-side cursors without hold
for iteration, which requires... | @pytest.mark.parametrize("database_url", DATABASE_URLS)
@async_adapter
async def test_iterate_outside_transaction_with_values(database_url):
| """
Ensure `iterate()` works even without a transaction on all drivers.
The asyncpg driver relies on server-side cursors without hold
for iteration, which requires a transaction to be created.
This is mentionned in both their documentation and their test suite.
"""
database_url = DatabaseUR... | :
async def db_lookup():
await database.fetch_one("SELECT pg_sleep(1)")
await asyncio.gather(db_lookup(), db_lookup())
run_database_queries()
@pytest.mark.parametrize("database_url", DATABASE_URLS)
@async_adapter
async def test_iterate_outside_transaction_with_values(datab... | 64 | 64 | 195 | 28 | 36 | irulast/databases | tests/test_databases.py | Python | test_iterate_outside_transaction_with_values | test_iterate_outside_transaction_with_values | 1,053 | 1,074 | 1,053 | 1,055 | aba37253a21b4ff23ce09bbccc15abe1646a278c | bigcode/the-stack | train |
05420d0752429abe827a7e4b | train | function | @pytest.mark.parametrize("database_url", DATABASE_URLS)
@mysql_versions
@async_adapter
async def test_custom_field(database_url):
"""
Test custom column types.
"""
async with Database(database_url) as database:
async with database.transaction(force_rollback=True):
today = datetime.d... | @pytest.mark.parametrize("database_url", DATABASE_URLS)
@mysql_versions
@async_adapter
async def test_custom_field(database_url):
| """
Test custom column types.
"""
async with Database(database_url) as database:
async with database.transaction(force_rollback=True):
today = datetime.date.today()
# execute()
query = custom_date.insert()
values = {"title": "Hello, world", "publ... | =query)
assert len(results) == 1
assert results[0]["data"] == {"text": "hello", "boolean": True, "int": 1}
@pytest.mark.parametrize("database_url", DATABASE_URLS)
@mysql_versions
@async_adapter
async def test_custom_field(database_url):
| 64 | 64 | 155 | 27 | 37 | irulast/databases | tests/test_databases.py | Python | test_custom_field | test_custom_field | 737 | 760 | 737 | 740 | 5bcbd9b43071f352486fac086d7f48c7275a8db3 | bigcode/the-stack | train |
1cf0d782bd67dc690e32374a | train | function | @async_adapter
async def test_should_remove_ref_on_disconnect():
async with Database("sqlite:///file::memory:?cache=shared", uri=True) as database:
query = sqlalchemy.schema.CreateTable(notes)
await database.execute(query)
query = notes.insert()
values = {"text": "example1", "comple... | @async_adapter
async def test_should_remove_ref_on_disconnect():
| async with Database("sqlite:///file::memory:?cache=shared", uri=True) as database:
query = sqlalchemy.schema.CreateTable(notes)
await database.execute(query)
query = notes.insert()
values = {"text": "example1", "completed": True}
await database.execute(query, values)
as... | True}
await database.execute(query, values)
query = notes.select().where(notes.c.text == "example1")
result = await database.fetch_one(query=query)
assert result.text == "example1"
assert result.completed is True
@async_adapter
async def test_should_remove_ref_on_disconnect():
| 64 | 64 | 124 | 13 | 50 | irulast/databases | tests/test_databases.py | Python | test_should_remove_ref_on_disconnect | test_should_remove_ref_on_disconnect | 1,256 | 1,269 | 1,256 | 1,257 | 411ce0c18e6df51d3749c1d1ccc2ed8283a7d025 | bigcode/the-stack | train |
1b88313a0ea6c7ddd9d3d093 | train | function | @pytest.mark.parametrize("database_url", DATABASE_URLS)
@mysql_versions
@async_adapter
async def test_execute_return_val(database_url):
"""
Test using return value from `execute()` to get an inserted primary key.
"""
async with Database(database_url) as database:
async with database.transaction(... | @pytest.mark.parametrize("database_url", DATABASE_URLS)
@mysql_versions
@async_adapter
async def test_execute_return_val(database_url):
| """
Test using return value from `execute()` to get an inserted primary key.
"""
async with Database(database_url) as database:
async with database.transaction(force_rollback=True):
query = notes.insert()
values = {"text": "example1", "completed": True}
pk = a... | as database:
async with database.transaction(force_rollback=True):
# fetch_all()
query = notes.select()
result = await database.fetch_one(query=query)
assert result is None
@pytest.mark.parametrize("database_url", DATABASE_URLS)
@mysql_versions
@async_adapter
asy... | 68 | 68 | 227 | 28 | 39 | irulast/databases | tests/test_databases.py | Python | test_execute_return_val | test_execute_return_val | 425 | 449 | 425 | 428 | edb15bdfc75d2b21b0495d77b713dca0e906e705 | bigcode/the-stack | train |
85b1f60b91f71fa34e5ff500 | train | function | @async_adapter
async def test_should_not_maintain_ref_when_no_cache_param():
async with Database("sqlite:///file::memory:", uri=True) as database:
query = sqlalchemy.schema.CreateTable(notes)
await database.execute(query)
query = notes.insert()
values = {"text": "example1", "complet... | @async_adapter
async def test_should_not_maintain_ref_when_no_cache_param():
| async with Database("sqlite:///file::memory:", uri=True) as database:
query = sqlalchemy.schema.CreateTable(notes)
await database.execute(query)
query = notes.insert()
values = {"text": "example1", "completed": True}
with pytest.raises(sqlite3.OperationalError):
... | .execute(query, values)
query = notes.select().where(notes.c.text == "example1")
result = await database.fetch_one(query=query)
assert result.text == "example1"
assert result.completed is True
@async_adapter
async def test_should_not_maintain_ref_when_no_cache_param():
| 64 | 64 | 90 | 18 | 45 | irulast/databases | tests/test_databases.py | Python | test_should_not_maintain_ref_when_no_cache_param | test_should_not_maintain_ref_when_no_cache_param | 1,228 | 1,237 | 1,228 | 1,229 | f9932eeafae6f9b66444590b3bb1252e45796ae3 | bigcode/the-stack | train |
d145efe67fbdb960af7b8f54 | train | class | class ClientTests(WebApiTestBase):
"""Tests for client related functions."""
@staticmethod
def init_all(api):
return [
{
'name': 'test_search',
'test': ClientTests('test_search', api),
},
{
'name': 'test_client_prop... | class ClientTests(WebApiTestBase):
| """Tests for client related functions."""
@staticmethod
def init_all(api):
return [
{
'name': 'test_search',
'test': ClientTests('test_search', api),
},
{
'name': 'test_client_properties',
'test': Cl... |
from ..common import (
WebApiTestBase, WebClientError as ClientError,
WebClientLoginError as ClientLoginError,
compat_mock, compat_urllib_error
)
class ClientTests(WebApiTestBase):
| 47 | 180 | 602 | 8 | 39 | fonclub/instagram_private_api | tests/web/client.py | Python | ClientTests | ClientTests | 9 | 87 | 9 | 9 | 3539a8c8ad265b31ea410d270bb771c751c5c9b7 | bigcode/the-stack | train |
5a985045204aadf9f0582738 | train | function | @app.route('/kmeans',methods=['POST','GET'])
def kmeans():
no_of_cluster = request.form['ip1']
query = "select latitude, longitude from all_month"
cursor.execute(query)
rows = cursor.fetchall()
x_ip = []
y_ip = []
for row in rows:
x_ip.append(row[0])
y_ip.append(row[1])
... | @app.route('/kmeans',methods=['POST','GET'])
def kmeans():
| no_of_cluster = request.form['ip1']
query = "select latitude, longitude from all_month"
cursor.execute(query)
rows = cursor.fetchall()
x_ip = []
y_ip = []
for row in rows:
x_ip.append(row[0])
y_ip.append(row[1])
X = np.array(list(zip(x_ip[:len(x_ip)], y_ip[:len(y_ip)])... | = ip1
while i<ip2:
casestr = casestr+"when MAG between "+str(i)+" and "+str(round(i+ip3,1))+" then '"+str(i)+" and "+str(round(i+ip3,1))+"' \n"
i = round(i+ip3,1)
print(casestr)
query = "SELECT CASE "+casestr+" END AS MAG1,COUNT(*) AS A from all_month WHERE MAG>="+str(ip1)+" and MAG<="+st... | 209 | 209 | 699 | 16 | 193 | abhishekmodi6020/Earthquake-Analytics | main.py | Python | kmeans | kmeans | 73 | 133 | 73 | 74 | d2e5ca777b450c937b38dfc24db4965d550ac64d | bigcode/the-stack | train |
de4eadf514dca0c10b718de7 | train | function | @app.route('/magcase',methods=['POST','GET'])
def magcase():
starttime = time.time()
ip1 = request.form['ip1']
ip2 = request.form['ip2']
ip3 = request.form['ip3']
ip1 = round(float(ip1),1)
ip2 = round(float(ip2),1)
ip3 = round(float(ip3),1)
casestr = ""
i = ip1
while i<ip2:
... | @app.route('/magcase',methods=['POST','GET'])
def magcase():
| starttime = time.time()
ip1 = request.form['ip1']
ip2 = request.form['ip2']
ip3 = request.form['ip3']
ip1 = round(float(ip1),1)
ip2 = round(float(ip2),1)
ip3 = round(float(ip3),1)
casestr = ""
i = ip1
while i<ip2:
casestr = casestr+"when MAG between "+str(i)+" and "+str(... | print(reader)
for row in reader:
print('\nrow :',row)
cursor.execute(query,row)
connection.commit()
return render_template('index.html')
@app.route('/')
def index():
return render_template('index.html')
@app.route('/page1')
def page1():
return render_templat... | 85 | 85 | 286 | 16 | 69 | abhishekmodi6020/Earthquake-Analytics | main.py | Python | magcase | magcase | 43 | 71 | 43 | 44 | 85676bd38e4aa32e96e2f0ba4d6a1d08abdfc74e | bigcode/the-stack | train |
708ac5710baf8b81219afeab | train | function | @app.route('/')
def index():
return render_template('index.html')
| @app.route('/')
def index():
| return render_template('index.html')
| ') as csvfile:
next(csvfile)
reader = csv.reader(csvfile, delimiter=',')
print(reader)
for row in reader:
print('\nrow :',row)
cursor.execute(query,row)
connection.commit()
return render_template('index.html')
@app.route('/')
def index()... | 64 | 64 | 14 | 6 | 58 | abhishekmodi6020/Earthquake-Analytics | main.py | Python | index | index | 35 | 37 | 35 | 36 | d95ea0fcf95cda77e9fa9fe724560bff60adf94a | bigcode/the-stack | train |
a7e4ddf87988a78d9bf79eb1 | train | function | @app.route('/bulkinsert', methods=['POST','GET'])
def bulkinsert():
query = "INSERT INTO dbo.EARTHQUAKE (TIME,LATITUDE,LONGITUDE,DEPTH,MAG,MAGTYPE,NST,GAP,DMIN,RMS,NET,ID,UPDATED,PLACE,TYPE,HORIZONTALERROR,DEPTHERROR,MAGERROR,MAGNST,STATUS,LOCATIONSOURCE,MAGSOURCE) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?... | @app.route('/bulkinsert', methods=['POST','GET'])
def bulkinsert():
| query = "INSERT INTO dbo.EARTHQUAKE (TIME,LATITUDE,LONGITUDE,DEPTH,MAG,MAGTYPE,NST,GAP,DMIN,RMS,NET,ID,UPDATED,PLACE,TYPE,HORIZONTALERROR,DEPTHERROR,MAGERROR,MAGNST,STATUS,LOCATIONSOURCE,MAGSOURCE) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
with open('all_month.csv',newline='') as csvfile:
... | SQL Server}'
connection = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = connection.cursor()
@app.route('/bulkinsert', methods=['POST','GET'])
def bulkinsert():
| 64 | 64 | 167 | 19 | 45 | abhishekmodi6020/Earthquake-Analytics | main.py | Python | bulkinsert | bulkinsert | 21 | 33 | 21 | 22 | 5fbb98ea27340b64bc48be89695cacd70a359478 | bigcode/the-stack | train |
a9b8babf3a754199b5ec2230 | train | function | @app.route('/page1')
def page1():
return render_template('page1.html')
| @app.route('/page1')
def page1():
| return render_template('page1.html')
| delimiter=',')
print(reader)
for row in reader:
print('\nrow :',row)
cursor.execute(query,row)
connection.commit()
return render_template('index.html')
@app.route('/')
def index():
return render_template('index.html')
@app.route('/page1')
def page1():
| 64 | 64 | 19 | 10 | 54 | abhishekmodi6020/Earthquake-Analytics | main.py | Python | page1 | page1 | 39 | 41 | 39 | 40 | 406bd071a9099f38a0c4c997f47ce963878e035f | bigcode/the-stack | train |
29c1afc2398508d78b6cf4ce | train | class | class DatabaseLoader(DataLoader, metaclass=ABCMeta):
def __init__(self, stock_id, is_etf=False,
logger_dir="database_loader", logger_name=datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")):
super().__init__(logger_dir=logger_dir, logger_name=logger_name)
self.stock_id = stock_id... | class DatabaseLoader(DataLoader, metaclass=ABCMeta):
| def __init__(self, stock_id, is_etf=False,
logger_dir="database_loader", logger_name=datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")):
super().__init__(logger_dir=logger_dir, logger_name=logger_name)
self.stock_id = stock_id
self.is_etf = is_etf
self.start_tim... | import datetime
import logging
from abc import ABCMeta, abstractmethod
import numpy as np
import utils.jikan as jikan
from data import StockCategory, parseOhlcData
from data.loader import DataLoader
from data.resource.ohlc_data import DayOhlcData, MinuteOhlcData
from utils import truncatedNormal, getValidPrices
class... | 89 | 256 | 1,992 | 12 | 76 | j32u4ukh/ProgramTrading | data/loader/database_loader.py | Python | DatabaseLoader | DatabaseLoader | 14 | 221 | 14 | 14 | df8b6d93d4021fa7d543c468bdf616e811e7a1c5 | bigcode/the-stack | train |
65ae23466ea21efe788a7d76 | train | class | class DayDatabaseLoader(DatabaseLoader):
def __init__(self, stock_id, is_etf=False,
logger_dir="database_loader", logger_name=datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")):
super().__init__(stock_id=stock_id, is_etf=is_etf,
logger_dir=logger_dir, logger_nam... | class DayDatabaseLoader(DatabaseLoader):
| def __init__(self, stock_id, is_etf=False,
logger_dir="database_loader", logger_name=datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")):
super().__init__(stock_id=stock_id, is_etf=is_etf,
logger_dir=logger_dir, logger_name=logger_name)
self.day_data = D... | argmin = np.argmin(nonzero_prices)
nonzero_prices[argmin] = low_value
prices = np.zeros_like(volumns)
# 最後一個 tick 一定有交易量,因此最後一個價格一定會映射到最後一個 tick
prices[indexs] = getValidPrices(nonzero_prices, is_etf=self.is_etf)
return prices, volumns
class DayDatabaseLoader(D... | 95 | 95 | 317 | 7 | 87 | j32u4ukh/ProgramTrading | data/loader/database_loader.py | Python | DayDatabaseLoader | DayDatabaseLoader | 224 | 253 | 224 | 224 | 871caac7ec7af9a56038b13da722d084e293edc4 | bigcode/the-stack | train |
0839ae1c49d65fdc79aaca47 | train | class | class TickDatabaseLoader(DatabaseLoader):
def __init__(self, stock_id, is_etf=False,
transaction_start=jikan.Hms(hour=9, minute=0), transaction_end=jikan.Hms(hour=13, minute=30)):
super().__init__(stock_id=stock_id, is_etf=is_etf, logger_name="TickDatabaseLoader")
self.minute_data ... | class TickDatabaseLoader(DatabaseLoader):
| def __init__(self, stock_id, is_etf=False,
transaction_start=jikan.Hms(hour=9, minute=0), transaction_end=jikan.Hms(hour=13, minute=30)):
super().__init__(stock_id=stock_id, is_etf=is_etf, logger_name="TickDatabaseLoader")
self.minute_data = MinuteOhlcData(stock_id=stock_id)
... | 時:分 -> datetime.datetime
:param open_value: 開盤價
:param high_value: 最高價
:param low_value: 最低價
:param close_value: 收盤價
:param volumn: 成交量
"""
yield f"{ohlc[0]}, {ohlc[1]}, {ohlc[2]}, {ohlc[3]}, {ohlc[4]}, {ohlc[5]}"
def loadData(se... | 256 | 256 | 1,221 | 7 | 248 | j32u4ukh/ProgramTrading | data/loader/database_loader.py | Python | TickDatabaseLoader | TickDatabaseLoader | 316 | 414 | 316 | 316 | 657b45dcc505f0325f344a7ee698b90016939b66 | bigcode/the-stack | train |
0bb96a8ae12d860708ec52ec | train | class | class MinuteDatabaseLoader(DatabaseLoader):
def __init__(self, stock_id, is_etf=False,
transaction_start=jikan.Hms(hour=9, minute=0), transaction_end=jikan.Hms(hour=13, minute=30),
logger_dir="database_loader", logger_name=datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")):
... | class MinuteDatabaseLoader(DatabaseLoader):
| def __init__(self, stock_id, is_etf=False,
transaction_start=jikan.Hms(hour=9, minute=0), transaction_end=jikan.Hms(hour=13, minute=30),
logger_dir="database_loader", logger_name=datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")):
super().__init__(stock_id=stock_id, is_... | _id=stock_id,
logger_dir=self.logger_dir, logger_name=self.logger_name)
def __getitem__(self, item):
pass
def __iter__(self):
for ohlc in self.ohlcs:
ohlc_data = f"{ohlc[0]}, {ohlc[1]}, {ohlc[2]}, {ohlc[3]}, {ohlc[4]}, {ohlc[5]}"
yiel... | 232 | 232 | 774 | 7 | 225 | j32u4ukh/ProgramTrading | data/loader/database_loader.py | Python | MinuteDatabaseLoader | MinuteDatabaseLoader | 256 | 312 | 256 | 256 | bb8eda1ff0a919ff38fb70be8d68e7573a4ea7f7 | bigcode/the-stack | train |
9b72e2c65c4bc6079a05c5d0 | train | class | class BaseAgent(object):
"""
Class for the basic agent objects.
To define your own agent, subclass this class and implement the functions below.
"""
def __init__(self,
env,
policy,
logger,
storage,
device,
... | class BaseAgent(object):
| """
Class for the basic agent objects.
To define your own agent, subclass this class and implement the functions below.
"""
def __init__(self,
env,
policy,
logger,
storage,
device,
num_checkpoints... | import torch
class BaseAgent(object):
| 8 | 64 | 212 | 5 | 2 | abhay97ps/visual-control-ppo-procgen | agents/base_agent.py | Python | BaseAgent | BaseAgent | 3 | 50 | 3 | 3 | f83fc004f6b33d4a3fa07596a1f311985c053073 | bigcode/the-stack | train |
98d382d65bd0434583a47c2e | train | function | def test_ipfs_url_success():
with open(SAMPLE_INDEX, 'r') as f:
expected_content = f.read()
connect_to_ipfs = mock.MagicMock()
connect_to_ipfs.return_value.cat.return_value = expected_content
with mock.patch('ipfshttpclient.connect', connect_to_ipfs):
assert get_web_archive_index(
... | def test_ipfs_url_success():
| with open(SAMPLE_INDEX, 'r') as f:
expected_content = f.read()
connect_to_ipfs = mock.MagicMock()
connect_to_ipfs.return_value.cat.return_value = expected_content
with mock.patch('ipfshttpclient.connect', connect_to_ipfs):
assert get_web_archive_index(
'ipfs://QmReQCtRpmEhd... | ReQCtRpmEhdWZVLhoE3e8bqreD8G3avGpVfcLD7r4K6W',
)
assert str(err_info.value) == (
'Cannot load index file from ipfs.'
)
def test_ipfs_url_success():
| 64 | 64 | 136 | 7 | 57 | TakashiMatsuda/ipwb | tests/test_backends.py | Python | test_ipfs_url_success | test_ipfs_url_success | 56 | 66 | 56 | 56 | 2f2b15e4cd94866b110d68364ce21111ba3ac860 | bigcode/the-stack | train |
f9f4f6bafe4e56c5817b6e57 | train | function | def test_ipfs_success():
with open(SAMPLE_INDEX, 'r') as f:
expected_content = f.read()
connect_to_ipfs = mock.MagicMock()
connect_to_ipfs.return_value.cat.return_value = expected_content
with mock.patch('ipfshttpclient.connect', connect_to_ipfs):
assert get_web_archive_index(
... | def test_ipfs_success():
| with open(SAMPLE_INDEX, 'r') as f:
expected_content = f.read()
connect_to_ipfs = mock.MagicMock()
connect_to_ipfs.return_value.cat.return_value = expected_content
with mock.patch('ipfshttpclient.connect', connect_to_ipfs):
assert get_web_archive_index(
'QmReQCtRpmEhdWZVLhoE... | _https():
assert get_web_archive_index(
'https://raw.githubusercontent.com/oduwsdl/ipwb/master/samples/' +
'indexes/salam-home.cdxj'
).startswith('!context ["http://tools.ietf.org/html/rfc7089"]')
def test_ipfs_success():
| 64 | 64 | 132 | 6 | 58 | TakashiMatsuda/ipwb | tests/test_backends.py | Python | test_ipfs_success | test_ipfs_success | 28 | 38 | 28 | 28 | f4dd3cd39f77d9988e491620666c30fde62c3443 | bigcode/the-stack | train |
e6c7c4fa14ada14727bbec66 | train | function | def test_https():
assert get_web_archive_index(
'https://raw.githubusercontent.com/oduwsdl/ipwb/master/samples/' +
'indexes/salam-home.cdxj'
).startswith('!context ["http://tools.ietf.org/html/rfc7089"]')
| def test_https():
| assert get_web_archive_index(
'https://raw.githubusercontent.com/oduwsdl/ipwb/master/samples/' +
'indexes/salam-home.cdxj'
).startswith('!context ["http://tools.ietf.org/html/rfc7089"]')
| AMPLE_INDEX = str(
Path(__file__).parent.parent / 'samples/indexes/salam-home.cdxj'
)
def test_local():
assert get_web_archive_index(SAMPLE_INDEX).startswith(
'!context ["http://tools.ietf.org/html/rfc7089"]'
)
def test_https():
| 64 | 64 | 60 | 4 | 60 | TakashiMatsuda/ipwb | tests/test_backends.py | Python | test_https | test_https | 21 | 25 | 21 | 21 | 4592c60343c7cb3a9f760c3ab7f788a9a6135425 | bigcode/the-stack | train |
6834541da0b02038935c8663 | train | function | def test_ipfs_failure():
with pytest.raises(BackendError) as err_info:
with mock.patch(
'ipfshttpclient.client.Client.cat',
side_effect=StatusError(original='')
):
get_web_archive_index(
'QmReQCtRpmEhdWZVLhoE3e8bqreD8G3avGpVfcLD7r4K6W',
... | def test_ipfs_failure():
| with pytest.raises(BackendError) as err_info:
with mock.patch(
'ipfshttpclient.client.Client.cat',
side_effect=StatusError(original='')
):
get_web_archive_index(
'QmReQCtRpmEhdWZVLhoE3e8bqreD8G3avGpVfcLD7r4K6W',
)
assert str(err_in... | 'QmReQCtRpmEhdWZVLhoE3e8bqreD8G3avGpVfcLD7r4K6W'
).startswith('!context ["http://tools.ietf.org/html/rfc7089"]')
def test_ipfs_failure():
| 64 | 64 | 110 | 6 | 58 | TakashiMatsuda/ipwb | tests/test_backends.py | Python | test_ipfs_failure | test_ipfs_failure | 41 | 53 | 41 | 41 | 7cfbf459361c3d5d59c640ab05942ab5cc14bf49 | bigcode/the-stack | train |
6fc38221ab2ce56def9889ef | train | function | def test_local():
assert get_web_archive_index(SAMPLE_INDEX).startswith(
'!context ["http://tools.ietf.org/html/rfc7089"]'
)
| def test_local():
| assert get_web_archive_index(SAMPLE_INDEX).startswith(
'!context ["http://tools.ietf.org/html/rfc7089"]'
)
| import mock
import pytest
from ipfshttpclient.exceptions import StatusError
from ipwb.backends import get_web_archive_index, BackendError
from pathlib import Path
SAMPLE_INDEX = str(
Path(__file__).parent.parent / 'samples/indexes/salam-home.cdxj'
)
def test_local():
| 64 | 64 | 35 | 4 | 60 | TakashiMatsuda/ipwb | tests/test_backends.py | Python | test_local | test_local | 15 | 18 | 15 | 15 | 7e52f131903bc5f8f3cdea9eb76e355540b84ded | bigcode/the-stack | train |
a41a9e00286287f5c5b5d63e | train | class | class ParaSailLexer(RegexLexer):
"""
For ParaSail source code.
.. versionadded:: 2.1
"""
name = 'ParaSail'
url = 'http://www.parasail-lang.org'
aliases = ['parasail']
filenames = ['*.psi', '*.psl']
mimetypes = ['text/x-parasail']
flags = re.MULTILINE
tokens = {
'r... | class ParaSailLexer(RegexLexer):
| """
For ParaSail source code.
.. versionadded:: 2.1
"""
name = 'ParaSail'
url = 'http://www.parasail-lang.org'
aliases = ['parasail']
filenames = ['*.psi', '*.psl']
mimetypes = ['text/x-parasail']
flags = re.MULTILINE
tokens = {
'root': [
(r'[^\S\n]+',... | """
pygments.lexers.parasail
~~~~~~~~~~~~~~~~~~~~~~~~
Lexer for ParaSail.
:copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, include
from pygments.token import Text, Comment, Operator, Ke... | 115 | 228 | 761 | 9 | 106 | edupyter/EDUPYTER38 | Lib/site-packages/pygments/lexers/parasail.py | Python | ParaSailLexer | ParaSailLexer | 20 | 79 | 20 | 20 | 5285eeb358a3fd5989056d3d35ae6070cf569bc0 | bigcode/the-stack | train |
033e54200988fb26549e5e5d | train | class | class FCBPlayerData(SoccerPlayer):
"""
FCB球员数据信息统计
----
param season: 赛季
param games: 参加比赛数
param shots: 射门次数
param goals: 进球数
param assists: 助攻数
"""
def __init__(self, name, number, age, position, salary, contract, season, games, shots, goals, assists):
SoccerPlayer.__in... | class FCBPlayerData(SoccerPlayer):
| """
FCB球员数据信息统计
----
param season: 赛季
param games: 参加比赛数
param shots: 射门次数
param goals: 进球数
param assists: 助攻数
"""
def __init__(self, name, number, age, position, salary, contract, season, games, shots, goals, assists):
SoccerPlayer.__init__(self, name, number, age, posit... | : 俱乐部
"""
def __init__(self, name, number, age, position, salary, contract, league, club):
self.name = name
self.number = number
self.age = age
self.pos = position
self.salary = salary
self.contract = contract
self.league = league
self.club = club
... | 90 | 90 | 303 | 10 | 79 | datamonday/PythonTricks | Homework/HW 03/test2.py | Python | FCBPlayerData | FCBPlayerData | 47 | 80 | 47 | 47 | 043b18976ea56300515e7595a17cc0155d0632ca | bigcode/the-stack | train |
f0b51d43b7bdd3e606c8ede5 | train | class | class ListInstanceAttr(object):
def gather_attrs(self):
# attrs = ['%s = %s' % (key, getattr(self, key)) for key in sorted(self.__dict__)]
# attrs = ['%r = %r' % (key, getattr(self, key)) for key in sorted(self.__dict__)]
attrs = [f'{key} = {getattr(self, key)}' for key in self.__dict__]
... | class ListInstanceAttr(object):
| def gather_attrs(self):
# attrs = ['%s = %s' % (key, getattr(self, key)) for key in sorted(self.__dict__)]
# attrs = ['%r = %r' % (key, getattr(self, key)) for key in sorted(self.__dict__)]
attrs = [f'{key} = {getattr(self, key)}' for key in self.__dict__]
return ', \n'.join(attrs)
... | ability to determine the type of an object at runtime.
- Python提供了可用于内省的工具,它们是类的一些特殊属性和函数,允许我们访问对象实现的一些内部机制。比如 `instance.__class__` 和 `instance.__dict__`。
"""
class ListInstanceAttr(object):
| 64 | 64 | 135 | 6 | 58 | datamonday/PythonTricks | Homework/HW 03/test2.py | Python | ListInstanceAttr | ListInstanceAttr | 12 | 20 | 12 | 12 | 7c4665480aa500ba6f0e0ece9f21862e83693250 | bigcode/the-stack | train |
d4875587da3fcee0f07e3419 | train | class | class SoccerPlayer(ListInstanceAttr):
"""
球员基本信息统计
---
param number: 球衣号码
param name: 姓名
param age: 年龄
param position: 位置
param salary: 年薪 (百万欧€)
param contract: 合同截止年限
param league: 联赛
param club: 俱乐部
"""
def __init__(self, name, number, age, position, salary, contra... | class SoccerPlayer(ListInstanceAttr):
| """
球员基本信息统计
---
param number: 球衣号码
param name: 姓名
param age: 年龄
param position: 位置
param salary: 年薪 (百万欧€)
param contract: 合同截止年限
param league: 联赛
param club: 俱乐部
"""
def __init__(self, name, number, age, position, salary, contract, league, club):
self.name =... | self):
return '[%s: \n%s]' % (self.__class__.__name__, self.gather_attrs())
# def __repr__(self):
# return '[%r: %r]' % (self.__class__.__name__, self.gather_attrs())
class SoccerPlayer(ListInstanceAttr):
| 63 | 64 | 161 | 7 | 56 | datamonday/PythonTricks | Homework/HW 03/test2.py | Python | SoccerPlayer | SoccerPlayer | 24 | 45 | 24 | 24 | 339be1293e1f4ff46c21a2a7985a9d7242b851c1 | bigcode/the-stack | train |
3095976c903d148983c94bf9 | train | class | class TestPlayer(unittest.TestCase):
def test_init(self):
messi = FCBPlayerData('Messi', 10, 33, 'RW', 70.7580, 2023, '20/21', 35, 196, 30, 9)
self.assertEqual(messi.name, 'Messi')
self.assertEqual(messi.number, 10)
self.assertEqual(messi.age, 33)
self.assertEqual(messi.pos, ... | class TestPlayer(unittest.TestCase):
| def test_init(self):
messi = FCBPlayerData('Messi', 10, 33, 'RW', 70.7580, 2023, '20/21', 35, 196, 30, 9)
self.assertEqual(messi.name, 'Messi')
self.assertEqual(messi.number, 10)
self.assertEqual(messi.age, 33)
self.assertEqual(messi.pos, 'RW')
self.assertEqual(messi.... | 196, 30, 9)
# print(messi, '\n')
# print('场均进球:', messi.avg_goals())
# print('进球效率:', messi.eff_goals())
# 单元测试
import unittest
class TestPlayer(unittest.TestCase):
| 64 | 64 | 191 | 7 | 56 | datamonday/PythonTricks | Homework/HW 03/test2.py | Python | TestPlayer | TestPlayer | 92 | 102 | 92 | 92 | 083da55a50d7b4558c5fa30b1b70b6e66e1c230c | bigcode/the-stack | train |
376ca6943da9e35918224e2d | train | function | def _ical_serialize_vc_alarm(record):
alarm = icalendar.Alarm()
alarm.add('trigger', timedelta(minutes=-int(record['_ical_alarm'])))
alarm.add('action', 'DISPLAY')
alarm.add('summary', _ical_summary(record))
alarm.add('description', str(record['url']))
return alarm
| def _ical_serialize_vc_alarm(record):
| alarm = icalendar.Alarm()
alarm.add('trigger', timedelta(minutes=-int(record['_ical_alarm'])))
alarm.add('action', 'DISPLAY')
alarm.add('summary', _ical_summary(record))
alarm.add('description', str(record['url']))
return alarm
| c_alarm(record))
cal.add_component(event)
def _ical_summary(record):
return '{}{} - {}'.format('(!) ' if not record['vc_capable_room'] or record['OWH'] else '',
'VC Assistance', record['title'])
def _ical_serialize_vc_alarm(record):
| 63 | 64 | 70 | 10 | 53 | ThiefMaster/indico-plugins-cern | vc_assistance/indico_vc_assistance/api.py | Python | _ical_serialize_vc_alarm | _ical_serialize_vc_alarm | 106 | 112 | 106 | 106 | b3bb877834d3643d6ff2e7500b94bf917027ee52 | bigcode/the-stack | train |
9649dbcb746c88138ea27d42 | train | function | def _ical_serialize_vc(cal, record, now):
event = icalendar.Event()
event.add('uid', record['_ical_id'])
event.add('dtstamp', now)
event.add('dtstart', record['startDate'])
event.add('dtend', record['endDate'])
event.add('url', record['url'])
event.add('categories', 'Videoconference assistan... | def _ical_serialize_vc(cal, record, now):
| event = icalendar.Event()
event.add('uid', record['_ical_id'])
event.add('dtstamp', now)
event.add('dtstart', record['startDate'])
event.add('dtend', record['endDate'])
event.add('url', record['url'])
event.add('categories', 'Videoconference assistance')
event.add('summary', _ical_summar... | in get_vc_capable_rooms(),
'OWH': not start_time_within_working_hours(event),
'_ical_id': f'indico-vc-assistance-{unique_id}@cern.ch'
}
if alarm:
data['_ical_alarm'] = alarm
return data
def _ical_serialize_vc(cal, record, now):
| 74 | 74 | 248 | 13 | 60 | ThiefMaster/indico-plugins-cern | vc_assistance/indico_vc_assistance/api.py | Python | _ical_serialize_vc | _ical_serialize_vc | 77 | 98 | 77 | 77 | 8abe5ceb3b10915d2e17e0e51b4ca8bc2265b76b | bigcode/the-stack | train |
6b4a174bac8ccf78a8718863 | train | function | def _ical_summary(record):
return '{}{} - {}'.format('(!) ' if not record['vc_capable_room'] or record['OWH'] else '',
'VC Assistance', record['title'])
| def _ical_summary(record):
| return '{}{} - {}'.format('(!) ' if not record['vc_capable_room'] or record['OWH'] else '',
'VC Assistance', record['title'])
| record['OWH']:
description.append('(!) Event starts out of working hours')
event.add('description', '\n'.join(description))
if '_ical_alarm' in record:
event.add_component(_ical_serialize_vc_alarm(record))
cal.add_component(event)
def _ical_summary(record):
| 64 | 64 | 43 | 6 | 58 | ThiefMaster/indico-plugins-cern | vc_assistance/indico_vc_assistance/api.py | Python | _ical_summary | _ical_summary | 101 | 103 | 101 | 101 | 2d3eb1e5495e3f3131d45a1905d22058ef818571 | bigcode/the-stack | train |
6f194960cdbd20800c76951f | train | class | class RoomVCListHook(HTTPAPIHook):
"""
Get a list of all room bookings for a given room in a given time period.
This will also output, for each of them, the associated event (if any)
and associated VC room (if any)
"""
TYPES = ('room-vc-list',)
RE = r'(?P<building>\d{1,4})\/(?P<floor>[\d\w])... | class RoomVCListHook(HTTPAPIHook):
| """
Get a list of all room bookings for a given room in a given time period.
This will also output, for each of them, the associated event (if any)
and associated VC room (if any)
"""
TYPES = ('room-vc-list',)
RE = r'(?P<building>\d{1,4})\/(?P<floor>[\d\w])-(?P<number>[\d\w]{1,3})'
VALID... | ')
if record['OWH']:
description.append('(!) Event starts out of working hours')
event.add('description', '\n'.join(description))
if '_ical_alarm' in record:
event.add_component(_ical_serialize_vc_alarm(record))
cal.add_component(event)
def _ical_summary(record):
return '{}{} - {}'... | 185 | 185 | 619 | 10 | 174 | ThiefMaster/indico-plugins-cern | vc_assistance/indico_vc_assistance/api.py | Python | RoomVCListHook | RoomVCListHook | 115 | 189 | 115 | 115 | 58a4e0b2778bb9bf56255570e76874386f9e7744 | bigcode/the-stack | train |
ad723629c7e8312964209483 | train | class | class VCAssistanceExportHook(HTTPAPIHook):
TYPES = (VCAssistanceRequest.name,)
RE = ''
DEFAULT_DETAIL = 'default'
MAX_RECORDS = {'default': 100}
GUEST_ALLOWED = False
VALID_FORMATS = ('json', 'jsonp', 'xml', 'ics')
def _getParams(self):
super()._getParams()
self._alarm = get... | class VCAssistanceExportHook(HTTPAPIHook):
| TYPES = (VCAssistanceRequest.name,)
RE = ''
DEFAULT_DETAIL = 'default'
MAX_RECORDS = {'default': 100}
GUEST_ALLOWED = False
VALID_FORMATS = ('json', 'jsonp', 'xml', 'ics')
def _getParams(self):
super()._getParams()
self._alarm = get_query_parameter(self._queryParams, ['alarm... | _query_parameter
from indico_vc_assistance.definition import VCAssistanceRequest
from indico_vc_assistance.util import (find_requests, get_vc_capable_rooms, is_vc_support,
start_time_within_working_hours)
class VCAssistanceExportHook(HTTPAPIHook):
| 64 | 64 | 197 | 12 | 52 | ThiefMaster/indico-plugins-cern | vc_assistance/indico_vc_assistance/api.py | Python | VCAssistanceExportHook | VCAssistanceExportHook | 26 | 48 | 26 | 26 | 29631b17702f7fc7fe6ee8558d61af9022dadcd3 | bigcode/the-stack | train |
48bd6fe787595cd2bd1cc06d | train | function | def _serialize_obj(req, alarm):
# Util to serialize an event in the context of a vc assistance request
event = req.event
url = event.external_url
title = event.title
unique_id = f'e{event.id}'
data = {
'event_id': req.event_id,
'startDate': event.start_dt,
'endDate': eve... | def _serialize_obj(req, alarm):
# Util to serialize an event in the context of a vc assistance request
| event = req.event
url = event.external_url
title = event.title
unique_id = f'e{event.id}'
data = {
'event_id': req.event_id,
'startDate': event.start_dt,
'endDate': event.end_dt,
'title': title,
'location': event.venue_name or None,
'room': event.get_... | results = find_requests(from_dt=self._fromDT, to_dt=self._toDT, contribs_and_sessions=False)
for req in results:
yield _serialize_obj(req, self._alarm)
def _serialize_obj(req, alarm):
# Util to serialize an event in the context of a vc assistance request
| 66 | 66 | 223 | 24 | 42 | ThiefMaster/indico-plugins-cern | vc_assistance/indico_vc_assistance/api.py | Python | _serialize_obj | _serialize_obj | 51 | 74 | 51 | 52 | 39624e4b931ce8a370c99fb2f7b9bb5a1d3af7f1 | bigcode/the-stack | train |
22e012ef7f3771d7a2f97c8d | train | function | def test_timer_context(capfd: pytest.CaptureFixture):
"""Test timing using context"""
timer = CommandTimer("My task", on_exit=print)
with timer:
time.sleep(1)
# Use approx due to differences in precision of timers on different OS's
assert pytest.approx(timer.last_duration, abs=0.5) == 1.0
... | def test_timer_context(capfd: pytest.CaptureFixture):
| """Test timing using context"""
timer = CommandTimer("My task", on_exit=print)
with timer:
time.sleep(1)
# Use approx due to differences in precision of timers on different OS's
assert pytest.approx(timer.last_duration, abs=0.5) == 1.0
out, err = capfd.readouterr()
assert out == "M... | time
import pytest
from c8ylp.timer import CommandTimer
def test_timer_calling_stop_before_start():
"""Test calling stop before timer has started"""
timer = CommandTimer("My task")
assert timer.stop() == 0
def test_timer_context(capfd: pytest.CaptureFixture):
| 64 | 64 | 112 | 12 | 51 | SoftwareAG/cumulocity-remote-access-local-proxy | tests/c8ylp/cli/test_command_timer.py | Python | test_timer_context | test_timer_context | 30 | 41 | 30 | 30 | b8501cd1c53f96d24bc0e05792f810527f95143e | bigcode/the-stack | train |
0ee02dd395d138d2e4f89cb9 | train | function | def test_timer_calling_stop_before_start():
"""Test calling stop before timer has started"""
timer = CommandTimer("My task")
assert timer.stop() == 0
| def test_timer_calling_stop_before_start():
| """Test calling stop before timer has started"""
timer = CommandTimer("My task")
assert timer.stop() == 0
| ,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Test command timer"""
import time
import pytest
from c8ylp.timer import CommandTimer
def test_timer_calling_stop_before_start():
| 64 | 64 | 37 | 9 | 54 | SoftwareAG/cumulocity-remote-access-local-proxy | tests/c8ylp/cli/test_command_timer.py | Python | test_timer_calling_stop_before_start | test_timer_calling_stop_before_start | 24 | 27 | 24 | 24 | 4ddc329a6066896d79a5390d24badc40182bba35 | bigcode/the-stack | train |
162724594a948dec854b9229 | train | function | def normpath(path):
'''
Returns Normalize path, eliminating double slashes, etc.
.. versionadded:: 2015.5.0
This can be useful at the CLI but is frequently useful when scripting.
.. code-block:: yaml
{%- from salt['file.normpath'](tpldir + '/../vars.jinja') import parent_vars %}
CLI... | def normpath(path):
| '''
Returns Normalize path, eliminating double slashes, etc.
.. versionadded:: 2015.5.0
This can be useful at the CLI but is frequently useful when scripting.
.. code-block:: yaml
{%- from salt['file.normpath'](tpldir + '/../vars.jinja') import parent_vars %}
CLI Example:
.. co... | .pardir']() %}
{% set final_path = salt['file.join']('subdir', pardir, 'confdir') %}
CLI Example:
.. code-block:: bash
salt '*' file.pardir
'''
return os.path.pardir
def normpath(path):
| 64 | 64 | 112 | 5 | 58 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | normpath | normpath | 5,345 | 5,363 | 5,345 | 5,345 | 8ce51f74a0c6757e6b9110133cdefbc073063fc4 | bigcode/the-stack | train |
239599e57a9a0da86d9133de | train | function | def __virtual__():
'''
Only work on POSIX-like systems
'''
# win_file takes care of windows
if salt.utils.is_windows():
return (False, 'The file execution module cannot be loaded: only available on non-Windows systems - use win_file instead.')
return True
| def __virtual__():
| '''
Only work on POSIX-like systems
'''
# win_file takes care of windows
if salt.utils.is_windows():
return (False, 'The file execution module cannot be loaded: only available on non-Windows systems - use win_file instead.')
return True
| edirs'
}
HASHES = [
['sha512', 128],
['sha384', 96],
['sha256', 64],
['sha224', 56],
['sha1', 40],
['md5', 32],
]
def __virtual__():
| 63 | 64 | 65 | 5 | 58 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | __virtual__ | __virtual__ | 73 | 80 | 73 | 73 | c9dff50393f7edeac20683b9bb73abbf4888d904 | bigcode/the-stack | train |
0bc3ca9f8e7ed1f941aba816 | train | function | def get_hash(path, form='sha256', chunk_size=65536):
'''
Get the hash sum of a file
This is better than ``get_sum`` for the following reasons:
- It does not read the entire file into memory.
- It does not return a string on error. The returned value of
``get_sum`` cannot really ... | def get_hash(path, form='sha256', chunk_size=65536):
| '''
Get the hash sum of a file
This is better than ``get_sum`` for the following reasons:
- It does not read the entire file into memory.
- It does not return a string on error. The returned value of
``get_sum`` cannot really be trusted since it is vulnerable to
coll... | _sum /etc/passwd sha512
'''
path = os.path.expanduser(path)
if not os.path.isfile(path):
return 'File not found'
return salt.utils.get_hash(path, form, 4096)
def get_hash(path, form='sha256', chunk_size=65536):
| 64 | 64 | 175 | 16 | 48 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | get_hash | get_hash | 511 | 536 | 511 | 511 | fcecb60a662c24025066286ff57d434522868756 | bigcode/the-stack | train |
dc0199ee6db9eeafea7ed253 | train | function | def restorecon(path, recursive=False):
'''
Reset the SELinux context on a given path
CLI Example:
.. code-block:: bash
salt '*' file.restorecon /home/user/.ssh/authorized_keys
'''
if recursive:
cmd = ['restorecon', '-FR', path]
else:
cmd = ['restorecon', '-F', pat... | def restorecon(path, recursive=False):
| '''
Reset the SELinux context on a given path
CLI Example:
.. code-block:: bash
salt '*' file.restorecon /home/user/.ssh/authorized_keys
'''
if recursive:
cmd = ['restorecon', '-FR', path]
else:
cmd = ['restorecon', '-F', path]
return not __salt__['cmd.retcode... | Returns True/False.
.. versionadded:: Hellium
CLI Example:
.. code-block:: bash
salt '*' file.path_exists_glob /etc/pam*/pass*
'''
return True if glob.glob(os.path.expanduser(path)) else False
def restorecon(path, recursive=False):
| 64 | 64 | 98 | 8 | 55 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | restorecon | restorecon | 3,231 | 3,245 | 3,231 | 3,231 | b821fb2eec413efb0076980386bc4149f84fd2ab | bigcode/the-stack | train |
dae7e7c3d560a88bd8881dc0 | train | function | def readdir(path):
'''
.. versionadded:: 2014.1.0
Return a list containing the contents of a directory
CLI Example:
.. code-block:: bash
salt '*' file.readdir /path/to/dir/
'''
path = os.path.expanduser(path)
if not os.path.isabs(path):
raise SaltInvocationError('Dir... | def readdir(path):
| '''
.. versionadded:: 2014.1.0
Return a list containing the contents of a directory
CLI Example:
.. code-block:: bash
salt '*' file.readdir /path/to/dir/
'''
path = os.path.expanduser(path)
if not os.path.isabs(path):
raise SaltInvocationError('Dir path must be absol... | ):
raise SaltInvocationError('Path to link must be absolute.')
if not os.path.islink(path):
raise SaltInvocationError('A valid link was not specified.')
if canonicalize:
return os.path.realpath(path)
else:
return os.readlink(path)
def readdir(path):
| 64 | 64 | 128 | 5 | 59 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | readdir | readdir | 3,019 | 3,041 | 3,019 | 3,019 | 78be5eb4602ff24032b2d72d41ede63698feac0a | bigcode/the-stack | train |
7f05e2a2482ffd3818f919ce | train | function | def get_selinux_context(path):
'''
Get an SELinux context from a given path
CLI Example:
.. code-block:: bash
salt '*' file.get_selinux_context /etc/hosts
'''
out = __salt__['cmd.run'](['ls', '-Z', path], python_shell=False)
try:
ret = re.search(r'\w+:\w+:\w+:\w+', out).g... | def get_selinux_context(path):
| '''
Get an SELinux context from a given path
CLI Example:
.. code-block:: bash
salt '*' file.get_selinux_context /etc/hosts
'''
out = __salt__['cmd.run'](['ls', '-Z', path], python_shell=False)
try:
ret = re.search(r'\w+:\w+:\w+:\w+', out).group(0)
except AttributeErr... | /.ssh/authorized_keys
'''
if recursive:
cmd = ['restorecon', '-FR', path]
else:
cmd = ['restorecon', '-F', path]
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def get_selinux_context(path):
| 64 | 64 | 126 | 7 | 57 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | get_selinux_context | get_selinux_context | 3,248 | 3,267 | 3,248 | 3,248 | e7b9671604e18b8b450c07b7a29d6e3c98bf1ce9 | bigcode/the-stack | train |
19b435f16529ea93d0b1635b | train | function | def _assert_occurrence(src, probe, target, amount=1):
'''
Raise an exception, if there are different amount of specified occurrences in src.
'''
occ = src.count(probe)
if occ > amount:
msg = 'more than'
elif occ < amount:
msg = 'less than'
elif not occ:
msg = 'no'
... | def _assert_occurrence(src, probe, target, amount=1):
| '''
Raise an exception, if there are different amount of specified occurrences in src.
'''
occ = src.count(probe)
if occ > amount:
msg = 'more than'
elif occ < amount:
msg = 'less than'
elif not occ:
msg = 'no'
else:
msg = None
if msg:
raise C... | try:
src = re.search(regex, src)
except Exception as ex:
raise CommandExecutionError("{0}: '{1}'".format(_get_error_message(ex), regex))
return src and src.group() or regex
def _assert_occurrence(src, probe, target, amount=1):
| 64 | 64 | 115 | 15 | 48 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | _assert_occurrence | _assert_occurrence | 1,372 | 1,387 | 1,372 | 1,372 | 719a22de7ded2783ee860934fdaf406d32e95fa2 | bigcode/the-stack | train |
ebf67f1050f0a97b84fa5c1a | train | function | def get_devmm(name):
'''
Get major/minor info from a device
CLI Example:
.. code-block:: bash
salt '*' file.get_devmm /dev/chr
'''
name = os.path.expanduser(name)
if is_chrdev(name) or is_blkdev(name):
stat_structure = os.stat(name)
return (
os.majo... | def get_devmm(name):
| '''
Get major/minor info from a device
CLI Example:
.. code-block:: bash
salt '*' file.get_devmm /dev/chr
'''
name = os.path.expanduser(name)
if is_chrdev(name) or is_blkdev(name):
stat_structure = os.stat(name)
return (
os.major(stat_structure.st_r... |
if tail == os.curdir: # xxx/newdir/. exists if xxx/newdir exists
return
os.mkdir(name)
check_perms(name,
None,
user,
group,
int('{0}'.format(mode)) if mode else None)
def get_devmm(name):
| 64 | 64 | 106 | 6 | 58 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | get_devmm | get_devmm | 4,656 | 4,674 | 4,656 | 4,656 | 3b8d9d5c42a46f7df9a1a28504d8ed7afbc1efc2 | bigcode/the-stack | train |
d53b788f3c76383b0a63da80 | train | function | def get_group(path, follow_symlinks=True):
'''
Return the group that owns a given file
path
file or directory of which to get the group
follow_symlinks
indicated if symlinks should be followed
CLI Example:
.. code-block:: bash
salt '*' file.get_group /etc/passwd
... | def get_group(path, follow_symlinks=True):
| '''
Return the group that owns a given file
path
file or directory of which to get the group
follow_symlinks
indicated if symlinks should be followed
CLI Example:
.. code-block:: bash
salt '*' file.get_group /etc/passwd
.. versionchanged:: 0.16.4
``follo... | /passwd
.. versionchanged:: 0.16.4
``follow_symlinks`` option added
'''
return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('gid', -1)
def get_group(path, follow_symlinks=True):
| 64 | 64 | 124 | 11 | 53 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | get_group | get_group | 212 | 231 | 212 | 212 | e170e09c0135a5b0f903620464d9c9795799aef6 | bigcode/the-stack | train |
75132a26dbbb6b31764a7981 | train | function | def write(path, *args, **kwargs):
'''
.. versionadded:: 2014.7.0
Write text to a file, overwriting any existing contents.
path
path to file
`*args`
strings to write to the file
CLI Example:
.. code-block:: bash
salt '*' file.write /etc/motd \\
"W... | def write(path, *args, **kwargs):
| '''
.. versionadded:: 2014.7.0
Write text to a file, overwriting any existing contents.
path
path to file
`*args`
strings to write to the file
CLI Example:
.. code-block:: bash
salt '*' file.write /etc/motd \\
"With all thine offerings thou shalt... | contents = []
preface = []
for line in args:
preface.append('{0}\n'.format(line))
with salt.utils.fopen(path, "w") as ofile:
contents = preface + contents
ofile.write(''.join(contents))
return 'Prepended {0} lines to "{1}"'.format(len(args), path)
def write(path, *args, **kwar... | 88 | 88 | 296 | 10 | 78 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | write | write | 2,590 | 2,635 | 2,590 | 2,590 | 79c7d97c2a67f89fe968c4527d53c184efb97c4f | bigcode/the-stack | train |
06b00c2ad06e335d2e5aff58 | train | function | def comment_line(path,
regex,
char='#',
cmnt=True,
backup='.bak'):
r'''
Comment or Uncomment a line in a text file.
:param path: string
The full path to the text file.
:param regex: string
A regex expression that begin... | def comment_line(path,
regex,
char='#',
cmnt=True,
backup='.bak'):
| r'''
Comment or Uncomment a line in a text file.
:param path: string
The full path to the text file.
:param regex: string
A regex expression that begins with ``^`` that will find the line you wish
to comment. Can be as simple as ``^color =``
:param char: string
The... | in a file
path
The full path to the file to be edited
regex
A regular expression used to find the lines that are to be commented;
this pattern will be wrapped in parenthesis and will move any
preceding/trailing ``^`` or ``$`` characters outside the parenthesis
(e.g., th... | 256 | 256 | 1,387 | 22 | 234 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | comment_line | comment_line | 1,041 | 1,213 | 1,041 | 1,045 | af9440fd48a5280fc7b122eac83cc437bc4276ed | bigcode/the-stack | train |
94a5e911f63b4c4963a782f4 | train | function | def get_mode(path, follow_symlinks=True):
'''
Return the mode of a file
path
file or directory of which to get the mode
follow_symlinks
indicated if symlinks should be followed
CLI Example:
.. code-block:: bash
salt '*' file.get_mode /etc/passwd
.. versionchange... | def get_mode(path, follow_symlinks=True):
| '''
Return the mode of a file
path
file or directory of which to get the mode
follow_symlinks
indicated if symlinks should be followed
CLI Example:
.. code-block:: bash
salt '*' file.get_mode /etc/passwd
.. versionchanged:: 2014.1.0
``follow_symlinks`` o... | etc/passwd
.. versionchanged:: 0.16.4
``follow_symlinks`` option added
'''
return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get('user', False)
def get_mode(path, follow_symlinks=True):
| 64 | 64 | 122 | 11 | 53 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | get_mode | get_mode | 321 | 340 | 321 | 321 | 8e6189cfa4ee6c790a75d301e85fbca5614baecd | bigcode/the-stack | train |
07b55c3b7c606ca3809f880b | train | function | def check_hash(path, file_hash):
'''
Check if a file matches the given hash string
Returns true if the hash matched, otherwise false. Raises ValueError if
the hash was not formatted correctly.
path
A file path
hash
A string in the form <hash_type>:<hash_value>. For example:
... | def check_hash(path, file_hash):
| '''
Check if a file matches the given hash string
Returns true if the hash matched, otherwise false. Raises ValueError if
the hash was not formatted correctly.
path
A file path
hash
A string in the form <hash_type>:<hash_value>. For example:
``md5:e138491e9d5b97023cea82... | form
desired sum format
chunk_size
amount to sum at once
CLI Example:
.. code-block:: bash
salt '*' file.get_hash /etc/shadow
'''
return salt.utils.get_hash(os.path.expanduser(path), form, chunk_size)
def check_hash(path, file_hash):
| 68 | 68 | 227 | 8 | 60 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | check_hash | check_hash | 539 | 567 | 539 | 539 | 307abbc306c0a7d7537cc2598da44571d345252b | bigcode/the-stack | train |
3d48d7b08abd8a431bf0d61e | train | function | def basename(path):
'''
Returns the final component of a pathname
.. versionadded:: 2015.5.0
This can be useful at the CLI but is frequently useful when scripting.
.. code-block:: yaml
{%- set filename = salt['file.basename'](source_file) %}
CLI Example:
.. code-block:: bash
... | def basename(path):
| '''
Returns the final component of a pathname
.. versionadded:: 2015.5.0
This can be useful at the CLI but is frequently useful when scripting.
.. code-block:: yaml
{%- set filename = salt['file.basename'](source_file) %}
CLI Example:
.. code-block:: bash
salt '*' file... | yaml
{%- from salt['file.normpath'](tpldir + '/../vars.jinja') import parent_vars %}
CLI Example:
.. code-block:: bash
salt '*' file.normpath 'a/b/c/..'
'''
return os.path.normpath(path)
def basename(path):
| 64 | 64 | 97 | 4 | 60 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | basename | basename | 5,366 | 5,384 | 5,366 | 5,366 | d7c28193f623f15740d31b3dafc8dfd8744743bf | bigcode/the-stack | train |
691b5c74a733736e1b97c8a3 | train | function | def gid_to_group(gid):
'''
Convert the group id to the group name on this system
gid
gid to convert to a group name
CLI Example:
.. code-block:: bash
salt '*' file.gid_to_group 0
'''
try:
gid = int(gid)
except ValueError:
# This is not an integer, mayb... | def gid_to_group(gid):
| '''
Convert the group id to the group name on this system
gid
gid to convert to a group name
CLI Example:
.. code-block:: bash
salt '*' file.gid_to_group 0
'''
try:
gid = int(gid)
except ValueError:
# This is not an integer, maybe it's already the grou... | def _get_bkroot():
'''
Get the location of the backup dir in the minion cache
'''
# Get the cachedir from the minion config
return os.path.join(__salt__['config.get']('cachedir'), 'file_backup')
def gid_to_group(gid):
| 64 | 64 | 158 | 7 | 57 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | gid_to_group | gid_to_group | 136 | 163 | 136 | 136 | d894d9cd8536f6cb9c7d7796d9a481d56854c205 | bigcode/the-stack | train |
0a0fcf09be9dc604302b83df | train | function | def manage_file(name,
sfn,
ret,
source,
source_sum,
user,
group,
mode,
saltenv,
backup,
makedirs=False,
template=None, # pylint: disable=W0613... | def manage_file(name,
sfn,
ret,
source,
source_sum,
user,
group,
mode,
saltenv,
backup,
makedirs=False,
template=None, # pylint: disable=W0613... | '''
Checks the destination against what was retrieved with get_managed and
makes the appropriate modifications (if necessary).
name
location to place the file
sfn
location of cached file on the minion
This is the path to the file stored on the minion. This file is placed
... | ion'.format(minionfile)
return ret
sfn = __salt__['cp.cache_file'](masterfile, saltenv)
if sfn:
with contextlib.nested(salt.utils.fopen(sfn, 'r'),
salt.utils.fopen(minionfile, 'r')) \
as (src, name_):
slines = src.readlines()
... | 256 | 256 | 3,269 | 81 | 174 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | manage_file | manage_file | 4,134 | 4,536 | 4,134 | 4,150 | 61992321590577c99ec88cdda303240973c7dc29 | bigcode/the-stack | train |
213f86ea9b68560c6dd30715 | train | function | def _binary_replace(old, new):
'''
This function does NOT do any diffing, it just checks the old and new files
to see if either is binary, and provides an appropriate string noting the
difference between the two files. If neither file is binary, an empty
string is returned.
This function should... | def _binary_replace(old, new):
| '''
This function does NOT do any diffing, it just checks the old and new files
to see if either is binary, and provides an appropriate string noting the
difference between the two files. If neither file is binary, an empty
string is returned.
This function should only be run AFTER it has been ... | not in_roots:
os.remove(sfn)
def _error(ret, err_msg):
'''
Common function for setting error information for return dicts
'''
ret['result'] = False
ret['comment'] = err_msg
return ret
def _binary_replace(old, new):
| 64 | 64 | 179 | 8 | 55 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | _binary_replace | _binary_replace | 106 | 125 | 106 | 106 | f56cde2bf2e3c7bc4a0f2e899ae02eea94798ee7 | bigcode/the-stack | train |
5b7d025ae14501355ebee1fc | train | function | def patch(originalfile, patchfile, options='', dry_run=False):
'''
.. versionadded:: 0.10.4
Apply a patch to a file or directory.
Equivalent to:
.. code-block:: bash
patch <options> -i <patchfile> <originalfile>
Or, when a directory is patched:
.. code-block:: bash
pat... | def patch(originalfile, patchfile, options='', dry_run=False):
| '''
.. versionadded:: 0.10.4
Apply a patch to a file or directory.
Equivalent to:
.. code-block:: bash
patch <options> -i <patchfile> <originalfile>
Or, when a directory is patched:
.. code-block:: bash
patch <options> -i <patchfile> -d <originalfile> -p0
original... | CLI Example:
.. code-block:: bash
salt '*' file.search /etc/crontab 'mymaintenance.sh'
'''
if multiline:
flags = _add_flags(flags, 'MULTILINE')
bufsize = 'file'
# This function wraps file.replace on purpose in order to enforce
# consistent usage, compatible regex's, expec... | 156 | 156 | 523 | 14 | 142 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | patch | patch | 2,266 | 2,345 | 2,266 | 2,266 | 78b88fa3c555e58f4e824664c78aef80125ce5d5 | bigcode/the-stack | train |
f8d99090da15ed6e629ad4d8 | train | function | def pardir():
'''
Return the relative parent directory path symbol for underlying OS
.. versionadded:: 2014.7.0
This can be useful when constructing Salt Formulas.
.. code-block:: yaml
{% set pardir = salt['file.pardir']() %}
{% set final_path = salt['file.join']('subdir', pardir... | def pardir():
| '''
Return the relative parent directory path symbol for underlying OS
.. versionadded:: 2014.7.0
This can be useful when constructing Salt Formulas.
.. code-block:: yaml
{% set pardir = salt['file.pardir']() %}
{% set final_path = salt['file.join']('subdir', pardir, 'confdir') %... | IDs are using each file
files[name].append(pid)
files[name] = sorted(set(files[name]))
pids[pid].append(name)
pids[pid] = sorted(set(pids[pid]))
if by_pid:
return pids
return files
def pardir():
| 64 | 64 | 117 | 4 | 59 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | pardir | pardir | 5,323 | 5,342 | 5,323 | 5,323 | 532786d0c4dad67724761ef5831390ca382e758c | bigcode/the-stack | train |
205c8ff0322961aa3d0cd23c | train | function | def contains_regex_multiline(path, regex):
'''
.. deprecated:: 0.17.0
Use :func:`search` instead.
Return True if the given regular expression matches anything in the text
of a given file
Traverses multiple lines at a time, via the salt BufferedReader (reads in
chunks)
CLI Example:
... | def contains_regex_multiline(path, regex):
| '''
.. deprecated:: 0.17.0
Use :func:`search` instead.
Return True if the given regular expression matches anything in the text
of a given file
Traverses multiple lines at a time, via the salt BufferedReader (reads in
chunks)
CLI Example:
.. code-block:: bash
salt '*'... | 'r') as target:
for line in target:
if lchar:
line = line.lstrip(lchar)
if re.search(regex, line):
return True
return False
except (IOError, OSError):
return False
def contains_regex_multiline(path, regex):
| 64 | 64 | 150 | 9 | 54 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | contains_regex_multiline | contains_regex_multiline | 2,411 | 2,434 | 2,411 | 2,411 | e080cfd49ad43070c2b629f4ad64ee5517b5e49f | bigcode/the-stack | train |
6f9288ac8caaba9f3c004e36 | train | function | def contains_regex(path, regex, lchar=''):
'''
.. deprecated:: 0.17.0
Use :func:`search` instead.
Return True if the given regular expression matches on any line in the text
of a given file.
If the lchar argument (leading char) is specified, it
will strip `lchar` from the left side of e... | def contains_regex(path, regex, lchar=''):
| '''
.. deprecated:: 0.17.0
Use :func:`search` instead.
Return True if the given regular expression matches on any line in the text
of a given file.
If the lchar argument (leading char) is specified, it
will strip `lchar` from the left side of each line before trying to match
CLI Ex... | ()
try:
with salt.utils.filebuffer.BufferedReader(path) as breader:
for chunk in breader:
if stripped_text in chunk:
return True
return False
except (IOError, OSError):
return False
def contains_regex(path, regex, lchar=''):
| 64 | 64 | 201 | 11 | 52 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | contains_regex | contains_regex | 2,377 | 2,408 | 2,377 | 2,377 | 17c5f966360c3cc4836c81ff50c2e1a48f670f56 | bigcode/the-stack | train |
3ce2bc6e47f7b74bb139c59a | train | function | def mknod_blkdev(name,
major,
minor,
user=None,
group=None,
mode='0660'):
'''
.. versionadded:: 0.17.0
Create a block device.
CLI Example:
.. code-block:: bash
salt '*' file.mknod_blkdev /dev/blk 8 999
... | def mknod_blkdev(name,
major,
minor,
user=None,
group=None,
mode='0660'):
| '''
.. versionadded:: 0.17.0
Create a block device.
CLI Example:
.. code-block:: bash
salt '*' file.mknod_blkdev /dev/blk 8 999
'''
name = os.path.expanduser(name)
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
log.deb... | _blkdev /dev/blk
'''
name = os.path.expanduser(name)
stat_structure = None
try:
stat_structure = os.stat(name)
except OSError as exc:
if exc.errno == errno.ENOENT:
# If the block device does not exist in the first place
return False
else:
... | 117 | 117 | 390 | 28 | 89 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | mknod_blkdev | mknod_blkdev | 4,776 | 4,824 | 4,776 | 4,781 | b71f67124483025cdeec22f94b31f2f415f353a1 | bigcode/the-stack | train |
c8dc8c0766c6361ad74ba4b9 | train | function | def replace(path,
pattern,
repl,
count=0,
flags=8,
bufsize=1,
append_if_not_found=False,
prepend_if_not_found=False,
not_found_content=None,
backup='.bak',
dry_run=False,
search_only=False... | def replace(path,
pattern,
repl,
count=0,
flags=8,
bufsize=1,
append_if_not_found=False,
prepend_if_not_found=False,
not_found_content=None,
backup='.bak',
dry_run=False,
search_only=False... | '''
.. versionadded:: 0.17.0
Replace occurrences of a pattern in a file. If ``show_changes`` is
``True``, then a diff of what changed will be returned, otherwise a
``True`` will be returned when changes are made, and ``False`` when
no changes are made.
This is a pure Python implementation ... | _file, '{0}.{1}'.format(path, time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime())))
except (OSError, IOError) as exc:
raise CommandExecutionError("Unable to create the backup file of {0}. Exception: {1}".format(path, exc))
changes_diff = None
if changed:
if show_changes:
... | 256 | 256 | 3,035 | 79 | 176 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | replace | replace | 1,656 | 2,012 | 1,656 | 1,671 | b759236cb590b9e70b7a67ca690bfd5ed1583000 | bigcode/the-stack | train |
450cf3ce06e4d36e50df84a6 | train | function | def sed_contains(path,
text,
limit='',
flags='g'):
'''
.. deprecated:: 0.17.0
Use :func:`search` instead.
Return True if the file at ``path`` contains ``text``. Utilizes sed to
perform the search (line-wise search).
Note: the ``p`` flag wil... | def sed_contains(path,
text,
limit='',
flags='g'):
| '''
.. deprecated:: 0.17.0
Use :func:`search` instead.
Return True if the file at ``path`` contains ``text``. Utilizes sed to
perform the search (line-wise search).
Note: the ``p`` flag will be added to any flags you pass in.
CLI Example:
.. code-block:: bash
salt '*' fil... | }/{after}/{flags}'.format(
limit='/{0}/ '.format(limit) if limit else '',
negate_match='!' if negate_match else '',
before=before,
after=after,
flags=flags
)
)
cmd.append(path)
return __salt__['cmd.run_all'](cmd, python_shell=False)
def se... | 89 | 89 | 297 | 17 | 72 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | sed_contains | sed_contains | 797 | 841 | 797 | 800 | d1b42d3f89bd82fa124d8377be1699208db9b79e | bigcode/the-stack | train |
ea070e2ff14f7664549606b8 | train | function | def is_chrdev(name):
'''
Check if a file exists and is a character device.
CLI Example:
.. code-block:: bash
salt '*' file.is_chrdev /dev/chr
'''
name = os.path.expanduser(name)
stat_structure = None
try:
stat_structure = os.stat(name)
except OSError as exc:
... | def is_chrdev(name):
| '''
Check if a file exists and is a character device.
CLI Example:
.. code-block:: bash
salt '*' file.is_chrdev /dev/chr
'''
name = os.path.expanduser(name)
stat_structure = None
try:
stat_structure = os.stat(name)
except OSError as exc:
if exc.errno == err... | .expanduser(name)
if is_chrdev(name) or is_blkdev(name):
stat_structure = os.stat(name)
return (
os.major(stat_structure.st_rdev),
os.minor(stat_structure.st_rdev))
else:
return (0, 0)
def is_chrdev(name):
| 64 | 64 | 124 | 6 | 58 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | is_chrdev | is_chrdev | 4,677 | 4,698 | 4,677 | 4,677 | 16a916609b146c9172093c4e6b1fdfdbec4ef426 | bigcode/the-stack | train |
8f2002d726c2f6548904f496 | train | function | def copy(src, dst, recurse=False, remove_existing=False):
'''
Copy a file or directory from source to dst
In order to copy a directory, the recurse flag is required, and
will by default overwrite files in the destination with the same path,
and retain all other existing files. (similar to cp -r on ... | def copy(src, dst, recurse=False, remove_existing=False):
| '''
Copy a file or directory from source to dst
In order to copy a directory, the recurse flag is required, and
will by default overwrite files in the destination with the same path,
and retain all other existing files. (similar to cp -r on unix)
remove_existing will remove all files in the ta... | (path))
return False
def rename(src, dst):
'''
Rename a file or directory
CLI Example:
.. code-block:: bash
salt '*' file.rename /path/to/src /path/to/dst
'''
src = os.path.expanduser(src)
dst = os.path.expanduser(dst)
if not os.path.isabs(src):
raise SaltInvoca... | 153 | 153 | 510 | 13 | 139 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | copy | copy | 2,863 | 2,924 | 2,863 | 2,863 | bb15498e013d96abe28b05fd1caa10d4557baf0c | bigcode/the-stack | train |
7b7aa7d0f23d3461660e8b0d | train | function | def restore_backup(path, backup_id):
'''
.. versionadded:: 0.17.0
Restore a previous version of a file that was backed up using Salt's
:doc:`file state backup </ref/states/backup_mode>` system.
path
The path on the minion to check for backups
backup_id
The numeric id for the ba... | def restore_backup(path, backup_id):
| '''
.. versionadded:: 0.17.0
Restore a previous version of a file that was backed up using Salt's
:doc:`file state backup </ref/states/backup_mode>` system.
path
The path on the minion to check for backups
backup_id
The numeric id for the backup you wish to restore, as found us... | folder. Move on to the next one.
continue
ssfile.setdefault(timestamp, {})['Backup Time'] = \
timestamp.strftime('%a %b %d %Y %H:%M:%S.%f')
location = os.path.join(bkdir, x)
ssfile[timestamp]['Size'] = os.stat(location).st_size
... | 141 | 141 | 473 | 8 | 132 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | restore_backup | restore_backup | 5,067 | 5,126 | 5,067 | 5,067 | 6fb08c1998a60511f7fcbef7943eaaa3c01501f5 | bigcode/the-stack | train |
63372b9571c7e65eec4cf0fe | train | function | def check_file_meta(
name,
sfn,
source,
source_sum,
user,
group,
mode,
saltenv,
contents=None):
'''
Check for the changes in the file metadata.
CLI Example:
.. code-block:: bash
salt '*' file.check_file_meta /etc/httpd/co... | def check_file_meta(
name,
sfn,
source,
source_sum,
user,
group,
mode,
saltenv,
contents=None):
| '''
Check for the changes in the file metadata.
CLI Example:
.. code-block:: bash
salt '*' file.check_file_meta /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' base
.. note::
Supported hash types include sha512, sha384... | salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' jinja True None None base
'''
# If the source is a list then find which file exists
source, source_hash = source_list(source, # pylint: disable=W0633
source_hash,
... | 256 | 256 | 865 | 37 | 218 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | check_file_meta | check_file_meta | 3,960 | 4,080 | 3,960 | 3,969 | 860070841d527795da8c64570e9e91d221bf0a90 | bigcode/the-stack | train |
14f7a08564e3a5a27f3d4fba | train | function | def chgrp(path, group):
'''
Change the group of a file
path
path to the file or directory
group
group owner
CLI Example:
.. code-block:: bash
salt '*' file.chgrp /etc/passwd root
'''
path = os.path.expanduser(path)
user = get_user(path)
return chown(... | def chgrp(path, group):
| '''
Change the group of a file
path
path to the file or directory
group
group owner
CLI Example:
.. code-block:: bash
salt '*' file.chgrp /etc/passwd root
'''
path = os.path.expanduser(path)
user = get_user(path)
return chown(path, user, group)
| false, but still need to be chowned
return os.lchown(path, uid, gid)
except OSError:
pass
err += 'File not found'
if err:
return err
return os.chown(path, uid, gid)
def chgrp(path, group):
| 64 | 64 | 86 | 7 | 57 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | chgrp | chgrp | 458 | 477 | 458 | 458 | 2daccb5713ae9ed88d38cf81c6c0cd612fc8ab0c | bigcode/the-stack | train |
325721f34169292fece4cd0f | train | function | def source_list(source, source_hash, saltenv):
'''
Check the source list and return the source to use
CLI Example:
.. code-block:: bash
salt '*' file.source_list salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' base
'''
contextkey = '{0}_|-{1}_|-{2}'.format(source, source... | def source_list(source, source_hash, saltenv):
| '''
Check the source list and return the source to use
CLI Example:
.. code-block:: bash
salt '*' file.source_list salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' base
'''
contextkey = '{0}_|-{1}_|-{2}'.format(source, source_hash, saltenv)
if contextkey in __context_... | 'No selinux context information is available for {0}'.format(path)
)
return ret
def set_selinux_context(path,
user=None,
role=None,
type=None, # pylint: disable=W0622
range=None): # pylint: dis... | 239 | 239 | 797 | 12 | 226 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | source_list | source_list | 3,305 | 3,389 | 3,305 | 3,305 | cb3f4c0124d96b725409c7e8fe2e78f9c44d6106 | bigcode/the-stack | train |
cc46636c7fba26663bcd8187 | train | function | def prepend(path, *args, **kwargs):
'''
.. versionadded:: 2014.7.0
Prepend text to the beginning of a file
path
path to file
`*args`
strings to prepend to the file
CLI Example:
.. code-block:: bash
salt '*' file.prepend /etc/motd \\
"With all thi... | def prepend(path, *args, **kwargs):
| '''
.. versionadded:: 2014.7.0
Prepend text to the beginning of a file
path
path to file
`*args`
strings to prepend to the file
CLI Example:
.. code-block:: bash
salt '*' file.prepend /etc/motd \\
"With all thine offerings thou shalt offer salt."... | ile.read(len(linesep)) != linesep:
ofile.seek(0, os.SEEK_END)
ofile.write(linesep)
# Append lines in text mode
with salt.utils.fopen(path, 'a') as ofile:
for new_line in args:
ofile.write('{0}{1}'.format(new_line, os.linesep))
return 'Wrote {0} lines to ... | 106 | 106 | 354 | 10 | 96 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | prepend | prepend | 2,533 | 2,587 | 2,533 | 2,533 | 5fbd8102dec7f99f325a8a70dc9b117570452a9e | bigcode/the-stack | train |
f6864ca7fdd15145ed05052e | train | function | def extract_hash(hash_fn, hash_type='sha256', file_name=''):
'''
This routine is called from the :mod:`file.managed
<salt.states.file.managed>` state to pull a hash from a remote file.
Regular expressions are used line by line on the ``source_hash`` file, to
find a potential candidate of the indicat... | def extract_hash(hash_fn, hash_type='sha256', file_name=''):
| '''
This routine is called from the :mod:`file.managed
<salt.states.file.managed>` state to pull a hash from a remote file.
Regular expressions are used line by line on the ``source_hash`` file, to
find a potential candidate of the indicated hash type. This avoids many
problems of arbitrary fil... | _REGISTRY:
context_dict = defaults if defaults else {}
if context:
context_dict.update(context)
data = salt.utils.templates.TEMPLATE_REGISTRY[template](
sfn,
name=name,
source=source,
... | 224 | 225 | 752 | 16 | 208 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | extract_hash | extract_hash | 3,637 | 3,702 | 3,637 | 3,637 | 07cac0d309e31cd53e286a0d9c7b86245bc52755 | bigcode/the-stack | train |
5d37e2159c9920e88c54e4a9 | train | function | def comment(path,
regex,
char='#',
backup='.bak'):
'''
.. deprecated:: 0.17.0
Use :py:func:`~salt.modules.file.replace` instead.
Comment out specified lines in a file
path
The full path to the file to be edited
regex
A regular expression u... | def comment(path,
regex,
char='#',
backup='.bak'):
| '''
.. deprecated:: 0.17.0
Use :py:func:`~salt.modules.file.replace` instead.
Comment out specified lines in a file
path
The full path to the file to be edited
regex
A regular expression used to find the lines that are to be commented;
this pattern will be wrapped in... | called will
overwrite this backup
CLI Example:
.. code-block:: bash
salt '*' file.uncomment /etc/hosts.deny 'ALL: PARANOID'
'''
return comment_line(path=path,
regex=regex,
char=char,
cmnt=False,
... | 84 | 84 | 283 | 16 | 68 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | comment | comment | 999 | 1,038 | 999 | 1,002 | ef92b2d0c62f61f0f8491d1068f75aae615ff67c | bigcode/the-stack | train |
ddef1379723924ff76cc51c6 | train | function | def rmdir(path):
'''
.. versionadded:: 2014.1.0
Remove the specified directory. Fails if a directory is not empty.
CLI Example:
.. code-block:: bash
salt '*' file.rmdir /tmp/foo/
'''
path = os.path.expanduser(path)
if not os.path.isabs(path):
raise SaltInvocationErro... | def rmdir(path):
| '''
.. versionadded:: 2014.1.0
Remove the specified directory. Fails if a directory is not empty.
CLI Example:
.. code-block:: bash
salt '*' file.rmdir /tmp/foo/
'''
path = os.path.expanduser(path)
if not os.path.isabs(path):
raise SaltInvocationError('File path must... | link'
if stat.S_ISFIFO(pstat.st_mode):
ret['type'] = 'pipe'
if stat.S_ISSOCK(pstat.st_mode):
ret['type'] = 'socket'
ret['target'] = os.path.realpath(path)
return ret
def rmdir(path):
| 64 | 64 | 135 | 5 | 58 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | rmdir | rmdir | 3,128 | 3,152 | 3,128 | 3,128 | 38e6b45b509fa8934b9c1333599780b3e0f9ee0e | bigcode/the-stack | train |
9612ac0e32de4e9c3d7538e1 | train | function | def makedirs_perms(name,
user=None,
group=None,
mode='0755'):
'''
Taken and modified from os.makedirs to set user, group and mode for each
directory created.
CLI Example:
.. code-block:: bash
salt '*' file.makedirs_perms /opt/code
... | def makedirs_perms(name,
user=None,
group=None,
mode='0755'):
| '''
Taken and modified from os.makedirs to set user, group and mode for each
directory created.
CLI Example:
.. code-block:: bash
salt '*' file.makedirs_perms /opt/code
'''
name = os.path.expanduser(name)
path = os.path
head, tail = path.split(name)
if not tail:
... | :
# all directories have the user, group and mode set!!
log.debug('Creating directory: %s', directory_to_create)
mkdir(directory_to_create, user=user, group=group, mode=mode)
def makedirs_perms(name,
user=None,
group=None,
mode='0755'):
| 67 | 67 | 224 | 22 | 45 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | makedirs_perms | makedirs_perms | 4,619 | 4,653 | 4,619 | 4,622 | 98cbe1305ee402eab5d8578132ead54949029a6d | bigcode/the-stack | train |
733bf0dfd2d1b7085104dd31 | train | function | def line(path, content, match=None, mode=None, location=None,
before=None, after=None, show_changes=True, backup=False,
quiet=False, indent=True):
'''
.. versionadded:: 2015.8.0
Edit a line in the configuration file.
:param path:
Filesystem path to the file to be edited.
... | def line(path, content, match=None, mode=None, location=None,
before=None, after=None, show_changes=True, backup=False,
quiet=False, indent=True):
| '''
.. versionadded:: 2015.8.0
Edit a line in the configuration file.
:param path:
Filesystem path to the file to be edited.
:param content:
Content of the line.
:param match:
Match the target line for an action by
a fragment of a string or regular expression.... | 0}: '{1}'".format(_get_error_message(ex), regex))
return src and src.group() or regex
def _assert_occurrence(src, probe, target, amount=1):
'''
Raise an exception, if there are different amount of specified occurrences in src.
'''
occ = src.count(probe)
if occ > amount:
msg = 'more th... | 256 | 256 | 2,161 | 36 | 220 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | line | line | 1,406 | 1,653 | 1,406 | 1,408 | 67848e97cd56701155232dee2a8097e43ed96fc4 | bigcode/the-stack | train |
15b36111299aa72ccfbb9fba | train | function | def access(path, mode):
'''
.. versionadded:: 2014.1.0
Test whether the Salt process has the specified access to the file. One of
the following modes must be specified:
.. code-block::text
f: Test the existence of the path
r: Test the readability of the path
w: Test the wr... | def access(path, mode):
| '''
.. versionadded:: 2014.1.0
Test whether the Salt process has the specified access to the file. One of
the following modes must be specified:
.. code-block::text
f: Test the existence of the path
r: Test the readability of the path
w: Test the writability of the path
... | lst = os.lstat(path)
return dict((key, getattr(lst, key)) for key in ('st_atime', 'st_ctime',
'st_gid', 'st_mode', 'st_mtime', 'st_nlink', 'st_size', 'st_uid'))
except Exception:
return {}
def access(path, mode):
| 71 | 72 | 243 | 6 | 65 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | access | access | 2,953 | 2,989 | 2,953 | 2,953 | e3c0e62c8f8d704cc1f837a8c0eb476f64c6011c | bigcode/the-stack | train |
c1fa339e8b5292ca929b743b | train | function | def readlink(path, canonicalize=False):
'''
.. versionadded:: 2014.1.0
Return the path that a symlink points to
If canonicalize is set to True, then it return the final target
CLI Example:
.. code-block:: bash
salt '*' file.readlink /path/to/link
'''
path = os.path.expanduser... | def readlink(path, canonicalize=False):
| '''
.. versionadded:: 2014.1.0
Return the path that a symlink points to
If canonicalize is set to True, then it return the final target
CLI Example:
.. code-block:: bash
salt '*' file.readlink /path/to/link
'''
path = os.path.expanduser(path)
if not os.path.isabs(path):
... | x': os.X_OK}
if mode in modes:
return os.access(path, modes[mode])
elif mode in six.itervalues(modes):
return os.access(path, mode)
else:
raise SaltInvocationError('Invalid mode specified.')
def readlink(path, canonicalize=False):
| 63 | 64 | 151 | 9 | 54 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | readlink | readlink | 2,992 | 3,016 | 2,992 | 2,992 | 1b02ffa77ba144db6cf07c0a083b0acadf432ee3 | bigcode/the-stack | train |
0fc21c213fee8721496fd0ed | train | function | def _get_bkroot():
'''
Get the location of the backup dir in the minion cache
'''
# Get the cachedir from the minion config
return os.path.join(__salt__['config.get']('cachedir'), 'file_backup')
| def _get_bkroot():
| '''
Get the location of the backup dir in the minion cache
'''
# Get the cachedir from the minion config
return os.path.join(__salt__['config.get']('cachedir'), 'file_backup')
| bin)):
if all((old_isbin, new_isbin)):
return 'Replace binary file'
elif old_isbin:
return 'Replace binary file with text file'
elif new_isbin:
return 'Replace text file with binary file'
return ''
def _get_bkroot():
| 63 | 64 | 57 | 7 | 56 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | _get_bkroot | _get_bkroot | 128 | 133 | 128 | 128 | 673e1cea75bf35c14cf1d2a300f41dc44e32cda9 | bigcode/the-stack | train |
181d567c104c2524b723b388 | train | function | def dirname(path):
'''
Returns the directory component of a pathname
.. versionadded:: 2015.5.0
This can be useful at the CLI but is frequently useful when scripting.
.. code-block:: yaml
{%- from salt['file.dirname'](tpldir) + '/vars.jinja' import parent_vars %}
CLI Example:
.... | def dirname(path):
| '''
Returns the directory component of a pathname
.. versionadded:: 2015.5.0
This can be useful at the CLI but is frequently useful when scripting.
.. code-block:: yaml
{%- from salt['file.dirname'](tpldir) + '/vars.jinja' import parent_vars %}
CLI Example:
.. code-block:: bash... | is frequently useful when scripting.
.. code-block:: yaml
{%- set filename = salt['file.basename'](source_file) %}
CLI Example:
.. code-block:: bash
salt '*' file.basename 'test/test.config'
'''
return os.path.basename(path)
def dirname(path):
| 64 | 64 | 106 | 4 | 60 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | dirname | dirname | 5,387 | 5,405 | 5,387 | 5,387 | afe5286ae1f7f797f914f4d8f3860f41f283401c | bigcode/the-stack | train |
58cb2e3fa32804bd59a000a7 | train | function | def lstat(path):
'''
.. versionadded:: 2014.1.0
Returns the lstat attributes for the given file or dir. Does not support
symbolic links.
CLI Example:
.. code-block:: bash
salt '*' file.lstat /path/to/file
'''
path = os.path.expanduser(path)
if not os.path.isabs(path):
... | def lstat(path):
| '''
.. versionadded:: 2014.1.0
Returns the lstat attributes for the given file or dir. Does not support
symbolic links.
CLI Example:
.. code-block:: bash
salt '*' file.lstat /path/to/file
'''
path = os.path.expanduser(path)
if not os.path.isabs(path):
raise SaltI... | :
raise CommandExecutionError(
'Could not copy \'{0}\' to \'{1}\''.format(src, dst)
)
if not salt.utils.is_windows():
check_perms(dst, None, pre_user, pre_group, pre_mode)
return True
def lstat(path):
| 64 | 64 | 165 | 5 | 58 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | lstat | lstat | 2,927 | 2,950 | 2,927 | 2,927 | 2c65334bc5a3ebcfdf6a8f463d763be978742841 | bigcode/the-stack | train |
40e8b7ed66ea15c02a33943c | train | function | def contains(path, text):
'''
.. deprecated:: 0.17.0
Use :func:`search` instead.
Return ``True`` if the file at ``path`` contains ``text``
CLI Example:
.. code-block:: bash
salt '*' file.contains /etc/crontab 'mymaintenance.sh'
'''
path = os.path.expanduser(path)
if n... | def contains(path, text):
| '''
.. deprecated:: 0.17.0
Use :func:`search` instead.
Return ``True`` if the file at ``path`` contains ``text``
CLI Example:
.. code-block:: bash
salt '*' file.contains /etc/crontab 'mymaintenance.sh'
'''
path = os.path.expanduser(path)
if not os.path.exists(path):
... | or option.startswith('--strip='):
has_strip_option = True
break
if not has_strip_option:
cmd.append('--strip=0')
else:
cmd.append(originalfile)
return __salt__['cmd.run_all'](cmd, python_shell=False)
def contains(path, text):
| 64 | 64 | 155 | 6 | 58 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | contains | contains | 2,348 | 2,374 | 2,348 | 2,348 | 12b5c65a59317d6b3fa831d5a49b8d2b95a1a22f | bigcode/the-stack | train |
ffd1a14f5d2d9679170cf6a7 | train | function | def check_managed_changes(
name,
source,
source_hash,
user,
group,
mode,
template,
context,
defaults,
saltenv,
contents=None,
skip_verify=False,
**kwargs):
'''
Return a dictionary of what changes need to be m... | def check_managed_changes(
name,
source,
source_hash,
user,
group,
mode,
template,
context,
defaults,
saltenv,
contents=None,
skip_verify=False,
**kwargs):
| '''
Return a dictionary of what changes need to be made for a file
CLI Example:
.. code-block:: bash
salt '*' file.check_managed_changes /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' jinja True None None base
'''
# If the ... | , val)
for key, val in six.iteritems(changes))
return None, ''.join(comments)
return True, 'The file {0} is in the correct state'.format(name)
def check_managed_changes(
name,
source,
source_hash,
user,
group,
mode,
template,
... | 94 | 94 | 316 | 52 | 42 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | check_managed_changes | check_managed_changes | 3,905 | 3,957 | 3,905 | 3,918 | 7289adbb6e748666ccf3aec9ffb19395c191b7d6 | bigcode/the-stack | train |
f8817939150342a2aa55f295 | train | function | def link(src, path):
'''
.. versionadded:: 2014.1.0
Create a hard link to a file
CLI Example:
.. code-block:: bash
salt '*' file.link /path/to/file /path/to/link
'''
src = os.path.expanduser(src)
if not os.path.isabs(src):
raise SaltInvocationError('File path must be... | def link(src, path):
| '''
.. versionadded:: 2014.1.0
Create a hard link to a file
CLI Example:
.. code-block:: bash
salt '*' file.link /path/to/file /path/to/link
'''
src = os.path.expanduser(src)
if not os.path.isabs(src):
raise SaltInvocationError('File path must be absolute.')
try... | Example:
.. code-block:: bash
salt '*' file.truncate /path/to/file 512
'''
path = os.path.expanduser(path)
with salt.utils.fopen(path, 'rb+') as seek_fh:
seek_fh.truncate(int(length))
def link(src, path):
| 64 | 64 | 130 | 6 | 58 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | link | link | 2,771 | 2,793 | 2,771 | 2,771 | d52db898f54eac6e022eb5b8e63d6a2901c12f9c | bigcode/the-stack | train |
83824209bbf68286c0550e94 | train | function | def open_files(by_pid=False):
'''
Return a list of all physical open files on the system.
CLI Examples:
.. code-block:: bash
salt '*' file.open_files
salt '*' file.open_files by_pid=True
'''
# First we collect valid PIDs
pids = {}
procfs = os.listdir('/proc/')
for ... | def open_files(by_pid=False):
| '''
Return a list of all physical open files on the system.
CLI Examples:
.. code-block:: bash
salt '*' file.open_files
salt '*' file.open_files by_pid=True
'''
# First we collect valid PIDs
pids = {}
procfs = os.listdir('/proc/')
for pfile in procfs:
try:
... | try:
opt = salt.utils.shlex_split(opt)
except AttributeError:
opt = salt.utils.shlex_split(str(opt))
if len(opt) > 1:
salt.utils.warn_until(
'Carbon',
'Additional command line options for file.grep should be '
'p... | 160 | 160 | 535 | 7 | 152 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | open_files | open_files | 5,243 | 5,320 | 5,243 | 5,243 | 9d00b98305d5874ba29a5da9b3066948d4fc672a | bigcode/the-stack | train |
6df2f04a03ac36b43e4d70d5 | train | function | def __clean_tmp(sfn):
'''
Clean out a template temp file
'''
if sfn.startswith(tempfile.gettempdir()):
# Don't remove if it exists in file_roots (any saltenv)
all_roots = itertools.chain.from_iterable(
six.itervalues(__opts__['file_roots']))
in_roots = any(sfn.sta... | def __clean_tmp(sfn):
| '''
Clean out a template temp file
'''
if sfn.startswith(tempfile.gettempdir()):
# Don't remove if it exists in file_roots (any saltenv)
all_roots = itertools.chain.from_iterable(
six.itervalues(__opts__['file_roots']))
in_roots = any(sfn.startswith(root) for root... | Only work on POSIX-like systems
'''
# win_file takes care of windows
if salt.utils.is_windows():
return (False, 'The file execution module cannot be loaded: only available on non-Windows systems - use win_file instead.')
return True
def __clean_tmp(sfn):
| 64 | 64 | 118 | 7 | 56 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | __clean_tmp | __clean_tmp | 83 | 94 | 83 | 83 | 6718bc48cdb5ea4a291b6b9afa4e40df4a1d2616 | bigcode/the-stack | train |
f336a60939de31045410e4b3 | train | function | def seek_read(path, size, offset):
'''
.. versionadded:: 2014.1.0
Seek to a position on a file and read it
path
path to file
seek
amount to read at once
offset
offset to start into the file
CLI Example:
.. code-block:: bash
salt '*' file.seek_read /... | def seek_read(path, size, offset):
| '''
.. versionadded:: 2014.1.0
Seek to a position on a file and read it
path
path to file
seek
amount to read at once
offset
offset to start into the file
CLI Example:
.. code-block:: bash
salt '*' file.seek_read /path/to/file 4096 0
'''
pat... | os.utime(name, times)
except TypeError:
raise SaltInvocationError('atime and mtime must be integers')
except (IOError, OSError) as exc:
raise CommandExecutionError(exc.strerror)
return os.path.exists(name)
def seek_read(path, size, offset):
| 64 | 64 | 162 | 9 | 55 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | seek_read | seek_read | 2,685 | 2,713 | 2,685 | 2,685 | f0fb0a38bf18d3842bf457bcbeba3f8db52c6243 | bigcode/the-stack | train |
cef009b43c77ebe4e754c326 | train | function | def apply_template_on_contents(
contents,
template,
context,
defaults,
saltenv):
'''
Return the contents after applying the templating engine
contents
template string
template
template format
context
Overrides default context variabl... | def apply_template_on_contents(
contents,
template,
context,
defaults,
saltenv):
| '''
Return the contents after applying the templating engine
contents
template string
template
template format
context
Overrides default context variables passed to the template.
defaults
Default context passed to the template.
CLI Example:
.. code-b... | , source_hash)
break
if ret is None:
# None of the list items matched
raise CommandExecutionError(
'none of the specified sources were found'
)
else:
ret = (source, source_hash)
__context__[contextkey] = ret
return ret
... | 89 | 89 | 297 | 23 | 65 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | apply_template_on_contents | apply_template_on_contents | 3,392 | 3,444 | 3,392 | 3,397 | fa787ca3e5c7d747539fb4efdfdfdad45ddd024f | bigcode/the-stack | train |
c7497dfea8b9e749f96f4f4c | train | function | def file_exists(path):
'''
Tests to see if path is a valid file. Returns True/False.
CLI Example:
.. code-block:: bash
salt '*' file.file_exists /etc/passwd
'''
return os.path.isfile(os.path.expanduser(path))
| def file_exists(path):
| '''
Tests to see if path is a valid file. Returns True/False.
CLI Example:
.. code-block:: bash
salt '*' file.file_exists /etc/passwd
'''
return os.path.isfile(os.path.expanduser(path))
| False
def directory_exists(path):
'''
Tests to see if path is a valid directory. Returns True/False.
CLI Example:
.. code-block:: bash
salt '*' file.directory_exists /etc
'''
return os.path.isdir(os.path.expanduser(path))
def file_exists(path):
| 64 | 64 | 59 | 5 | 59 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | file_exists | file_exists | 3,199 | 3,210 | 3,199 | 3,199 | c072f491cf5d769d93bc59cf13a74f09e5b24e64 | bigcode/the-stack | train |
481d8acc9a1c2f2cf6923770 | train | function | def get_managed(
name,
template,
source,
source_hash,
user,
group,
mode,
saltenv,
context,
defaults,
skip_verify,
**kwargs):
'''
Return the managed file data for file.managed
name
location where the file... | def get_managed(
name,
template,
source,
source_hash,
user,
group,
mode,
saltenv,
context,
defaults,
skip_verify,
**kwargs):
| '''
Return the managed file data for file.managed
name
location where the file lives on the server
template
template format
source
managed source file
source_hash
hash of the source file
user
user owner
group
group owner
mode
... | '*' file.apply_template_on_contents \\
contents='This is a {{ template }} string.' \\
template=jinja \\
"context={}" "defaults={'template': 'cool'}" \\
saltenv=base
'''
if template in salt.utils.templates.TEMPLATE_REGISTRY:
context_dict = defaults if defa... | 256 | 256 | 1,412 | 46 | 209 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | get_managed | get_managed | 3,447 | 3,634 | 3,447 | 3,459 | 9593e62beb8b19ddeb79f02da3c93321cddc357a | bigcode/the-stack | train |
4768dae61db82e729f2f632c | train | function | def join(*args):
'''
Return a normalized file system path for the underlying OS
.. versionadded:: 2014.7.0
This can be useful at the CLI but is frequently useful when scripting
combining path variables:
.. code-block:: yaml
{% set www_root = '/var' %}
{% set app_dir = 'myapp'... | def join(*args):
| '''
Return a normalized file system path for the underlying OS
.. versionadded:: 2014.7.0
This can be useful at the CLI but is frequently useful when scripting
combining path variables:
.. code-block:: yaml
{% set www_root = '/var' %}
{% set app_dir = 'myapp' %}
myap... | :: yaml
{%- from salt['file.dirname'](tpldir) + '/vars.jinja' import parent_vars %}
CLI Example:
.. code-block:: bash
salt '*' file.dirname 'test/path/filename.config'
'''
return os.path.dirname(path)
def join(*args):
| 64 | 64 | 151 | 5 | 59 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | join | join | 5,408 | 5,433 | 5,408 | 5,408 | d5797b2252e35e2a2ca16f3501d4f48b93115fbb | bigcode/the-stack | train |
01a1bd27badad1dabaf9761e | train | function | def path_exists_glob(path):
'''
Tests to see if path after expansion is a valid path (file or directory).
Expansion allows usage of ? * and character ranges []. Tilde expansion
is not supported. Returns True/False.
.. versionadded:: Hellium
CLI Example:
.. code-block:: bash
salt ... | def path_exists_glob(path):
| '''
Tests to see if path after expansion is a valid path (file or directory).
Expansion allows usage of ? * and character ranges []. Tilde expansion
is not supported. Returns True/False.
.. versionadded:: Hellium
CLI Example:
.. code-block:: bash
salt '*' file.path_exists_glob /e... | _exists(path):
'''
Tests to see if path is a valid file. Returns True/False.
CLI Example:
.. code-block:: bash
salt '*' file.file_exists /etc/passwd
'''
return os.path.isfile(os.path.expanduser(path))
def path_exists_glob(path):
| 64 | 64 | 102 | 7 | 57 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | path_exists_glob | path_exists_glob | 3,213 | 3,228 | 3,213 | 3,213 | db5d065560b463c9311dcae37622ccb798aae82a | bigcode/the-stack | train |
bee43a6a1f7f91ad1765d2cc | train | function | def delete_backup(path, backup_id):
'''
.. versionadded:: 0.17.0
Delete a previous version of a file that was backed up using Salt's
:doc:`file state backup </ref/states/backup_mode>` system.
path
The path on the minion to check for backups
backup_id
The numeric id for the back... | def delete_backup(path, backup_id):
| '''
.. versionadded:: 0.17.0
Delete a previous version of a file that was backed up using Salt's
:doc:`file state backup </ref/states/backup_mode>` system.
path
The path on the minion to check for backups
backup_id
The numeric id for the backup you wish to delete, as found usin... | = 'Successfully restored {0} to ' \
'{1}'.format(backup['Location'], path)
# Try to set proper ownership
if not salt.utils.is_windows():
try:
fstat = os.stat(path)
except (OSError, IOError):
ret['comment'] += ', but was unable to set ownership'
... | 102 | 102 | 343 | 8 | 93 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | delete_backup | delete_backup | 5,129 | 5,173 | 5,129 | 5,129 | d0404815eb1e79e60d5074ddaab23fb1689deac9 | bigcode/the-stack | train |
88ddb3181232457d53f15352 | train | function | def rename(src, dst):
'''
Rename a file or directory
CLI Example:
.. code-block:: bash
salt '*' file.rename /path/to/src /path/to/dst
'''
src = os.path.expanduser(src)
dst = os.path.expanduser(dst)
if not os.path.isabs(src):
raise SaltInvocationError('File path must b... | def rename(src, dst):
| '''
Rename a file or directory
CLI Example:
.. code-block:: bash
salt '*' file.rename /path/to/src /path/to/dst
'''
src = os.path.expanduser(src)
dst = os.path.expanduser(dst)
if not os.path.isabs(src):
raise SaltInvocationError('File path must be absolute.')
try... | (path):
raise SaltInvocationError('File path must be absolute.')
try:
os.symlink(src, path)
return True
except (OSError, IOError):
raise CommandExecutionError('Could not create \'{0}\''.format(path))
return False
def rename(src, dst):
| 64 | 64 | 134 | 6 | 57 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | rename | rename | 2,837 | 2,860 | 2,837 | 2,837 | f13475d4b6ffb75f62d2bf3e1aeaad6fb6ed43c2 | bigcode/the-stack | train |
e1ed1be939182282cb5cf6bc | train | function | def list_backups(path, limit=None):
'''
.. versionadded:: 0.17.0
Lists the previous versions of a file backed up using Salt's :doc:`file
state backup </ref/states/backup_mode>` system.
path
The path on the minion to check for backups
limit
Limit the number of results to the mos... | def list_backups(path, limit=None):
| '''
.. versionadded:: 0.17.0
Lists the previous versions of a file backed up using Salt's :doc:`file
state backup </ref/states/backup_mode>` system.
path
The path on the minion to check for backups
limit
Limit the number of results to the most recent N backups
CLI Example:... | .nknod /dev/fifo p
'''
ret = False
makedirs_(name, user, group)
if ntype == 'c':
ret = mknod_chrdev(name, major, minor, user, group, mode)
elif ntype == 'b':
ret = mknod_blkdev(name, major, minor, user, group, mode)
elif ntype == 'p':
ret = mknod_fifo(name, user, group, m... | 172 | 172 | 575 | 9 | 162 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | list_backups | list_backups | 4,933 | 5,001 | 4,933 | 4,933 | 82943303a73c8b319e1c446c73ac0da8f135043d | bigcode/the-stack | train |
47f36c6ac074c17046ef3827 | train | function | def get_uid(path, follow_symlinks=True):
'''
Return the id of the user that owns a given file
path
file or directory of which to get the uid
follow_symlinks
indicated if symlinks should be followed
CLI Example:
.. code-block:: bash
salt '*' file.get_uid /etc/passwd
... | def get_uid(path, follow_symlinks=True):
| '''
Return the id of the user that owns a given file
path
file or directory of which to get the uid
follow_symlinks
indicated if symlinks should be followed
CLI Example:
.. code-block:: bash
salt '*' file.get_uid /etc/passwd
.. versionchanged:: 0.16.4
``... | root
'''
if user is None:
user = salt.utils.get_user()
try:
if isinstance(user, int):
return user
return pwd.getpwnam(user).pw_uid
except KeyError:
return ''
def get_uid(path, follow_symlinks=True):
| 63 | 64 | 128 | 11 | 52 | stephane-martin/salt-debian-packaging | salt-2016.3.2/salt/modules/file.py | Python | get_uid | get_uid | 277 | 296 | 277 | 277 | 57b568914cf3a6b50a6cc8e8400889e7886b3a6a | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.