language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static Builder from(GatewayMessage message) { return new Builder().headers(message.headers).data(message.data); }
python
def make_report(self): """ Makes a html report and saves it into the same folder where logs are stored. """ if self.execution_stats is None: raise RuntimeError('Cannot produce a report without running the executor first, check EOExecutor.run ' 'method')...
java
public static <V> String printNodeTree(ParsingResult<V> parsingResult, Predicate<Node<V>> nodeFilter, Predicate<Node<V>> subTreeFilter) { checkArgNotNull(parsingResult, "parsingResult"); checkArgNotNull(nodeFilter, "nodeFilter"); checkArgNotNull(subTree...
python
def validate(ref_voicing, ref_cent, est_voicing, est_cent): """Checks that voicing and frequency arrays are well-formed. To be used in conjunction with :func:`mir_eval.melody.validate_voicing` Parameters ---------- ref_voicing : np.ndarray Reference boolean voicing array ref_cent : np....
java
public JPanel addToolbar(JComponent screen, JComponent toolbar) { JPanel panelMain = new JPanel(); panelMain.setOpaque(false); panelMain.setLayout(new BoxLayout(panelMain, BoxLayout.Y_AXIS)); panelMain.add(toolbar); toolbar.setAlignmentX(0); panelMain.add(screen); ...
java
private boolean load(Reader reader) { // Read VTIMEZONE block into string array try { vtzlines = new LinkedList<String>(); boolean eol = false; boolean start = false; boolean success = false; StringBuilder line = new StringBuilder(); ...
python
def select(self, *cluster_ids): """Select a list of clusters.""" # HACK: allow for `select(1, 2, 3)` in addition to `select([1, 2, 3])` # This makes it more convenient to select multiple clusters with # the snippet: `:c 1 2 3` instead of `:c 1,2,3`. if cluster_ids and isinstance(...
java
public void delete(String resourceGroupName, String applicationSecurityGroupName) { deleteWithServiceResponseAsync(resourceGroupName, applicationSecurityGroupName).toBlocking().last().body(); }
java
public void put(double x, double y, double w) { if(w == 0.) { return; } if(sumWe <= 0.) { sumX = x * w; sumY = y * w; sumWe = w; return; } // Delta to previous mean final double deltaX = x * sumWe - sumX; final double deltaY = y * sumWe - sumY; final double ...
java
public void onApplicationEvent(ApplicationEvent event) { // All events we care about are subtypes of ClientSecurityEvent if( event instanceof ClientSecurityEvent ) { Authentication authentication = (Authentication) event.getSource(); if( logger.isDebugEnabled() ) { ...
python
def handle_string_response(self, call_id, payload): """Handler for response `StringResponse`. This is the response for the following requests: 1. `DocUriAtPointReq` or `DocUriForSymbolReq` 2. `DebugToStringReq` """ self.log.debug('handle_string_response: in [typehint...
java
private void checkConsistency(StorageInfo remote, StorageInfo local, boolean image, Object name) throws IOException { if (!remote.equals(local)) { throwIOException("Remote " + (image ? "image" : "edits") + " storage is different than local. Local: (" + local.toColonSeparatedString() ...
python
def get(self, url, data=None): """ Executes an HTTP GET request for the given URL. ``data`` should be a dictionary of url parameters """ response = self.http.get(url, headers=self.headers, params=data, ...
python
def save(self, filename): '''save settings to a file. Return True/False on success/failure''' try: f = open(filename, mode='w') except Exception: return False for k in self.list(): f.write("%s=%s\n" % (k, self.get(k))) f.close() return ...
java
public void setLocalSecondaryIndexes(java.util.Collection<LocalSecondaryIndexInfo> localSecondaryIndexes) { if (localSecondaryIndexes == null) { this.localSecondaryIndexes = null; return; } this.localSecondaryIndexes = new java.util.ArrayList<LocalSecondaryIndexInfo>(loc...
java
public static CPOptionValue fetchByCompanyId_First(long companyId, OrderByComparator<CPOptionValue> orderByComparator) { return getPersistence() .fetchByCompanyId_First(companyId, orderByComparator); }
python
def neighbor(self, **kwargs): """Experimental neighbor method. Args: ip_addr (str): IP Address of BGP neighbor. remote_as (str): Remote ASN of BGP neighbor. rbridge_id (str): The rbridge ID of the device on which BGP will be configured in a VCS fabric...
java
public FormValidation doCheckName(@QueryParameter String value) throws IOException, ServletException { Jenkins.getInstance().checkPermission(Computer.CREATE); if(Util.fixEmpty(value)==null) return FormValidation.ok(); try { checkName(value); return F...
python
def getobject(bunchdt, key, name): """get the object if you have the key and the name returns a list of objects, in case you have more than one You should not have more than one""" # TODO : throw exception if more than one object, or return more objects idfobjects = bunchdt[key] if idfobjects: ...
java
public String substituteLinkForUnknownTarget( CmsObject cms, String link, String targetDetailPage, boolean forceSecure) { if (CmsStringUtil.isEmpty(link)) { return ""; } String sitePath = link; String siteRoot = null; if (hasScheme(lin...
java
private boolean hasStep(final SlideContent slideContent) { boolean res = false; for (final S step : getStepList()) { if (step.name().equalsIgnoreCase(slideContent.getName())) { res = true; } } return res; }
python
def create_template(self, s, provider_name=None): """Creates a template from the given string based on the specified provider or the provider with highest precedence. Args: s: The string to convert to a template. provider_name: The name of the provider to use to create t...
java
private static double getX(Coordinate c) { double value = c.getX(); if (value > 1000000) { value = 1000000; } else if (value < -1000000) { value = -1000000; } return value; }
java
public Matrix4d rotateAround(Quaterniondc quat, double ox, double oy, double oz) { return rotateAround(quat, ox, oy, oz, this); }
java
@Override public CommerceShippingFixedOptionRel findByPrimaryKey( Serializable primaryKey) throws NoSuchShippingFixedOptionRelException { CommerceShippingFixedOptionRel commerceShippingFixedOptionRel = fetchByPrimaryKey(primaryKey); if (commerceShippingFixedOptionRel == null) { if (_log.isDebugEnabled()) { ...
python
def check_exists(filename, oappend=False): """ Avoid overwriting some files accidentally. """ if op.exists(filename): if oappend: return oappend logging.error("`{0}` found, overwrite (Y/N)?".format(filename)) overwrite = (raw_input() == 'Y') else: overwrit...
java
public static NotCondition.Builder not(Condition.Builder conditionBuilder) { return NotCondition.builder().condition(conditionBuilder); }
java
private void initShadowResponsiveEffectEnabled(TypedArray attrs) { int index = R.styleable.ActionButton_shadowResponsiveEffect_enabled; if (attrs.hasValue(index)) { shadowResponsiveEffectEnabled = attrs.getBoolean(index, shadowResponsiveEffectEnabled); LOGGER.trace("Initialized Action Button Shadow Responsive...
java
@SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; jScrollPane1 = new javax.swing.JScrollPane(); textArea = new javax.swing.JTextArea(); jPanel1 = ne...
python
def get(self, request): """ Returns a json representing the menu voices in a format eaten by the js menu. Raised ImproperlyConfigured exceptions can be viewed in the browser console """ self.app_list = site.get_app_list(request) self.apps_dict = self.c...
java
public static void copy(final InputStream inputStream, final OutputStream outputStream) throws IOException { new ByteSource() { @Override public InputStream openStream() { return inputStream; } }.copyTo(new ByteSink() { @Override public OutputStream openStream() { ...
java
void get_features(final State s, final List<Integer> cluster4, final List<Integer> cluster6, final List<Integer> cluster, List<Integer> features) { Context ctx = new Context(); get_context(s, ctx); get_ba...
java
public static filterglobal_binding get(nitro_service service) throws Exception{ filterglobal_binding obj = new filterglobal_binding(); filterglobal_binding response = (filterglobal_binding) obj.get_resource(service); return response; }
python
def configure(self, address): """Configure socket's addresses with nanoconfig""" global nanoconfig_started if len(self._endpoints): raise ValueError("Nanoconfig address must be sole endpoint") endpoint_id = _nn_check_positive_rtn( wrapper.nc_configure(self.fd, add...
java
private int getIsoLevel(String isoLevel) { if (isoLevel.equalsIgnoreCase(LITERAL_IL_READ_UNCOMMITTED)) { return IL_READ_UNCOMMITTED; } else if (isoLevel.equalsIgnoreCase(LITERAL_IL_READ_COMMITTED)) { return IL_READ_COMMITTED; } ...
python
def recv_raw(self, x=MTU): """Receives a packet, then returns a tuple containing (cls, pkt_data, time)""" # noqa: E501 ll = self.ins.datalink() if ll in conf.l2types: cls = conf.l2types[ll] else: cls = conf.default_l2 warning("Unable to guess datalink...
java
@Override public int compare(S solution1, S solution2) { if (solution1 == null) { return 1; } else if (solution2 == null) { return -1; } int dominate1; // dominate1 indicates if some objective of solution1 // dominates the same objective in solution2. dominate2 int domin...
java
public String getUUID() { StringBuilder uuid = new StringBuilder(36); int i = (int)System.currentTimeMillis(); int j = seed.nextInt(); hexFormat(i,uuid); uuid.append(fixedPart); hexFormat(j,uuid); return uuid.toString(); }
java
public String getSemanticTypes(int i) { if (OntClassMention_Type.featOkTst && ((OntClassMention_Type)jcasType).casFeat_semanticTypes == null) jcasType.jcas.throwFeatMissing("semanticTypes", "de.julielab.jules.types.OntClassMention"); jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((On...
python
def create_choice_model(data, alt_id_col, obs_id_col, choice_col, specification, model_type, intercept_ref_pos=None, shape_ref_pos=None, ...
java
public List<Object> receiveAndConvertBatch(Destination destination, int batchSize) throws JmsException { List<Message> messages = receiveBatch(destination, batchSize); List<Object> result = new ArrayList<Object>(messages.size()); for (Message next : messages) { result.add(doConvertFr...
java
public static <I extends ImageGray<I>, D extends ImageGray<D>> PointTracker<I> klt(int scaling[], ConfigGeneralDetector configExtract, int featureRadius, Class<I> imageType, Class<D> derivType) { PkltConfig config = new PkltConfig(); config.pyramidScaling = scaling; config.templateRadius = featureRadius;...
python
def _expandOlemaVerbChains( clauseTokens, clauseID, foundChains ): ''' Meetod, mis proovib laiendada 'olema'-l6pulisi (predikaadi) verbiahelaid, lisades võimalusel nende otsa teisi verbe, nt "on olnud" + "tehtud", "ei olnud" + "tehtud", "ei oleks" + "arvatud"; Vastavalt l...
python
def get_html_filename(filename): """Converts the filename to a .html extension""" if ".html" in filename: newFilename = filename elif ".md" in filename: newFilename = filename.replace(".md", ".html") elif ".tile" in filename: newFilename = filename.replace(".tile", ".html") e...
java
public BufferedWriter getWriter(boolean isAppend) throws IORuntimeException { try { return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(FileUtil.touch(file), isAppend), charset)); } catch (Exception e) { throw new IORuntimeException(e); } }
python
def _setup(self): """ Generates _id_map from _alternatives to allow validating contents """ cls = self.__class__ cls._id_map = {} cls._name_map = {} for index, info in enumerate(cls._alternatives): if len(info) < 3: info = info + ({},)...
java
private static int zero(byte[] block, int offset, int len) { Util.zero(block, offset, len); return len; }
java
public static SegwitAddress fromKey(NetworkParameters params, ECKey key) { checkArgument(key.isCompressed(), "only compressed keys allowed"); return fromHash(params, key.getPubKeyHash()); }
java
public void put(Object key, Object value) { int weight = getWeight(key) + getWeight(value) + OVERHEAD; currentWeight += weight; if (cache.put(key, value == null ? NULL_VALUE : value) != null) { currentWeight -= weight; } }
java
public int getNrOfClasses() { HashMap<Integer, Integer> classes = new HashMap<Integer, Integer>(); for (DataObject currentObject : dataList) { if (!classes.containsKey(currentObject.getClassLabel())) classes.put(currentObject.getClassLabel(), 1); } return classes.size(); }
java
public boolean isStaleElementException(WebDriverException e) { boolean result = false; if (e instanceof StaleElementReferenceException) { result = true; } else { String msg = e.getMessage(); if (msg != null) { result = msg.contains("Element doe...
python
def run(configobj, wcsmap=None): """ Initial example by Nadia ran MD with configobj EPAR using: It can be run in one of two ways: from stsci.tools import teal 1. Passing a config object to teal teal.teal('drizzlepac/pars/astrodrizzle.cfg') 2. Passing a task name: ...
python
def ping(): ''' Returns true if the device is reachable, else false. ''' try: cookie = logon() logout(cookie) except salt.exceptions.CommandExecutionError: return False except Exception as err: log.debug(err) return False return True
java
private boolean parseEscapedHash(String hash) { if (StringUtils.isEmpty(hash)) return false; hashEscaped = true; int maxPage = -1; try { for (String str : hash.split("&")) { int idx = str.indexOf("="); if (idx <= 0) continue; String name = URLDecoder.decode(str.substring(0...
python
def mount(device, mountpoint, options=None, persist=False, filesystem="ext3"): """Mount a filesystem at a particular mountpoint""" cmd_args = ['mount'] if options is not None: cmd_args.extend(['-o', options]) cmd_args.extend([device, mountpoint]) try: subprocess.check_output(cmd_args...
java
public <T> CompletableFuture<T> putAsync(final Class<T> type, @DelegatesTo(HttpConfig.class) final Closure closure) { return CompletableFuture.supplyAsync(() -> put(type, closure), getExecutor()); }
python
def ensure_compliance(self): """Ensure that the all registered files comply to registered criteria. """ for p in self.paths: if os.path.exists(p): if self.is_compliant(p): continue log('File %s is not in compliance.' % p, level=INF...
java
@SuppressWarnings("unchecked") private void checkNeedUpdateTopologies(Map<String, StateHeartbeat> localWorkerStats, Map<Integer, LocalAssignment> localAssignments) throws Exception { Set<String> topologies = new HashSet<>(); for (Map.Entry<Integer, LocalAs...
java
void addIndexCondition(Expression[] exprList, Index index, int colCount, boolean isJoin) { // VoltDB extension if (rangeIndex == index && isJoinIndex && (!isJoin) && (multiColumnCount > 0) && (colCount == 0)) { // This is one particular set of conditions wh...
python
def _redraw(self): """ Forgets the current layout and redraws with the most recent information :return: None """ for row in self._rows: for widget in row: widget.grid_forget() offset = 0 if not self.headers else 1 for i, row in enumer...
python
def get_stations(self): """ Fetch the list of stations """ url = 'http://webservices.ns.nl/ns-api-stations-v2' raw_stations = self._request('GET', url) return self.parse_stations(raw_stations)
java
private static void changeNetworkWPA2EAP(WifiManager wifiManager, WifiParsedResult wifiResult) { WifiConfiguration config = changeNetworkCommon(wifiResult); // Hex passwords that are 64 bits long are not to be quoted. config.preSharedKey = quoteNonHex(wifiResult.getPassword(), 64); config.allowedAuthAlg...
java
public void setFrameData(String id, byte[] data) { if (allow(ID3V2)) { id3v2.updateFrameData(id, data); } }
python
def get_path(language): ''' Returns the full path to the language file ''' filename = language.lower() + '.json' lang_file_path = os.path.join(_DEFAULT_DIR, filename) if not os.path.exists(lang_file_path): raise IOError('Could not find {} language file'.format(language)) return lang_file_path
python
async def add_message(self, request): """Registers a new message for the user.""" session = await get_session(request) user_id = session.get('user_id') if not user_id: raise web.HTTPNotAuthorized() form = await request.post() if form.get('text'): ...
python
def ntp(name, servers): ''' Ensures that the NTP servers are configured. Servers are provided as an individual string or list format. Only four NTP servers will be reviewed. Any entries past four will be ignored. name: The name of the module function to execute. servers(str, list): The IP address ...
java
public float get(int row, int col) { if (row < 0 || row > 3) { throw new IndexOutOfBoundsException("Index: " + row + ", Size: 4"); } if (col < 0 || col > 3) { throw new IndexOutOfBoundsException("Index: " + col + ", Size: 4"); } return m_data[row * 4 + co...
java
private static AbstractPlanNode pushDownAggregate(AbstractPlanNode root, AggregatePlanNode distNode, AggregatePlanNode coordNode, ParsedSelectStmt selectStmt) { AggregatePlanNode rootAggNode; ...
python
def lfsr_next_one_seed(seed_iter, min_value_shift): """High-quality seeding for LFSR generators. The LFSR generator components discard a certain number of their lower bits when generating each output. The significant bits of their state must not all be zero. We must ensure that when seeding the gen...
java
@Override public void draw(float x,float y,float width,float height) { init(); draw(x,y,width,height,Color.white); }
java
private ColumnDef getColumnDefByName(CfDef columnFamily, ByteBuffer columnName) { for (ColumnDef columnDef : columnFamily.getColumn_metadata()) { byte[] currName = columnDef.getName(); if (ByteBufferUtil.compare(currName, columnName) == 0) { retur...
python
def is_dirty(using=None): """ Returns True if the current transaction requires a commit for changes to happen. """ if using is None: dirty = False for using in tldap.backend.connections: connection = tldap.backend.connections[using] if connection.is_dirty(): ...
python
def register_options(cls, register): """Register an option to make capturing snapshots optional. This class is intended to be extended by Jvm resolvers (coursier and ivy), and the option name should reflect that. """ super(JvmResolverBase, cls).register_options(register) # TODO This flag should be d...
python
def to_array(self): """ Serializes this Document to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(Document, self).to_array() array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str if self....
python
def _set_vlan_name(self, v, load=False): """ Setter method for vlan_name, mapped from YANG variable /interface_vlan/interface/vlan/vlan_name (string) If this variable is read-only (config: false) in the source YANG file, then _set_vlan_name is considered as a private method. Backends looking to popu...
java
public String generateJava2ContentParser(TypeName paramTypeName) { if (!managedParams.containsKey(paramTypeName)) { managedParams.put(paramTypeName, "" + (managedParams.size() + 1)); } return PARAM_PARSER_PREFIX + managedParams.get(paramTypeName); }
python
def int(self, *args): """ Return the integer stored in the specified node. Any type of integer will be decoded: byte, short, long, long long """ data = self.bytes(*args) if data is not None: if len(data) == 1: return struct.unpack("...
java
public JobScheduleDeleteOptions withIfModifiedSince(DateTime ifModifiedSince) { if (ifModifiedSince == null) { this.ifModifiedSince = null; } else { this.ifModifiedSince = new DateTimeRfc1123(ifModifiedSince); } return this; }
python
def _get_out_file(work_dir, paired): """Retrieve manta output variant file, depending on analysis. """ if paired: if paired.normal_bam: base_file = "somaticSV.vcf.gz" else: base_file = "tumorSV.vcf.gz" else: base_file = "diploidSV.vcf.gz" return os.pat...
python
def report( vulnerabilities, fileobj, print_sanitised, ): """ Prints issues in color-coded text format. Args: vulnerabilities: list of vulnerabilities to report fileobj: The output file object, which may be sys.stdout """ n_vulnerabilities = len(vulnerabilities) unsa...
java
public StartGameSessionPlacementRequest withDesiredPlayerSessions(DesiredPlayerSession... desiredPlayerSessions) { if (this.desiredPlayerSessions == null) { setDesiredPlayerSessions(new java.util.ArrayList<DesiredPlayerSession>(desiredPlayerSessions.length)); } for (DesiredPlayerSess...
java
public void fastClear(int index) { assert index >= 0 && index < numBits; int wordNum = index >> 6; int bit = index & 0x03f; long bitmask = 1L << bit; bits[wordNum] &= ~bitmask; // hmmm, it takes one more instruction to clear than it does to set... any // way to wo...
python
def update(self, data): """ Update metadata, handle virtual hierarchy """ # Nothing to do if no data if data is None: return for key, value in sorted(data.items()): # Handle child attributes if key.startswith('/'): name = key.lstrip('/'...
python
def _balance(self, ): """ calc unbalanced charges and radicals for skin atoms """ meta = h.meta for n in (skin_reagent.keys() | skin_product.keys()): lost = skin_reagent[n] cycle_lost = cycle(lost) new = skin_product[n] cycle_new = cycle(ne...
java
public void doGenerateExampleQueries(String args) { Boolean del = false; if (args != null && "overwrite".equals(args)) { del = true; } if (corpusList != null) { for (Long corpusId : corpusList) { System.out.println("generate example queries " + corpusId); que...
python
def setHierarchyLookup(self, columnName, tableType=None): """ Sets the hierarchy lookup for the inputed table type and column. :param columnName | <str> tableType | <subclass of Table> """ if tableType: tableType = self.table...
python
def compute_and_save_video_metrics( output_dirs, problem_name, video_length, frame_shape): """Compute and saves the video metrics.""" statistics, all_results = compute_video_metrics_from_png_files( output_dirs, problem_name, video_length, frame_shape) for results, output_dir in zip(all_results, output_d...
java
@Override public Writer append(CharSequence csq, int start, int end) throws IOException { encodedAppender.append(encoder, null, csq, 0, end - start); return this; }
java
public static double[] calcInverseSunVector( double[] sunVector ) { double m = Math.max(Math.abs(sunVector[0]), Math.abs(sunVector[1])); return new double[]{-sunVector[0] / m, -sunVector[1] / m, -sunVector[2] / m}; }
java
public static boolean isAsciiPrintable(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if (CharUtils.isAsciiPrintable(str.charAt(i)) == false) { return false; } } re...
python
def grep_full_py_identifiers(tokens): """ :param typing.Iterable[(str,str)] tokens: :rtype: typing.Iterator[str] """ global py_keywords tokens = list(tokens) i = 0 while i < len(tokens): token_type, token = tokens[i] i += 1 if token_type != "id": conti...
java
public static void marginals(final Hypergraph graph, final Hyperpotential w, final Algebra s, final Scores scores) { final int n = graph.getNodes().size(); final double[] alpha = scores.alpha; final double[] beta = scores.beta; final double[] marginal = new double[n]; ...
java
@Override public DescribeReceiptRuleResult describeReceiptRule(DescribeReceiptRuleRequest request) { request = beforeClientExecution(request); return executeDescribeReceiptRule(request); }
python
def get (self, feature): """ Returns all values of 'feature'. """ if type(feature) == type([]): feature = feature[0] if not isinstance(feature, b2.build.feature.Feature): feature = b2.build.feature.get(feature) assert isinstance(feature, b2.build.feature.F...
python
def list_views(): """ List all registered views """ echo_header("List of registered views") for view in current_app.appbuilder.baseviews: click.echo( "View:{0} | Route:{1} | Perms:{2}".format( view.__class__.__name__, view.route_base, view.base_permissions ...
java
@Override protected boolean prepare(final Context2D context, final Attributes attr, final double alpha) { final double r = attr.getRadius(); if (r > 0) { context.beginPath(); context.arc(0, 0, r, 0, Math.PI * 2, true); context.closePath(); ...
python
def get_child_books(self, book_id): """Gets the child books of the given ``id``. arg: book_id (osid.id.Id): the ``Id`` of the ``Book`` to query return: (osid.commenting.BookList) - the child books of the ``id`` raise: NotFound - a ``Book`` identified ...
python
def to_json(self, lev=0, indent=None): """ Serialize the content of this instance into a JSON string. :param lev: :param indent: Number of spaces that should be used for indentation :return: """ if lev: return self.to_dict(lev + 1) ...
java
private void readFile(InputStream is) throws IOException { StreamHelper.skip(is, 64); int index = 64; ArrayList<Integer> offsetList = new ArrayList<Integer>(); List<String> nameList = new ArrayList<String>(); while (true) { byte[] table = new byte[32]; is.read(...
python
def _post_run_hook(self, runtime): ''' generates a report showing slices from each axis of an arbitrary volume of in_file, with the resulting binary brain mask overlaid ''' self._anat_file = self.inputs.in_file self._mask_file = self.aggregate_outputs(runtime=runtime).mask_file ...