docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Returns a function that checkes whether a number belongs to an interval.
Args:
interval: A tensorboard.hparams.Interval protobuf describing the interval.
Returns:
A function taking a number (a float or an object of a type in
six.integer_types) that returns True if the number belongs to (the closed)
... | def _create_interval_filter(interval):
def filter_fn(value):
if (not isinstance(value, six.integer_types) and
not isinstance(value, float)):
raise error.HParamsError(
'Cannot use an interval filter for a value of type: %s, Value: %s' %
(type(value), value))
return interval... | 58,044 |
Sets the metrics for session_group to those of its "median session".
The median session is the session in session_group with the median value
of the metric given by 'aggregation_metric'. The median is taken over the
subset of sessions in the group whose 'aggregation_metric' was measured
at the largest training... | def _set_median_session_metrics(session_group, aggregation_metric):
measurements = sorted(_measurements(session_group, aggregation_metric),
key=operator.attrgetter('metric_value.value'))
median_session = measurements[(len(measurements) - 1) // 2].session_index
del session_group.metric_v... | 58,047 |
A generator for the values of the metric across the sessions in the group.
Args:
session_group: A SessionGroup protobuffer.
metric_name: A MetricName protobuffer.
Yields:
The next metric value wrapped in a _Measurement instance. | def _measurements(session_group, metric_name):
for session_index, session in enumerate(session_group.sessions):
metric_value = _find_metric_value(session, metric_name)
if not metric_value:
continue
yield _Measurement(metric_value, session_index) | 58,049 |
Constructor.
Args:
context: A backend_context.Context instance.
request: A ListSessionGroupsRequest protobuf. | def __init__(self, context, request):
self._context = context
self._request = request
self._extractors = _create_extractors(request.col_params)
self._filters = _create_filters(request.col_params, self._extractors)
# Since an context.experiment() call may search through all the runs, we
# ca... | 58,050 |
This function converts the MP3 files stored in a folder to WAV. If required, the output names of the WAV files are based on MP3 tags, otherwise the same names are used.
ARGUMENTS:
- dirName: the path of the folder where the MP3s are stored
- Fs: the sampling rate of the generated WAV files
... | def convertDirMP3ToWav(dirName, Fs, nC, useMp3TagsAsName = False):
types = (dirName+os.sep+'*.mp3',) # the tuple of file types
filesToProcess = []
for files in types:
filesToProcess.extend(glob.glob(files))
for f in filesToProcess:
#tag.link(f)
audioFile = eyed3.loa... | 58,086 |
This function converts the WAV files stored in a folder to WAV using a different sampling freq and number of channels.
ARGUMENTS:
- dirName: the path of the folder where the WAVs are stored
- Fs: the sampling rate of the generated WAV files
- nC: the number of channesl of the ge... | def convertFsDirWavToWav(dirName, Fs, nC):
types = (dirName+os.sep+'*.wav',) # the tuple of file types
filesToProcess = []
for files in types:
filesToProcess.extend(glob.glob(files))
newDir = dirName + os.sep + "Fs" + str(Fs) + "_" + "NC"+str(nC)
if os.path.exists(newDir) and ne... | 58,087 |
This function computes the self-similarity matrix for a sequence
of feature vectors.
ARGUMENTS:
- featureVectors: a numpy matrix (nDims x nVectors) whose i-th column
corresponds to the i-th feature vector
RETURNS:
- S: the self-similarity matrix (nV... | def selfSimilarityMatrix(featureVectors):
[nDims, nVectors] = featureVectors.shape
[featureVectors2, MEAN, STD] = aT.normalizeFeatures([featureVectors.T])
featureVectors2 = featureVectors2[0].T
S = 1.0 - distance.squareform(distance.pdist(featureVectors2.T, 'cosine'))
return S | 58,091 |
This function converts segment endpoints and respective segment
labels to fix-sized class labels.
ARGUMENTS:
- seg_start: segment start points (in seconds)
- seg_end: segment endpoints (in seconds)
- seg_label: segment labels
- win_size: fix-sized window (in seconds)
RETURNS... | def segs2flags(seg_start, seg_end, seg_label, win_size):
flags = []
class_names = list(set(seg_label))
curPos = win_size / 2.0
while curPos < seg_end[-1]:
for i in range(len(seg_start)):
if curPos > seg_start[i] and curPos <= seg_end[i]:
break
flags.appen... | 58,093 |
This function reads a segmentation ground truth file, following a simple CSV format with the following columns:
<segment start>,<segment end>,<class label>
ARGUMENTS:
- gt_file: the path of the CSV segment file
RETURNS:
- seg_start: a numpy array of segments' start positions
- seg_... | def readSegmentGT(gt_file):
f = open(gt_file, 'rt')
reader = csv.reader(f, delimiter=',')
seg_start = []
seg_end = []
seg_label = []
for row in reader:
if len(row) == 3:
seg_start.append(float(row[0]))
seg_end.append(float(row[1]))
#if row[2]!="ot... | 58,095 |
This function prints the cluster purity and speaker purity for
each WAV file stored in a provided directory (.SEGMENT files
are needed as ground-truth)
ARGUMENTS:
- folder_name: the full path of the folder where the WAV and
SEGMENT (ground-truth) fi... | def speakerDiarizationEvaluateScript(folder_name, ldas):
types = ('*.wav', )
wavFilesList = []
for files in types:
wavFilesList.extend(glob.glob(os.path.join(folder_name, files)))
wavFilesList = sorted(wavFilesList)
# get number of unique speakers per file (from ground-truth)... | 58,106 |
This function generates a chordial visualization for the recordings of the provided path.
ARGUMENTS:
- folder: path of the folder that contains the WAV files to be processed
- dimReductionMethod: method used to reduce the dimension of the initial feature space before computing the similari... | def visualizeFeaturesFolder(folder, dimReductionMethod, priorKnowledge = "none"):
if dimReductionMethod=="pca":
allMtFeatures, wavFilesList, _ = aF.dirWavFeatureExtraction(folder, 30.0, 30.0, 0.050, 0.050, compute_beat = True)
if allMtFeatures.shape[0]==0:
print("Error: No data foun... | 58,113 |
Computes the spectral flux feature of the current frame
ARGUMENTS:
X: the abs(fft) of the current frame
X_prev: the abs(fft) of the previous frame | def stSpectralFlux(X, X_prev):
# compute the spectral flux as the sum of square distances:
sumX = numpy.sum(X + eps)
sumPrevX = numpy.sum(X_prev + eps)
F = numpy.sum((X / sumX - X_prev/sumPrevX) ** 2)
return F | 58,124 |
Computes the MFCCs of a frame, given the fft mag
ARGUMENTS:
X: fft magnitude abs(FFT)
fbank: filter bank (see mfccInitFilterBanks)
RETURN
ceps: MFCCs (13 element vector)
Note: MFCC calculation is, in general, taken from the
scikits.talkbox library (MI... | def stMFCC(X, fbank, n_mfcc_feats):
mspec = numpy.log10(numpy.dot(X, fbank.T)+eps)
ceps = dct(mspec, type=2, norm='ortho', axis=-1)[:n_mfcc_feats]
return ceps | 58,128 |
Short-term FFT mag for spectogram estimation:
Returns:
a numpy array (nFFT x numOfShortTermWindows)
ARGUMENTS:
signal: the input signal samples
fs: the sampling freq (in Hz)
win: the short-term window size (in samples)
step: the short-term win... | def stChromagram(signal, fs, win, step, PLOT=False):
win = int(win)
step = int(step)
signal = numpy.double(signal)
signal = signal / (2.0 ** 15)
DC = signal.mean()
MAX = (numpy.abs(signal)).max()
signal = (signal - DC) / (MAX - DC)
N = len(signal) # total number of signals
... | 58,131 |
This function extracts an estimate of the beat rate for a musical signal.
ARGUMENTS:
- st_features: a numpy array (n_feats x numOfShortTermWindows)
- win_len: window size in seconds
RETURNS:
- BPM: estimates of beats per minute
- Ratio: a confidence measure | def beatExtraction(st_features, win_len, PLOT=False):
# Features that are related to the beat tracking task:
toWatch = [0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
max_beat_time = int(round(2.0 / win_len))
hist_all = numpy.zeros((max_beat_time,))
for ii, i in enumerate(toWa... | 58,133 |
Short-term FFT mag for spectogram estimation:
Returns:
a numpy array (nFFT x numOfShortTermWindows)
ARGUMENTS:
signal: the input signal samples
fs: the sampling freq (in Hz)
win: the short-term window size (in samples)
step: the short-term win... | def stSpectogram(signal, fs, win, step, PLOT=False):
win = int(win)
step = int(step)
signal = numpy.double(signal)
signal = signal / (2.0 ** 15)
DC = signal.mean()
MAX = (numpy.abs(signal)).max()
signal = (signal - DC) / (MAX - DC)
N = len(signal) # total number of signals
... | 58,134 |
This function extracts the mid-term features of the WAVE files of a particular folder.
The resulting feature vector is extracted by long-term averaging the mid-term features.
Therefore ONE FEATURE VECTOR is extracted for each WAV file.
ARGUMENTS:
- dirName: the path of the WAVE directory
... | def dirWavFeatureExtraction(dirName, mt_win, mt_step, st_win, st_step,
compute_beat=False):
all_mt_feats = numpy.array([])
process_times = []
types = ('*.wav', '*.aif', '*.aiff', '*.mp3', '*.au', '*.ogg')
wav_file_list = []
for files in types:
wav_file_lis... | 58,138 |
This function extracts the mid-term features of the WAVE
files of a particular folder without averaging each file.
ARGUMENTS:
- dirName: the path of the WAVE directory
- mt_win, mt_step: mid-term window and step (in seconds)
- st_win, st_step: short-term window and step (... | def dirWavFeatureExtractionNoAveraging(dirName, mt_win, mt_step, st_win, st_step):
all_mt_feats = numpy.array([])
signal_idx = numpy.array([])
process_times = []
types = ('*.wav', '*.aif', '*.aiff', '*.ogg')
wav_file_list = []
for files in types:
wav_file_list.extend(glob.glob(os... | 58,140 |
Tokenizes a piece of text into its word pieces.
This uses a greedy longest-match-first algorithm to perform tokenization
using the given vocabulary.
For example:
input = "unaffable"
output = ["un", "##aff", "##able"]
Args:
text: A single token or whitespa... | def _tokenize_wordpiece(self, text):
output_tokens = []
for token in self.basic_tokenizer._whitespace_tokenize(text):
chars = list(token)
if len(chars) > self.max_input_chars_per_word:
output_tokens.append(self.vocab.unknown_token)
contin... | 60,621 |
Take an IP string/int and return an object of the correct type.
Args:
address: A string or integer, the IP address. Either IPv4 or
IPv6 addresses may be supplied; integers less than 2**32 will
be considered to be IPv4 by default.
Returns:
An IPv4Address or IPv6Address obje... | def ip_address(address):
try:
return IPv4Address(address)
except (AddressValueError, NetmaskValueError):
pass
try:
return IPv6Address(address)
except (AddressValueError, NetmaskValueError):
pass
raise ValueError('%r does not appear to be an IPv4 or IPv6 address... | 61,572 |
Take an IP string/int and return an object of the correct type.
Args:
address: A string or integer, the IP network. Either IPv4 or
IPv6 networks may be supplied; integers less than 2**32 will
be considered to be IPv4 by default.
Returns:
An IPv4Network or IPv6Network objec... | def ip_network(address, strict=True):
try:
return IPv4Network(address, strict)
except (AddressValueError, NetmaskValueError):
pass
try:
return IPv6Network(address, strict)
except (AddressValueError, NetmaskValueError):
pass
raise ValueError('%r does not appear ... | 61,573 |
Count the number of zero bits on the right hand side.
Args:
number: an integer.
bits: maximum number of bits to count.
Returns:
The number of zero bits on the right hand side of the number. | def _count_righthand_zero_bits(number, bits):
if number == 0:
return bits
for i in range(bits):
if (number >> i) & 1:
return i
# All bits of interest were zero, even if there are more in the number
return bits | 61,575 |
Collapse a list of IP objects.
Example:
collapse_addresses([IPv4Network('192.0.2.0/25'),
IPv4Network('192.0.2.128/25')]) ->
[IPv4Network('192.0.2.0/24')]
Args:
addresses: An iterator of IPv4Network or IPv6Network objects.
Returns:
... | def collapse_addresses(addresses):
i = 0
addrs = []
ips = []
nets = []
# split IP addresses and networks
for ip in addresses:
if isinstance(ip, _BaseAddress):
if ips and ips[-1]._version != ip._version:
raise TypeError("%s and %s are not of the same vers... | 61,577 |
Return prefix length from the bitwise netmask.
Args:
ip_int: An integer, the netmask in expanded bitwise format
Returns:
An integer, the prefix length.
Raises:
ValueError: If the input intermingles zeroes & ones | def _prefix_from_ip_int(self, ip_int):
trailing_zeroes = _count_righthand_zero_bits(ip_int,
self._max_prefixlen)
prefixlen = self._max_prefixlen - trailing_zeroes
leading_ones = ip_int >> trailing_zeroes
all_ones = (1 << prefi... | 61,578 |
Return prefix length from a numeric string
Args:
prefixlen_str: The string to be converted
Returns:
An integer, the prefix length.
Raises:
NetmaskValueError: If the input is not a valid netmask | def _prefix_from_prefix_string(self, prefixlen_str):
# int allows a leading +/- as well as surrounding whitespace,
# so we ensure that isn't the case
if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str):
self._report_invalid_netmask(prefixlen_str)
try:
... | 61,579 |
Turn a netmask/hostmask string into a prefix length
Args:
ip_str: The netmask/hostmask to be converted
Returns:
An integer, the prefix length.
Raises:
NetmaskValueError: If the input is not a valid netmask/hostmask | def _prefix_from_ip_string(self, ip_str):
# Parse the netmask/hostmask like an IP address.
try:
ip_int = self._ip_int_from_string(ip_str)
except AddressValueError:
self._report_invalid_netmask(ip_str)
# Try matching a netmask (this would be /1*0*/ as a b... | 61,580 |
Turn the given IP string into an integer for comparison.
Args:
ip_str: A string, the IP ip_str.
Returns:
The IP ip_str as an integer.
Raises:
AddressValueError: if ip_str isn't a valid IPv4 Address. | def _ip_int_from_string(self, ip_str):
if not ip_str:
raise AddressValueError('Address cannot be empty')
octets = ip_str.split('.')
if len(octets) != 4:
raise AddressValueError("Expected 4 octets in %r" % ip_str)
try:
return _int_from_bytes(... | 61,586 |
Convert a decimal octet into an integer.
Args:
octet_str: A string, the number to parse.
Returns:
The octet as an integer.
Raises:
ValueError: if the octet isn't strictly a decimal from [0..255]. | def _parse_octet(self, octet_str):
if not octet_str:
raise ValueError("Empty octet not permitted")
# Whitelist the characters, since int() allows a lot of bizarre stuff.
if not self._DECIMAL_DIGITS.issuperset(octet_str):
msg = "Only decimal digits permitted in %r... | 61,587 |
Verify that the netmask is valid.
Args:
netmask: A string, either a prefix or dotted decimal
netmask.
Returns:
A boolean, True if the prefix represents a valid IPv4
netmask. | def _is_valid_netmask(self, netmask):
mask = netmask.split('.')
if len(mask) == 4:
try:
for x in mask:
if int(x) not in self._valid_mask_octets:
return False
except ValueError:
# Found something ... | 61,588 |
Expand a shortened IPv6 address.
Args:
ip_str: A string, the IPv6 address.
Returns:
A string, the expanded IPv6 address. | def _explode_shorthand_ip_string(self):
if isinstance(self, IPv6Network):
ip_str = str(self.network_address)
elif isinstance(self, IPv6Interface):
ip_str = str(self.ip)
else:
ip_str = str(self)
ip_int = self._ip_int_from_string(ip_str)
... | 61,592 |
Find a device in Zenoss. If device not found, returns None.
Parameters:
device: (Optional) Will use the grain 'fqdn' by default
CLI Example:
salt '*' zenoss.find_device | def find_device(device=None):
data = [{'uid': '/zport/dmd/Devices', 'params': {}, 'limit': None}]
all_devices = _router_request('DeviceRouter', 'getDevices', data=data)
for dev in all_devices['devices']:
if dev['name'] == device:
# We need to save the has for later operations
... | 61,746 |
A function to set the prod_state in zenoss.
Parameters:
prod_state: (Required) Integer value of the state
device: (Optional) Will use the grain 'fqdn' by default.
CLI Example:
salt zenoss.set_prod_state 1000 hostname | def set_prod_state(prod_state, device=None):
if not device:
device = __salt__['grains.get']('fqdn')
device_object = find_device(device)
if not device_object:
return "Unable to find a device in Zenoss for {0}".format(device)
log.info('Setting prodState to %d on %s device', prod_s... | 61,748 |
Filters file path against unwanted directories and decides whether file is marked as deleted.
Returns:
True if file is desired deleted file, else False.
Args:
path: A string - path to file | def _valid_deleted_file(path):
ret = False
if path.endswith(' (deleted)'):
ret = True
if re.compile(r"\(path inode=[0-9]+\)$").search(path):
ret = True
regex = re.compile("|".join(LIST_DIRS))
if regex.match(path):
ret = False
return ret | 61,749 |
Ensure an update is installed on the minion
Args:
name(str):
Name of the Windows KB ("KB123456")
source (str):
Source of .msu file corresponding to the KB
Example:
.. code-block:: yaml
KB123456:
wusa.installed:
- source: salt://kb12... | def installed(name, source):
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
# Input validation
if not name:
raise SaltInvocationError('Must specify a KB "name"')
if not source:
raise SaltInvocationError('Must specify a "source" ... | 61,842 |
Ensure an update is uninstalled from the minion
Args:
name(str):
Name of the Windows KB ("KB123456")
Example:
.. code-block:: yaml
KB123456:
wusa.uninstalled | def uninstalled(name):
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
# Is the KB already uninstalled
if not __salt__['wusa.is_installed'](name):
ret['result'] = True
ret['comment'] = '{0} already uninstalled'.format(name)
r... | 61,843 |
Create the salt proxy file and start the proxy process
if required
Parameters:
proxyname:
Name to be used for this proxy (should match entries in pillar)
start:
Boolean indicating if the process should be started
default = True
CLI Example:
.. code-... | def configure_proxy(proxyname, start=True):
changes_new = []
changes_old = []
status_file = True
test = __opts__['test']
# write the proxy file if necessary
proxyfile = '/etc/salt/proxy'
status_file, msg_new, msg_old = _proxy_conf_file(proxyfile, test)
changes_new.extend(msg_new)
... | 62,004 |
Ensure that the named package is not installed.
Args:
name (str): The flatpak package.
Returns:
dict: The ``result`` and ``output``.
Example:
.. code-block:: yaml
uninstall_package:
flatpack.uninstalled:
- name: gimp | def uninstalled(name):
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
old = __salt__['flatpak.is_installed'](name)
if not old:
ret['comment'] = 'Package {0} is not installed'.format(name)
ret['result'] = True
return ret
e... | 62,457 |
Adds a new location to install flatpak packages from.
Args:
name (str): The repository's name.
location (str): The location of the repository.
Returns:
dict: The ``result`` and ``output``.
Example:
.. code-block:: yaml
add_flathub:
flatpack.add_remote:
... | def add_remote(name, location):
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
old = __salt__['flatpak.is_remote_added'](name)
if not old:
if __opts__['test']:
ret['comment'] = 'Remote "{0}" would have been added'.format(name)
... | 62,458 |
Set an effect to the lamp.
Arguments:
* **value**: 0~255 brightness of the lamp.
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
* **transition**: Transition 0~200. Default 0.
CLI Example:
.. code-block:: bash
salt '*' hue.brightness... | def call_brightness(*args, **kwargs):
res = dict()
if 'value' not in kwargs:
raise CommandExecutionError("Parameter 'value' is missing")
try:
brightness = max(min(int(kwargs['value']), 244), 1)
except Exception as err:
raise CommandExecutionError("Parameter 'value' does no... | 62,477 |
Set the mired color temperature. More: http://en.wikipedia.org/wiki/Mired
Arguments:
* **value**: 150~500.
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
CLI Example:
.. code-block:: bash
salt '*' hue.temperature value=150
salt ... | def call_temperature(*args, **kwargs):
res = dict()
if 'value' not in kwargs:
raise CommandExecutionError("Parameter 'value' (150~500) is missing")
try:
value = max(min(int(kwargs['value']), 500), 150)
except Exception as err:
raise CommandExecutionError("Parameter 'value' ... | 62,478 |
Sets the timezone using the tzutil.
Args:
timezone (str): A valid timezone
Returns:
bool: ``True`` if successful, otherwise ``False``
Raises:
CommandExecutionError: If invalid timezone is passed
CLI Example:
.. code-block:: bash
salt '*' timezone.set_zone 'Ameri... | def set_zone(timezone):
# if it's one of the key's just use it
if timezone.lower() in mapper.win_to_unix:
win_zone = timezone
elif timezone.lower() in mapper.unix_to_win:
# if it's one of the values, use the key
win_zone = mapper.get_win(timezone)
else:
# Raise err... | 63,586 |
Compares the given timezone with the machine timezone. Mostly useful for
running state checks.
Args:
timezone (str):
The timezone to compare. This can be in Windows or Unix format. Can
be any of the values returned by the ``timezone.list`` function
Returns:
bool: ``... | def zone_compare(timezone):
# if it's one of the key's just use it
if timezone.lower() in mapper.win_to_unix:
check_zone = timezone
elif timezone.lower() in mapper.unix_to_win:
# if it's one of the values, use the key
check_zone = mapper.get_win(timezone)
else:
# R... | 63,587 |
Set the Windows computer name
Args:
name (str):
The new name to give the computer. Requires a reboot to take effect.
Returns:
dict:
Returns a dictionary containing the old and new names if successful.
``False`` if not.
CLI Example:
.. code-block::... | def set_computer_name(name):
if six.PY2:
name = _to_unicode(name)
if windll.kernel32.SetComputerNameExW(
win32con.ComputerNamePhysicalDnsHostname, name):
ret = {'Computer Name': {'Current': get_computer_name()}}
pending = get_pending_computer_name()
if pending n... | 63,934 |
Set the Windows computer description
Args:
desc (str):
The computer description
Returns:
str: Description if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
salt 'minion-id' system.set_computer_desc 'This computer belongs to Dave!' | def set_computer_desc(desc=None):
if six.PY2:
desc = _to_unicode(desc)
# Make sure the system exists
# Return an object containing current information array for the computer
system_info = win32net.NetServerGetInfo(None, 101)
# If desc is passed, decode it for unicode
if desc is No... | 63,936 |
Set the hostname of the windows minion, requires a restart before this will
be updated.
.. versionadded:: 2016.3.0
Args:
hostname (str): The hostname to set
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
salt 'minion-id'... | def set_hostname(hostname):
with salt.utils.winapi.Com():
conn = wmi.WMI()
comp = conn.Win32_ComputerSystem()[0]
return comp.Rename(Name=hostname) | 63,938 |
A helper function that attempts to parse the input time_str as a date.
Args:
time_str (str): A string representing the time
fmts (list): A list of date format strings
Returns:
datetime: Returns a datetime object if parsed properly, otherwise None | def _try_parse_datetime(time_str, fmts):
result = None
for fmt in fmts:
try:
result = datetime.strptime(time_str, fmt)
break
except ValueError:
pass
return result | 63,944 |
Set the Windows system date. Use <mm-dd-yy> format for the date.
Args:
newdate (str):
The date to set. Can be any of the following formats
- YYYY-MM-DD
- MM-DD-YYYY
- MM-DD-YY
- MM/DD/YYYY
- MM/DD/YY
- YYYY/MM/DD
Retu... | def set_system_date(newdate):
fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y',
'%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d']
# Get date/time object from newdate
dt_obj = _try_parse_datetime(newdate, fmts)
if dt_obj is None:
return False
# Set time using set_system_date_time()
return s... | 63,947 |
Ensures that the named bridge exists, eventually creates it.
Args:
name: The name of the bridge.
parent: The name of the parent bridge (if the bridge shall be created
as a fake bridge). If specified, vlan must also be specified.
vlan: The VLAN ID of the bridge (if the bridge sha... | def present(name, parent=None, vlan=None):
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
# Comment and change messages
comment_bridge_created = 'Bridge {0} created.'.format(name)
comment_bridge_notcreated = 'Unable to create bridge: {0}.'.format(name)
comment_bridge_exist... | 63,963 |
Ensures that the named bridge does not exist, eventually deletes it.
Args:
name: The name of the bridge. | def absent(name):
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
# Comment and change messages
comment_bridge_deleted = 'Bridge {0} deleted.'.format(name)
comment_bridge_notdeleted = 'Unable to delete bridge: {0}.'.format(name)
comment_bridge_notexists = 'Bridge {0} does ... | 63,964 |
Internal function for running commands. Used by the uninstall function.
Args:
cmd (str, list): The command to run
Returns:
str: The stdout of the command | def _run(self, cmd):
if isinstance(cmd, six.string_types):
cmd = salt.utils.args.shlex_split(cmd)
try:
log.debug(cmd)
p = subprocess.Popen(
cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subpr... | 66,018 |
Get the Security ID for the user
Args:
username (str): The user name for which to look up the SID
Returns:
str: The user SID
CLI Example:
.. code-block:: bash
salt '*' user.getUserSid jsnuffy | def getUserSid(username):
if six.PY2:
username = _to_unicode(username)
domain = win32api.GetComputerName()
if username.find('\\') != -1:
domain = username.split('\\')[0]
username = username.split('\\')[-1]
domain = domain.upper()
return win32security.ConvertSidToStringS... | 66,060 |
Add user to a group
Args:
name (str): The user name to add to the group
group (str): The name of the group to which to add the user
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' user.addgroup jsnuffy 'Power Users' | def addgroup(name, group):
if six.PY2:
name = _to_unicode(name)
group = _to_unicode(group)
name = _cmd_quote(name)
group = _cmd_quote(group).lstrip('\'').rstrip('\'')
user = info(name)
if not user:
return False
if group in user['groups']:
return True
c... | 66,061 |
Change the home directory of the user, pass True for persist to move files
to the new home directory if the old home directory exist.
Args:
name (str): The name of the user whose home directory you wish to change
home (str): The new location of the home directory
Returns:
bool: Tr... | def chhome(name, home, **kwargs):
if six.PY2:
name = _to_unicode(name)
home = _to_unicode(home)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
persist = kwargs.pop('persist', False)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if persist:
log.info('Ignorin... | 66,062 |
In case net user doesn't return the userprofile we can get it from the
registry
Args:
user (str): The user name, used in debug message
sid (str): The sid to lookup in the registry
Returns:
str: Profile directory | def _get_userprofile_from_registry(user, sid):
profile_dir = __utils__['reg.read_value'](
'HKEY_LOCAL_MACHINE',
'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\{0}'.format(sid),
'ProfileImagePath'
)['vdata']
log.debug(
'user %s with sid=%s profile is locat... | 66,065 |
Return a list of groups the named user belongs to
Args:
name (str): The user name for which to list groups
Returns:
list: A list of groups to which the user belongs
CLI Example:
.. code-block:: bash
salt '*' user.list_groups foo | def list_groups(name):
if six.PY2:
name = _to_unicode(name)
ugrp = set()
try:
user = info(name)['groups']
except KeyError:
return False
for group in user:
ugrp.add(group.strip(' *'))
return sorted(list(ugrp)) | 66,066 |
Return the list of all info for all users
Args:
refresh (bool, optional): Refresh the cached user information. Useful
when used from within a state function. Default is False.
Returns:
dict: A dictionary containing information about all users on the system
CLI Example:
..... | def getent(refresh=False):
if 'user.getent' in __context__ and not refresh:
return __context__['user.getent']
ret = []
for user in __salt__['user.list_users']():
stuff = {}
user_info = __salt__['user.info'](user)
stuff['gid'] = ''
stuff['groups'] = user_info['g... | 66,067 |
Change the username for a named user
Args:
name (str): The user name to change
new_name (str): The new name for the current user
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' user.rename jsnuffy jshmoe | def rename(name, new_name):
if six.PY2:
name = _to_unicode(name)
new_name = _to_unicode(new_name)
# Load information for the current name
current_info = info(name)
if not current_info:
raise CommandExecutionError('User \'{0}\' does not exist'.format(name))
# Look for a... | 66,069 |
Internal function for obfuscating the password used for AutoLogin
This is later written as the contents of the ``/etc/kcpassword`` file
.. versionadded:: 2017.7.3
Adapted from:
https://github.com/timsutton/osx-vm-templates/blob/master/scripts/support/set_kcpassword.py
Args:
password(str)... | def _kcpassword(password):
# The magic 11 bytes - these are just repeated
# 0x7D 0x89 0x52 0x23 0xD2 0xBC 0xDD 0xEA 0xA3 0xB9 0x1F
key = [125, 137, 82, 35, 210, 188, 221, 234, 163, 185, 31]
key_len = len(key)
# Convert each character to a byte
password = list(map(ord, password))
# pad... | 66,160 |
.. versionadded:: 2016.3.0
Configures the machine to auto login with the specified user
Args:
name (str): The user account use for auto login
password (str): The password to user for auto login
.. versionadded:: 2017.7.3
Returns:
bool: ``True`` if successful, otherw... | def enable_auto_login(name, password):
# Make the entry into the defaults file
cmd = ['defaults',
'write',
'/Library/Preferences/com.apple.loginwindow.plist',
'autoLoginUser',
name]
__salt__['cmd.run'](cmd)
current = get_auto_login()
# Create/Update ... | 66,161 |
Get the ACL of an object. Will filter by user if one is provided.
Args:
path: The path to the object
objectType: The type of object (FILE, DIRECTORY, REGISTRY)
user: A user name to filter by
Returns (dict): A dictionary containing the ACL
CLI Example:
.. code-block:: bash
... | def get(path, objectType, user=None):
ret = {'Path': path,
'ACLs': []}
sidRet = _getUserSid(user)
if path and objectType:
dc = daclConstants()
objectTypeBit = dc.getObjectTypeBit(objectType)
path = dc.processPath(path, objectTypeBit)
tdacl = _get_dacl(path, ... | 66,451 |
helper function to set the inheritance
Args:
path (str): The path to the object
objectType (str): The type of object
inheritance (bool): True enables inheritance, False disables
copy (bool): Copy inherited ACEs to the DACL before disabling
inheritance
clear (bool... | def _set_dacl_inheritance(path, objectType, inheritance=True, copy=True, clear=False):
ret = {'result': False,
'comment': '',
'changes': {}}
if path:
try:
sd = win32security.GetNamedSecurityInfo(path, objectType, win32security.DACL_SECURITY_INFORMATION)
... | 66,455 |
enable/disable inheritance on an object
Args:
path: The path to the object
objectType: The type of object (FILE, DIRECTORY, REGISTRY)
clear: True will remove non-Inherited ACEs from the ACL
Returns (dict): A dictionary containing the results
CLI Example:
.. code-block:: bash
... | def enable_inheritance(path, objectType, clear=False):
dc = daclConstants()
objectType = dc.getObjectTypeBit(objectType)
path = dc.processPath(path, objectType)
return _set_dacl_inheritance(path, objectType, True, None, clear) | 66,456 |
Disable inheritance on an object
Args:
path: The path to the object
objectType: The type of object (FILE, DIRECTORY, REGISTRY)
copy: True will copy the Inherited ACEs to the DACL before disabling inheritance
Returns (dict): A dictionary containing the results
CLI Example:
.. ... | def disable_inheritance(path, objectType, copy=True):
dc = daclConstants()
objectType = dc.getObjectTypeBit(objectType)
path = dc.processPath(path, objectType)
return _set_dacl_inheritance(path, objectType, False, copy, None) | 66,457 |
Check a specified path to verify if inheritance is enabled
Args:
path: path of the registry key or file system object to check
objectType: The type of object (FILE, DIRECTORY, REGISTRY)
user: if provided, will consider only the ACEs for that user
Returns (bool): 'Inheritance' of True/F... | def check_inheritance(path, objectType, user=None):
ret = {'result': False,
'Inheritance': False,
'comment': ''}
sidRet = _getUserSid(user)
dc = daclConstants()
objectType = dc.getObjectTypeBit(objectType)
path = dc.processPath(path, objectType)
try:
sd = w... | 66,458 |
Gets the difference between the candidate and the current configuration.
.. code-block:: yaml
get the diff:
junos:
- diff
- id: 10
Parameters:
Optional
* id:
The rollback id value [0-49]. (default = 0) | def diff(name, **kwargs):
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.diff'](**kwargs)
return ret | 66,922 |
Shuts down the device.
.. code-block:: yaml
shut the device:
junos:
- shutdown
- in_min: 10
Parameters:
Optional
* kwargs:
* reboot:
Whether to reboot instead of shutdown. (default=False)
* at:
... | def shutdown(name, **kwargs):
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.shutdown'](**kwargs)
return ret | 66,924 |
Copies the file from the local device to the junos device.
.. code-block:: yaml
/home/m2/info.txt:
junos:
- file_copy
- dest: info_copy.txt
Parameters:
Required
* src:
The sorce path where the file is kept.
* dest:
... | def file_copy(name, dest=None, **kwargs):
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.file_copy'](name, dest, **kwargs)
return ret | 66,927 |
List details of available certificates in the LocalMachine certificate
store.
Args:
certificate_store (str): The name of the certificate store on the local
machine.
Returns:
dict: A dictionary of certificates found in the store | def _list_certs(certificate_store='My'):
ret = dict()
blacklist_keys = ['DnsNameList', 'Thumbprint']
ps_cmd = ['Get-ChildItem',
'-Path', r"'Cert:\LocalMachine\{0}'".format(certificate_store),
'|',
'Select-Object DnsNameList, SerialNumber, Subject, Thumbprint, ... | 67,004 |
Execute a powershell command from the WebAdministration PS module.
Args:
cmd (list): The command to execute in a list
return_json (bool): True formats the return in JSON, False just returns
the output of the command.
Returns:
str: The output from the command | def _srvmgr(cmd, return_json=False):
if isinstance(cmd, list):
cmd = ' '.join(cmd)
if return_json:
cmd = 'ConvertTo-Json -Compress -Depth 4 -InputObject @({0})' \
''.format(cmd)
cmd = 'Import-Module WebAdministration; {0}'.format(cmd)
ret = __salt__['cmd.run_all'](c... | 67,006 |
Delete a website from IIS.
Args:
name (str): The IIS site name.
Returns:
bool: True if successful, otherwise False
.. note::
This will not remove the application pool used by the site.
CLI Example:
.. code-block:: bash
salt '*' win_iis.remove_site name='My Test... | def remove_site(name):
current_sites = list_sites()
if name not in current_sites:
log.debug('Site already absent: %s', name)
return True
ps_cmd = ['Remove-WebSite', '-Name', r"'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to... | 67,012 |
Stop a Web Site in IIS.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the website to stop.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.stop_site name='My Test Site' | def stop_site(name):
ps_cmd = ['Stop-WebSite', r"'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
return cmd_ret['retcode'] == 0 | 67,013 |
Start a Web Site in IIS.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the website to start.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.start_site name='My Test Site' | def start_site(name):
ps_cmd = ['Start-WebSite', r"'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
return cmd_ret['retcode'] == 0 | 67,014 |
Get all configured IIS bindings for the specified site.
Args:
site (str): The name if the IIS Site
Returns:
dict: A dictionary of the binding names and properties.
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_bindings site | def list_bindings(site):
ret = dict()
sites = list_sites()
if site not in sites:
log.warning('Site not found: %s', site)
return ret
ret = sites[site]['bindings']
if not ret:
log.warning('No bindings found for site: %s', site)
return ret | 67,015 |
Remove an IIS binding.
Args:
site (str): The IIS site name.
hostheader (str): The host header of the binding.
ipaddress (str): The IP address of the binding.
port (int): The TCP port of the binding.
Returns:
bool: True if successful, otherwise False
CLI Example:
... | def remove_binding(site, hostheader='', ipaddress='*', port=80):
name = _get_binding_info(hostheader, ipaddress, port)
current_bindings = list_bindings(site)
if name not in current_bindings:
log.debug('Binding already absent: %s', name)
return True
ps_cmd = ['Remove-WebBinding',
... | 67,018 |
List certificate bindings for an IIS site.
.. versionadded:: 2016.11.0
Args:
site (str): The IIS site name.
Returns:
dict: A dictionary of the binding names and properties.
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_bindings site | def list_cert_bindings(site):
ret = dict()
sites = list_sites()
if site not in sites:
log.warning('Site not found: %s', site)
return ret
for binding in sites[site]['bindings']:
if sites[site]['bindings'][binding]['certificatehash']:
ret[binding] = sites[site]['... | 67,019 |
Stop an IIS application pool.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the App Pool to stop.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.stop_apppool name='MyTestPool' | def stop_apppool(name):
ps_cmd = ['Stop-WebAppPool', r"'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
return cmd_ret['retcode'] == 0 | 67,024 |
Start an IIS application pool.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the App Pool to start.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.start_apppool name='MyTestPool' | def start_apppool(name):
ps_cmd = ['Start-WebAppPool', r"'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
return cmd_ret['retcode'] == 0 | 67,025 |
Restart an IIS application pool.
.. versionadded:: 2016.11.0
Args:
name (str): The name of the IIS application pool.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.restart_apppool name='MyTestPool' | def restart_apppool(name):
ps_cmd = ['Restart-WebAppPool', r"'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
return cmd_ret['retcode'] == 0 | 67,026 |
Get all configured IIS applications for the specified site.
Args:
site (str): The IIS site name.
Returns: A dictionary of the application names and properties.
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_apps site | def list_apps(site):
ret = dict()
ps_cmd = list()
ps_cmd.append("Get-WebApplication -Site '{0}'".format(site))
ps_cmd.append(r"| Select-Object applicationPool, path, PhysicalPath, preloadEnabled,")
ps_cmd.append(r"@{ Name='name'; Expression={ $_.path.Split('/', 2)[-1] } },")
ps_cmd.append(r... | 67,029 |
Remove an IIS application.
Args:
name (str): The application name.
site (str): The IIS site name.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.remove_app name='app0' site='site0' | def remove_app(name, site):
current_apps = list_apps(site)
if name not in current_apps:
log.debug('Application already absent: %s', name)
return True
ps_cmd = ['Remove-WebApplication',
'-Name', "'{0}'".format(name),
'-Site', "'{0}'".format(site)]
cmd_r... | 67,031 |
Get all configured IIS virtual directories for the specified site, or for
the combination of site and application.
Args:
site (str): The IIS site name.
app (str): The IIS application.
Returns:
dict: A dictionary of the virtual directory names and properties.
CLI Example:
... | def list_vdirs(site, app=_DEFAULT_APP):
ret = dict()
ps_cmd = ['Get-WebVirtualDirectory',
'-Site', r"'{0}'".format(site),
'-Application', r"'{0}'".format(app),
'|', "Select-Object PhysicalPath, @{ Name = 'name';",
r"Expression = { $_.path.Split('/')[... | 67,032 |
Remove an IIS virtual directory.
Args:
name (str): The virtual directory name.
site (str): The IIS site name.
app (str): The IIS application.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.remove_vdir nam... | def remove_vdir(name, site, app=_DEFAULT_APP):
current_vdirs = list_vdirs(site, app)
app_path = os.path.join(*app.rstrip('/').split('/'))
if app_path:
app_path = '{0}\\'.format(app_path)
vdir_path = r'IIS:\Sites\{0}\{1}{2}'.format(site, app_path, name)
if name not in current_vdirs:
... | 67,034 |
r'''
Backup an IIS Configuration on the System.
.. versionadded:: 2017.7.0
.. note::
Backups are stored in the ``$env:Windir\System32\inetsrv\backup``
folder.
Args:
name (str): The name to give the backup
Returns:
bool: True if successful, otherwise False
CLI... | def create_backup(name):
r
if name in list_backups():
raise CommandExecutionError('Backup already present: {0}'.format(name))
ps_cmd = ['Backup-WebConfiguration',
'-Name', "'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to ba... | 67,035 |
Remove an IIS Configuration backup from the System.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the backup to remove
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.remove_backup backup_20170209 | def remove_backup(name):
if name not in list_backups():
log.debug('Backup already removed: %s', name)
return True
ps_cmd = ['Remove-WebConfigurationBackup',
'-Name', "'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to... | 67,036 |
Returns a list of worker processes that correspond to the passed
application pool.
.. versionadded:: 2017.7.0
Args:
apppool (str): The application pool to query
Returns:
dict: A dictionary of worker processes with their process IDs
CLI Example:
.. code-block:: bash
... | def list_worker_processes(apppool):
ps_cmd = ['Get-ChildItem',
r"'IIS:\AppPools\{0}\WorkerProcesses'".format(apppool)]
cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True)
try:
items = salt.utils.json.loads(cmd_ret['stdout'], strict=False)
except ValueError:
raise Command... | 67,037 |
Helper function for adding new IDE controllers
.. versionadded:: 2016.3.0
Args:
ide_controller_label: label of the IDE controller
controller_key: if not None, the controller key to use; otherwise it is randomly generated
bus_number: bus number
Returns: created device spec for an IDE con... | def _add_new_ide_controller_helper(ide_controller_label,
controller_key,
bus_number):
if controller_key is None:
controller_key = randint(-200, 250)
ide_spec = vim.vm.device.VirtualDeviceSpec()
ide_spec.device = vim.vm.devic... | 67,056 |
Check if the package is valid on the given mirrors.
Args:
package: The name of the package
cyg_arch: The cygwin architecture
mirrors: any mirrors to check
Returns (bool): True if Valid, otherwise False
CLI Example:
.. code-block:: bash
salt '*' cyg.check_valid_packag... | def check_valid_package(package,
cyg_arch='x86_64',
mirrors=None):
if mirrors is None:
mirrors = [{DEFAULT_MIRROR: DEFAULT_MIRROR_KEY}]
LOG.debug('Checking Valid Mirrors: %s', mirrors)
for mirror in mirrors:
for mirror_url, key in mirror... | 67,632 |
Manage the sending of authentication traps.
Args:
status (bool): True to enable traps. False to disable.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_snmp.set_auth_traps_enabled status='True' | def set_auth_traps_enabled(status=True):
vname = 'EnableAuthenticationTraps'
current_status = get_auth_traps_enabled()
if bool(status) == current_status:
_LOG.debug('%s already contains the provided value.', vname)
return True
vdata = int(status)
__utils__['reg.set_value'](_HK... | 67,982 |
This module can also be run directly for testing
Args:
detail|list : Provide ``detail`` or version ``list``.
system|system+user: System installed and System and User installs. | def __main():
if len(sys.argv) < 3:
sys.stderr.write('usage: {0} <detail|list> <system|system+user>\n'.format(sys.argv[0]))
sys.exit(64)
user_pkgs = False
version_only = False
if six.text_type(sys.argv[1]) == 'list':
version_only = True
if six.text_type(sys.argv[2]) == '... | 69,142 |
Squished GUID (SQUID) to GUID.
A SQUID is a Squished/Compressed version of a GUID to use up less space
in the registry.
Args:
squid (str): Squished GUID.
Returns:
str: the GUID if a valid SQUID provided. | def __squid_to_guid(self, squid):
if not squid:
return ''
squid_match = self.__squid_pattern.match(squid)
guid = ''
if squid_match is not None:
guid = '{' +\
squid_match.group(1)[::-1]+'-' +\
squid_match.group(2)[::-1]+'-' ... | 69,144 |
Test for ``1`` as a number or a string and return ``True`` if it is.
Args:
value: string or number or None.
Returns:
bool: ``True`` if 1 otherwise ``False``. | def __one_equals_true(value):
if isinstance(value, six.integer_types) and value == 1:
return True
elif (isinstance(value, six.string_types) and
re.match(r'\d+', value, flags=re.IGNORECASE + re.UNICODE) is not None and
six.text_type(value) == '1'):
... | 69,145 |
Calls RegQueryValueEx
If PY2 ensure unicode string and expand REG_EXPAND_SZ before returning
Remember to catch not found exceptions when calling.
Args:
handle (object): open registry handle.
value_name (str): Name of the value you wished returned
Returns:
... | def __reg_query_value(handle, value_name):
# item_value, item_type = win32api.RegQueryValueEx(self.__reg_uninstall_handle, value_name)
item_value, item_type = win32api.RegQueryValueEx(handle, value_name) # pylint: disable=no-member
if six.PY2 and isinstance(item_value, six.string_types... | 69,146 |
For the uninstall section of the registry return the name value.
Args:
value_name (str): Registry value name.
wanted_type (str):
The type of value wanted if the type does not match
None is return. wanted_type support values are
``str`` ``i... | def get_install_value(self, value_name, wanted_type=None):
try:
item_value, item_type = self.__reg_query_value(self.__reg_uninstall_handle, value_name)
except pywintypes.error as exc: # pylint: disable=no-member
if exc.winerror == winerror.ERROR_FILE_NOT_FOUND:
... | 69,148 |
For the product section of the registry return the name value.
Args:
value_name (str): Registry value name.
wanted_type (str):
The type of value wanted if the type does not match
None is return. wanted_type support values are
``str`` ``int... | def get_product_value(self, value_name, wanted_type=None):
if not self.__reg_products_handle:
return None
subkey, search_value_name = os.path.split(value_name)
try:
if subkey:
handle = win32api.RegOpenKeyEx( # pylint: disable=no-member
... | 69,149 |
Returns information on a package.
Args:
pkg_id (str): Package Id of the software/component
Returns:
dict or list: List if ``version_only`` is ``True`` otherwise dict | def __getitem__(self, pkg_id):
if pkg_id in self.__reg_software:
return self.__reg_software[pkg_id]
else:
raise KeyError(pkg_id) | 69,154 |
Returns information on a package.
Args:
pkg_id (str): Package Id of the software/component.
Returns:
list: List of version numbers installed. | def pkg_version_list(self, pkg_id):
pkg_data = self.__reg_software.get(pkg_id, None)
if not pkg_data:
return []
if isinstance(pkg_data, list):
# raw data is 'pkgid': [sorted version list]
return pkg_data # already sorted oldest to newest
# ... | 69,156 |
Provided with a valid Windows Security Identifier (SID) and returns a Username
Args:
sid (str): Security Identifier (SID).
Returns:
str: Username in the format of username@realm or username@computer. | def __sid_to_username(sid):
if sid is None or sid == '':
return ''
try:
sid_bin = win32security.GetBinarySid(sid) # pylint: disable=no-member
except pywintypes.error as exc: # pylint: disable=no-member
raise ValueError(
'pkg: Sof... | 69,157 |
Convert user name to a uid
Args:
user (str): The user to lookup
Returns:
str: The user id of the user
CLI Example:
.. code-block:: bash
salt '*' file.user_to_uid myusername | def user_to_uid(user):
if user is None:
user = salt.utils.user.get_user()
return salt.utils.win_dacl.get_sid_string(user) | 69,298 |
Return the mode of a file
Right now we're just returning None because Windows' doesn't have a mode
like Linux
Args:
path (str): The path to the file or directory
Returns:
None
CLI Example:
.. code-block:: bash
salt '*' file.get_mode /etc/passwd | def get_mode(path):
if not os.path.exists(path):
raise CommandExecutionError('Path not found: {0}'.format(path))
func_name = '{0}.get_mode'.format(__virtualname__)
if __opts__.get('fun', '') == func_name:
log.info('The function %s should not be used on Windows systems; '
... | 69,301 |
Return a dictionary object with the Windows
file attributes for a file.
Args:
path (str): The path to the file or directory
Returns:
dict: A dictionary of file attributes
CLI Example:
.. code-block:: bash
salt '*' file.get_attributes c:\\temp\\a.txt | def get_attributes(path):
if not os.path.exists(path):
raise CommandExecutionError('Path not found: {0}'.format(path))
# set up dictionary for attribute values
attributes = {}
# Get cumulative int value of attributes
intAttributes = win32file.GetFileAttributes(path)
# Assign indi... | 69,306 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.