language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static void pause(Context context, String clientId) { Intent intent = new Intent(context, PlaybackService.class); intent.setAction(ACTION_PAUSE_PLAYER); intent.putExtra(BUNDLE_KEY_SOUND_CLOUD_CLIENT_ID, clientId); context.startService(intent); }
java
public final Iterable<T> getScheduledTasks() { return Iterables.transform(this.cancellableTaskMap.asMap().values(), new Function<CancellableTask<K, T>, T>() { @Override public T apply(CancellableTask<K, T> cancellableTask) { return cancellableTask.getScheduledTask(); } }); }
python
def info_gain(current_impurity, true_branch, false_branch, criterion): """Information Gain. The uncertainty of the starting node, minus the weighted impurity of two child nodes. """ measure_impurity = gini_impurity if criterion == "gini" else entropy p = float(len(true_branch)) / (len(true_branch) + len(false_branch)) return current_impurity - p * measure_impurity(true_branch) - (1 - p) * measure_impurity(false_branch)
python
def run_process(self, process): """Runs a single action.""" message = u'#{bright}' message += u'{} '.format(str(process)[:68]).ljust(69, '.') stashed = False if self.unstaged_changes and not self.include_unstaged_changes: out, err, code = self.git.stash(keep_index=True, quiet=True) stashed = code == 0 try: result = process(files=self.files, cwd=self.cwd, fix=self.fix) # Check for modified files out, err, code = self.git.status(porcelain=True, untracked_files='no') for line in out.splitlines(): file_status = Status(line) # Make sure the file is one of the files that was processed if file_status.path in self.files and file_status.is_modified: mtime = os.path.getmtime(file_status.path) if os.path.exists(file_status.path) else 0 if mtime > self.file_mtimes.get(file_status.path, 0): self.file_mtimes[file_status.path] = mtime result.add_modified_file(file_status.path) if self.stage_modified_files: self.git.add(file_status.path) except: # noqa: E722 raise finally: if stashed: self.git.reset(hard=True, quiet=True) self.git.stash.pop(index=True, quiet=True) if result.is_success: message += u' #{green}[SUCCESS]' elif result.is_failure: message += u' #{red}[FAILURE]' elif result.is_skip: message += u' #{cyan}[SKIPPED]' elif result.is_error: message += u' #{red}[ERROR!!]' return result, message
python
def get_mode(self): """Gets the mode of the score. If this system is based on grades, the mode of the output score is returned. return: (decimal) - the median score *compliance: mandatory -- This method must be implemented.* """ # http://stackoverflow.com/questions/10797819/finding-the-mode-of-a-list-in-python return max(set(self._entry_scores), key=self._entry_scores.count)
java
private void readProcCpuInfoFile() { // This directory needs to be read only once if (readCpuInfoFile) { return; } // Read "/proc/cpuinfo" file BufferedReader in = null; FileReader fReader = null; try { fReader = new FileReader(procfsCpuFile); in = new BufferedReader(fReader); } catch (FileNotFoundException f) { // shouldn't happen.... return; } Matcher mat = null; try { numProcessors = 0; String str = in.readLine(); while (str != null) { mat = PROCESSOR_FORMAT.matcher(str); if (mat.find()) { numProcessors++; } mat = FREQUENCY_FORMAT.matcher(str); if (mat.find()) { cpuFrequency = (long)(Double.parseDouble(mat.group(1)) * 1000); // kHz } str = in.readLine(); } } catch (IOException io) { LOG.warn("Error reading the stream " + io); } finally { // Close the streams try { fReader.close(); try { in.close(); } catch (IOException i) { LOG.warn("Error closing the stream " + in); } } catch (IOException i) { LOG.warn("Error closing the stream " + fReader); } } readCpuInfoFile = true; }
java
private boolean isNormal() { if (getNameCount() == 0 || (getNameCount() == 1 && !isAbsolute())) { return true; } boolean foundNonParentName = isAbsolute(); // if there's a root, the path doesn't start with .. boolean normal = true; for (Name name : names) { if (name.equals(Name.PARENT)) { if (foundNonParentName) { normal = false; break; } } else { if (name.equals(Name.SELF)) { normal = false; break; } foundNonParentName = true; } } return normal; }
python
def run(self): """Runs the thread This method handles sending the heartbeat to the Discord websocket server, so the connection can remain open and the bot remain online for those commands that require it to be. Args: None """ while self.should_run: try: self.logger.debug('Sending heartbeat, seq ' + last_sequence) self.ws.send(json.dumps({ 'op': 1, 'd': last_sequence })) except Exception as e: self.logger.error(f'Got error in heartbeat: {str(e)}') finally: elapsed = 0.0 while elapsed < self.interval and self.should_run: time.sleep(self.TICK_INTERVAL) elapsed += self.TICK_INTERVAL
python
def iterkeys(self): "Returns an iterator over the keys of ConfigMap." return chain(self._pb.StringMap.keys(), self._pb.IntMap.keys(), self._pb.FloatMap.keys(), self._pb.BoolMap.keys())
python
def _unscramble_regressor_columns(parent_data, data): """Reorder the columns of a confound matrix such that the columns are in the same order as the input data with any expansion columns inserted immediately after the originals. """ matches = ['_power[0-9]+', '_derivative[0-9]+'] var = OrderedDict((c, deque()) for c in parent_data.columns) for c in data.columns: col = c for m in matches: col = re.sub(m, '', col) if col == c: var[col].appendleft(c) else: var[col].append(c) unscrambled = reduce((lambda x, y: x + y), var.values()) return data[[*unscrambled]]
java
@Override public void send(final CEMI frame, final BlockingMode mode) throws KNXConnectionClosedException { if (frame.getMessageCode() != CEMILData.MC_LDATA_IND) throw new KNXIllegalArgumentException("cEMI frame is not an L-Data.ind"); try { if (loopbackEnabled) { synchronized (loopbackFrames) { loopbackFrames.add((CEMILData) frame); } logger.trace("add to multicast loopback frame buffer: {}", frame); } // filter IP system broadcasts and always send them unsecured if (RoutingSystemBroadcast.isSystemBroadcast(frame)) { final byte[] buf = PacketHelper.toPacket(new RoutingSystemBroadcast(frame)); final DatagramPacket p = new DatagramPacket(buf, buf.length, systemBroadcast, DEFAULT_PORT); if (sysBcastSocket != null) sysBcastSocket.send(p); else socket.send(p); } else super.send(frame, NonBlocking); // we always succeed... setState(OK); } catch (final IOException e) { close(CloseEvent.INTERNAL, "communication failure", LogLevel.ERROR, e); throw new KNXConnectionClosedException("connection closed (" + e.getMessage() + ")"); } catch (final KNXTimeoutException ignore) {} catch (final InterruptedException e) { Thread.currentThread().interrupt(); } }
python
def get_monitor_physical_size(monitor): """ Returns the physical size of the monitor. Wrapper for: void glfwGetMonitorPhysicalSize(GLFWmonitor* monitor, int* width, int* height); """ width_value = ctypes.c_int(0) width = ctypes.pointer(width_value) height_value = ctypes.c_int(0) height = ctypes.pointer(height_value) _glfw.glfwGetMonitorPhysicalSize(monitor, width, height) return width_value.value, height_value.value
python
def close(self): """ Deletes this Ethernet switch. """ yield from self._telnet.close() self._telnet_server.close() for nio in self._nios.values(): if nio: yield from nio.close() self.manager.port_manager.release_tcp_port(self._console, self._project) if self._hypervisor: try: yield from self._hypervisor.send('ethsw delete "{}"'.format(self._name)) log.info('Ethernet switch "{name}" [{id}] has been deleted'.format(name=self._name, id=self._id)) except DynamipsError: log.debug("Could not properly delete Ethernet switch {}".format(self._name)) if self._hypervisor and self in self._hypervisor.devices: self._hypervisor.devices.remove(self) if self._hypervisor and not self._hypervisor.devices: yield from self.hypervisor.stop() self._hypervisor = None return True
python
def add_record_references(self, app_id, record_id, field_id, target_record_ids): """Bulk operation to directly add record references without making any additional requests Warnings: Does not perform any app, record, or target app/record validation Args: app_id (str): Full App ID string record_id (str): Full parent Record ID string field_id (str): Full field ID to target reference field on parent Record string target_record_ids (List(str)): List of full target reference Record ID strings """ self._swimlane.request( 'post', 'app/{0}/record/{1}/add-references'.format(app_id, record_id), json={ 'fieldId': field_id, 'targetRecordIds': target_record_ids } )
java
public void addValues(String name, List<V> values) { List<V> lo = get(name); if (lo == null) { lo = new ArrayList<>(); } lo.addAll(values); put(name, lo); }
python
def _parse_port_ranges(pool_str): """Given a 'N-P,X-Y' description of port ranges, return a set of ints.""" ports = set() for range_str in pool_str.split(','): try: a, b = range_str.split('-', 1) start, end = int(a), int(b) except ValueError: log.error('Ignoring unparsable port range %r.', range_str) continue if start < 1 or end > 65535: log.error('Ignoring out of bounds port range %r.', range_str) continue ports.update(set(range(start, end + 1))) return ports
java
public void addAttributeValue(final String attributeName, final Value attributeValue, Environment in) { if (in == null) in = GlobalEnvironment.INSTANCE; Attribute attr = attributes.get(attributeName); if (attr == null) { attr = new Attribute(attributeName); attributes.put(attr.getName(), attr); } attr.addValue(attributeValue, in); Map<String, Object> valueMap = contentMap.get(in); if(valueMap == null) valueMap = new HashMap<>(); valueMap.put(attributeName, attributeValue.getRaw()); contentMap.put(in, valueMap); //TODO check for loops and process such situation if (attributeValue instanceof IncludeValue) externalConfigurations.add(((IncludeValue) attributeValue).getConfigName()); }
python
def _ScanFileSystem(self, scan_node, base_path_specs): """Scans a file system scan node for file systems. This method checks if the file system contains a known Windows directory. Args: scan_node (SourceScanNode): file system scan node. base_path_specs (list[PathSpec]): file system base path specifications. Raises: ScannerError: if the scan node is invalid. """ if not scan_node or not scan_node.path_spec: raise errors.ScannerError('Invalid or missing file system scan node.') file_system = resolver.Resolver.OpenFileSystem(scan_node.path_spec) if not file_system: return try: path_resolver = windows_path_resolver.WindowsPathResolver( file_system, scan_node.path_spec.parent) if self._ScanFileSystemForWindowsDirectory(path_resolver): base_path_specs.append(scan_node.path_spec) finally: file_system.Close()
python
def decipher(self,string): """Decipher string using Bifid cipher according to initialised key. Punctuation and whitespace are removed from the input. Example:: plaintext = Bifid('phqgmeaylnofdxkrcvszwbuti',5).decipher(ciphertext) :param string: The string to decipher. :returns: The deciphered string. """ ret = '' string = string.upper() rowseq,colseq = [],[] # take blocks of length period, reform rowseq,colseq from them for i in range(0,len(string),self.period): tempseq = [] for j in range(0,self.period): if i+j >= len(string): continue tempseq.append(int(self.key.index(string[i + j]) / 5)) tempseq.append(int(self.key.index(string[i + j]) % 5)) rowseq.extend(tempseq[0:int(len(tempseq)/2)]) colseq.extend(tempseq[int(len(tempseq)/2):]) for i in range(len(rowseq)): ret += self.key[rowseq[i]*5 + colseq[i]] return ret
python
def check_npndarray(val, dtype=None, writeable=True, verbose=True): """Check if input object is a numpy array. Parameters ---------- val : np.ndarray Input object """ if not isinstance(val, np.ndarray): raise TypeError('Input is not a numpy array.') if ((not isinstance(dtype, type(None))) and (not np.issubdtype(val.dtype, dtype))): raise TypeError('The numpy array elements are not of type: {}' ''.format(dtype)) if not writeable and verbose and val.flags.writeable: warn('Making input data immutable.') val.flags.writeable = writeable
java
public static void multTransAB(double alpha , DMatrix1Row a , DMatrix1Row b , DMatrix1Row c ) { // TODO add a matrix vectory multiply here if( a.numCols >= EjmlParameters.MULT_TRANAB_COLUMN_SWITCH ) { MatrixMatrixMult_DDRM.multTransAB_aux(alpha, a, b, c, null); } else { MatrixMatrixMult_DDRM.multTransAB(alpha, a, b, c); } }
python
def require(f): ''' The @require decorator, usable in an immutable class (see immutable), specifies that the following function is actually a validation check on the immutable class. These functions will appear as static members of the class and get called automatically when the relevant data change. Daughter classes can overload requirements to change them, or may add new requirements with different function names. ''' (args, varargs, kwargs, dflts) = getargspec_py27like(f) if varargs is not None or kwargs is not None or dflts: raise ValueError( 'Requirements may not accept variable, variadic keyword, or default arguments') f._pimms_immutable_data_ = {} f._pimms_immutable_data_['is_check'] = True f._pimms_immutable_data_['inputs'] = args f._pimms_immutable_data_['name'] = f.__name__ f = staticmethod(f) return f
python
def set_current_editor(self, file): """ Focus the **Script_Editor_tabWidget** Widget tab Model editor with given file. :param file: File. :type file: unicode :return: Method success. :rtype: bool """ index = self.find_editor_tab(file) if index is not None: self.Script_Editor_tabWidget.setCurrentIndex(index) return True
java
public static CellStyle createDefaultCellStyle(Workbook workbook) { final CellStyle cellStyle = workbook.createCellStyle(); setAlign(cellStyle, HorizontalAlignment.CENTER, VerticalAlignment.CENTER); setBorder(cellStyle, BorderStyle.THIN, IndexedColors.BLACK); return cellStyle; }
python
def json(self, *, # type: ignore loads: Callable[[Any], Any]=json.loads) -> None: """Return parsed JSON data. .. versionadded:: 0.22 """ return loads(self.data)
python
def set_impact_state(self): """We just go an impact, so we go unreachable But only if we enable this state change in the conf :return: None """ cls = self.__class__ if cls.enable_problem_impacts_states_change: logger.debug("%s is impacted and goes UNREACHABLE", self) # Track the old state (problem occured before a new check) self.state_before_impact = self.state self.state_id_before_impact = self.state_id # This flag will know if we override the impact state self.state_changed_since_impact = False # Set unreachable self.set_unreachable()
python
def checksum(path, hashfunc="md5"): """Return checksum of files given by path. Wildcards can be used in check sum. Function is strongly dependent on checksumdir package by 'cakepietoast'. :param path: path of files to get hash from :param hashfunc: function used to get hash, default 'md5' :return: (str) hash of the file/files given by path """ import checksumdir hash_func = checksumdir.HASH_FUNCS.get(hashfunc) if not hash_func: raise NotImplementedError("{} not implemented.".format(hashfunc)) if os.path.isdir(path): return checksumdir.dirhash(path, hashfunc=hashfunc) hashvalues = [] path_list = list(sorted(glob.glob(path))) logger.debug("path_list: len: %i", len(path_list)) if len(path_list) > 0: logger.debug("first ... last: %s ... %s", str(path_list[0]), str(path_list[-1])) for path in path_list: if os.path.isfile(path): hashvalues.append(checksumdir._filehash(path, hashfunc=hash_func)) logger.debug("one hash per file: len: %i", len(hashvalues)) if len(path_list) > 0: logger.debug("first ... last: %s ... %s", str(hashvalues[0]), str(hashvalues[-1])) checksum_hash = checksumdir._reduce_hash(hashvalues, hashfunc=hash_func) logger.debug("total hash: {}".format(str(checksum_hash))) return checksum_hash
python
def _or_join(self, terms): """ Joins terms using OR operator. Args: terms (list): terms to join Examples: self._or_join(['term1', 'term2']) -> 'term1 | term2' Returns: str """ from six import text_type if isinstance(terms, (tuple, list)): if len(terms) > 1: return ' | '.join(text_type(t) for t in terms) else: return terms[0] else: return terms
python
def create_file_new_actions(self, fnames): """Return actions for submenu 'New...'""" if not fnames: return [] new_file_act = create_action(self, _("File..."), icon=ima.icon('filenew'), triggered=lambda: self.new_file(fnames[-1])) new_module_act = create_action(self, _("Module..."), icon=ima.icon('spyder'), triggered=lambda: self.new_module(fnames[-1])) new_folder_act = create_action(self, _("Folder..."), icon=ima.icon('folder_new'), triggered=lambda: self.new_folder(fnames[-1])) new_package_act = create_action(self, _("Package..."), icon=ima.icon('package_new'), triggered=lambda: self.new_package(fnames[-1])) return [new_file_act, new_folder_act, None, new_module_act, new_package_act]
python
def create(name, **params): ''' Function to create device in Server Density. For more info, see the `API docs`__. .. __: https://apidocs.serverdensity.com/Inventory/Devices/Creating CLI Example: .. code-block:: bash salt '*' serverdensity_device.create lama salt '*' serverdensity_device.create rich_lama group=lama_band installedRAM=32768 ''' log.debug('Server Density params: %s', params) params = _clean_salt_variables(params) params['name'] = name api_response = requests.post( 'https://api.serverdensity.io/inventory/devices/', params={'token': get_sd_auth('api_token')}, data=params ) log.debug('Server Density API Response: %s', api_response) log.debug('Server Density API Response content: %s', api_response.content) if api_response.status_code == 200: try: return salt.utils.json.loads(api_response.content) except ValueError: log.error('Could not parse API Response content: %s', api_response.content) raise CommandExecutionError( 'Failed to create, API Response: {0}'.format(api_response) ) else: return None
python
def _scale_enum(anchor, scales): """ Enumerate a set of anchors for each scale wrt an anchor. """ w, h, x_ctr, y_ctr = AnchorGenerator._whctrs(anchor) ws = w * scales hs = h * scales anchors = AnchorGenerator._mkanchors(ws, hs, x_ctr, y_ctr) return anchors
python
def orng_type(self, table_name, col): ''' Returns an Orange datatype for a given mysql column. :param table_name: target table name :param col: column to determine the Orange datatype ''' mysql_type = self.types[table_name][col] n_vals = len(self.db.col_vals[table_name][col]) if mysql_type in OrangeConverter.continuous_types or ( n_vals >= 50 and mysql_type in OrangeConverter.integer_types): return 'c' elif mysql_type in OrangeConverter.ordinal_types + OrangeConverter.integer_types: return 'd' else: return 'string'
java
public List<LabeledUtterance> list(UUID appId, String versionId, ListExamplesOptionalParameter listOptionalParameter) { return listWithServiceResponseAsync(appId, versionId, listOptionalParameter).toBlocking().single().body(); }
java
public final void helpComplete(int maxTasks) { Thread t; ForkJoinWorkerThread wt; if (maxTasks > 0 && status >= 0) { if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) (wt = (ForkJoinWorkerThread) t).pool.helpComplete(wt.workQueue, this, maxTasks); else ForkJoinPool.common.externalHelpComplete(this, maxTasks); } }
java
public ConnectedCrud<T, K> table(DataSource dataSource, String table) throws SQLException { Connection connection = dataSource.getConnection(); try { return new ConnectedCrud<T, K>(new DataSourceTransactionTemplate(dataSource), table(connection, table)); } finally { connection.close(); } }
java
protected boolean needsPropertyChangeSupport(ClassNode declaringClass, SourceUnit sourceUnit) { boolean foundAdd = false, foundRemove = false, foundFire = false; ClassNode consideredClass = declaringClass; while (consideredClass!= null) { for (MethodNode method : consideredClass.getMethods()) { // just check length, MOP will match it up foundAdd = foundAdd || method.getName().equals("addPropertyChangeListener") && method.getParameters().length == 1; foundRemove = foundRemove || method.getName().equals("removePropertyChangeListener") && method.getParameters().length == 1; foundFire = foundFire || method.getName().equals("firePropertyChange") && method.getParameters().length == 3; if (foundAdd && foundRemove && foundFire) { return false; } } consideredClass = consideredClass.getSuperClass(); } // check if a super class has @Bindable annotations consideredClass = declaringClass.getSuperClass(); while (consideredClass!=null) { if (hasBindableAnnotation(consideredClass)) return false; for (FieldNode field : consideredClass.getFields()) { if (hasBindableAnnotation(field)) return false; } consideredClass = consideredClass.getSuperClass(); } if (foundAdd || foundRemove || foundFire) { sourceUnit.getErrorCollector().addErrorAndContinue( new SimpleMessage("@Bindable cannot be processed on " + declaringClass.getName() + " because some but not all of addPropertyChangeListener, removePropertyChange, and firePropertyChange were declared in the current or super classes.", sourceUnit) ); return false; } return true; }
python
def get_thumbnail_image(self, page=1): """ Downloads and returns the thumbnail sized image of a single page. The page kwarg specifies which page to return. One is the default. """ url = self.get_thumbnail_image_url(page=page) return self._get_url(url)
java
private double[] parseVector(String s) { String[] entries = WHITESPACE_PATTERN.split(s); double[] d = new double[entries.length]; for(int i = 0; i < entries.length; i++) { try { d[i] = ParseUtil.parseDouble(entries[i]); } catch(NumberFormatException e) { throw new AbortException("Could not parse vector."); } } return d; }
java
public <E> E deserialize(final String str, final Class<E> type, final Collection<Converter<?>> converters) { logger.debug("deserialize(\"{}\", {})", str, type); if (converters == null || converters.isEmpty()) { // when possible, just reuse the base converter @SuppressWarnings("unchecked") final E result = (E) _baseConverter.fromString(type, str); return result; } final DelegatingConverter delegatingConverter = new DelegatingConverter(); if (converters != null) { for (final Converter<?> converter : converters) { delegatingConverter.addConverter(converter); delegatingConverter.initialize(converter, _injectionManager); } } final List<Converter<?>> baseconverters = _baseConverter.getConverters(); for (final Converter<?> converter : baseconverters) { delegatingConverter.addConverter(converter); } @SuppressWarnings("unchecked") final E result = (E) delegatingConverter.fromString(type, str); return result; }
java
public synchronized CounterGroup getGroup(String groupName) { CounterGroup grp = groups.get(groupName); if (grp == null) { grp = new CounterGroup(groupName); groups.put(groupName, grp); } return grp; }
java
public void banUser(Jid jid, String reason) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException { changeAffiliationByAdmin(jid, MUCAffiliation.outcast, reason); }
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case SimpleAntlrPackage.PARAMETER__TYPE: return TYPE_EDEFAULT == null ? type != null : !TYPE_EDEFAULT.equals(type); case SimpleAntlrPackage.PARAMETER__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); } return super.eIsSet(featureID); }
java
public IntIterator getIntIterator() { return new IntIterator() { int wordindex; int i = 0; IntArray buf; int currentword; public IntIterator init(IntArray b) { this.buf = b; this.wordindex = this.buf.get(this.i); this.currentword = this.buf.get(this.i + 1); return this; } @Override public boolean hasNext() { return this.currentword != 0; } @Override public int next() { final int offset = Integer .numberOfTrailingZeros(this.currentword); this.currentword ^= 1 << offset; final int answer = this.wordindex * WORDSIZE + offset; if (this.currentword == 0) { this.i += 2; if (this.i < this.buf.size()) { this.currentword = this.buf.get(this.i + 1); this.wordindex += this.buf.get(this.i) + 1; } } return answer; } }.init(this.buffer); }
java
@Override public ResetJobBookmarkResult resetJobBookmark(ResetJobBookmarkRequest request) { request = beforeClientExecution(request); return executeResetJobBookmark(request); }
java
@Override public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException { Cache<ResultSet, String[]> cache = localColNames.get(); try { String[] colLabels = cache.get(rs, () -> { return JdbcHelper.extractColumnLabels(rs); }); Map<String, Object> row = new HashMap<>(); for (int i = 0; i < colLabels.length; i++) { row.put(colLabels[i], rs.getObject(colLabels[i])); } return row; } catch (ExecutionException e) { throw new RuntimeException(e); } }
python
def cross_entropy_error(self, input_data, targets, average=True, cache=None, prediction=False, sum_errors=True): """ Computes the cross-entropy error for all tasks. """ loss = [] if cache is None: cache = self.n_tasks * [None] for targets_task, cache_task, task in \ izip(targets, cache, self.tasks): loss.append(task.cross_entropy_error( input_data, targets_task, average=average, cache=cache_task, prediction=prediction)) if sum_errors: return sum(loss) else: return loss
java
public boolean compareOneScreenshot(File baseImg, File targetImg, int rows, int columns) { boolean match = true; BufferedImage[][] baseBfImg = splitImage(baseImg, rows, columns); BufferedImage[][] targetBfImg = splitImage(targetImg, rows, columns); BufferedImage[][] diffImg = new BufferedImage[rows][columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { byte[] baseImgBytes = toByteArray(baseBfImg[i][j]); byte[] targetImgBytes = toByteArray(targetBfImg[i][j]); if (Arrays.equals(baseImgBytes, targetImgBytes)) { diffImg[i][j] = darken(targetBfImg[i][j]); } else { match = false; diffImg[i][j] = targetBfImg[i][j]; } } } if (match) { LOG.info("screenshot.match", targetImg.getName()); } else { LOG.error("screenshot.unmatch", targetImg.getName()); writeDiffImg(targetImg, diffImg); } return match; }
java
public static void closeAll(Logger log, java.io.Closeable... closeables) { for (java.io.Closeable c : closeables) { if (c != null) { try { if (log != null) { log.debug("Closing {}", c); } c.close(); } catch (Exception e) { if (log != null && log.isDebugEnabled()) { log.debug("Exception in closing {}", c, e); } } } } }
java
private void traverse(final Path path, final boolean watch, final boolean remove) { log.debug("traverse start. path : {}, watch : {}, remove : {}", path, watch, remove); if (Files.notExists(path)) { return; } if (Files.isDirectory(path)) { if (validPath(path)) { try (DirectoryStream<Path> ds = Files.newDirectoryStream(path)) { if (watch) { WatchKey key = path.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); watchDirs.put(key, path); } for (Path child : ds) { traverse(child, watch, remove); } } catch (IOException ex) { throw new UroborosqlRuntimeException("I/O error occured.", ex); } } } else if (path.toString().endsWith(fileExtension)) { String sqlName = getSqlName(path); this.sqlInfos.compute(sqlName, (k, v) -> v == null ? new SqlInfo(sqlName, path, dialect, charset) : v.computePath(path, remove)); } }
java
public static String read(Container container, String ddPath) { if (container == null || ddPath == null) { return ""; } Entry entry = container.getEntry(ddPath); if (entry == null) { throw new IllegalStateException(ddPath); } InputStream input; try { input = entry.adapt(InputStream.class); } catch (UnableToAdaptException e) { throw new IllegalStateException(e); } try { SAXParserFactory parserFactory = SAXParserFactory.newInstance(); SAXParser parser = parserFactory.newSAXParser(); XMLReader xmlReader = parser.getXMLReader(); xmlReader.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(String arg0, String arg1) throws SAXException, IOException { return new InputSource(new ByteArrayInputStream(new byte[0])); } }); Source saxSource = new SAXSource(xmlReader, new InputSource(input)); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); StringWriter writer = new StringWriter(); Result result = new StreamResult(writer); transformer.transform(saxSource, result); return writer.toString(); } catch (ParserConfigurationException e) { throw new IllegalStateException(e); } catch (SAXException e) { throw new IllegalStateException(e); } catch (TransformerConfigurationException e) { throw new IllegalStateException(e); } catch (TransformerException e) { throw new IllegalStateException(e); } finally { try { input.close(); } catch (IOException e) { } } }
java
public HFCAAffiliationResp create(User registrar, boolean force) throws AffiliationException, InvalidArgumentException { if (registrar == null) { throw new InvalidArgumentException("Registrar should be a valid member"); } String createURL = ""; try { createURL = client.getURL(HFCA_AFFILIATION); logger.debug(format("affiliation url: %s, registrar: %s", createURL, registrar.getName())); Map<String, String> queryParm = new HashMap<String, String>(); queryParm.put("force", String.valueOf(force)); String body = client.toJson(affToJsonObject()); JsonObject result = client.httpPost(createURL, body, registrar); logger.debug(format("identity url: %s, registrar: %s done.", createURL, registrar)); this.deleted = false; return getResponse(result); } catch (HTTPException e) { String msg = format("[Code: %d] - Error while creating affiliation '%s' from url '%s': %s", e.getStatusCode(), this.name, createURL, e.getMessage()); AffiliationException affiliationException = new AffiliationException(msg, e); logger.error(msg); throw affiliationException; } catch (Exception e) { String msg = format("Error while creating affiliation %s url: %s %s ", this.name, createURL, e.getMessage()); AffiliationException affiliationException = new AffiliationException(msg, e); logger.error(msg); throw affiliationException; } }
java
public static ObjectTypeAttributeDefinition.Builder getAttributeBuilder(boolean allowNull, boolean referenceCredentialStore) { AttributeDefinition csAttr = referenceCredentialStore ? credentialStoreAttributeWithCapabilityReference : credentialStoreAttribute; return getAttributeBuilder(CREDENTIAL_REFERENCE, CREDENTIAL_REFERENCE, allowNull, csAttr); }
java
public Byte getGroupingByte(String label) { PrimitiveObject o = getPrimitiveObject(KEY, label, ObjectUtil.BYTE, "Byte"); if (o == null) { return null; } return (Byte) o.getObject(); }
python
def get_db(db, ip='localhost', port=27017, user=None, password=None): ''' Returns a pymongo Database object. .. note: Both ``user`` and ``password`` are required when connecting to a MongoDB database that has authentication enabled. Arguments: db (str): Name of the MongoDB database. Required. ip (str): IP address of the MongoDB server. Default is ``localhost``. port (int): Port of the MongoDB server. Default is ``27017``. user (str): Username, if authentication is enabled on the MongoDB database. Default is ``None``, which results in requesting the connection without authentication. password (str): Password, if authentication is enabled on the MongoDB database. Default is ``None``, which results in requesting the connection without authentication. ''' if platform.system().lower() == 'darwin': connect = False else: connect = True if user and password: import urllib pwd = urllib.quote_plus(password) uri = 'mongodb://{}:{}@{}:{}'.format(user, pwd, ip, port) conn = MongoClient(uri, connect=connect) else: conn = MongoClient(ip, port, connect=connect) return conn[db]
python
def add_tracks(self, subtracks): """ Add one or more tracks to this view. subtracks : Track or iterable of Tracks A single Track instance or an iterable of them. """ if isinstance(subtracks, Track): subtracks = [subtracks] for subtrack in subtracks: subtrack.subgroups['view'] = self.view self.add_child(subtrack) self.subtracks.append(subtrack)
java
protected boolean isMySQLDatabase() throws HandlerException { String dbName = determineDatabaseType(); if (dbName == null) { return false; } return "MySQL".equalsIgnoreCase(dbName); }
java
private byte[] fetchDecoderOutput() { final CompositeByteBuf decoded = Unpooled.compositeBuffer(); for (;;) { final ByteBuf buf = decoder.readInbound(); if (buf == null) { break; } if (!buf.isReadable()) { buf.release(); continue; } decoded.addComponent(true, buf); } final byte[] ret = ByteBufUtil.getBytes(decoded); decoded.release(); return ret; }
java
public void onGeometryIndexSnappingEnd(GeometryIndexSnappingEndEvent event) { for (GeometryIndex index : event.getIndices()) { update(event.getGeometry(), index, false); } }
python
def create(vm_): ''' Create a single VM from a data dict ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'digitalocean', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) kwargs = { 'name': vm_['name'], 'size': get_size(vm_), 'image': get_image(vm_), 'region': get_location(vm_), 'ssh_keys': [], 'tags': [] } # backwards compat ssh_key_name = config.get_cloud_config_value( 'ssh_key_name', vm_, __opts__, search_global=False ) if ssh_key_name: kwargs['ssh_keys'].append(get_keyid(ssh_key_name)) ssh_key_names = config.get_cloud_config_value( 'ssh_key_names', vm_, __opts__, search_global=False, default=False ) if ssh_key_names: for key in ssh_key_names.split(','): kwargs['ssh_keys'].append(get_keyid(key)) key_filename = config.get_cloud_config_value( 'ssh_key_file', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if not __opts__.get('ssh_agent', False) and key_filename is None: raise SaltCloudConfigError( 'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name ' 'because it does not supply a root password upon building the server.' ) ssh_interface = config.get_cloud_config_value( 'ssh_interface', vm_, __opts__, search_global=False, default='public' ) if ssh_interface in ['private', 'public']: log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface) kwargs['ssh_interface'] = ssh_interface else: raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'." ) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None, ) if private_networking is not None: if not isinstance(private_networking, bool): raise SaltCloudConfigError("'private_networking' should be a boolean value.") kwargs['private_networking'] = private_networking if not private_networking and ssh_interface == 'private': raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface if defined as 'private' " "then private_networking should be set as 'True'." ) backups_enabled = config.get_cloud_config_value( 'backups_enabled', vm_, __opts__, search_global=False, default=None, ) if backups_enabled is not None: if not isinstance(backups_enabled, bool): raise SaltCloudConfigError("'backups_enabled' should be a boolean value.") kwargs['backups'] = backups_enabled ipv6 = config.get_cloud_config_value( 'ipv6', vm_, __opts__, search_global=False, default=None, ) if ipv6 is not None: if not isinstance(ipv6, bool): raise SaltCloudConfigError("'ipv6' should be a boolean value.") kwargs['ipv6'] = ipv6 monitoring = config.get_cloud_config_value( 'monitoring', vm_, __opts__, search_global=False, default=None, ) if monitoring is not None: if not isinstance(monitoring, bool): raise SaltCloudConfigError("'monitoring' should be a boolean value.") kwargs['monitoring'] = monitoring kwargs['tags'] = config.get_cloud_config_value( 'tags', vm_, __opts__, search_global=False, default=False ) userdata_file = config.get_cloud_config_value( 'userdata_file', vm_, __opts__, search_global=False, default=None ) if userdata_file is not None: try: with salt.utils.files.fopen(userdata_file, 'r') as fp_: kwargs['user_data'] = salt.utils.cloud.userdata_template( __opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read()) ) except Exception as exc: log.exception( 'Failed to read userdata from %s: %s', userdata_file, exc) create_dns_record = config.get_cloud_config_value( 'create_dns_record', vm_, __opts__, search_global=False, default=None, ) if create_dns_record: log.info('create_dns_record: will attempt to write DNS records') default_dns_domain = None dns_domain_name = vm_['name'].split('.') if len(dns_domain_name) > 2: log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN') default_dns_hostname = '.'.join(dns_domain_name[:-2]) default_dns_domain = '.'.join(dns_domain_name[-2:]) else: log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name']) default_dns_hostname = dns_domain_name[0] dns_hostname = config.get_cloud_config_value( 'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname, ) dns_domain = config.get_cloud_config_value( 'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain, ) if dns_hostname and dns_domain: log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain) __add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain, name=dns_hostname, record_type=t, record_data=d) log.debug('create_dns_record: %s', __add_dns_addr__) else: log.error('create_dns_record: could not determine dns_hostname and/or dns_domain') raise SaltCloudConfigError( '\'create_dns_record\' must be a dict specifying "domain" ' 'and "hostname" or the minion name must be an FQDN.' ) __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) try: ret = create_node(kwargs) except Exception as exc: log.error( 'Error creating %s on DIGITALOCEAN\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False def __query_node_data(vm_name): data = show_instance(vm_name, 'action') if not data: # Trigger an error in the wait_for_ip function return False if data['networks'].get('v4'): for network in data['networks']['v4']: if network['type'] == 'public': return data return False try: data = salt.utils.cloud.wait_for_ip( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=10), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) if not vm_.get('ssh_host'): vm_['ssh_host'] = None # add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA')) arec_map = dict(list(zip(addr_families, dns_arec_types))) for facing, addr_family, ip_address in [(net['type'], family, net['ip_address']) for family in addr_families for net in data['networks'][family]]: log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address) dns_rec_type = arec_map[addr_family] if facing == 'public': if create_dns_record: __add_dns_addr__(dns_rec_type, ip_address) if facing == ssh_interface: if not vm_['ssh_host']: vm_['ssh_host'] = ip_address if vm_['ssh_host'] is None: raise SaltCloudSystemExit( 'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks'])) ) log.debug( 'Found public IP address to use for ssh minion bootstrapping: %s', vm_['ssh_host'] ) vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret.update(data) log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) return ret
python
def create_token_response(self, request, token_handler): """Return token or error in json format. :param request: OAuthlib request. :type request: oauthlib.common.Request :param token_handler: A token handler instance, for example of type oauthlib.oauth2.BearerToken. If the access token request is valid and authorized, the authorization server issues an access token and optional refresh token as described in `Section 5.1`_. If the request failed client authentication or is invalid, the authorization server returns an error response as described in `Section 5.2`_. .. _`Section 5.1`: https://tools.ietf.org/html/rfc6749#section-5.1 .. _`Section 5.2`: https://tools.ietf.org/html/rfc6749#section-5.2 """ headers = self._get_default_headers() try: if self.request_validator.client_authentication_required(request): log.debug('Authenticating client, %r.', request) if not self.request_validator.authenticate_client(request): log.debug('Client authentication failed, %r.', request) raise errors.InvalidClientError(request=request) elif not self.request_validator.authenticate_client_id(request.client_id, request): log.debug('Client authentication failed, %r.', request) raise errors.InvalidClientError(request=request) log.debug('Validating access token request, %r.', request) self.validate_token_request(request) except errors.OAuth2Error as e: log.debug('Client error in token request, %s.', e) headers.update(e.headers) return headers, e.json, e.status_code token = token_handler.create_token(request, self.refresh_token) for modifier in self._token_modifiers: token = modifier(token) self.request_validator.save_token(token, request) log.debug('Issuing token %r to client id %r (%r) and username %s.', token, request.client_id, request.client, request.username) return headers, json.dumps(token), 200
python
def add(self, phrase, id=None): """ Adds a new phrase to the dictionary :param phrase: the new phrase as a list of tokens :param phrase_id: optionally the phrase_id can be set on addition. Beware, if you set one id you should set them all as the auto-generated ids do not take into account phrase_ids set this way. :return: None """ phrase_id = id if id is not None else self.get_next_id() PhraseDictionary._add_phrase(phrase, phrase_id, self, self.word_list) self.id2phrase[phrase_id] = phrase
python
def discrete(self, vertices, count=None, scale=1.0): """ Discretize the B-Spline curve. Parameters ------------- vertices : (n, 2) or (n, 3) float Points in space scale : float Scale of overall drawings (for precision) count : int Number of segments to return Returns ------------- discrete : (m, 2) or (m, 3) float Curve as line segments """ discrete = discretize_bspline( control=vertices[self.points], knots=self.knots, count=count, scale=scale) return self._orient(discrete)
python
def extendSection(self, sectionIndex, data): """ Extends an existing section in the L{PE} instance. @type sectionIndex: int @param sectionIndex: The index for the section to be extended. @type data: str @param data: The data to include in the section. @raise IndexError: If an invalid C{sectionIndex} was specified. @raise SectionHeadersException: If there is not section to extend. """ fa = self.ntHeaders.optionalHeader.fileAlignment.value sa = self.ntHeaders.optionalHeader.sectionAlignment.value if len(self.sectionHeaders): if len(self.sectionHeaders) == sectionIndex: try: # we are in the last section or self.sectionHeaders has only 1 sectionHeader instance vzLastSection = self.sectionHeaders[-1].misc.value rzLastSection = self.sectionHeaders[-1].sizeOfRawData.value self.sectionHeaders[-1].misc.value = self._adjustSectionAlignment(vzLastSection + len(data), fa, sa) self.sectionHeaders[-1].sizeOfRawData.value = self._adjustFileAlignment(rzLastSection + len(data), fa) vz = self.sectionHeaders[-1].misc.value rz = self.sectionHeaders[-1].sizeOfRawData.value except IndexError: raise IndexError("list index out of range.") if vz < rz: print "WARNING: VirtualSize (%x) is less than SizeOfRawData (%x)" % (vz, rz) if len(data) % fa == 0: self.sections[-1] += data else: self.sections[-1] += data + "\xcc" * (fa - len(data) % fa) else: # if it is not the last section ... try: # adjust data of the section the user wants to extend counter = sectionIndex - 1 vzCurrentSection = self.sectionHeaders[counter].misc.value rzCurrentSection = self.sectionHeaders[counter].sizeOfRawData.value self.sectionHeaders[counter].misc.value = self._adjustSectionAlignment(vzCurrentSection + len(data), fa, sa) self.sectionHeaders[counter].sizeOfRawData.value = self._adjustFileAlignment(rzCurrentSection + len(data), fa) if len(data) % fa == 0: self.sections[counter] += data else: self.sections[counter] += data + "\xcc" * (fa - len(data) % fa) counter += 1 while(counter != len(self.sectionHeaders)): vzPreviousSection = self.sectionHeaders[counter - 1].misc.value vaPreviousSection = self.sectionHeaders[counter - 1].virtualAddress.value rzPreviousSection = self.sectionHeaders[counter - 1].sizeOfRawData.value roPreviousSection = self.sectionHeaders[counter - 1].pointerToRawData.value # adjust VA and RO of the next section self.sectionHeaders[counter].virtualAddress.value = self._adjustSectionAlignment(vzPreviousSection + vaPreviousSection, fa, sa) self.sectionHeaders[counter].pointerToRawData.value = self._adjustFileAlignment(rzPreviousSection + roPreviousSection, fa) vz = self.sectionHeaders[counter].virtualAddress.value rz = self.sectionHeaders[counter].pointerToRawData.value if vz < rz: print "WARNING: VirtualSize (%x) is less than SizeOfRawData (%x)" % (vz, rz) counter += 1 except IndexError: raise IndexError("list index out of range.") else: raise excep.SectionHeadersException("There is no section to extend.")
java
public void process( T image , GrayS32 output ) { InputSanityCheck.checkSameShape(image,output); stopRequested = false; // long time0 = System.currentTimeMillis(); search.process(image); if( stopRequested ) return; // long time1 = System.currentTimeMillis(); FastQueue<float[]> regionColor = search.getModeColor(); GrayS32 pixelToRegion = search.getPixelToRegion(); GrowQueue_I32 regionPixelCount = search.getRegionMemberCount(); FastQueue<Point2D_I32> modeLocation = search.getModeLocation(); merge.process(pixelToRegion,regionPixelCount,regionColor,modeLocation); if( stopRequested ) return; // long time2 = System.currentTimeMillis(); segment.process(pixelToRegion, output, regionPixelCount); if( stopRequested ) return; // long time3 = System.currentTimeMillis(); if( prune != null) prune.process(image,output,regionPixelCount,regionColor); // long time4 = System.currentTimeMillis(); // System.out.println("Search: "+(time1-time0)+" Merge: "+(time2-time1)+ // " segment: "+(time3-time2)+" Prune: "+(time4-time3)); }
python
def write_to_buffer(self, buf): """Save the context to a buffer.""" doc = self.to_dict() if config.rxt_as_yaml: content = dump_yaml(doc) else: content = json.dumps(doc, indent=4, separators=(",", ": ")) buf.write(content)
java
public AVQuery<T> whereMatchesKeyInQuery(String key, String keyInQuery, AVQuery<?> query) { Map<String, Object> inner = new HashMap<String, Object>(); inner.put("className", query.getClassName()); inner.put("where", query.conditions.compileWhereOperationMap()); if (query.conditions.getSkip() > 0) inner.put("skip", query.conditions.getSkip()); if (query.conditions.getLimit() > 0) inner.put("limit", query.conditions.getLimit()); if (!StringUtil.isEmpty(query.getOrder())) inner.put("order", query.getOrder()); Map<String, Object> queryMap = new HashMap<String, Object>(); queryMap.put("query", inner); queryMap.put("key", keyInQuery); return addWhereItem(key, "$select", queryMap); }
python
def _generate_tokens(self, text): """ Generates tokens for the given code. """ # This is technically an undocumented API for Python3, but allows us to use the same API as for # Python2. See http://stackoverflow.com/a/4952291/328565. for index, tok in enumerate(tokenize.generate_tokens(io.StringIO(text).readline)): tok_type, tok_str, start, end, line = tok yield Token(tok_type, tok_str, start, end, line, index, self._line_numbers.line_to_offset(start[0], start[1]), self._line_numbers.line_to_offset(end[0], end[1]))
python
def create_multireddit(self, name, description_md=None, icon_name=None, key_color=None, subreddits=None, visibility=None, weighting_scheme=None, overwrite=False, *args, **kwargs): # pylint: disable=W0613 """Create a new multireddit. :param name: The name of the new multireddit. :param description_md: Optional description for the multireddit, formatted in markdown. :param icon_name: Optional, choose an icon name from this list: ``art and design``, ``ask``, ``books``, ``business``, ``cars``, ``comics``, ``cute animals``, ``diy``, ``entertainment``, ``food and drink``, ``funny``, ``games``, ``grooming``, ``health``, ``life advice``, ``military``, ``models pinup``, ``music``, ``news``, ``philosophy``, ``pictures and gifs``, ``science``, ``shopping``, ``sports``, ``style``, ``tech``, ``travel``, ``unusual stories``, ``video``, or ``None``. :param key_color: Optional rgb hex color code of the form `#xxxxxx`. :param subreddits: Optional list of subreddit names or Subreddit objects to initialize the Multireddit with. You can always add more later with :meth:`~praw.objects.Multireddit.add_subreddit`. :param visibility: Choose a privacy setting from this list: ``public``, ``private``, ``hidden``. Defaults to private if blank. :param weighting_scheme: Choose a weighting scheme from this list: ``classic``, ``fresh``. Defaults to classic if blank. :param overwrite: Allow for overwriting / updating multireddits. If False, and the multi name already exists, throw 409 error. If True, and the multi name already exists, use the given properties to update that multi. If True, and the multi name does not exist, create it normally. :returns: The newly created Multireddit object. The additional parameters are passed directly into :meth:`~praw.__init__.BaseReddit.request_json` """ url = self.config['multireddit_about'].format(user=self.user.name, multi=name) if subreddits: subreddits = [{'name': six.text_type(sr)} for sr in subreddits] model = {} for key in ('description_md', 'icon_name', 'key_color', 'subreddits', 'visibility', 'weighting_scheme'): value = locals()[key] if value: model[key] = value method = 'PUT' if overwrite else 'POST' return self.request_json(url, data={'model': json.dumps(model)}, method=method, *args, **kwargs)
java
private void error(String expected, String actual) { if (!recovering) { recovering = true; final String outputString = (EOF_STRING.equals(actual) || UNTERMINATED_COMMENT_STRING.equals(actual) || COMMENT_NOT_ALLOWED.equals(actual)) ? actual : "'" + actual + "'"; errors.add(SyntaxError._UnexpectedToken(expected, outputString, lookahead(1).beginLine)); } }
java
public void getWvWAbilityInfo(int[] ids, Callback<List<WvWAbility>> callback) throws GuildWars2Exception, NullPointerException { isParamValid(new ParamChecker(ids)); gw2API.getWvWAbilityInfo(processIds(ids), GuildWars2.lang.getValue()).enqueue(callback); }
java
@Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case XbasePackage.XFOR_LOOP_EXPRESSION__FOR_EXPRESSION: return getForExpression(); case XbasePackage.XFOR_LOOP_EXPRESSION__EACH_EXPRESSION: return getEachExpression(); case XbasePackage.XFOR_LOOP_EXPRESSION__DECLARED_PARAM: return getDeclaredParam(); } return super.eGet(featureID, resolve, coreType); }
python
def save_local_scope( self, line_number, saved_function_call_index ): """Save the local scope before entering a function call by saving all the LHS's of assignments so far. Args: line_number(int): Of the def of the function call about to be entered into. saved_function_call_index(int): Unique number for each call. Returns: saved_variables(list[SavedVariable]) first_node(EntryOrExitNode or None or RestoreNode): Used to connect previous statements to this function. """ saved_variables = list() saved_variables_so_far = set() first_node = None # Make e.g. save_N_LHS = assignment.LHS for each AssignmentNode for assignment in [node for node in self.nodes if (type(node) == AssignmentNode or type(node) == AssignmentCallNode or type(Node) == BBorBInode)]: # type() is used on purpose here if assignment.left_hand_side in saved_variables_so_far: continue saved_variables_so_far.add(assignment.left_hand_side) save_name = 'save_{}_{}'.format(saved_function_call_index, assignment.left_hand_side) previous_node = self.nodes[-1] saved_scope_node = RestoreNode( save_name + ' = ' + assignment.left_hand_side, save_name, [assignment.left_hand_side], line_number=line_number, path=self.filenames[-1] ) if not first_node: first_node = saved_scope_node self.nodes.append(saved_scope_node) # Save LHS saved_variables.append(SavedVariable(LHS=save_name, RHS=assignment.left_hand_side)) self.connect_if_allowed(previous_node, saved_scope_node) return (saved_variables, first_node)
java
@PublicEvolving @Deprecated public <ACC, R> SingleOutputStreamOperator<R> fold(ACC initialValue, FoldFunction<T, ACC> foldFunction, WindowFunction<ACC, R, K, W> function) { TypeInformation<ACC> foldAccumulatorType = TypeExtractor.getFoldReturnTypes(foldFunction, input.getType(), Utils.getCallLocationName(), true); TypeInformation<R> resultType = getWindowFunctionReturnType(function, foldAccumulatorType); return fold(initialValue, foldFunction, function, foldAccumulatorType, resultType); }
java
public void removeObect(StringKey skey) { if (skey == null || cache == null) return; cache.remove(skey.getKey()); }
java
static void init(String configName) { MAIN = DbKit.getConfig(configName).dbProFactory.getDbPro(configName); // new DbPro(configName); map.put(configName, MAIN); }
python
def defines(self, id, domain='messages'): """ Checks if a message has a translation (it does not take into account the fallback mechanism). @rtype: bool @return: true if the message has a translation, false otherwise """ assert isinstance(id, (str, unicode)) assert isinstance(domain, (str, unicode)) return id in self.messages.get(domain, {})
java
public FirefoxProfile getFirefoxProfile() { if (firefoxProfile == null) { firefoxProfile = new FirefoxProfile(); firefoxProfile.setAcceptUntrustedCertificates(true); firefoxProfile.setAssumeUntrustedCertificateIssuer(false); /* default download folder, set to 2 to use custom download folder */ firefoxProfile.setPreference("browser.download.folderList", 2); /* comma separated list if MIME types to save without asking */ firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "text/plain"); /* do not show download manager */ firefoxProfile.setPreference("browser.download.manager.showWhenStarting", false); } return firefoxProfile; }
java
public static void removeLocalBundle(String name, Version version, boolean removePhysical, boolean doubleTap) throws BundleException { name = name.trim(); CFMLEngine engine = CFMLEngineFactory.getInstance(); CFMLEngineFactory factory = engine.getCFMLEngineFactory(); BundleFile bf = _getBundleFile(factory, name, version, null); if (bf != null) { BundleDefinition bd = bf.toBundleDefinition(); if (bd != null) { Bundle b = bd.getLocalBundle(); if (b != null) { stopIfNecessary(b); b.uninstall(); } } } if (!removePhysical) return; // remove file if (bf != null) { if (!bf.getFile().delete() && doubleTap) bf.getFile().deleteOnExit(); } }
python
def buildcontainer(self): """generate HTML div""" if self.container: return # Create HTML div with style if self.options['chart'].width: if str(self.options['chart'].width)[-1] != '%': self.div_style += 'width:%spx;' % self.options['chart'].width else: self.div_style += 'width:%s;' % self.options['chart'].width if self.options['chart'].height: if str(self.options['chart'].height)[-1] != '%': self.div_style += 'height:%spx;' % self.options['chart'].height else: self.div_style += 'height:%s;' % self.options['chart'].height self.div_name = self.options['chart'].__dict__['renderTo'] # recheck div name self.container = self.containerheader + \ '<div id="%s" style="%s">%s</div>\n' % (self.div_name, self.div_style, self.loading)
python
def instrument(self, container: Container ) -> None: """ Instruments the program inside the container for computing test suite coverage. Params: container: the container that should be instrumented. """ path = "containers/{}/instrument".format(container.uid) r = self.__api.post(path) if r.status_code != 204: logger.info("failed to instrument container: %s", container.uid) self.__api.handle_erroneous_response(r)
java
public void run() { try { final byte[] buffer = new byte[512 * 1024]; while (!this.closed.get()) { // int r = this.is.read(buffer, 0, buffer.length); if (r < 0) throw new EOFException(); // int offset = 0; while (r > 0) { final int w = write(buffer, offset, r); r -= w; offset += w; } } } catch (IOException e) { this.exception = e; } catch (Exception e) { logger.error("failed to transfer data", e); } finally { if (!this.closed.get()) { try { close(); } catch (IOException e) { logger.error("failed to close is", e); } } } }
python
def convert(model, features, target): """Convert a Support Vector Regressor (SVR) model to the protobuf spec. Parameters ---------- model: SVR A trained SVR encoder model. feature_names: [str] Name of the input columns. target: str Name of the output column. Returns ------- model_spec: An object of type Model_pb. Protobuf representation of the model """ spec = _generate_base_svm_regression_spec(model) spec = set_regressor_interface_params(spec, features, target) return _MLModel(spec)
java
@Nonnull public DigestAuthServerBuilder setNonce (@Nonnull final String sNonce) { if (!HttpStringHelper.isQuotedTextContent (sNonce)) throw new IllegalArgumentException ("nonce is invalid: " + sNonce); m_sNonce = sNonce; return this; }
python
def normalize(self, text): """ Normalizes text. Converts to lowercase, Unicode NFC normalization and removes mentions and links :param text: Text to be normalized. """ #print 'Normalize...\n' text = text.lower() text = unicodedata.normalize('NFC', text) text = self.strip_mentions_links(text) return text
java
public Properties getAttributes(Attributes attrs) { Properties attributes = new Properties(); attributes.putAll(attributeValues); if (defaultContent != null) { attributes.put(ElementTags.ITEXT, defaultContent); } if (attrs != null) { for (int i = 0; i < attrs.getLength(); i++) { String attribute = getName(attrs.getQName(i)); attributes.setProperty(attribute, attrs.getValue(i)); } } return attributes; }
python
def y(self,*args,**kwargs): """ NAME: y PURPOSE: return y INPUT: t - (optional) time at which to get y ro= (Object-wide default) physical scale for distances to use to convert use_physical= use to override Object-wide default for using a physical scale for output OUTPUT: y(t) HISTORY: 2010-09-21 - Written - Bovy (NYU) """ thiso= self(*args,**kwargs) if not len(thiso.shape) == 2: thiso= thiso.reshape((thiso.shape[0],1)) if len(thiso[:,0]) != 4 and len(thiso[:,0]) != 6: raise AttributeError("orbit must track azimuth to use x()") elif len(thiso[:,0]) == 4: return thiso[0,:]*nu.sin(thiso[3,:]) else: return thiso[0,:]*nu.sin(thiso[5,:])
python
def field_to_dict(fields): """ Build dictionnary which dependancy for each field related to "root" fields = ["toto", "toto__tata", "titi__tutu"] dico = { "toto": { EMPTY_DICT, "tata": EMPTY_DICT }, "titi" : { "tutu": EMPTY_DICT } } EMPTY_DICT is useful because we don't lose field without it dico["toto"] would only contains "tata" inspired from django.db.models.sql.add_select_related """ field_dict = {} for field in fields: d_tmp = field_dict for part in field.split(LOOKUP_SEP)[:-1]: d_tmp = d_tmp.setdefault(part, {}) d_tmp = d_tmp.setdefault( field.split(LOOKUP_SEP)[-1], deepcopy(EMPTY_DICT) ).update(deepcopy(EMPTY_DICT)) return field_dict
java
public String getErrorString() { StringBuilder ret = new StringBuilder(); if (hasExceptions()) { for (Exception ex : exceptions) { ret.append(HBCIUtils.exception2StringShort(ex)); ret.append(System.getProperty("line.separator")); } } if (hasErrors()) { for (HBCIRetVal hbciRetVal : getErrors()) { ret.append(hbciRetVal.toString()); ret.append(System.getProperty("line.separator")); } } return ret.toString().trim(); }
python
def find_name(name, state, high): ''' Scan high data for the id referencing the given name and return a list of (IDs, state) tuples that match Note: if `state` is sls, then we are looking for all IDs that match the given SLS ''' ext_id = [] if name in high: ext_id.append((name, state)) # if we are requiring an entire SLS, then we need to add ourselves to everything in that SLS elif state == 'sls': for nid, item in six.iteritems(high): if item['__sls__'] == name: ext_id.append((nid, next(iter(item)))) # otherwise we are requiring a single state, lets find it else: # We need to scan for the name for nid in high: if state in high[nid]: if isinstance(high[nid][state], list): for arg in high[nid][state]: if not isinstance(arg, dict): continue if len(arg) != 1: continue if arg[next(iter(arg))] == name: ext_id.append((nid, state)) return ext_id
python
def hicpro_contact_chart (self): """ Generate the HiC-Pro interaction plot """ # Specify the order of the different possible categories keys = OrderedDict() keys['cis_shortRange'] = { 'color': '#0039e6', 'name': 'Unique: cis <= 20Kbp' } keys['cis_longRange'] = { 'color': '#809fff', 'name': 'Unique: cis > 20Kbp' } keys['trans_interaction'] = { 'color': '#009933', 'name': 'Unique: trans' } keys['duplicates'] = { 'color': '#a9a2a2', 'name': 'Duplicate read pairs' } # Config for the plot config = { 'id': 'hicpro_contact_plot', 'title': 'HiC-Pro: Contact Statistics', 'ylab': '# Pairs', 'cpswitch_counts_label': 'Number of Pairs' } return bargraph.plot(self.hicpro_data, keys, config)
java
public ClientWmsLayerInfo createClientWmsLayerInfo(WmsSelectedLayerInfo wmsSelectedLayerInfo, MapWidget mapWidget) { WmsLayerConfiguration wmsConfig = new WmsLayerConfiguration(); wmsConfig.setFormat("image/png"); wmsConfig.setLayers(wmsSelectedLayerInfo.getWmsLayerInfo().getName()); wmsConfig.setVersion(wmsSelectedLayerInfo.getWmsVersion()); wmsConfig.setBaseUrl(wmsSelectedLayerInfo.getBaseWmsUrl()); wmsConfig.setTransparent(true); wmsConfig.setMaximumResolution(Double.MAX_VALUE); wmsConfig.setMinimumResolution(1 / mapWidget.getMapModel().getMapInfo().getMaximumScale()); wmsConfig.setCrs(mapWidget.getMapModel().getCrs()); Bbox bounds = wmsSelectedLayerInfo.getWmsLayerInfo().getBoundingBox(mapWidget.getMapModel().getCrs()); if (bounds == null) { bounds = mapWidget.getMapModel().getMapInfo().getInitialBounds(); } TileConfiguration tileConfig = new TileConfiguration(256, 256, new Coordinate(bounds.getX(), bounds.getY()), mapWidget.getMapModel().getMapView().getResolutions()); ClientWmsLayer wmsLayer = new ClientWmsLayer(wmsSelectedLayerInfo.getName(), mapWidget.getMapModel().getCrs(), wmsConfig, tileConfig, wmsSelectedLayerInfo.getWmsLayerInfo()); ClientWmsLayerInfo wmsLayerInfo = new ClientWmsLayerInfo(wmsLayer); return wmsLayerInfo; }
python
def features_tags_parse_str_to_dict(obj): """ Parse tag strings of all features in the collection into a Python dictionary, if possible. """ features = obj['features'] for i in tqdm(range(len(features))): tags = features[i]['properties'].get('tags') if tags is not None: try: tags = json.loads("{" + tags.replace("=>", ":") + "}") except: try: tags = eval("{" + tags.replace("=>", ":") + "}") except: tags = None if type(tags) == dict: features[i]['properties']['tags'] = {k:tags[k] for k in tags} elif tags is None and 'tags' in features[i]['properties']: del features[i]['properties']['tags'] return obj
python
def savef(self, format, *args): """ Equivalent to zconfig_save, taking a format string instead of a fixed filename. """ return lib.zconfig_savef(self._as_parameter_, format, *args)
python
def element_href(name): """ Get specified element href by element name :param name: name of element :return: string href location of object, else None """ if name: element = fetch_meta_by_name(name) if element.href: return element.href
java
public static <V> V runWithMock(EbeanServer mock, Callable<V> test) throws Exception { return start(mock).run(test); }
python
def request_finished_callback(sender, **kwargs): """This function logs if the user acceses the page""" logger = logging.getLogger(__name__) level = settings.AUTOMATED_LOGGING['loglevel']['request'] user = get_current_user() uri, application, method, status = get_current_environ() excludes = settings.AUTOMATED_LOGGING['exclude']['request'] if status and status in excludes: return if method and method.lower() in excludes: return if not settings.AUTOMATED_LOGGING['request']['query']: uri = urllib.parse.urlparse(uri).path logger.log(level, ('%s performed request at %s (%s %s)' % (user, uri, method, status)).replace(" ", " "), extra={ 'action': 'request', 'data': { 'user': user, 'uri': uri, 'method': method, 'application': application, 'status': status } })
java
public void play(Module module, int source, boolean loop, boolean start) { this.source = source; this.loop = loop; this.module = module; done = false; ibxm = new IBXM(48000); ibxm.set_module(module); songDuration = ibxm.calculate_song_duration(); if (bufferNames != null) { AL10.alSourceStop(source); bufferNames.flip(); AL10.alDeleteBuffers(bufferNames); } bufferNames = BufferUtils.createIntBuffer(2); AL10.alGenBuffers(bufferNames); remainingBufferCount = 2; for (int i=0;i<2;i++) { stream(bufferNames.get(i)); } AL10.alSourceQueueBuffers(source, bufferNames); AL10.alSourcef(source, AL10.AL_PITCH, 1.0f); AL10.alSourcef(source, AL10.AL_GAIN, 1.0f); if (start) { AL10.alSourcePlay(source); } }
java
public ModuleInfo getModuleInfo(final String moduleName) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()"); } return moduleNameToModuleInfo.get(moduleName); }
python
def _list_files(self, args): ''' List files for an installed package ''' if len(args) < 2: raise SPMInvocationError('A package name must be specified') package = args[-1] files = self._pkgdb_fun('list_files', package, self.db_conn) if files is None: raise SPMPackageError('package {0} not installed'.format(package)) else: for file_ in files: if self.opts['verbose']: status_msg = ','.join(file_) else: status_msg = file_[0] self.ui.status(status_msg)
java
@Override protected String resolveField(Field field) { final String fallBackName = field.getName(); final String resourceName = field.getAnnotation(Resource.class).name(); return getName(resourceName, fallBackName); }