language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def compress(pdf_in, pdf_output): """ mac下安装 brew install ghostscript :param pdf_in: :param pdf_output: :return: """ cmd = 'gs -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/screen -sOutputFile=%s %s' cmd = cmd % (pdf_output, pdf_in) os.system(cmd)
java
public void addForwardedField(int sourceField, FieldSet destinationFields) { FieldSet fs; if((fs = this.forwardedFields.get(sourceField)) != null) { fs.addAll(destinationFields); } else { fs = new FieldSet(destinationFields); this.forwardedFields.put(sourceField, fs); } }
python
def event_detail(self, event_detail): """ :param event_detail: :return: """ if event_detail is not None: if isinstance(event_detail, str): self._event_detail = event_detail else: try: for key, val in even...
java
protected void handleError(final AccountState.Error error, final AuthenticationResponse response, final PasswordPolicyConfiguration configuration, final List<MessageDescriptor> messages) throws LoginException { LOGGER.debug("Handling LDAP account state error [{}]", error); ...
python
def get_related(self): """Check if any of the context interfaces have relation ids. Set self.related and return True if one of the interfaces has relation ids. """ # Fresh start self.related = False try: for interface in self.interfaces: ...
java
public static String dropWhile(GString self, @ClosureParams(value=SimpleType.class, options="char") Closure condition) { return dropWhile(self.toString(), condition).toString(); }
java
public static lbvserver_stats get(nitro_service service, String name) throws Exception{ lbvserver_stats obj = new lbvserver_stats(); obj.set_name(name); lbvserver_stats response = (lbvserver_stats) obj.stat_resource(service); return response; }
python
def compile(self, s): """ Compile the given script. Returns a bytes object with the compiled script. """ f = io.BytesIO() for t in s.split(): t_up = t.upper() if t_up in self.opcode_to_int: f.write(int2byte(self.opcode_to_int[t])) ...
java
@Override public VType put(KType key, VType value) { assert assigned < mask + 1; final int mask = this.mask; if (Intrinsics.<KType> isEmpty(key)) { hasEmptyKey = true; VType previousValue = Intrinsics.<VType> cast(values[mask + 1]); values[mask + 1] = value; return previousValue; ...
python
def _set_body(self, body): """Set the main body for this control flow structure.""" assert isinstance(body, CodeStatement) if isinstance(body, CodeBlock): self.body = body else: self.body._add(body)
java
public UriTemplateBuilder template(String... template) { UriTemplateParser parser = new UriTemplateParser(); for(String t : template) { addComponents(parser.scan(t)); } return this; }
python
def handle_starting_instance(self): """Starting up PostgreSQL may take a long time. In case we are the leader we may want to fail over to.""" # Check if we are in startup, when paused defer to main loop for manual failovers. if not self.state_handler.check_for_startup() or self.is_pause...
python
def _batch_norm(name, x): """Batch normalization.""" with tf.name_scope(name): return tf.contrib.layers.batch_norm( inputs=x, decay=.9, center=True, scale=True, activation_fn=None, updates_collections=None, is_training=False)
java
@Nullable public static String getUntilLastIncl (@Nullable final String sStr, final char cSearch) { return _getUntilLast (sStr, cSearch, true); }
java
public static br add(nitro_service client, br resource) throws Exception { resource.validate("add"); return ((br[]) resource.perform_operation(client, "add"))[0]; }
python
def html_email(email, title=None): """ >>> html_email('username@example.com') '<a href="mailto:username@example.com">username@example.com</a>' """ if not title: title = email return '<a href="mailto:{email}">{title}</a>'.format(email=email, title=title)
java
public String getEffectiveListName() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { String activeListName = getActiveListName(); if (activeListName != null) { return activeListName; } return getDefaultListName(); }
java
@Override public void setValueAt(final Object value, final List<Integer> row, final int col) { getBacking().setValueAt(value, getRowIndex(row), col); }
python
def service_create(image=str, name=str, command=str, hostname=str, replicas=int, target_port=int, published_port=int): ''' Create Docker Swarm Service Create image The docker image ...
java
public String getContent() { String content = ""; NodeList list = dom.getChildNodes(); for (int i=0;i<list.getLength();i++) { if (list.item(i) instanceof Text) { content += (list.item(i).getNodeValue()); } } return content; }
python
def json_api_call(req_function): """ Wrap a view-like function that returns an object that is convertable from json """ @wraps(req_function) def newreq(request, *args, **kwargs): outp = req_function(request, *args, **kwargs) if issubclass(outp.__class__, HttpResponse): ...
java
public synchronized OServerAdmin createDatabase(final String iDatabaseType, String iStorageMode) throws IOException { storage.checkConnection(); try { if (storage.getName() == null || storage.getName().length() <= 0) { OLogManager.instance().error(this, "Cannot create unnamed remote storage....
python
def generate_nodes(tpm, cm, network_state, indices, node_labels=None): """Generate |Node| objects for a subsystem. Args: tpm (np.ndarray): The system's TPM cm (np.ndarray): The corresponding CM. network_state (tuple): The state of the network. indices (tuple[int]): Indices to ge...
java
String getProcErrorOutput(Process proc) throws IOException { StringBuffer output = new StringBuffer(); InputStream procIn = proc.getInputStream(); int read; // Dump the data printed by the process do { byte[] buffer = new byte[BUFFER_SIZE]; read = procIn....
python
def getServiceNamesToTraceIds(self, time_stamp, service_name, rpc_name): """ Given a time stamp, server service name, and rpc name, fetch all of the client services calling in paired with the lists of every trace Ids (list<i64>) from the server to client. The three arguments specify epoch time in micro...
java
private void findNextExpireTime() { if (objects.size() == 0) { nextTimeSomeExpired = NO_OBJECTS; } else { nextTimeSomeExpired = NO_OBJECTS; Collection<Long> longs = null; synchronized (objects) { long...
java
public void finish() throws CmsException { m_finished = true; m_requiresCleanup = false; CmsProject project = getProject(); CmsObject projectCms = OpenCms.initCmsObject(m_adminCms); projectCms.getRequestContext().setCurrentProject(project); if (m_configuration.isAutoPubl...
java
@Override public MatchResult matches(List<String> lines) { MatchResult result = NO_MATCH; for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (line.contains("<PC-Substance") && result == NO_MATCH) result = new MatchResult(true, this, i); if (li...
python
def read_metadata(self, key): """ return the meta data array for this key """ if getattr(getattr(self.group, 'meta', None), key, None) is not None: return self.parent.select(self._get_metadata_path(key)) return None
java
public static CmsSelectWidgetOption getWidgetOptionForType(CmsObject cms, String typeName) { String niceTypeName = typeName; try { Locale locale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms); niceTypeName = CmsWorkplaceMessages.getResourceTypeName(locale, typeName); ...
python
def get_all_dataset_names(configuration=None, **kwargs): # type: (Optional[Configuration], Any) -> List[str] """Get all dataset names in HDX Args: configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration. **kwargs: See below ...
python
def get(self, filename): """ Check if a distribution archive exists in the local cache. :param filename: The filename of the distribution archive (a string). :returns: The pathname of a distribution archive on the local file system or :data:`None`. """ ...
java
protected void estimateCase1( double betas[] ) { betas[0] = matchScale(nullPts[0], controlWorldPts); betas[0] = adjustBetaSign(betas[0],nullPts[0]); betas[1] = 0; betas[2] = 0; betas[3] = 0; }
java
public static cacheobject[] get(nitro_service service, cacheobject_args args) throws Exception{ cacheobject obj = new cacheobject(); options option = new options(); option.set_args(nitro_util.object_to_string_withoutquotes(args)); cacheobject[] response = (cacheobject[])obj.get_resources(service, option); ret...
java
protected void setupForbiddenEndElements() { forbiddenIdEndElements.put(THREAD_SUBJECT, THREAD_SUBJECT); forbiddenIdEndElements.put(THREAD_PARENT, THREAD_PARENT); forbiddenIdEndElements.put(THREAD_ANCESTOR, THREAD_ANCESTOR); forbiddenIdEndElements.put(THREAD_PAGE, THREAD_PAGE); forbiddenIdEndElements.put(THRE...
java
public static void move(final Object ar, final int pos, final int off, final int l) { System.arraycopy(ar, pos, ar, pos + off, l); }
python
def set_backlight(self, backlight): """Enable or disable the backlight. If PWM is not enabled (default), a non-zero backlight value will turn on the backlight and a zero value will turn it off. If PWM is enabled, backlight can be any value from 0.0 to 1.0, with 1.0 being full intensity...
python
def _get_calculated_size(self, size, data): """ Get's the final size of the field and runs the lambda functions recursively until a final size is derived. If size is None then it will just return the length of the data as it is assumed it is the final field (None should only be s...
java
public static <T> Predicate<T> getEquals(T target2) { return target -> target.equals(target2); }
python
def hdel(self, hashkey, *keys): """Emulate hdel""" redis_hash = self._get_hash(hashkey, 'HDEL') count = 0 for key in keys: attribute = self._encode(key) if attribute in redis_hash: count += 1 del redis_hash[attribute] ...
java
public PrivateZoneInner createOrUpdate(String resourceGroupName, String privateZoneName, PrivateZoneInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, privateZoneName, parameters).toBlocking().last().body(); }
python
def run(path, timer=False, repeat=3, number=10000, precision=2): """ Extracts and runs the '@cyther' code from the given file 'path' name """ code = extractAtCyther(path) if not code: output = "There was no '@cyther' code collected from the " \ "file '{}'\n".format(path) ...
python
def _build_url(self, shorten=True): """Build the url for a cable ratings page""" self.url = URL_FORMAT.format(*self._get_url_params(shorten=shorten))
java
public UOWControl getUOWControl(UserTransaction userTx) //LIDB4171-35.03 F84120 { final boolean entryEnabled = TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled(); if (entryEnabled) { Tr.entry(tc, "getUOWControl"); } UOWControl uowCtrl = ne...
python
def check_password(password, encoded, setter=None, preferred='default'): """ Return a boolean of whether the raw password matches the three part encoded digest. If setter is specified, it'll be called when you need to regenerate the password. """ if password is None: return False ...
python
def cmd_wp_changealt(self, args): '''handle wp change target alt of multiple waypoints''' if len(args) < 2: print("usage: wp changealt WPNUM NEWALT <NUMWP>") return idx = int(args[0]) if idx < 1 or idx > self.wploader.count(): print("Invalid wp number ...
python
def _generate_property_iv(entity_iv, pk, rk, property_name, isJavaV1): ''' Uses the entity_iv, partition key, and row key to generate and return the iv for the specified property. ''' digest = Hash(SHA256(), default_backend()) if not isJavaV1: digest.update(entity_iv + ...
java
private static void addSuggestion(List<LocationSuggestion> suggestions, String address) { suggestions.add(new LocationSuggestion(address)); }
python
def get_end_start_epochs(year, month, day, direction, unit, count): """ Gets epoch from a start date and epoch from a shifted date Args: year: Int between 1 and 9999. month: Int between 1 and 12. day: Int between 1 and 31. direction: String to shift time forwards or backwards. ...
python
def ufo2glyphs(options): """Convert one designspace file or one or more UFOs to a Glyphs.app source file.""" import fontTools.designspaceLib import defcon sources = options.designspace_file_or_UFOs designspace_file = None if ( len(sources) == 1 and sources[0].endswith(".designsp...
python
def create_oracle(username, password, host, port, database, **kwargs): # pragma: no cover """ create an engine connected to a oracle database using cx_oracle. """ return create_engine( _create_oracle(username, password, host, port, database), **kwargs )
java
public boolean isSortedFromTo(int from, int to) { if (size==0) return true; checkRangeFromTo(from, to, size); Object[] theElements = elements; for (int i=from+1; i<=to; i++ ) { if (((Comparable)theElements[i]).compareTo((Comparable) theElements[i-1]) < 0) return false; } return true; }
python
def get_series_vintage_dates(self, series_id): """ Get a list of vintage dates for a series. Vintage dates are the dates in history when a series' data values were revised or new data values were released. Parameters ---------- series_id : str Fred series id ...
python
def page_erase(addr): """Erases a single page.""" if __verbose: print("Erasing page: 0x%x..." % (addr)) # Send DNLOAD with first byte=0x41 and page address buf = struct.pack("<BI", 0x41, addr) __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, buf, __TIMEOUT) # Execute last co...
java
public com.ibm.wsspi.cache.CacheEntry getEntry(Object cacheId){ CacheEntry cacheEntry = new CacheEntry(cacheInstance.getEntry(cacheId)); return cacheEntry; }
java
private IAsyncResultHandler<IApiConnectionResponse> createApiConnectionResponseHandler() { return (IAsyncResult<IApiConnectionResponse> result) -> { if (result.isSuccess()) { requestMetric.setApiEnd(new Date()); // The result came back. NB: still need to put it throug...
python
def add_step_timing_signal(x, step, hparams): """Add n-dimensional embedding as the step (vertical) timing signal. Args: x: a tensor with shape [batch, length, depth] step: step hparams: model hyper parameters Returns: a Tensor with the same shape as x. """ if hparams.recurrence_type == "ac...
python
def _clear_context(): ''' Clear any lxc variables set in __context__ ''' for var in [x for x in __context__ if x.startswith('lxc.')]: log.trace('Clearing __context__[\'%s\']', var) __context__.pop(var, None)
java
@Nullable @CheckReturnValue public static String trimStartAndEnd (@Nullable final String sSrc, @Nullable final String sLead, @Nullable final String sTail) { final String sInbetween = trimStart (sSrc, sLead); return trimEnd (sI...
python
def tagscleanupdicts(configuration=None, url=None, keycolumn=5, failchained=True): # type: (Optional[Configuration], Optional[str], int, bool) -> Tuple[Dict,List] """ Get tags cleanup dictionaries Args: configuration (Optional[Configuration]): HDX configuration. Defaults to ...
java
private List<CmsSelectWidgetOption> getProjects() { List<CmsSelectWidgetOption> projects = new ArrayList<CmsSelectWidgetOption>(); try { String defProject = null; if ((m_user != null) && CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_user.getName())) { defProject = ...
java
private void flushCharacters() { int indentLength = 0; int len = charBuffer.length(); /* * Count characters from end of ignorable whitespace to first end of line we hit */ for ( int i = len - 1; i >= 0; i-- ) { char ch = charBuffer.charAt( i ); ...
java
public static MatrixAccumulator mkManhattanNormAccumulator() { return new MatrixAccumulator() { private double result = 0.0; @Override public void update(int i, int j, double value) { result += Math.abs(value); } @Override ...
python
def update_dataset(self,dataStr,flatten=False): ''' update class with a data structure. :keyword flatten: use this to automatically flatten variables (squeeze dimensions) ''' #Load keys and dimensions ######################### dataDim = dataStr....
python
def write_config(ip, mac, single, double, long, touch): """Write the current configuration of a myStrom button.""" click.echo("Write configuration to device %s" % ip) data = { 'single': single, 'double': double, 'long': long, 'touch': touch, } request = requests.post(...
java
private int[] buildIndex(final int[] counts, int[] positions, int minsupp) { // Count the number of frequent items: int numfreq = 0; for(int i = 0; i < counts.length; i++) { if(counts[i] >= minsupp) { ++numfreq; } } // Build the index table int[] idx = new int[numfreq]; f...
java
private String ipAddressFromNI(String niSpec, String name) { String result = "UNKNOWN"; NetworkInterface ni = null; String[] parts = niSpec.split(":"); String niName = "eth0"; // default NIC name Scheme scheme = Scheme.ipv4; int index = 0; // default index Scope scope = Scope.global; // ...
python
def install_dap_from_path(path, update=False, update_allpaths=False, first=True, force=False, nodeps=False, reinstall=False, __ui__=''): '''Installs a dap from a given path''' will_uninstall = False dap_obj = dapi.Dap(path) name = dap_obj.meta['package_name'] if name in ge...
java
public static IntCountsHistogram decodeFromByteBuffer(final ByteBuffer buffer, final long minBarForHighestTrackableValue) { return (IntCountsHistogram) decodeFromByteBuffer(buffer, IntCountsHistogram.class, minBarForHighestTrackableValue); ...
java
boolean isNameUnique(String name, String currentJobName) { Item item = getItem(name); if(null==item) { // the candidate name didn't return any items so the name is unique return true; } else if(item.getName().equals(currentJobName)) { // the candidate...
java
public boolean canTraverseOutsideSubtree() { if (null != m_left && m_left.canTraverseOutsideSubtree()) return true; if (null != m_right && m_right.canTraverseOutsideSubtree()) return true; return false; }
python
def check_cousins(self, individual_1_id, individual_2_id): """ Check if two family members are cousins. If two individuals share any grandparents they are cousins. Arguments: individual_1_id (str): The id of an individual individual_2_id (str): ...
python
def dry_run_scan(self, scan_id, targets): """ Dry runs a scan. """ os.setsid() for _, target in enumerate(targets): host = resolve_hostname(target[0]) if host is None: logger.info("Couldn't resolve %s.", target[0]) continue por...
python
def generate_with_delta_f_and_max_freq(self, t_num, max_freq, delta_f, low_frequency_cutoff=None, cached_mem=None): """Generate the template with index t_num using custom length.""" approximant = self.approximant(t_num...
python
def sensitivity(imgs, bg=None): ''' Extract pixel sensitivity from a set of homogeneously illuminated images This method is detailed in Section 5 of: --- K.Bedrich, M.Bokalic et al.: ELECTROLUMINESCENCE IMAGING OF PV DEVICES: ADVANCED FLAT FIELD CALIBRATION,2017 --- ''' ...
java
void splitBranches(final Element elem, final Branch filter) { final List<Element> ditavalRefs = getChildElements(elem, DITAVAREF_D_DITAVALREF); if (ditavalRefs.size() > 0) { // remove ditavalrefs for (final Element branch: ditavalRefs) { elem.removeChild(branch); ...
java
private void buildAttributeValueObject(final String name) { attributeValue_5.name = name; attributeValue_5.quality = AttrQuality.ATTR_VALID; attributeValue_5.data_format = AttrDataFormat.FMT_UNKNOWN; attributeValue_5.time = new TimeVal(); attributeValue_5.r_dim = new AttributeDim...
java
public Iterable<Result<DeleteError>> removeObjects(final String bucketName, final Iterable<String> objectNames) { return new Iterable<Result<DeleteError>>() { @Override public Iterator<Result<DeleteError>> iterator() { return new Iterator<Result<DeleteError>>() { private Result<DeleteE...
java
@Override public ListPhoneNumbersOptedOutResult listPhoneNumbersOptedOut(ListPhoneNumbersOptedOutRequest request) { request = beforeClientExecution(request); return executeListPhoneNumbersOptedOut(request); }
java
public static int calculateMod11CheckSum(int[] weights, StringNumber number) { int c = calculateChecksum(weights, number, false) % 11; if (c == 1) { throw new IllegalArgumentException(ERROR_INVALID_CHECKSUM + number); } return c == 0 ? 0 : 11 - c; }
java
private void mergePossibleResponse() { // TODO only HttpResponse element? if (!runtimeStack.isEmpty() && runtimeStack.peek().getTypes().contains(Types.RESPONSE)) { mergeReturnElement(runtimeStack.peek()); } }
java
public String showPrompt() { String prompt = isAnsiEnabled() ? ansiPrompt(PROMPT).toString() : PROMPT; return showPrompt(prompt); }
python
def async_refresh_state(self): """Request each state to provide status update.""" _LOGGER.debug('Setting up extended status') ext_status = ExtendedSend( address=self._address, commandtuple=COMMAND_EXTENDED_GET_SET_0X2E_0X00, cmd2=0x02, userdata=Use...
python
def first_seen(self, first_seen): """Set Document first seen.""" self._group_data['firstSeen'] = self._utils.format_datetime( first_seen, date_format='%Y-%m-%dT%H:%M:%SZ' )
python
def compare_disks(disk0, disk1, configuration): """Compares two disks according to the given configuration.""" with DiskComparator(disk0, disk1) as comparator: results = comparator.compare( size=configuration.get('get_file_size', False), identify=configuration.get('identify_files...
java
public void marshall(GetRateBasedRuleManagedKeysRequest getRateBasedRuleManagedKeysRequest, ProtocolMarshaller protocolMarshaller) { if (getRateBasedRuleManagedKeysRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { proto...
java
public void printStackTrace(PrintStream stream) { if (getRootCause() != null) { stream.println(this.getMessage()); getRootCause().printStackTrace(stream); } else { this.printStackTrace(stream); } }
python
def _parse_season(self, row): """ Parse the season string from the table. The season is generally located in the first column of the stats tables and should be parsed to detonate which season metrics are being pulled from. Parameters ---------- row : PyQ...
java
protected boolean matches(File f, boolean isFile) { if (fileFilter != null) { if (isFile && directoriesOnly) { return false; } else if (!isFile && filesOnly) { return false; } else if (fileNameRegex != null) { Matcher m = fileNa...
java
public static Optional<SuggestedFix> removeModifiers( ModifiersTree originalModifiers, VisitorState state, Set<Modifier> toRemove) { SuggestedFix.Builder fix = SuggestedFix.builder(); List<ErrorProneToken> tokens = state.getTokensForNode(originalModifiers); int basePos = ((JCTree) originalModifiers).g...
python
def to_networkx(self, labels=None, edge_labels=False): """ Get a networkx representation of the binary search tree. """ import networkx as nx graph = nx.DiGraph() for node in self._traverse_nodes(): u = node.key graph.add_node(u) # Minor redundancy # ...
java
public String convertOBPYoaOrentToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); }
python
def linreg_ols_pinv(y, X, rcond=1e-15): """Linear Regression, OLS, by multiplying with Pseudoinverse""" import numpy as np try: # multiply with inverse to compute coefficients return np.dot(np.linalg.pinv( np.dot(X.T, X), rcond=rcond), np.dot(X.T, y)) except np.linalg.LinAlgError: ...
java
public static double spearmanRankCorrelationCoefficient(double[] a, double[] b) { check(a, b); int N = a.length; int NcubedMinusN = (N * N * N) - N; // Convert a and b into rankings. The last value of this array is the ...
java
@Override public String selectMajorCurrency(final String ccy1, final String ccy2) { return ranks.getOrDefault(StringUtil.toUpperCase(ccy1), DEFAULT_UNRANKED_VALUE).intValue() <= ranks.getOrDefault(StringUtil.toUpperCase(ccy2), DEFAULT_UNRANKED_VALUE).intValue() ? ccy1 : ccy2; }
python
def update_or_create(cls, append_lists=True, with_status=False, remove_members=False, **kwargs): """ Update or create group entries. If the group exists, the members will be updated. Set append_lists=True to add new members to the list, or False to reset the list...
java
@Override public Response toResponse(Throwable ex) { return Response.status(Status.INTERNAL_SERVER_ERROR).entity(new ErrorMessage(Status.INTERNAL_SERVER_ERROR.getStatusCode(), ex.getMessage())) .type(MediaType.APPLICATION_JSON_TYPE).build(); }
java
public static synchronized void suppressMethod(Class<?> clazz, boolean excludePrivateMethods) { Method[] methods = null; if (excludePrivateMethods) { methods = clazz.getMethods(); } else { methods = clazz.getDeclaredMethods(); } for (Method method : methods) { MockRepository.addMethodToSuppress(met...
python
def minimum_image_dr( self, r1, r2, cutoff=None ): """ Calculate the shortest distance between two points in the cell, accounting for periodic boundary conditions. Args: r1 (np.array): fractional coordinates of point r1. r2 (np.array): fractional coordinates of ...
python
def clear_highest_numeric_score(self): """Clears the highest numeric score. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid...