language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def ReadAllFlowObjects(self, client_id = None, min_create_time = None, max_create_time = None, include_child_flows = True, cursor=None): """Returns all flow objects.""" conditions = [] args = [] if client_id is not None: conditions.append("client_id = %s") args.append(db_utils.ClientIDToInt(client_id)) if min_create_time is not None: conditions.append("timestamp >= FROM_UNIXTIME(%s)") args.append(mysql_utils.RDFDatetimeToTimestamp(min_create_time)) if max_create_time is not None: conditions.append("timestamp <= FROM_UNIXTIME(%s)") args.append(mysql_utils.RDFDatetimeToTimestamp(max_create_time)) if not include_child_flows: conditions.append("parent_flow_id IS NULL") query = "SELECT {} FROM flows".format(self.FLOW_DB_FIELDS) if conditions: query += " WHERE " + " AND ".join(conditions) cursor.execute(query, args) return [self._FlowObjectFromRow(row) for row in cursor.fetchall()]
java
public static Key[] globalKeysOfClass(final Class clz) { return KeySnapshot.globalSnapshot().filter(new KeySnapshot.KVFilter() { @Override public boolean filter(KeySnapshot.KeyInfo k) { return Value.isSubclassOf(k._type, clz); } }).keys(); }
java
public void subtractValue(int idx, double val) { int c = get1dConfigIdx(idx); values.set(c, s.minus(values.get(c), val)); }
python
def set_rate(self, param): """ Models "Rate Command" functionality of device. Sets the target rate of temperature change. :param param: Rate of temperature change in C/min, multiplied by 100, as a string. Must be positive. :return: Empty string. """ # TODO: Is not having leading zeroes / 4 digits an error? rate = int(param) if 1 <= rate <= 15000: self.device.temperature_rate = rate / 100.0 return ""
python
def set(self, key, value=None, dir=False, refresh=False, ttl=None, prev_value=None, prev_index=None, prev_exist=None, timeout=None): """Requests to create an ordered node into a node by the given key.""" url = self.make_key_url(key) data = self.build_args({ 'value': (six.text_type, value), 'dir': (bool, dir or None), 'refresh': (bool, refresh or None), 'ttl': (int, ttl), 'prevValue': (six.text_type, prev_value), 'prevIndex': (int, prev_index), 'prevExist': (bool, prev_exist), }) try: res = self.session.put(url, data=data, timeout=timeout) except: self.erred() return self.wrap_response(res)
java
private TimephasedCost[] splitFirstDay(ProjectCalendar calendar, TimephasedCost assignment) { TimephasedCost[] result = new TimephasedCost[2]; // // Retrieve data used to calculate the pro-rata work split // Date assignmentStart = assignment.getStart(); Date assignmentFinish = assignment.getFinish(); Duration calendarWork = calendar.getWork(assignmentStart, assignmentFinish, TimeUnit.MINUTES); if (calendarWork.getDuration() != 0) { // // Split the first day // Date splitFinish; double splitCost; if (calendar.isWorkingDate(assignmentStart)) { Date splitStart = assignmentStart; Date splitFinishTime = calendar.getFinishTime(splitStart); splitFinish = DateHelper.setTime(splitStart, splitFinishTime); Duration calendarSplitWork = calendar.getWork(splitStart, splitFinish, TimeUnit.MINUTES); splitCost = (assignment.getTotalAmount().doubleValue() * calendarSplitWork.getDuration()) / calendarWork.getDuration(); TimephasedCost split = new TimephasedCost(); split.setStart(splitStart); split.setFinish(splitFinish); split.setTotalAmount(Double.valueOf(splitCost)); result[0] = split; } else { splitFinish = assignmentStart; splitCost = 0; } // // Split the remainder // Date splitStart = calendar.getNextWorkStart(splitFinish); splitFinish = assignmentFinish; TimephasedCost split; if (splitStart.getTime() > splitFinish.getTime()) { split = null; } else { splitCost = assignment.getTotalAmount().doubleValue() - splitCost; split = new TimephasedCost(); split.setStart(splitStart); split.setFinish(splitFinish); split.setTotalAmount(Double.valueOf(splitCost)); split.setAmountPerDay(assignment.getAmountPerDay()); } result[1] = split; } return result; }
java
protected <E extends Throwable, V extends ATSecDBValidator> Set<ATError> handleException(E e, Log logger, V validator, String key, String suffix, String defaultMessagePrefix) { return handleException(e, logger, validator, key, suffix, defaultMessagePrefix, new Object[] {}); }
java
static String [] searchJrtFSForClasses( URL url ) throws IOException { try { Path path = FileSystems.getFileSystem(new URI("jrt:/")).getPath("modules", url.getPath()); return Files.walk(path).map(Path::toString) .filter(BshClassPath::isClassFileName) .map(BshClassPath::canonicalizeClassName) .toArray(String[]::new); } catch (URISyntaxException e) { /* ignore */ } return new String[0]; }
java
public Object setState(final Object state) { final Object oldState = this.state; this.state = state; return oldState; }
java
@SuppressWarnings("unchecked") public static boolean findClass(String className) { try { return getClassLoader().loadClass(className) != null; } catch (ClassNotFoundException e) { return false; } catch (NoClassDefFoundError e) { return false; } }
java
private void handleAttlistDecl() throws XMLStreamException { /* This method will handle PEs that contain the whole element * name. Since it's illegal to have partials, we can then proceed * to just use normal parsing... */ char c = skipObligatoryDtdWs(); final PrefixedName elemName = readDTDQName(c); /* Ok, event needs to know its exact starting point (opening '<' * char), let's get that info now (note: data has been preserved * earlier) */ Location loc = getStartLocation(); // Ok, where's our element? HashMap<PrefixedName,DTDElement> m = getElementMap(); DTDElement elem = m.get(elemName); if (elem == null) { // ok, need a placeholder // Let's add ATTLIST location as the temporary location too elem = DTDElement.createPlaceholder(mConfig, loc, elemName); m.put(elemName, elem); } // Ok, need to loop to get all attribute defs: int index = 0; while (true) { /* White space is optional, if we get the closing '>' char; * otherwise it's obligatory. */ c = getNextExpanded(); if (isSpaceChar(c)) { // Let's push it back in case it's LF, to be handled properly --mInputPtr; c = skipDtdWs(true); /* 26-Jan-2006, TSa: actually there are edge cases where * we may get the attribute name right away (esp. * with PEs...); so let's defer possible error for * later on. Should not allow missing spaces between * attribute declarations... ? */ /* } else if (c != '>') { throwDTDUnexpectedChar(c, "; excepted either '>' closing ATTLIST declaration, or a white space character separating individual attribute declarations"); */ } if (c == '>') { break; } handleAttrDecl(elem, c, index, loc); ++index; } }
python
def poke_64(library, session, address, data): """Write an 64-bit value from the specified address. Corresponds to viPoke64 function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param address: Source address to read the value. :param data: value to be written to the bus. :return: return value of the library call. :rtype: :class:`pyvisa.constants.StatusCode` """ return library.viPoke64(session, address, data)
java
private boolean lookAheadFor(char expect) { boolean matched = false; int c; while (true) { c = stream.getChar(); if (c == ' ') { continue; } else if (c == expect) { matched = true; break; } else { break; } } stream.ungetChar(c); return matched; }
python
def trainSequences(sequences, exp, idOffset=0): """Train the network on all the sequences""" for seqId in sequences: # Make sure we learn enough times to deal with high order sequences and # remove extra predictions. iterations = 3*len(sequences[seqId]) for p in range(iterations): # Ensure we generate new random location for each sequence presentation s = sequences.provideObjectsToLearn([seqId]) objectSDRs = dict() objectSDRs[seqId + idOffset] = s[seqId] exp.learnObjects(objectSDRs, reset=False) # TM needs reset between sequences, but not other regions exp.TMColumns[0].reset() # L2 needs resets when we switch to new object exp.sendReset()
python
def _accept(random_sample: float, cost_diff: float, temp: float) -> Tuple[bool, float]: """Calculates probability and draws if solution should be accepted. Based on exp(-Delta*E/T) formula. Args: random_sample: Uniformly distributed random number in the range [0, 1). cost_diff: Cost difference between new and previous solutions. temp: Current temperature. Returns: Tuple of boolean and float, with boolean equal to True if solution is accepted, and False otherwise. The float value is acceptance probability. """ exponent = -cost_diff / temp if exponent >= 0.0: return True, 1.0 else: probability = math.exp(exponent) return probability > random_sample, probability
python
def list_event_types(self, publisher_id): """ListEventTypes. Get the event types for a specific publisher. :param str publisher_id: ID for a publisher. :rtype: [EventTypeDescriptor] """ route_values = {} if publisher_id is not None: route_values['publisherId'] = self._serialize.url('publisher_id', publisher_id, 'str') response = self._send(http_method='GET', location_id='db4777cd-8e08-4a84-8ba3-c974ea033718', version='5.0', route_values=route_values) return self._deserialize('[EventTypeDescriptor]', self._unwrap_collection(response))
python
def run_std_server(self): """Starts a TensorFlow server and joins the serving thread. Typically used for parameter servers. Raises: ValueError: if not enough information is available in the estimator's config to create a server. """ config = tf.estimator.RunConfig() server = tf.train.Server( config.cluster_spec, job_name=config.task_type, task_index=config.task_id, protocol=config.protocol) server.join()
java
@Nonnull private static Image makeBadgedImage(@Nonnull final Image original){ final BufferedImage result = new BufferedImage(original.getWidth(null), original.getHeight(null), BufferedImage.TYPE_INT_ARGB); final Graphics2D gfx = result.createGraphics(); try{ gfx.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); gfx.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); gfx.drawImage(original, 0, 0, null); final Image badge = original.getWidth(null)>16 ? BADGE_ICON_16 : BADGE_ICON_10; gfx.drawImage(badge, result.getWidth()-badge.getWidth(null),result.getHeight()- badge.getHeight(null), null); }finally{ gfx.dispose(); } return result; }
python
def add_subroute(self, pattern: str) -> "URLDispatcher": """ create new URLDispatcher routed by pattern """ return URLDispatcher( urlmapper=self.urlmapper, prefix=self.prefix + pattern, applications=self.applications, extra_environ=self.extra_environ)
java
public static double method2(ICountFingerprint fp1, ICountFingerprint fp2) { long maxSum = 0, minSum = 0; int i = 0, j = 0; while (i < fp1.numOfPopulatedbins() || j < fp2.numOfPopulatedbins()) { Integer hash1 = i < fp1.numOfPopulatedbins() ? fp1.getHash(i) : null; Integer hash2 = j < fp2.numOfPopulatedbins() ? fp2.getHash(j) : null; Integer count1 = i < fp1.numOfPopulatedbins() ? fp1.getCount(i) : null; Integer count2 = j < fp2.numOfPopulatedbins() ? fp2.getCount(j) : null; if (count2 == null || (hash1 != null && hash1 < hash2)) { maxSum += count1; i++; continue; } if (count1 == null || (hash2 != null && hash1 > hash2)) { maxSum += count2; j++; continue; } if (hash1.equals(hash2)) { maxSum += Math.max(count1, count2); minSum += Math.min(count1, count2); i++; j++; } } return ((double) minSum) / maxSum; }
python
def _execute_lua(self, keys, args, client): """ Sets KEYS and ARGV alongwith redis.call() function in lua globals and executes the lua redis script """ lua, lua_globals = Script._import_lua(self.load_dependencies) lua_globals.KEYS = self._python_to_lua(keys) lua_globals.ARGV = self._python_to_lua(args) def _call(*call_args): # redis-py and native redis commands are mostly compatible argument # wise, but some exceptions need to be handled here: if str(call_args[0]).lower() == 'lrem': response = client.call( call_args[0], call_args[1], call_args[3], # "count", default is 0 call_args[2]) else: response = client.call(*call_args) return self._python_to_lua(response) lua_globals.redis = {"call": _call} return self._lua_to_python(lua.execute(self.script), return_status=True)
java
private void setMandatoryAttachments(CareerDevelopmentAwardAttachments careerDevelopmentAwardAttachments) { if (careerDevelopmentAwardAttachments.getResearchStrategy() == null) { careerDevelopmentAwardAttachments.setResearchStrategy(ResearchStrategy.Factory.newInstance()); } }
python
def get(self, key): """Gets a value by a key. Args: key (str): Key to retrieve the value. Returns: Retrieved value. """ self._create_file_if_none_exists() with open(self.filename, 'rb') as file_object: cache_pickle = pickle.load(file_object) val = cache_pickle.get(key, None) return val
java
public int prepare(Xid xid) throws XAException { if (!warned) { log.prepareCalledOnLocaltx(); } warned = true; return XAResource.XA_OK; }
java
public void marshall(DeleteHsmRequest deleteHsmRequest, ProtocolMarshaller protocolMarshaller) { if (deleteHsmRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deleteHsmRequest.getClusterId(), CLUSTERID_BINDING); protocolMarshaller.marshall(deleteHsmRequest.getHsmId(), HSMID_BINDING); protocolMarshaller.marshall(deleteHsmRequest.getEniId(), ENIID_BINDING); protocolMarshaller.marshall(deleteHsmRequest.getEniIp(), ENIIP_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
python
def get_data_path(module_id: str) -> Path: """ Get the path for persistent storage of a module. This method creates the queried path if not existing. Args: module_id (str): Module ID Returns: The data path of indicated module. """ profile = coordinator.profile data_path = get_base_path() / 'profiles' / profile / module_id if not data_path.exists(): data_path.mkdir(parents=True) return data_path
python
def get_train_op(loss, params): """Generate training operation that updates variables based on loss.""" with tf.variable_scope("get_train_op"): mlperf_log.transformer_print( key=mlperf_log.OPT_LR_WARMUP_STEPS, value=params.learning_rate_warmup_steps) learning_rate = get_learning_rate( params.learning_rate, params.hidden_size, params.learning_rate_warmup_steps) log_id = mlperf_log.resnet_print(key=mlperf_log.OPT_LR, deferred=True) learning_rate = tf_mlperf_log.log_deferred(op=learning_rate, log_id=log_id, every_n=100) # Create optimizer. Use LazyAdamOptimizer from TF contrib, which is faster # than the TF core Adam optimizer. mlperf_log.transformer_print(key=mlperf_log.OPT_NAME, value=mlperf_log.LAZY_ADAM) mlperf_log.transformer_print(key=mlperf_log.OPT_HP_ADAM_BETA1, value=params.optimizer_adam_beta1) mlperf_log.transformer_print(key=mlperf_log.OPT_HP_ADAM_BETA2, value=params.optimizer_adam_beta2) mlperf_log.transformer_print(key=mlperf_log.OPT_HP_ADAM_EPSILON, value=params.optimizer_adam_epsilon) optimizer = tf.contrib.opt.LazyAdamOptimizer( learning_rate, beta1=params.optimizer_adam_beta1, beta2=params.optimizer_adam_beta2, epsilon=params.optimizer_adam_epsilon) # Calculate and apply gradients using LazyAdamOptimizer. global_step = tf.train.get_global_step() tvars = tf.trainable_variables() gradients = optimizer.compute_gradients( loss, tvars, colocate_gradients_with_ops=True) train_op = optimizer.apply_gradients( gradients, global_step=global_step, name="train") # Save gradient norm to Tensorboard tf.summary.scalar("global_norm/gradient_norm", tf.global_norm(list(zip(*gradients))[0])) return train_op
java
public static int correctDCH( int N , int messageNoMask , int generator , int totalBits, int dataBits) { int bestHamming = 255; int bestMessage = -1; int errorBits = totalBits-dataBits; // exhaustively check all possibilities for (int i = 0; i < N; i++) { int test = i << errorBits; test = test ^ bitPolyModulus(test,generator,totalBits,dataBits); int distance = DescriptorDistance.hamming(test^messageNoMask); // see if it found a better match if( distance < bestHamming ) { bestHamming = distance; bestMessage = i; } else if( distance == bestHamming ) { // ambiguous so reject bestMessage = -1; } } return bestMessage; }
java
public static SipSessionKey getSipSessionKey(final String applicationSessionId, final String applicationName, final Message message, boolean inverted) { if (logger.isDebugEnabled()){ logger.debug("getSipSessionKey - applicationSessionId=" + applicationSessionId + ", applicationName=" + applicationName + ", message=" + message + ", inverted=" + inverted); } if(applicationName == null) { throw new NullPointerException("the application name cannot be null for sip session key creation"); } final ToHeader to = (ToHeader) message.getHeader(ToHeader.NAME); final FromHeader from = (FromHeader) message.getHeader(FromHeader.NAME); // final URI toUri = to.getAddress().getURI(); // final URI fromUri = from.getAddress().getURI(); // String toUriString = null; // String fromURIString = null; // if(toUri.isSipURI()) { // toUriString = encode(((SipUri)toUri)); // } else { // toUriString = toUri.toString(); // } // if(fromUri.isSipURI()) { // fromURIString = encode(((SipUri)fromUri)); // } else { // fromURIString = fromUri.toString(); // } final String toTag = to.getTag(); final String fromTag = from.getTag(); if(inverted) { return new SipSessionKey( toTag, fromTag, ((CallIdHeader) message.getHeader(CallIdHeader.NAME)).getCallId(), applicationSessionId, applicationName); } else { return new SipSessionKey( fromTag, toTag, ((CallIdHeader) message.getHeader(CallIdHeader.NAME)).getCallId(), applicationSessionId, applicationName); } }
python
def _generate_delete_sql(self, delete_keys): """ Generate forward delete operations for SQL items. """ for key in delete_keys: app_label, sql_name = key old_node = self.from_sql_graph.nodes[key] operation = DeleteSQL(sql_name, old_node.reverse_sql, reverse_sql=old_node.sql) sql_deps = [n.key for n in self.from_sql_graph.node_map[key].children] sql_deps.append(key) self.add_sql_operation(app_label, sql_name, operation, sql_deps)
java
public void addMetricsGraph(String title, String value) { if (metrics != null) { Metrics.Graph graph = metrics.createGraph(title); graph.addPlotter(new Metrics.Plotter(value) { @Override public int getValue() { return 1; } }); } }
python
def sasdata2dataframe(self, table: str, libref: str ='', dsopts: dict = None, rowsep: str = '\x01', colsep: str = '\x02', **kwargs) -> '<Pandas Data Frame object>': """ This method exports the SAS Data Set to a Pandas Data Frame, returning the Data Frame object. table - the name of the SAS Data Set you want to export to a Pandas Data Frame libref - the libref for the SAS Data Set. rowsep - the row seperator character to use; defaults to '\n' colsep - the column seperator character to use; defaults to '\t' port - port to use for socket. Defaults to 0 which uses a random available ephemeral port """ dsopts = dsopts if dsopts is not None else {} method = kwargs.pop('method', None) if method and method.lower() == 'csv': return self.sasdata2dataframeCSV(table, libref, dsopts, **kwargs) port = kwargs.get('port', 0) if port==0 and self.sascfg.tunnel: # we are using a tunnel; default to that port port = self.sascfg.tunnel datar = "" if libref: tabname = libref+"."+table else: tabname = table code = "proc sql; create view sasdata2dataframe as select * from "+tabname+self._sb._dsopts(dsopts)+";quit;\n" code += "data _null_; file STDERR;d = open('sasdata2dataframe');\n" code += "lrecl = attrn(d, 'LRECL'); nvars = attrn(d, 'NVARS');\n" code += "lr='LRECL='; vn='VARNUMS='; vl='VARLIST='; vt='VARTYPE=';\n" code += "put lr lrecl; put vn nvars; put vl;\n" code += "do i = 1 to nvars; var = varname(d, i); put var; end;\n" code += "put vt;\n" code += "do i = 1 to nvars; var = vartype(d, i); put var; end;\n" code += "run;" ll = self.submit(code, "text") l2 = ll['LOG'].rpartition("LRECL= ") l2 = l2[2].partition("\n") lrecl = int(l2[0]) l2 = l2[2].partition("VARNUMS= ") l2 = l2[2].partition("\n") nvars = int(l2[0]) l2 = l2[2].partition("\n") varlist = l2[2].split("\n", nvars) del varlist[nvars] l2 = l2[2].partition("VARTYPE=") l2 = l2[2].partition("\n") vartype = l2[2].split("\n", nvars) del vartype[nvars] topts = dict(dsopts) topts['obs'] = 0 topts['firstobs'] = '' code = "data work._n_u_l_l_;output;run;\n" code += "data _null_; set "+tabname+self._sb._dsopts(topts)+" work._n_u_l_l_;put 'FMT_CATS=';\n" for i in range(nvars): code += "_tom = vformatn('"+varlist[i]+"'n);put _tom;\n" code += "run;\nproc delete data=work._n_u_l_l_;run;" ll = self.submit(code, "text") l2 = ll['LOG'].rpartition("FMT_CATS=") l2 = l2[2].partition("\n") varcat = l2[2].split("\n", nvars) del varcat[nvars] try: sock = socks.socket() if self.sascfg.tunnel: sock.bind(('localhost', port)) else: sock.bind(('', port)) port = sock.getsockname()[1] except OSError: print('Error try to open a socket in the sasdata2dataframe method. Call failed.') return None if self.sascfg.ssh: if not self.sascfg.tunnel: host = self.sascfg.hostip #socks.gethostname() else: host = 'localhost' else: host = '' rdelim = "'"+'%02x' % ord(rowsep.encode(self.sascfg.encoding))+"'x" cdelim = "'"+'%02x' % ord(colsep.encode(self.sascfg.encoding))+"'x " code = "" code += "filename sock socket '"+host+":"+str(port)+"' lrecl="+str(self.sascfg.lrecl)+" recfm=v termstr=LF;\n" code += " data _null_; set "+tabname+self._sb._dsopts(dsopts)+";\n file sock dlm="+cdelim+"; put " for i in range(nvars): code += "'"+varlist[i]+"'n " if vartype[i] == 'N': if varcat[i] in self._sb.sas_date_fmts: code += 'E8601DA10. '+cdelim else: if varcat[i] in self._sb.sas_time_fmts: code += 'E8601TM15.6 '+cdelim else: if varcat[i] in self._sb.sas_datetime_fmts: code += 'E8601DT26.6 '+cdelim else: code += 'best32. '+cdelim if not (i < (len(varlist)-1)): code += rdelim code += "; run;\n" sock.listen(1) self._asubmit(code, 'text') r = [] df = None datar = b'' trows = kwargs.get('trows', None) if not trows: trows = 100000 newsock = (0,0) try: newsock = sock.accept() while True: data = newsock[0].recv(4096) if len(data): datar += data else: break data = datar.rpartition(colsep.encode()+rowsep.encode()+b'\n') datap = data[0]+data[1] datar = data[2] datap = datap.decode(self.sascfg.encoding, errors='replace') for i in datap.split(sep=colsep+rowsep+'\n'): if i != '': r.append(tuple(i.split(sep=colsep))) if len(r) > trows: tdf = pd.DataFrame.from_records(r, columns=varlist) for i in range(nvars): if vartype[i] == 'N': if varcat[i] not in self._sb.sas_date_fmts + self._sb.sas_time_fmts + self._sb.sas_datetime_fmts: if tdf.dtypes[tdf.columns[i]].kind not in ('f','u','i','b','B','c','?'): tdf[varlist[i]] = pd.to_numeric(tdf[varlist[i]], errors='coerce') else: if tdf.dtypes[tdf.columns[i]].kind not in ('M'): tdf[varlist[i]] = pd.to_datetime(tdf[varlist[i]], errors='coerce') else: tdf[varlist[i]].replace(' ', np.NaN, True) if df is not None: df = df.append(tdf, ignore_index=True) else: df = tdf r = [] except: print("sasdata2dataframe was interupted. Trying to return the saslog instead of a data frame.") if newsock[0]: newsock[0].shutdown(socks.SHUT_RDWR) newsock[0].close() sock.close() ll = self.submit("", 'text') return ll['LOG'] newsock[0].shutdown(socks.SHUT_RDWR) newsock[0].close() sock.close() if len(r) > 0 or df is None: tdf = pd.DataFrame.from_records(r, columns=varlist) for i in range(nvars): if vartype[i] == 'N': if varcat[i] not in self._sb.sas_date_fmts + self._sb.sas_time_fmts + self._sb.sas_datetime_fmts: if tdf.dtypes[tdf.columns[i]].kind not in ('f','u','i','b','B','c','?'): tdf[varlist[i]] = pd.to_numeric(tdf[varlist[i]], errors='coerce') else: if tdf.dtypes[tdf.columns[i]].kind not in ('M'): tdf[varlist[i]] = pd.to_datetime(tdf[varlist[i]], errors='coerce') else: tdf[varlist[i]].replace(' ', np.NaN, True) if df is not None: df = df.append(tdf, ignore_index=True) else: df = tdf return df
python
def load_user(): """Read user config file and return it as a dict.""" config_path = get_user_config_path() config = {} # TODO: This may be overkill and too slow just for reading a config file with open(config_path) as f: code = compile(f.read(), config_path, 'exec') exec(code, config) keys = list(six.iterkeys(config)) for k in keys: if k.startswith('_'): del config[k] return config
java
@RequirePOST public HttpResponse doUpgrade(StaplerRequest req, StaplerResponse rsp) { final String thruVerParam = req.getParameter("thruVer"); final VersionNumber thruVer = thruVerParam.equals("all") ? null : new VersionNumber(thruVerParam); saveAndRemoveEntries(new Predicate<Map.Entry<SaveableReference, VersionRange>>() { @Override public boolean apply(Map.Entry<SaveableReference, VersionRange> entry) { VersionNumber version = entry.getValue().max; return version != null && (thruVer == null || !version.isNewerThan(thruVer)); } }); return HttpResponses.forwardToPreviousPage(); }
python
def _parse_json(self, resources, exactly_one=True): """ Parse type, words, latitude, and longitude and language from a JSON response. """ code = resources['status'].get('code') if code: # https://docs.what3words.com/api/v2/#errors exc_msg = "Error returned by What3Words: %s" % resources['status']['message'] if code == 401: raise exc.GeocoderAuthenticationFailure(exc_msg) raise exc.GeocoderQueryError(exc_msg) def parse_resource(resource): """ Parse record. """ if 'geometry' in resource: words = resource['words'] position = resource['geometry'] latitude, longitude = position['lat'], position['lng'] if latitude and longitude: latitude = float(latitude) longitude = float(longitude) return Location(words, (latitude, longitude), resource) else: raise exc.GeocoderParseError('Error parsing result.') location = parse_resource(resources) if exactly_one: return location else: return [location]
java
public Observable<Void> resendRequestEmailsAsync(String resourceGroupName, String certificateOrderName, String name) { return resendRequestEmailsWithServiceResponseAsync(resourceGroupName, certificateOrderName, name).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
java
@Override public String remove(Object key) { String result = m_configurationStrings.remove(key); m_configurationObjects.remove(key); return result; }
java
protected ConnectionListener validateConnectionListener(Collection<ConnectionListener> listeners, ConnectionListener cl, int newState) { ManagedConnectionFactory mcf = pool.getConnectionManager().getManagedConnectionFactory(); if (mcf instanceof ValidatingManagedConnectionFactory) { ValidatingManagedConnectionFactory vcf = (ValidatingManagedConnectionFactory)mcf; try { Set candidateSet = Collections.singleton(cl.getManagedConnection()); candidateSet = vcf.getInvalidConnections(candidateSet); if (candidateSet != null && !candidateSet.isEmpty()) { if (Tracer.isEnabled()) Tracer.destroyConnectionListener(pool.getConfiguration().getId(), this, cl, false, false, true, false, false, false, false, Tracer.isRecordCallstacks() ? new Throwable("CALLSTACK") : null); destroyAndRemoveConnectionListener(cl, listeners); } else { cl.validated(); if (cl.changeState(VALIDATION, newState)) { return cl; } else { if (Tracer.isEnabled()) Tracer.destroyConnectionListener(pool.getConfiguration().getId(), this, cl, false, false, true, false, false, false, false, Tracer.isRecordCallstacks() ? new Throwable("CALLSTACK") : null); destroyAndRemoveConnectionListener(cl, listeners); } } } catch (ResourceException re) { if (Tracer.isEnabled()) Tracer.destroyConnectionListener(pool.getConfiguration().getId(), this, cl, false, false, true, false, false, false, false, Tracer.isRecordCallstacks() ? new Throwable("CALLSTACK") : null); destroyAndRemoveConnectionListener(cl, listeners); } } else { log.debug("mcf is not instance of ValidatingManagedConnectionFactory"); if (cl.changeState(VALIDATION, newState)) { return cl; } else { if (Tracer.isEnabled()) Tracer.destroyConnectionListener(pool.getConfiguration().getId(), this, cl, false, false, true, false, false, false, false, Tracer.isRecordCallstacks() ? new Throwable("CALLSTACK") : null); destroyAndRemoveConnectionListener(cl, listeners); } } return null; }
java
@Nullable public static SSLSession findSslSession(@Nullable Channel channel) { if (channel == null) { return null; } final SslHandler sslHandler = channel.pipeline().get(SslHandler.class); return sslHandler != null ? sslHandler.engine().getSession() : null; }
java
@PostConstruct public synchronized void initialize() { final FwWebDirection direction = assistWebDirection(); final SessionResourceProvider provider = direction.assistSessionResourceProvider(); sessionSharedStorage = prepareSessionSharedStorage(provider); httpSessionArranger = prepareHttpSessionArranger(provider); showBootLogging(); }
java
@MustBeLocked (ELockType.WRITE) @Nonnull protected final IMPLTYPE internalCreateItem (@Nonnull final IMPLTYPE aNewItem) { return internalCreateItem (aNewItem, true); }
java
int addElement(Object element, int column) { if (element == null) throw new NullPointerException("addCell - null argument"); if ((column < 0) || (column > columns)) throw new IndexOutOfBoundsException("addCell - illegal column argument"); if ( !((getObjectID(element) == CELL) || (getObjectID(element) == TABLE)) ) throw new IllegalArgumentException("addCell - only Cells or Tables allowed"); int lColspan = ( (Cell.class.isInstance(element)) ? ((Cell) element).getColspan() : 1); if (!reserve(column, lColspan)) { return -1; } cells[column] = element; currentColumn += lColspan - 1; return column; }
java
public CmsPublishList fillPublishList(CmsRequestContext context, CmsPublishList publishList) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.fillPublishList(dbc, publishList); checkPublishPermissions(dbc, publishList); } catch (CmsTooManyPublishResourcesException e) { throw e; } catch (Exception e) { if (publishList.isDirectPublish()) { dbc.report( null, Messages.get().container( Messages.ERR_GET_PUBLISH_LIST_DIRECT_1, CmsFileUtil.formatResourceNames(context, publishList.getDirectPublishResources())), e); } else { dbc.report( null, Messages.get().container( Messages.ERR_GET_PUBLISH_LIST_PROJECT_1, context.getCurrentProject().getName()), e); } } finally { dbc.clear(); } return publishList; }
python
def is_aka_dora(tile, aka_enabled): """ :param tile: int 136 tiles format :param aka_enabled: depends on table rules :return: boolean """ if not aka_enabled: return False if tile in [FIVE_RED_MAN, FIVE_RED_PIN, FIVE_RED_SOU]: return True return False
java
private boolean matchesFilter(Category cat, List<String> filterList) throws WikiTitleParsingException { String categoryTitle = cat.getTitle().getPlainTitle(); for (String filter : filterList) { if (categoryTitle.startsWith(filter)) { logger.info(categoryTitle + " starts with " + filter + " => removing"); return true; } } return false; }
python
def load_settings(path, setttings_only = True): """ loads the settings that has been save with Script.save_b26. Args: path: path to folder saved by Script.save_b26 setttings_only: if true returns only the settings if the .b26 file contains only a single script Returns: a dictionary with the settings """ # check that path exists if not os.path.exists(path): print(path) raise AttributeError('Path given does not exist!') tag = '_'.join(os.path.basename(os.path.dirname(os.path.abspath(path) + '/')).split('_')[3:]) search_str = os.path.abspath(path)+'/*'+tag +'.b26' fname = glob.glob(search_str) if len(fname)>1: print(('warning more than one .b26 file found, loading ', fname[0])) elif len(fname) == 0: print(('no .b26 file found in folder {:s}, check path !'.format(search_str))) return fname = fname[0] fname = Script.check_filename(fname) settings = load_b26_file(fname)['scripts'] if len(list(settings.keys())) == 1 and setttings_only: settings = settings[list(settings.keys())[0]]['settings'] return settings
python
def _notify_listeners(self, sender, message): """ Notifies listeners of a new message """ uid = message['uid'] msg_topic = message['topic'] self._ack(sender, uid, 'fire') all_listeners = set() for lst_topic, listeners in self.__listeners.items(): if fnmatch.fnmatch(msg_topic, lst_topic): all_listeners.update(listeners) self._ack(sender, uid, 'notice', 'ok' if all_listeners else 'none') try: results = [] for listener in all_listeners: result = listener.handle_message(sender, message['topic'], message['content']) if result: results.append(result) self._ack(sender, uid, 'send', json.dumps(results)) except: self._ack(sender, uid, 'send', "Error")
python
def updateattachmentflags(self, bugid, attachid, flagname, **kwargs): """ Updates a flag for the given attachment ID. Optional keyword args are: status: new status for the flag ('-', '+', '?', 'X') requestee: new requestee for the flag """ # Bug ID was used for the original custom redhat API, no longer # needed though ignore = bugid flags = {"name": flagname} flags.update(kwargs) update = {'ids': [int(attachid)], 'flags': [flags]} return self._proxy.Bug.update_attachment(update)
java
public void marshall(ListSourceCredentialsRequest listSourceCredentialsRequest, ProtocolMarshaller protocolMarshaller) { if (listSourceCredentialsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
java
public int getLength() { int count=0; for (int handle=m_firstChild; handle!=DTM.NULL; handle=m_parentDTM.getNextSibling(handle)) { ++count; } return count; }
java
private boolean hasTemplate(String href) { if (href == null) { return false; } return URI_TEMPLATE_PATTERN.matcher(href).find(); }
java
@Nonnull public static <T> LOiToFltFunctionBuilder<T> oiToFltFunction(Consumer<LOiToFltFunction<T>> consumer) { return new LOiToFltFunctionBuilder(consumer); }
java
public void setExecutionSummaries(java.util.Collection<JobExecutionSummaryForThing> executionSummaries) { if (executionSummaries == null) { this.executionSummaries = null; return; } this.executionSummaries = new java.util.ArrayList<JobExecutionSummaryForThing>(executionSummaries); }
python
def set_dimension(tensor, axis, value): """Set the length of a tensor along the specified dimension. Args: tensor: Tensor to define shape of. axis: Dimension to set the static shape for. value: Integer holding the length. Raises: ValueError: When the tensor already has a different length specified. """ shape = tensor.shape.as_list() if shape[axis] not in (value, None): message = 'Cannot set dimension {} of tensor {} to {}; is already {}.' raise ValueError(message.format(axis, tensor.name, value, shape[axis])) shape[axis] = value tensor.set_shape(shape)
java
@Activate protected void activate(ComponentContext context) { if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) Tr.event(tc, "activate", context); }
java
public static void addManifestLocations(VirtualFile file, List<VirtualFile> paths) throws IOException { if (file == null) { throw MESSAGES.nullArgument("file"); } if (paths == null) { throw MESSAGES.nullArgument("paths"); } boolean trace = VFSLogger.ROOT_LOGGER.isTraceEnabled(); Manifest manifest = getManifest(file); if (manifest == null) { return; } Attributes mainAttributes = manifest.getMainAttributes(); String classPath = mainAttributes.getValue(Attributes.Name.CLASS_PATH); if (classPath == null) { if (trace) { VFSLogger.ROOT_LOGGER.tracef("Manifest has no Class-Path for %s", file.getPathName()); } return; } VirtualFile parent = file.getParent(); if (parent == null) { VFSLogger.ROOT_LOGGER.debugf("%s has no parent.", file); return; } if (trace) { VFSLogger.ROOT_LOGGER.tracef("Parsing Class-Path: %s for %s parent=%s", classPath, file.getName(), parent.getName()); } StringTokenizer tokenizer = new StringTokenizer(classPath); while (tokenizer.hasMoreTokens()) { String path = tokenizer.nextToken(); try { VirtualFile vf = parent.getChild(path); if (vf.exists()) { if (paths.contains(vf) == false) { paths.add(vf); // Recursively process the jar Automounter.mount(file, vf); addManifestLocations(vf, paths); } else if (trace) { VFSLogger.ROOT_LOGGER.tracef("%s from manifest is already in the classpath %s", vf.getName(), paths); } } else if (trace) { VFSLogger.ROOT_LOGGER.trace("Unable to find " + path + " from " + parent.getName()); } } catch (IOException e) { VFSLogger.ROOT_LOGGER.debugf("Manifest Class-Path entry %s ignored for %s reason= %s", path, file.getPathName(), e); } } }
java
private Document parse(File file) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { return new InputSource(new StringReader("")); } }); return builder.parse(file); } catch (Exception e) { throw new TestException(e); } }
java
@Override public Query createNamedQuery(String name) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "em.createNamedQuery(" + name + ");\n" + toString()); return getEMInvocationInfo(false).createNamedQuery(name); }
python
def _publish_replset(self, data, base_prefix): """ Given a response to replSetGetStatus, publishes all numeric values of the instance, aggregate stats of healthy nodes vs total nodes, and the observed statuses of all nodes in the replica set. """ prefix = base_prefix + ['replset'] self._publish_dict_with_prefix(data, prefix) total_nodes = len(data['members']) healthy_nodes = reduce(lambda value, node: value + node['health'], data['members'], 0) self._publish_dict_with_prefix({ 'healthy_nodes': healthy_nodes, 'total_nodes': total_nodes }, prefix) for node in data['members']: replset_node_name = node[self.config['replset_node_name']] node_name = str(replset_node_name.split('.')[0]) self._publish_dict_with_prefix(node, prefix + ['node', node_name])
python
def requestAvatarId(self, credentials): """ Return the ID associated with these credentials. @param credentials: something which implements one of the interfaces in self.credentialInterfaces. @return: a Deferred which will fire a string which identifies an avatar, an empty tuple to specify an authenticated anonymous user (provided as checkers.ANONYMOUS) or fire a Failure(UnauthorizedLogin). @see: L{twisted.cred.credentials} """ username, domain = credentials.username.split("@") key = self.users.key(domain, username) if key is None: return defer.fail(UnauthorizedLogin()) def _cbPasswordChecked(passwordIsCorrect): if passwordIsCorrect: return username + '@' + domain else: raise UnauthorizedLogin() return defer.maybeDeferred(credentials.checkPassword, key).addCallback(_cbPasswordChecked)
java
@SuppressWarnings("rawtypes") public Collection getCMP20Collection(Collection keys) throws FinderException, RemoteException { return ivEntityHelper.getCMP20Collection(this, keys); }
java
private RSAPrivateKey loadPrivateKeyFromPEMFile(String filename) { try { String publicKeyFile = FileReader.readFileFromClassPathOrPath(filename); byte[] publicKeyBytes = DatatypeConverter.parseBase64Binary(publicKeyFile.replace("-----BEGIN RSA PRIVATE KEY-----", "").replace("-----END RSA PRIVATE KEY-----", "")); return (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(publicKeyBytes)); } catch (Exception e) { throw new RuntimeException("Exception reading private key from PEM file", e); } }
python
def render_tree(self, **kwargs): """Render the graph, and return (l)xml etree""" self.setup(**kwargs) svg = self.svg.root for f in self.xml_filters: svg = f(svg) self.teardown() return svg
java
@Override public void validate(ValidationHelper helper, Context context, String key, ServerVariables t) { if (t != null) { boolean mapContainsInvalidKey = false; for (String k : t.keySet()) { if (k == null || k.isEmpty()) { mapContainsInvalidKey = true; } else { //Ensure map doesn't contain null value if (t.get(k) == null) { final String message = Tr.formatMessage(tc, "nullValueInMap", k); helper.addValidationEvent(new ValidationEvent(ValidationEvent.Severity.ERROR, context.getLocation(), message)); } } } //Ensure map doesn't contain an invalid key if (mapContainsInvalidKey) { final String message = Tr.formatMessage(tc, "nullOrEmptyKeyInMap"); helper.addValidationEvent(new ValidationEvent(ValidationEvent.Severity.ERROR, context.getLocation(), message)); } } }
java
@Override public T transformElement(Tuple2<AerospikeKey, AerospikeRecord> tuple, DeepJobConfig<T, ? extends DeepJobConfig> config) { try { return (T) UtilAerospike.getObjectFromAerospikeRecord(config.getEntityClass(), tuple._2(), (AerospikeDeepJobConfig) this.deepJobConfig); } catch (Exception e) { LOG.error("Cannot convert AerospikeRecord: ", e); throw new DeepTransformException("Could not transform from AerospikeRecord to Entity " + e.getMessage(), e); } }
java
@Override public void loadModel(InputStream modelIs) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { IOUtils.copy(modelIs, baos); } catch (IOException e) { LOG.error("Load model err.", e); } InputStream isForSVMLoad = new ByteArrayInputStream(baos.toByteArray()); try (ZipInputStream zipInputStream = new ZipInputStream(isForSVMLoad)) { ZipEntry entry; while ((entry = zipInputStream.getNextEntry()) != null) { if (entry.getName().endsWith(".model")) { BufferedReader br = new BufferedReader(new InputStreamReader(zipInputStream, Charset.defaultCharset())); this.model = svm.svm_load_model(br); } } } catch (IOException e) { // Do Nothing. } modelIs = new ByteArrayInputStream(baos.toByteArray()); try (ZipInputStream zipInputStream = new ZipInputStream(modelIs)) { ZipEntry entry; while ((entry = zipInputStream.getNextEntry()) != null) { if (entry.getName().endsWith(".lbindexer")) { String lbIndexer = IOUtils.toString(zipInputStream, Charset.defaultCharset()); this.labelIndexer = new LabelIndexer(new ArrayList<>()); this.labelIndexer.readFromSerializedString(lbIndexer); } } } catch (IOException e) { LOG.error("Err in load LabelIndexer", e); } }
java
public String getDetailName(CmsResource res, Locale locale, List<Locale> defaultLocales) throws CmsException { String urlName = readBestUrlName(res.getStructureId(), locale, defaultLocales); if (urlName == null) { urlName = res.getStructureId().toString(); } return urlName; }
python
def get_next_invalid_time_from_t(self, timestamp): """Get next invalid time for time range :param timestamp: time we compute from :type timestamp: int :return: timestamp of the next invalid time (LOCAL TIME) :rtype: int """ if not self.is_time_valid(timestamp): return timestamp # First we search for the day of time range t_day = self.get_next_invalid_day(timestamp) # We search for the min of all tr.start > sec_from_morning # if it's the next day, use a start of the day search for timerange if timestamp < t_day: sec_from_morning = self.get_next_future_timerange_invalid(t_day) else: # it is in this day, so look from t (can be in the evening or so) sec_from_morning = self.get_next_future_timerange_invalid(timestamp) # tr can't be valid, or it will be return at the beginning # sec_from_morning = self.get_next_future_timerange_invalid(t) # Ok we've got a next invalid day and a invalid possibility in # timerange, so the next invalid is this day+sec_from_morning if t_day is not None and sec_from_morning is not None: return t_day + sec_from_morning + 1 # We've got a day but no sec_from_morning: the timerange is full (0->24h) # so the next invalid is this day at the day_start if t_day is not None and sec_from_morning is None: return t_day # Then we search for the next day of t # The sec will be the min of the day timestamp = get_day(timestamp) + 86400 t_day2 = self.get_next_invalid_day(timestamp) sec_from_morning = self.get_next_future_timerange_invalid(t_day2) if t_day2 is not None and sec_from_morning is not None: return t_day2 + sec_from_morning + 1 if t_day2 is not None and sec_from_morning is None: return t_day2 # I did not found any valid time return None
java
@Deprecated public void sendRow(long sheetId, long rowId, RowEmail email) throws SmartsheetException { this.createResource("sheets/" + sheetId + "/rows/" + rowId + "/emails", RowEmail.class, email); }
java
protected boolean txWarning(List<ValidationMessage> errors, String txLink, IssueType type, int line, int col, String path, boolean thePass, String msg, Object... theMessageArguments) { if (!thePass) { msg = formatMessage(msg, theMessageArguments); errors.add(new ValidationMessage(Source.TerminologyEngine, type, line, col, path, msg, IssueSeverity.WARNING).setTxLink(txLink)); } return thePass; }
java
public static ProtoFile parse(String name, String data) { return new ProtoParser(name, data.toCharArray()).readProtoFile(); }
java
@Override public final void handleMessage(Exchange exchange) throws HandlerException { if (ExchangePhase.IN.equals(exchange.getPhase())) { ExchangeContract contract = exchange.getContract(); KnowledgeOperation operation = getOperation(contract.getProviderOperation()); if (operation == null) { operation = getOperation(contract.getConsumerOperation()); } if (operation == null) { // we use "default" here instead of getDefaultOperation() so that a // user can define a name="default" in their switchyard.xml operation = _operations.get(DEFAULT); } handleOperation(exchange, operation); } }
python
async def flush(self, request: Request, stacks: List[Stack]): """ For all stacks to be sent, append a pause after each text layer. """ ns = await self.expand_stacks(request, stacks) ns = self.split_stacks(ns) ns = self.clean_stacks(ns) await self.next(request, [Stack(x) for x in ns])
python
def parse_url_query_params(url, fragment=True): """Parse url query params :param fragment: bool: flag is used for parsing oauth url :param url: str: url string :return: dict """ parsed_url = urlparse(url) if fragment: url_query = parse_qsl(parsed_url.fragment) else: url_query = parse_qsl(parsed_url.query) # login_response_url_query can have multiple key url_query = dict(url_query) return url_query
java
@Override public <C extends CrudResponse, T extends AssociationEntity> C disassociateWithEntity(Class<T> type, Integer entityId, AssociationField<T, ? extends BullhornEntity> associationName, Set<Integer> associationIds) { return this.handleDisassociateWithEntity(type, entityId, associationName, associationIds); }
java
protected Pair<Integer, FlatBufferBuilder> encodeStaticHeader(byte type) { FlatBufferBuilder fbb = new FlatBufferBuilder(12); int staticInfoOffset = UIStaticInfoRecord.createUIStaticInfoRecord(fbb, type); fbb.finish(staticInfoOffset); int lengthHeader = fbb.offset(); //MUST be called post finish to get real length return new Pair<>(lengthHeader, fbb); }
java
private String antToRegexConverter(String antStyleLocationPattern) { String regexStyleLocationPattern = antStyleLocationPattern.replace("\\", "/"); regexStyleLocationPattern = regexStyleLocationPattern.replaceAll("\\.", "\\\\."); // replace . with \\. regexStyleLocationPattern = regexStyleLocationPattern.replaceAll("//", "/");//Solution for known test cases with // issue at org.globus.gsi.proxy.ProxyPathValidatorTest line 536, Needs Review regexStyleLocationPattern = regexStyleLocationPattern.replace('?', '.'); // replace ? with . regexStyleLocationPattern = regexStyleLocationPattern.replaceAll("\\*", "[^/]*"); //replace all * with [^/]*, this will make ** become [^/]*[^/]* regexStyleLocationPattern = regexStyleLocationPattern.replaceAll("\\[\\^/\\]\\*\\[\\^/\\]\\*", ".*"); //now replace the .*.* with just .* regexStyleLocationPattern = "^" + this.mainClassPath + regexStyleLocationPattern + "$"; //add the beginning and end symbols, and mainClassPath, if the object is of the type classpath:/ return regexStyleLocationPattern; }
python
def parse_all_data(self): """Parses the master df.""" self._master_df.columns = ["domain", "entity", "state", "last_changed"] # Check if state is float and store in numericals category. self._master_df["numerical"] = self._master_df["state"].apply( lambda x: functions.isfloat(x) ) # Multiindexing self._master_df.set_index( ["domain", "entity", "numerical", "last_changed"], inplace=True )
python
def is_ternary(self, keyword): """return true if the given keyword is a ternary keyword for this ControlLine""" return keyword in { 'if':set(['else', 'elif']), 'try':set(['except', 'finally']), 'for':set(['else']) }.get(self.keyword, [])
java
public Request makeRequest(HttpMethod httpMethod, String urlPath, boolean cached) throws IOException { Preconditions.checkState(lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS)); return new Request(httpMethod, new URL(StringUtils.format("%s%s", getCurrentKnownLeader(cached), urlPath))); }
python
def get_version(package): """ Return package version as listed in `__version__` in `init.py`. """ init_py = codecs.open(os.path.join(package, '__init__.py'), encoding='utf-8').read() return re.search("^__version__ = ['\"]([^'\"]+)['\"]", init_py, re.MULTILINE).group(1)
python
def read_actions(): """Yields actions for pressed keys.""" while True: key = get_key() # Handle arrows, j/k (qwerty), and n/e (colemak) if key in (const.KEY_UP, const.KEY_CTRL_N, 'k', 'e'): yield const.ACTION_PREVIOUS elif key in (const.KEY_DOWN, const.KEY_CTRL_P, 'j', 'n'): yield const.ACTION_NEXT elif key in (const.KEY_CTRL_C, 'q'): yield const.ACTION_ABORT elif key in ('\n', '\r'): yield const.ACTION_SELECT
python
def fill_with_sample_data(self): """This function fills the corresponding object with sample data.""" # replace these sample data with another dataset later # this function is deprecated as soon as a common file format for this # type of data will be available self.p01 = np.array([[0.576724636119866, 0.238722774405744, 0.166532122130638, 0.393474644666218], [0.303345245644811, 0.0490956843857575, 0.0392403031072856, 0.228441890034704]]) self.p10 = np.array([[0.158217002255554, 0.256581140990052, 0.557852226779526, 0.422638238585814], [0.0439831163244427, 0.0474928027621488, 0.303675296728195, 0.217512052135178]]) self.pxx = np.array([[0.265058361624580, 0.504696084604205, 0.275615651089836, 0.183887116747968], [0.652671638030746, 0.903411512852094, 0.657084400164519, 0.554046057830118]]) self.wxx = np.array([[[0.188389148850583, 0.0806836453984190, 0.0698113025807722, 0.0621499191745602], [0.240993281622128, 0.0831019646519721, 0.0415130545715575, 0.155284541403192]], [[0.190128959522795, 0.129220679033862, 0.0932213021787505, 0.193080698516532], [0.196379692358065, 0.108549414860949, 0.0592714297292217, 0.0421945385836429]], [[0.163043672107111, 0.152063537378127, 0.102823783410167, 0.0906028835221283], [0.186579466868095, 0.189705690316132, 0.0990207345993082, 0.107831389238912]], [[0.197765724699431, 0.220046257566978, 0.177876233348082, 0.261288786454262], [0.123823472714948, 0.220514673922285, 0.102486496386323, 0.101975538893918]], [[0.114435243444815, 0.170857634762767, 0.177327072603662, 0.135362730582518], [0.0939211776723413,0.174291820501902, 0.125275822078525, 0.150842841725936]], [[0.0988683809545079, 0.152323481100248, 0.185606883566286, 0.167242856061538], [0.0760275616817939, 0.127275603247149, 0.202466168603738, 0.186580243138018]], [[0.0473688704207573, 0.0948047647595988, 0.193333422312280, 0.0902721256884624], [0.0822753470826286, 0.0965608324996108, 0.369966294031327, 0.255290907016382]]])
python
def show_firmware_version_output_show_firmware_version_copy_right_info(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_firmware_version = ET.Element("show_firmware_version") config = show_firmware_version output = ET.SubElement(show_firmware_version, "output") show_firmware_version = ET.SubElement(output, "show-firmware-version") copy_right_info = ET.SubElement(show_firmware_version, "copy-right-info") copy_right_info.text = kwargs.pop('copy_right_info') callback = kwargs.pop('callback', self._callback) return callback(config)
java
public void setComparator(int index, Comparator<T> comparator) { if (comparator instanceof InvertibleComparator) { this.comparators.set(index, (InvertibleComparator<T>) comparator); } else { this.comparators.set(index, new InvertibleComparator<T>(comparator)); } }
java
public static Trades adaptTrades( BitcoindeTradesWrapper bitcoindeTradesWrapper, CurrencyPair currencyPair) { List<Trade> trades = new ArrayList<>(); long lastTradeId = 0; for (BitcoindeTrade bitcoindeTrade : bitcoindeTradesWrapper.getTrades()) { final long tid = bitcoindeTrade.getTid(); if (tid > lastTradeId) { lastTradeId = tid; } trades.add( new Trade( null, bitcoindeTrade.getAmount(), currencyPair, bitcoindeTrade.getPrice(), DateUtils.fromMillisUtc(bitcoindeTrade.getDate() * 1000L), String.valueOf(tid))); } return new Trades(trades, lastTradeId, TradeSortType.SortByID); }
python
def set_enable_flag_keep_rect_within_constraints(self, enable): """ Enable/disables the KeepRectangleWithinConstraint for child states """ for child_state_v in self.child_state_views(): self.keep_rect_constraints[child_state_v].enable = enable child_state_v.keep_rect_constraints[child_state_v._name_view].enable = enable
python
def remove_node(self, node): """ Removes node from circle and rebuild it. """ try: self._nodes.remove(node) del self._weights[node] except (KeyError, ValueError): pass self._hashring = dict() self._sorted_keys = [] self._build_circle()
java
public GitlabMergeRequestApprovals setMergeRequestApprovers(GitlabMergeRequest mr, Collection<Integer> userApproverIds, Collection<Integer> groupApproverIds) throws IOException { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(mr.getProjectId()) + GitlabMergeRequest.URL + "/" + mr.getIid() + GitlabMergeRequestApprovals.APPROVERS_URL; return put() .with("approver_ids", userApproverIds) .with("approver_group_ids", groupApproverIds) .to(tailUrl, GitlabMergeRequestApprovals.class); }
python
def get_default_config_filename(): """Returns the configuration filepath. If PEYOTL_CONFIG_FILE is in the env that is the preferred choice; otherwise ~/.peyotl/config is preferred. If the preferred file does not exist, then the packaged peyotl/default.conf from the installation of peyotl is used. A RuntimeError is raised if that fails. """ global _CONFIG_FN if _CONFIG_FN is not None: return _CONFIG_FN with _CONFIG_FN_LOCK: if _CONFIG_FN is not None: return _CONFIG_FN if 'PEYOTL_CONFIG_FILE' in os.environ: cfn = os.path.abspath(os.environ['PEYOTL_CONFIG_FILE']) else: cfn = os.path.expanduser("~/.peyotl/config") if not os.path.isfile(cfn): # noinspection PyProtectedMember if 'PEYOTL_CONFIG_FILE' in os.environ: from peyotl.utility.get_logger import warn_from_util_logger msg = 'Filepath "{}" specified via PEYOTL_CONFIG_FILE={} was not found'.format(cfn, os.environ[ 'PEYOTL_CONFIG_FILE']) warn_from_util_logger(msg) from pkg_resources import Requirement, resource_filename pr = Requirement.parse('peyotl') cfn = resource_filename(pr, 'peyotl/default.conf') if not os.path.isfile(cfn): raise RuntimeError('The peyotl configuration file cascade failed looking for "{}"'.format(cfn)) _CONFIG_FN = os.path.abspath(cfn) return _CONFIG_FN
java
public static String[] readStringArray(DataInput in) throws IOException { int len = in.readInt(); if (len == -1) return null; String[] s = new String[len]; for (int i = 0; i < len; i++) { s[i] = readString(in); } return s; }
python
def CollectMetrics(self, request, context): """Dispatches the request to the plugins collect method""" LOG.debug("CollectMetrics called") try: metrics_to_collect = [] for metric in request.metrics: metrics_to_collect.append(Metric(pb=metric)) metrics_collected = self.plugin.collect(metrics_to_collect) return MetricsReply(metrics=[m.pb for m in metrics_collected]) except Exception as err: msg = "message: {}\n\nstack trace: {}".format( err, traceback.format_exc()) return MetricsReply(metrics=[], error=msg)
java
public void clearPersonData() { this.rollbar.configure(new ConfigProvider() { @Override public Config provide(ConfigBuilder builder) { return builder .person(null) .build(); } }); }
java
public void similar(IMatrix U, IMatrix result) { if ((result.rows != U.columns) || (result.columns != U.columns)) result.reshape(U.columns, U.columns); double realsum, imagsum, realinnersum, imaginnersum; for (int i = 0; i < U.columns; i++) for (int j = 0; j < U.columns; j++) { realsum = 0d; imagsum = 0d; for (int k = 0; k < U.columns; k++) { realinnersum = 0d; imaginnersum = 0d; for (int l = 0; l < U.columns; l++) { realinnersum += realmatrix[k][l] * U.realmatrix[l][j] - imagmatrix[k][l] * U.imagmatrix[l][j]; imaginnersum += realmatrix[k][l] * U.imagmatrix[l][j] + imagmatrix[k][l] * U.realmatrix[l][j]; } realsum += U.realmatrix[k][i] * realinnersum - U.imagmatrix[k][i] * imaginnersum; imagsum += U.realmatrix[k][i] * imaginnersum + U.imagmatrix[k][i] * realinnersum; } result.realmatrix[i][j] = realsum; result.imagmatrix[i][j] = imagsum; } }
java
public boolean check(ByteBuffer data) { assert (data != null); int size = data.limit(); // This function is on critical path. It deliberately doesn't use // recursion to get a bit better performance. Trie current = this; int start = 0; while (true) { // We've found a corresponding subscription! if (current.refcnt > 0) { return true; } // We've checked all the data and haven't found matching subscription. if (size == 0) { return false; } // If there's no corresponding slot for the first character // of the prefix, the message does not match. byte c = data.get(start); if (c < current.min || c >= current.min + current.count) { return false; } // Move to the next character. if (current.count == 1) { current = current.next[0]; } else { current = current.next[c - current.min]; if (current == null) { return false; } } start++; size--; } }
python
def add_existing_session(self, dwProcessId, bStarted = False): """ Use this method only when for some reason the debugger's been attached to the target outside of WinAppDbg (for example when integrating with other tools). You don't normally need to call this method. Most users should call L{attach}, L{execv} or L{execl} instead. @type dwProcessId: int @param dwProcessId: Global process ID. @type bStarted: bool @param bStarted: C{True} if the process was started by the debugger, or C{False} if the process was attached to instead. @raise WindowsError: The target process does not exist, is not attached to the debugger anymore. """ # Register the process object with the snapshot. if not self.system.has_process(dwProcessId): aProcess = Process(dwProcessId) self.system._add_process(aProcess) else: aProcess = self.system.get_process(dwProcessId) # Test for debug privileges on the target process. # Raises WindowsException on error. aProcess.get_handle() # Register the process ID with the debugger. if bStarted: self.__attachedDebugees.add(dwProcessId) else: self.__startedDebugees.add(dwProcessId) # Match the system kill-on-exit flag to our own. self.__setSystemKillOnExitMode() # Scan the process threads and loaded modules. # This is prefered because the thread and library events do not # properly give some information, like the filename for each module. aProcess.scan_threads() aProcess.scan_modules()
java
private void scheduleEvictionTask(long timeoutInMilliSeconds) { EvictionTask evictionTask = new EvictionTask(); // Before creating new Timers, which create new Threads, we // must ensure that we are not using any application classloader // as the current thread's context classloader. Otherwise, it // is possible that the new Timer thread would hold on to the // app classloader indefinitely, thereby leaking it and all // classes that it loaded, long after the app has been stopped. SwapTCCLAction swapTCCL = new SwapTCCLAction(); AccessController.doPrivileged(swapTCCL); try { timer = new Timer(true); long period = timeoutInMilliSeconds / 3; long delay = period; timer.schedule(evictionTask, delay, period); } finally { AccessController.doPrivileged(swapTCCL); } }
java
protected ZooKeeperServer createZookeeperServer(File logDir) { try { return new ZooKeeperServer(logDir, logDir, 2000); } catch (IOException e) { throw new CitrusRuntimeException("Failed to create embedded zookeeper server", e); } }
java
public com.google.protobuf.ByteString getDeviceTypeBytes() { java.lang.Object ref = deviceType_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); deviceType_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } }
java
public void init(Object env, Map<String,Object> properties, Object applet) { m_resources = null; super.init(env, properties, applet); if (m_env == null) { if (env != null) m_env = (Environment)env; else m_env = this.getEnvironment(); this.setProperties(Utility.putAllIfNew(this.getProperties(), m_env.getProperties())); // Start with environment properties } m_env.addApplication(this); m_databaseCollection = new DatabaseCollection(this); }