language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def do_transition_for(brain_or_object, transition): """Performs a workflow transition for the passed in object. :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: The object where the transtion was performed ...
python
def _execute(self, native, command, data=None, returning=True, mapper=dict): """ Executes the inputted command into the current \ connection cursor. :param command | <str> ...
python
def get_health(self, consumers=2, messages=100): """ Returns health information on transport & Redis connections. """ data = {'consumers': consumers, 'messages': messages} try: self._request('GET', '/health', data=json.dumps(data)) return True exc...
java
public void setLength(long newLength) throws IOException { if (newLength < 0) { throw new IllegalArgumentException("newLength < 0"); } try { Libcore.os.ftruncate(fd, newLength); } catch (ErrnoException errnoException) { throw errnoException.rethrowAsIO...
java
private boolean isCausal(KamEdge edge) { return edge.getRelationshipType() == RelationshipType.INCREASES || edge.getRelationshipType() == RelationshipType.DIRECTLY_INCREASES || edge.getRelationshipType() == RelationshipType.DECREASES || edge.getRelationshipType() ...
python
def restore_geometry_on_layout_change(self, value): """ Setter for **self.__restore_geometry_on_layout_change** attribute. :param value: Attribute value. :type value: bool """ if value is not None: assert type(value) is bool, "'{0}' attribute: '{1}' type is ...
python
def set(self, values): """ Set the object parameters using a dictionary """ if hasattr(self, "inputs"): for item in self.inputs: if hasattr(self, item): setattr(self, item, values[item])
python
def remove(self, x): """Removes given arg (or list thereof) from Args object.""" def _remove(x): found = self.first(x) if found is not None: self._args.pop(found) if _is_collection(x): for item in x: _remove(x) else: ...
python
def cnvlTc(idxPrc, aryPrfTcChunk, lstHrf, varTr, varNumVol, queOut, varOvsmpl=10, varHrfLen=32, ): """ Convolution of time courses with HRF model. """ # *** prepare hrf time courses for convolution print("------...
java
protected Object traceChainedPropertyValue(String chainedName) { final Object failureValue = getTypeFailureMap().get(chainedName); if (failureValue != null) { return failureValue; } final String firstName = Srl.substringFirstFront(chainedName, "."); final String neste...
java
protected FlushStrategy elementAsFlushStrategy(XMLStreamReader reader, Map<String, String> expressions) throws XMLStreamException, ParserException { String elementtext = rawElementText(reader); if (expressions != null && elementtext != null && elementtext.indexOf("${") != -1) expressions....
python
def police_priority_map_exceed_map_pri7_exceed(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") police_priority_map = ET.SubElement(config, "police-priority-map", xmlns="urn:brocade.com:mgmt:brocade-policer") name_key = ET.SubElement(police_priority_map, ...
python
def set_op_upstreams(op_run, op): """Set the upstream operations for operation run.""" # We get a list of all upstream ops or the current op upstream_ops = op.upstream_operations.values_list('id', flat=True) # We get latest op runs for the upstream_ops latest_op_runs = OperationRun.objects.filter(id...
java
public double[][] toDenseArray() { double[][] arr = new double[rows][backingMatrix.columns()]; for (int i = 0; i < rowToReal.length; ++i) arr[i] = backingMatrix.getRow(rowToReal[i]); return arr; }
java
@Override public void initialize() throws RepositoryException{ initialized = true; try { queryEngine = configuration.loadQueryEngine(); queryEngine.connect(); } catch (Exception e){ throw new RepositoryException(e); } }
java
public static SerializedRecord anonymize(SerializedRecord sr) throws Exception { String hostname = sr.get("hostname"); if (hostname == null) throw new Exception("Malformed SerializedRecord: no hostname found"); if ("true".equalsIgnoreCase(Environment .getProperty("anonymizer.hash.host...
python
def get_base_logfilename(logname): """ Return filename for a logfile, filename will contain the actual path + filename :param logname: Name of the log including the extension, should describe what it contains (eg. "device_serial_port.log") """ logdir = get_base_dir() fname = os.path.join(lo...
java
public void reinitialize( HttpServletRequest request, HttpServletResponse response, ServletContext servletContext ) { super.reinitialize( request, response, servletContext ); if ( _pageInputs == null ) { Map map = InternalUtils.getActionOutputMap( request, false ); ...
java
public static void touch(final File folder , final String fileName) throws IOException { if(!folder.exists()){ folder.mkdirs(); } final File touchedFile = new File(folder, fileName); // The JVM will only 'touch' the file if you instantiate a // FileOutputStream inst...
python
def _get_groups(self, data): """ Get all groups defined """ groups = [] for attribute in SOURCE_KEYS: for k, v in data[attribute].items(): if k == None: k = 'Sources' if k not in groups: groups.append(k) ...
java
private boolean _canSkipWhileScanning(MetricSchemaRecordQuery query, RecordType type) { if( (RecordType.METRIC.equals(type) || RecordType.SCOPE.equals(type)) && !SchemaService.containsFilter(query.getTagKey()) && !SchemaService.containsFilter(query.getTagValue()) && !SchemaService.containsFilter(query.g...
python
def show_spindle_dialog(self): """Create the spindle detection dialog.""" self.spindle_dialog.update_groups() self.spindle_dialog.update_cycles() self.spindle_dialog.show()
java
public static String getLoginTarget(CmsObject currentCms, CmsWorkplaceSettings settings, String requestedResource) throws CmsException { String directEditPath = CmsLoginHelper.getDirectEditPath(currentCms, settings.getUserSettings(), false); String target = ""; boolean checkRole = false; ...
python
def gcstats(): """Count the number of instances of each type/class :returns: A dict() mapping type (as a string) to an integer number of references """ all = gc.get_objects() _stats = {} for obj in all: K = type(obj) if K is StatsDelta: continue # avoid counting ou...
python
def update(self, **kwargs): """Due to a password decryption bug we will disable update() method for 12.1.0 and up """ tmos_version = self._meta_data['bigip'].tmos_version if LooseVersion(tmos_version) > LooseVersion('12.0.0'): msg = "Update() is unsupported for User...
python
def speak_phrase(self, text, language, format_audio=None, option=None): """ This method is very similar to the above, the difference between them is that this method creates an object of class TranslateSpeak(having therefore different attributes) and use a...
java
public Object getTag() { Object result = null; if (view != null) { result = view.getTag(); } return result; }
python
def hideFromPublicBundle(self, otpk_pub): """ Hide a one-time pre key from the public bundle. :param otpk_pub: The public key of the one-time pre key to hide, encoded as a bytes-like object. """ self.__checkSPKTimestamp() for otpk in self.__otpks: ...
python
def disableHook(self, msgObj): """ Disable yank-pop. The ``enableHook`` method (see below) connects this method to the ``qtesigKeyseqComplete`` signal to catch consecutive calls to this ``yank-pop`` macro. Once the user issues a key sequence for any other macro but this ...
python
def _init_mask_psf(self): """ smaller frame that encolses all the idex_mask :param idex_mask: :param nx: :param ny: :return: """ if not hasattr(self, '_x_min_psf'): idex_2d = self._idex_mask_2d self._x_min_psf = np.min(np.where(idex...
java
private static boolean setParamFromString(String name, String value) throws ConfigurationException { try { Field field = config.getClass().getDeclaredField(name); String fieldType = field.getType().toString(); if (fieldType.compareToIgnoreCase("int") == 0) { ...
python
def add_traits(self, **traits): """Dynamically add trait attributes to the Widget.""" super(Widget, self).add_traits(**traits) for name, trait in traits.items(): if trait.get_metadata('sync'): self.keys.append(name) self.send_state(name)
java
@Override public void notifyMessageReceived(SQSMessage message) throws JMSException { SQSMessageIdentifier messageIdentifier = SQSMessageIdentifier.fromSQSMessage(message); unAckMessages.put(message.getReceiptHandle(), messageIdentifier); }
java
public int getExternalFieldValue(final String externalFieldName, final JBBPCompiledBlock compiledBlock, final JBBPIntegerValueEvaluator evaluator) { final String normalizedName = JBBPUtils.normalizeFieldNameOrPath(externalFieldName); if (this.externalValueProvider == null) { throw new JBBPEvalException("R...
java
@Override public InputStream getResourceAsStream(String name) { byte[] b = null; try { Asset resource = AssetCache.getAsset(mdwPackage.getName() + "/" + name); if (resource != null) b = resource.getRawContent(); if (b == null) b = f...
python
def GetAllUserSummaries(): """Returns a string containing summary info for all GRR users.""" grr_api = maintenance_utils.InitGRRRootAPI() user_wrappers = sorted(grr_api.ListGrrUsers(), key=lambda x: x.username) summaries = [_Summarize(w.data) for w in user_wrappers] return "\n\n".join(summaries)
java
public JType generate(JCodeModel codeModel, String className, String packageName, URL schemaUrl) { JPackage jpackage = codeModel._package(packageName); ObjectNode schemaNode = readSchema(schemaUrl); return ruleFactory.getSchemaRule().apply(className, schemaNode, null, jpackage, new Schema(nul...
java
public static MultiLineString removeDuplicateCoordinates(MultiLineString multiLineString, double tolerance) throws SQLException { ArrayList<LineString> lines = new ArrayList<LineString>(); for (int i = 0; i < multiLineString.getNumGeometries(); i++) { LineString line = (LineString) multiLine...
java
@BetaApi public final Policy getIamPolicyImage(ProjectGlobalImageResourceName resource) { GetIamPolicyImageHttpRequest request = GetIamPolicyImageHttpRequest.newBuilder() .setResource(resource == null ? null : resource.toString()) .build(); return getIamPolicyImage(request); ...
python
def run_job(): """Takes an async object and executes its job.""" async = get_current_async() async_options = async.get_options() job = async_options.get('job') if not job: raise Exception('This async contains no job to execute!') __, args, kwargs = job if args is None: arg...
java
public static tunnelip6_stats get(nitro_service service, String tunnelip6) throws Exception{ tunnelip6_stats obj = new tunnelip6_stats(); obj.set_tunnelip6(tunnelip6); tunnelip6_stats response = (tunnelip6_stats) obj.stat_resource(service); return response; }
java
public alluxio.grpc.WorkerNetAddressOrBuilder getWorkerAddressOrBuilder() { return workerAddress_ == null ? alluxio.grpc.WorkerNetAddress.getDefaultInstance() : workerAddress_; }
java
public void addListeners() { String strMessage = "Create new user account"; String strTerms = this.getProperty("terms"); // Terms resource EY if (strTerms == null) strTerms = "terms"; if (this.getTask() != null) if (this.getTask().getApplication() != null) ...
python
def read_from_list_with_ids(self, lines): """ Read text fragments from a given list of tuples:: [(id_1, text_1), (id_2, text_2), ..., (id_n, text_n)]. :param list lines: the list of ``[id, text]`` fragments (see above) """ self.log(u"Reading text fragments from list...
python
def receiver_directory(self): """Parent directory of the downloads directory""" if self._receiver_directory is None: self._receiver_directory = self.downloads_directory.parent return self._receiver_directory
python
def main(api_endpoint, credentials, device_model_id, device_id, lang, verbose, input_audio_file, output_audio_file, block_size, grpc_deadline, *args, **kwargs): """File based sample for the Google Assistant API. Examples: $ python -m audiofileinput -i <input file> -o <output fi...
java
public static Date parse(String dateString) throws ParseException { // Return null if no date provided if (dateString == null || dateString.isEmpty()) return null; // Parse date according to format DateFormat dateFormat = new SimpleDateFormat(DateField.FORMAT); ...
python
def stream(self, transaction=None): """Read the documents in this collection. This sends a ``RunQuery`` RPC and then returns an iterator which consumes each document returned in the stream of ``RunQueryResponse`` messages. .. note:: The underlying stream of response...
python
def _EccZmaxRperiRap(self,*args,**kwargs): """ NAME: EccZmaxRperiRap (_EccZmaxRperiRap) PURPOSE: evaluate the eccentricity, maximum height above the plane, peri- and apocenter in the Staeckel approximation INPUT: Either: a) R,vR,vT,z,vz[,phi...
python
def parse_events(cls, ev_args, parent_ctx): """ Capture the events sent to :meth:`.XSO.parse_events`, including the initial `ev_args` to a list and call :meth:`_set_captured_events` on the result of :meth:`.XSO.parse_events`. Like the method it overrides, :meth:`parse_ev...
python
def build_return_url(self): ''' If the Tool Consumer sent a return URL, add any set messages to the URL. ''' if not self.launch_presentation_return_url: return None lti_message_fields = ['lti_errormsg', 'lti_errorlog', 'lti_msg',...
java
private void setRequestLanguages(WbGetEntitiesActionData properties) { if (this.filter.excludeAllLanguages() || this.filter.getLanguageFilter() == null) { return; } properties.languages = ApiConnection.implodeObjects(this.filter .getLanguageFilter()); }
java
@Override public final void setHasName(final CatalogGs pHasName) { this.hasName = pHasName; if (this.itsId == null) { this.itsId = new IdI18nCatalogGs(); } this.itsId.setHasName(this.hasName); }
python
def p_ExtendedAttributeArgList(p): """ExtendedAttributeArgList : IDENTIFIER "(" ArgumentList ")" """ p[0] = model.ExtendedAttribute( value=model.ExtendedAttributeValue(name=p[1], arguments=p[3]))
java
void storeBlock(BlockId blockId, ByteBuffer block) throws IOException { synchronized (m_accessLock) { if (m_blockPathMap.containsKey(blockId)) { throw new IllegalArgumentException("Request to store block that is already stored: " + ...
python
def _writeSentenceInBlock(sentence, blockID, sentenceID): '''writes the sentence in a block to a file with the id''' with open("sentenceIDs.txt", "a") as fp: fp.write("sentenceID: "+str(blockID)+"_"+str(sentenceID)+"\n") fp.write("sentence string: "+sentence+"\n") fp.write("\n")
java
public final void mLCURLY() throws RecognitionException { try { int _type = LCURLY; int _channel = DEFAULT_TOKEN_CHANNEL; // druidG.g:575:8: ( '{' ) // druidG.g:575:11: '{' { match('{'); } state.type = _type; state.channel = _channel; } finally { // do for sure before leaving } ...
python
def id_lookup(paper_id, idtype): """Take an ID of type PMID, PMCID, or DOI and lookup the other IDs. If the DOI is not found in Pubmed, try to obtain the DOI by doing a reverse-lookup of the DOI in CrossRef using article metadata. Parameters ---------- paper_id : str ID of the article....
python
def _get_all_offsets(self, offset_ns=None): """ returns all token offsets of this document as a generator of (token node ID str, character onset int, character offset int) tuples. Parameters ---------- offset_ns : str or None The namespace from which the offs...
python
def WriteSignedBinary(binary_urn, binary_content, private_key, public_key, chunk_size = 1024, token = None): """Signs a binary and saves it to the datastore. If a signed binary with the given URN already e...
python
def image_from_file(filename, remote_addr=None, cert=None, key=None, verify_cert=True, aliases=None, public=False, saltenv='base', _raw=False): ''' Create a...
java
static void Print(AddressBook addressBook) { for (Person person: addressBook.getPeopleList()) { System.out.println("Person ID: " + person.getId()); System.out.println(" Name: " + person.getName()); if (!person.getEmail().isEmpty()) { System.out.println(" E-mail address: " + person.getEma...
python
def mqp_lm1b_base(): """Series of architectures for language modeling.""" hparams = mtf_transformer2.mtf_unitransformer_base() hparams.d_model = 1024 hparams.max_length = 256 hparams.batch_size = 256 # Parameters for my_layer_stack() hparams.num_hidden_layers = 6 hparams.d_ff = 8192 hparams.d_kv = 128...
python
def reindex(report): """Reindex report so that 'TOTAL' is the last row""" index = list(report.index) i = index.index('TOTAL') return report.reindex(index[:i] + index[i+1:] + ['TOTAL'])
python
def load_velo_scan(file): """Load and parse a velodyne binary file.""" scan = np.fromfile(file, dtype=np.float32) return scan.reshape((-1, 4))
java
protected void openEditDialog(boolean isNew, String mode) { // create a form to submit a post request to the editor JSP Map<String, String> formValues = new HashMap<String, String>(); if (m_editableData.getSitePath() != null) { formValues.put("resource", m_editableData.getSitePath()...
python
def get_my_item_id_from_section(self, section): """returns the first item associated with this magic Part Id in the Section""" for question_map in section._my_map['questions']: if question_map['assessmentPartId'] == str(self.get_id()): return section.get_question(question_map...
java
public Observable<Page<VirtualNetworkInner>> listByResourceGroupAsync(final String resourceGroupName) { return listByResourceGroupWithServiceResponseAsync(resourceGroupName) .map(new Func1<ServiceResponse<Page<VirtualNetworkInner>>, Page<VirtualNetworkInner>>() { @Override ...
java
private String getPrefix() { final String prefix; if (loader.isPresent()) { prefix = loader.get().getPackage().getName().replace(Constant.DOT, File.separator); } else { prefix = resourcesDir; } return prefix; }
java
private int getDatastreamPaneIndex(String id) { int index = -1; for (int i=0; i < m_datastreamPanes.length; i++) { if(m_datastreamPanes[i].getItemId().equals(id)){ index = i; break; } } return index; }
python
def execute(self, X): """Execute the program according to X. Parameters ---------- X : {array-like}, shape = [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features. Returns ----...
java
public Option defaultValue(String defaultValue) throws RequiredParametersException { if (this.choices.isEmpty()) { return this.setDefaultValue(defaultValue); } else { if (this.choices.contains(defaultValue)) { return this.setDefaultValue(defaultValue); } else { throw new RequiredParametersException...
java
@com.fasterxml.jackson.annotation.JsonProperty("ErrorDetails") public java.util.List<ErrorDetail> getErrorDetails() { return errorDetails; }
python
def process_superclass(self, entity: List[dict]) -> List[dict]: """ Replaces ILX ID with superclass ID """ superclass = entity.pop('superclass') label = entity['label'] if not superclass.get('ilx_id'): raise self.SuperClassDoesNotExistError( f'Superclass not g...
python
def rotate2d(self, theta, origin=None, axis='z', radians=False): ''' :theta: float radians to rotate self around origin :origin: optional Point, defaults to 0,0,0 Returns a Point rotated by :theta: around :origin:. ''' origin = Point._convert(origin) delta = se...
java
public static synchronized short getNearestColor( final Color awtColor) { if (triplets == null) { triplets = HSSFColor.getTripletHash(); } if (triplets == null || triplets.isEmpty()) { System.out.println("Unable to get triplet hashtable"); return ...
python
def render_html(input_text, **context): """ A module-level convenience method that creates a default bbcode parser, and renders the input string as HTML. """ global g_parser if g_parser is None: g_parser = Parser() return g_parser.format(input_text, **context)
python
def set_backup_heartbeat(self, interface_id): """ Set this interface as the backup heartbeat interface. Clusters and Master NGFW Engines only. :param str,int interface_id: interface as backup :raises InterfaceNotFound: specified interface is not found :raises Upd...
python
def hashjoin(left, right, key=None, lkey=None, rkey=None, cache=True, lprefix=None, rprefix=None): """Alternative implementation of :func:`petl.transform.joins.join`, where the join is executed by constructing an in-memory lookup for the right hand table, then iterating over rows from the left ...
python
def rgb2hex(rgb): """ Convert RGB(A) tuple to hex. """ if len(rgb) > 3: rgb = rgb[:-1] return "#{0:02x}{1:02x}{2:02x}".format(*(int(v*255) for v in rgb))
python
def setup(parser): """Add common sampling options to CLI parser. Parameters ---------- parser : argparse object Returns ---------- Updated argparse object """ parser.add_argument( '-p', '--paramfile', type=str, required=True, help='Parameter Range File') parser....
java
@SuppressWarnings("SameParameterValue") // Using same method params as in restrictStateBounds @Nullable State restrictStateBoundsCopy(State state, State prevState, float pivotX, float pivotY, boolean allowOverscroll, boolean allowOverzoom, boolean restrictRotation) { tmpState.set(state); ...
python
def extendInformation(self, response): """ This extends the objects stdout and stderr by 'response's stdout and stderr """ if response.stdout: self.stdout += '\r\n' + response.stdout if response.stderr: self.stderr += '\r\n' + response.stderr
java
protected void writeOperand (final float real) throws IOException { final int byteCount = NumberFormatUtil.formatFloatFast (real, formatDecimal.getMaximumFractionDigits (), formatBuffer); i...
python
def _find_classes_param(self): """ Searches the wrapped model for the classes_ parameter. """ for attr in ["classes_"]: try: return getattr(self.estimator, attr) except AttributeError: continue raise YellowbrickTypeError( ...
python
def splittermixerfieldlists(data, commdct, objkey): """docstring for splittermixerfieldlists""" objkey = objkey.upper() objindex = data.dtls.index(objkey) objcomms = commdct[objindex] theobjects = data.dt[objkey] fieldlists = [] for theobject in theobjects: fieldlist = list(range(1, ...
java
static void addToRecentConnectionSettings(Hashtable settings, ConnectionSetting newSetting) throws IOException { settings.put(newSetting.getName(), newSetting); ConnectionDialogCommon.storeRecentConnectionSettings(settings); }
java
public com.google.privacy.dlp.v2.PrivacyMetric.LDiversityConfigOrBuilder getLDiversityConfigOrBuilder() { if (typeCase_ == 4) { return (com.google.privacy.dlp.v2.PrivacyMetric.LDiversityConfig) type_; } return com.google.privacy.dlp.v2.PrivacyMetric.LDiversityConfig.getDefaultInstance(); }
python
def ensure_pyplot(self): """ Ensures that pyplot has been imported into the embedded IPython shell. Also, makes sure to set the backend appropriately if not set already. """ # We are here if the @figure pseudo decorator was used. Thus, it's # possible that we could be h...
python
def Header(self): """ Get the block header. Returns: neo.Core.Header: """ if not self._header: self._header = Header(self.PrevHash, self.MerkleRoot, self.Timestamp, self.Index, self.ConsensusData, self.NextConsensus, self...
java
public String getRemoteAddr() { String addr = "127.0.0.1"; HttpConnection connection = getHttpConnection(); if (connection != null) { addr = connection.getRemoteAddr(); if (addr == null) addr = connection.getRemoteHost(); } return addr; }
python
def get_torque_state(self): """ get the torque state of motor Returns: bool: True if torque is enabled, else False """ data = [] data.append(0x09) data.append(self.servoid) data.append(RAM_READ_REQ) data.append(TORQUE_CONTROL_RAM) data...
java
public static boolean setCurrentFile(File databaseDir, long descriptorNumber) throws IOException { String manifest = descriptorFileName(descriptorNumber); String temp = tempFileName(descriptorNumber); File tempFile = new File(databaseDir, temp); writeStringToFileSync(man...
java
@Override public List<com.enioka.jqm.api.Deliverable> getJobDeliverables(int idJob) { DbConn cnx = null; try { cnx = getDbSession(); // TODO: no intermediate entity here: directly SQL => API object. List<Deliverable> deliverables = Deliverable.select...
java
public ValueInterval<T, I, V> withValue(V value) { return new ValueInterval<>(this.interval, value); }
java
public void setTime(final long millis) { int millisOfDay = ISOChronology.getInstanceUTC().millisOfDay().get(millis); setMillis(getChronology().millisOfDay().set(getMillis(), millisOfDay)); }
python
def _call(callback, args=[], kwargs={}): """ Calls a callback with optional args and keyword args lists. This method exists so we can inspect the `_max_calls` attribute that's set by `_on`. If this value is None, the callback is considered to have no limit. Otherwise, an integer value is expected an...
java
@Override public <T> T convertValues(Collection<String> input, Class<T> rawType, Type type, String defaultValue) throws IllegalArgumentException { if (rawType.isArray()) { if (input == null) { input = getMultipleValues(defaultValue, null); } return createA...
java
public boolean removeCustomer(Long customerId) { Customer customer = getCustomer(customerId); if(customer != null){ customerRepository.delete(customer); return true; } return false; }
python
def connect(self): """Connect to wdb server""" log.info('Connecting socket on %s:%d' % (self.server, self.port)) tries = 0 while not self._socket and tries < 10: try: time.sleep(.2 * tries) self._socket = Socket((self.server, self.port)) ...