language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static Request newUpdateOpenGraphObjectRequest(Session session, String id, String title, String imageUrl, String url, String description, GraphObject objectProperties, Callback callback) { OpenGraphObject openGraphObject = OpenGraphObject.Factory.createForPost(OpenGraphObject.class, null, title, imageUrl, url, description); openGraphObject.setId(id); openGraphObject.setData(objectProperties); return newUpdateOpenGraphObjectRequest(session, openGraphObject, callback); }
java
public final void nonWildcardTypeArguments() throws RecognitionException { int nonWildcardTypeArguments_StartIndex = input.index(); try { if ( state.backtracking>0 && alreadyParsedRule(input, 136) ) { return; } // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1275:5: ( '<' typeList '>' ) // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1275:7: '<' typeList '>' { match(input,53,FOLLOW_53_in_nonWildcardTypeArguments6218); if (state.failed) return; pushFollow(FOLLOW_typeList_in_nonWildcardTypeArguments6220); typeList(); state._fsp--; if (state.failed) return; match(input,56,FOLLOW_56_in_nonWildcardTypeArguments6222); if (state.failed) return; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving if ( state.backtracking>0 ) { memoize(input, 136, nonWildcardTypeArguments_StartIndex); } } }
java
public void patch(String jobId, JobPatchParameter jobPatchParameter, JobPatchOptions jobPatchOptions) { patchWithServiceResponseAsync(jobId, jobPatchParameter, jobPatchOptions).toBlocking().single().body(); }
java
@SuppressWarnings("unchecked") public EList<IfcStructuralLoadGroup> getLoadedBy() { return (EList<IfcStructuralLoadGroup>) eGet(Ifc2x3tc1Package.Literals.IFC_STRUCTURAL_ANALYSIS_MODEL__LOADED_BY, true); }
python
def c_drop(self, frequency): ''' Capacitance of an electrode covered in liquid, normalized per unit area (i.e., units are F/mm^2). ''' try: return np.interp(frequency, self._c_drop['frequency'], self._c_drop['capacitance'] ) except: pass return self._c_drop
python
def event_actions(self): """ Take actions for timed events Returns ------- None """ system = self.system dae = system.dae if self.switch: system.Breaker.apply(self.t) for item in system.check_event(self.t): system.__dict__[item].apply(self.t) dae.rebuild = True self.switch = False
java
public void mTokens() throws RecognitionException { // InternalSimpleExpressions.g:1:8: ( T__11 | T__12 | T__13 | T__14 | T__15 | T__16 | T__17 | T__18 | T__19 | T__20 | T__21 | T__22 | T__23 | T__24 | T__25 | RULE_ID | RULE_INT | RULE_STRING | RULE_ML_COMMENT | RULE_SL_COMMENT | RULE_WS | RULE_ANY_OTHER ) int alt12=22; alt12 = dfa12.predict(input); switch (alt12) { case 1 : // InternalSimpleExpressions.g:1:10: T__11 { mT__11(); } break; case 2 : // InternalSimpleExpressions.g:1:16: T__12 { mT__12(); } break; case 3 : // InternalSimpleExpressions.g:1:22: T__13 { mT__13(); } break; case 4 : // InternalSimpleExpressions.g:1:28: T__14 { mT__14(); } break; case 5 : // InternalSimpleExpressions.g:1:34: T__15 { mT__15(); } break; case 6 : // InternalSimpleExpressions.g:1:40: T__16 { mT__16(); } break; case 7 : // InternalSimpleExpressions.g:1:46: T__17 { mT__17(); } break; case 8 : // InternalSimpleExpressions.g:1:52: T__18 { mT__18(); } break; case 9 : // InternalSimpleExpressions.g:1:58: T__19 { mT__19(); } break; case 10 : // InternalSimpleExpressions.g:1:64: T__20 { mT__20(); } break; case 11 : // InternalSimpleExpressions.g:1:70: T__21 { mT__21(); } break; case 12 : // InternalSimpleExpressions.g:1:76: T__22 { mT__22(); } break; case 13 : // InternalSimpleExpressions.g:1:82: T__23 { mT__23(); } break; case 14 : // InternalSimpleExpressions.g:1:88: T__24 { mT__24(); } break; case 15 : // InternalSimpleExpressions.g:1:94: T__25 { mT__25(); } break; case 16 : // InternalSimpleExpressions.g:1:100: RULE_ID { mRULE_ID(); } break; case 17 : // InternalSimpleExpressions.g:1:108: RULE_INT { mRULE_INT(); } break; case 18 : // InternalSimpleExpressions.g:1:117: RULE_STRING { mRULE_STRING(); } break; case 19 : // InternalSimpleExpressions.g:1:129: RULE_ML_COMMENT { mRULE_ML_COMMENT(); } break; case 20 : // InternalSimpleExpressions.g:1:145: RULE_SL_COMMENT { mRULE_SL_COMMENT(); } break; case 21 : // InternalSimpleExpressions.g:1:161: RULE_WS { mRULE_WS(); } break; case 22 : // InternalSimpleExpressions.g:1:169: RULE_ANY_OTHER { mRULE_ANY_OTHER(); } break; } }
java
@Override public LookupInBuilder lookupIn(String docId) { AsyncLookupInBuilder asyncBuilder = asyncBucket.lookupIn(docId); return new LookupInBuilder(asyncBuilder, kvTimeout, TIMEOUT_UNIT); }
java
@Factory public static <T extends Throwable> Matcher<T> hasCause(final Matcher<?> matcher) { return new ThrowableCauseMatcher<T>(matcher); }
java
@Override protected boolean hasUnderflow(N node) { if(node.isLeaf()) { return node.getNumEntries() < leafMinimum; } else { return node.getNumEntries() < dirMinimum; } }
java
public void setBandwidthSegment(com.google.api.ads.admanager.axis.v201902.BandwidthGroupTargeting bandwidthSegment) { this.bandwidthSegment = bandwidthSegment; }
java
private Zxid getNextProposedZxid() { if (lastProposedZxid.getEpoch() != establishedEpoch) { lastProposedZxid = new Zxid(establishedEpoch, -1); } lastProposedZxid = new Zxid(establishedEpoch, lastProposedZxid.getXid() + 1); return lastProposedZxid; }
java
private CmsXmlContent writeContent(CmsObject cms, CmsFile file, CmsXmlContent content, String encoding) throws CmsException { String decodedContent = content.toString(); try { file.setContents(decodedContent.getBytes(encoding)); } catch (UnsupportedEncodingException e) { throw new CmsException( org.opencms.workplace.editors.Messages.get().container( org.opencms.workplace.editors.Messages.ERR_INVALID_CONTENT_ENC_1, file.getRootPath()), e); } // the file content might have been modified during the write operation cms.getRequestContext().setAttribute(ATTR_EDITOR_SAVING, "true"); try { file = cms.writeFile(file); } finally { cms.getRequestContext().removeAttribute(ATTR_EDITOR_SAVING); } return CmsXmlContentFactory.unmarshal(cms, file); }
python
def do_load(self, filename): """Load disk image for analysis""" try: self.__session.load(filename) except IOError as e: self.logger.error(e.strerror)
python
def delete_campaign(self, campaign_id): """Delete an update campaign. :param str campaign_id: Campaign ID to delete (Required) :return: void """ api = self._get_api(update_service.DefaultApi) api.update_campaign_destroy(campaign_id) return
java
public NimbusClient createClient(String host, int port) { Map<String, Object> nimbusConf = Maps.newHashMap(); nimbusConf.put(Config.NIMBUS_HOST, host); nimbusConf.put(Config.NIMBUS_THRIFT_PORT, port); nimbusConf.put(Config.STORM_THRIFT_TRANSPORT_PLUGIN, "backtype.storm.security.auth.SimpleTransportPlugin"); NimbusClient nimbusClient = NimbusClient.getConfiguredClient(nimbusConf); return nimbusClient; }
java
public void lockResource(CmsRequestContext context, CmsResource resource, CmsLockType type) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.ALL); m_driverManager.lockResource(dbc, resource, type); } catch (Exception e) { CmsMessageContainer messageContainer; if (e instanceof CmsLockException) { messageContainer = ((CmsLockException)e).getMessageContainer(); } else { messageContainer = Messages.get().container( Messages.ERR_LOCK_RESOURCE_2, context.getSitePath(resource), type.toString()); } dbc.report(null, messageContainer, e); } finally { dbc.clear(); } }
python
def delete_object(self, bucket, obj, version_id): """Delete an existing object. :param bucket: The bucket (instance or id) to get the object from. :param obj: A :class:`invenio_files_rest.models.ObjectVersion` instance. :param version_id: The version ID. :returns: A Flask response. """ if version_id is None: # Create a delete marker. with db.session.begin_nested(): ObjectVersion.delete(bucket, obj.key) db.session.commit() else: # Permanently delete specific object version. check_permission( current_permission_factory(bucket, 'object-delete-version'), hidden=False, ) obj.remove() db.session.commit() if obj.file_id: remove_file_data.delay(str(obj.file_id)) return self.make_response('', 204)
java
@Nullable private static String getQualifiedNameThroughCast(Node node) { if (node.isName()) { String name = node.getString(); return name.isEmpty() ? null : name; } else if (node.isGetProp()) { String left = getQualifiedNameThroughCast(node.getFirstChild()); if (left == null) { return null; } String right = node.getLastChild().getString(); return left + "." + right; } else if (node.isCast()) { return getQualifiedNameThroughCast(node.getFirstChild()); } return null; }
python
def _ident(*elements): """Return True if all sequences are equal. """ try: # for hashable elements return len(set(elements)) == 1 except TypeError: # for unhashable elements for e1, e2 in zip(elements, elements[1:]): if e1 != e2: return False return True
python
def apply(self, total_fee, refund_fee, out_refund_no, transaction_id=None, out_trade_no=None, fee_type='CNY', op_user_id=None, device_info=None, refund_account='REFUND_SOURCE_UNSETTLED_FUNDS', notify_url=None): """ 申请退款 :param total_fee: 订单总金额,单位为分 :param refund_fee: 退款总金额,单位为分 :param out_refund_no: 商户系统内部的退款单号,商户系统内部唯一,同一退款单号多次请求只退一笔 :param transaction_id: 可选,微信订单号 :param out_trade_no: 可选,商户系统内部的订单号,与 transaction_id 二选一 :param fee_type: 可选,货币类型,符合ISO 4217标准的三位字母代码,默认人民币:CNY :param op_user_id: 可选,操作员帐号, 默认为商户号 :param device_info: 可选,终端设备号 :param refund_account: 可选,退款资金来源,仅针对老资金流商户使用,默认使用未结算资金退款 :param notify_url: 可选,异步接收微信支付退款结果通知的回调地址 :return: 返回的结果数据 """ data = { 'appid': self.appid, 'device_info': device_info, 'transaction_id': transaction_id, 'out_trade_no': out_trade_no, 'out_refund_no': out_refund_no, 'total_fee': total_fee, 'refund_fee': refund_fee, 'refund_fee_type': fee_type, 'op_user_id': op_user_id if op_user_id else self.mch_id, 'refund_account': refund_account, 'notify_url': notify_url, } return self._post('secapi/pay/refund', data=data)
java
Node parseAndRecordTypeNode(JsDocToken token) { return parseAndRecordTypeNode(token, stream.getLineno(), stream.getCharno(), token == JsDocToken.LEFT_CURLY, false); }
python
def set_plot_tcrhoc(self,linestyle=['-'],burn_limit=0.997,marker=['o'],markevery=500,end_model=[-1],deg_line=True): ''' Plots HRDs end_model - array, control how far in models a run is plottet, if -1 till end symbs_1 - set symbols of runs ''' if len(linestyle)==0: linestyle=200*['-'] for i in range(len(self.runs_H5_surf)): m1p65_last=se(self.runs_H5_out[i]) t1_model=-1 if end_model[i] != -1: t1_model=end_model[i] model=m1p65_last.se.cycles model_list=[] for k in range(0,len(model),5): model_list.append(model[k]) rho1=m1p65_last.get(model_list,'rho') #[:(t1_model-t0_model)] T1=m1p65_last.get(model_list,'temperature')#[:(t1_model-t0_model)] T_unit=m1p65_last.get('temperature_unit') mass=m1p65_last.get(model_list,'mass') mini=m1p65_last.get('mini') zini=m1p65_last.get('zini') #info=m1p65_last.burnstage_upgrade() #burn_info=[] #burn_cycle=[] #for k in range(len(info[0])): # if 'start' in info[3][k]: # burn_info.append( info[3][k]) # burn_cycle.append(info[0][k]) #print burn_info #print burn_cycle ''' #H #Maybe use get_elemental_abunds(), too slow if individually taken h=m1p65_last.get(model_list,'H-1') h_ini=mini*h[0][-1] h_limit=h_ini*burn_limit print h_limit #He he=m1p65_last.get(model_list,'He-4') he+=m1p65_last.get(model_list,'He-3') he_ini=mini*he[0][-1] he_limit=he_ini*burn_limit print he_limit if mini>5: c=m1p65_last.get(model_list,'C-12') c_ini=mini*c[0][-1] c_limit=c_ini*burn_limit if mini>10: ne=m1p65_last.get(model_list,'Ne-20') ne_ini= mini*ne[0][-1] ne_limit=ne_ini*burn_limit o=m1p65_last.get(model_list,'O-16') o_ini=mini*o[0][-1] o_limit=o_ini*burn_limit si=m1p65_last.get(model_list,'Si-28') si_ini=mini*si[0][-1] si_limit=si_ini*burn_limit print '#############################3' print h_ini,he_ini rho=[] T=[] he_depl_idx=-1 h_depl_idx=-1 c_depl_idx=-1 ne_depl_idx=-1 o_depl_idx=-1 si_depl_idx=-1 ''' rho=[] T=[] for k in range(len(model_list)): rho_center=rho1[k][0] T_center=T1[k][0] rho.append(rho_center) T.append(T_center) ''' mass11=np.array([0]+list(mass[k])) delta_mass=mass11[1:]-mass11[:-1] #for the low-mass + massive AGB if (sum(np.array(he[k])*np.array(delta_mass))<he_limit) and (he_depl_idx==-1): he_depl_idx=k if (sum(np.array(h[k])*np.array(delta_mass))<h_limit) and (h_depl_idx==-1): h_depl_idx=k #for the SAGB + massive if mini>5: if (sum(np.array(c[k])*np.array(delta_mass))<c_limit) and (c_depl_idx==-1): c_depl_idx=k #for the massive stars if mini>10: if (sum(np.array(ne[k])*np.array(delta_mass))<ne_limit) and (ne_depl_idx==-1): ne_depl_idx=k if (sum(np.array(o[k])*np.array(delta_mass))<o_limit) and (o_depl_idx==-1): o_depl_idx=k if (sum(np.array(si[k])*np.array(delta_mass))<si_limit) and (si_depl_idx==-1): si_depl_idx=k ''' T=np.log10(np.array(T)*T_unit) #T_degeneracy=np.log10(np.array(rho)**(2./3.)) rho=np.log10(np.array(rho)) figure(1) #plot(logTeff,logL,marker=symbs[i],label=self.run_label[i],linestyle=linestyle[i],markevery=markevery) #pl.plot(rho,T,marker=symbs[i],label=self.run_label[i],linestyle=linestyle[i],markevery=markevery) label=str(mini)+'$M_{\odot}$, Z='+str(zini) plt.plot(rho,T,label=label,linestyle=linestyle[i],marker=marker[i],markevery=markevery) ''' #plt.plot(rho,T_degeneracy,color='b',linestyle='-',label='$P_e = P_{e,deg}$') print burn_info print burn_cycle burn_cycle=np.array(burn_cycle)/100. print 'changed cycles:', burn_cycle print len(rho) #For different burning stages: if 'H_start' in burn_info: plt.plot(rho[burn_cycle[0]],T[burn_cycle[0]],marker='o',color='b') if 'He_start' in burn_info: plt.plot(rho[burn_cycle[1]],T[burn_cycle[1]],marker='o',color='r') if 'C_start' in burn_info: plt.plot(rho[burn_cycle[2]],T[burn_cycle[2]],marker='o',color='g') if 'Ne_start' in burn_info: plt.plot(rho[burn_cycle[3]],T[burn_cycle[3]],marker='D',color='b') if 'O_start' in burn_info: plt.plot(rho[burn_cycle[4]],T[burn_cycle[4]],marker='D',color='r') if 'Si_start' in burn_info: plt.plot(rho[burn_cycle[5]],T[burn_cycle[5]],marker='D',color='g') ''' #ax = plt.gca() #ax.invert_xaxis() plt.rcParams.update({'font.size': 16}) plt.rc('xtick', labelsize=16) plt.rc('ytick', labelsize=16) legend(loc=4) plt.xlabel('log $\\rho_{\\rm c}$',fontsize=18) plt.ylabel('log $T_{\\rm c}$',fontsize=18) ''' #plt.gca().invert_xaxis() figure(0) #pl.plot(rho,T,marker=symbs[i],label=self.run_label[i],linestyle=linestyle[i],markevery=markevery) plt.plot(rho,T,label=self.extra_label[i],linestyle=linestyle[i]) plt.plot(rho,T_degeneracy,color='b',linestyle='-',label='$P_e = P_{e,deg}$') #For different burning stages: if not h_depl_idx ==-1: plt.plot(rho[h_depl_idx],T[h_depl_idx],marker='o',color='b') if not he_depl_idx ==-1: plt.plot(rho[he_depl_idx],T[he_depl_idx],marker='o',color='r') if not c_depl_idx ==-1: plt.plot(rho[c_depl_idx],T[c_depl_idx],marker='o',color='g') if not ne_depl_idx ==-1: plt.plot(rho[ne_depl_idx],T[ne_depl_idx],marker='D',color='b') if not o_depl_idx ==-1: plt.plot(rho[o_depl_idx],T[o_depl_idx],marker='D',color='r') if not si_depl_idx ==-1: plt.plot(rho[si_depl_idx],T[si_depl_idx],marker='D',color='g') #ax = plt.gca() #ax.invert_xaxis() plt.rcParams.update({'font.size': 16}) plt.rc('xtick', labelsize=16) plt.rc('ytick', labelsize=16) legend(loc=4) plt.xlabel('log $\\rho_{\\rm c}$',fontsize=18) plt.ylabel('log $T_{\\rm c}$',fontsize=18) #plt.gca().invert_xaxis() ''' i+=1 if deg_line==True: rho=np.arange(0,9,0.01) T_degeneracy=2./3. *rho +np.log10(1.207e5 * 1.8/(2.**(5./3.))) #T_degeneracy=np.log10( (10**np.array(rho))**(2./3.)) plt.plot(rho,T_degeneracy,color='b',linestyle='-',label='$P_e = P_{e,deg}$') plt.legend(loc=2)
java
public static List<Integer> exactTokenFinder(final String pattern, final String[] tokens) { final String[] patternTokens = pattern.split(" "); int i, j; final int patternLength = patternTokens.length; final int sentenceLength = tokens.length; final List<Integer> neTokens = new ArrayList<Integer>(); for (j = 0; j <= sentenceLength - patternLength; ++j) { for (i = 0; i < patternLength && patternTokens[i].equals(tokens[i + j]); ++i) { ; } if (i >= patternLength) { neTokens.add(j); neTokens.add(i + j); } } return neTokens; }
java
@Override public <T> T create(EntityCreateOperation<T> creator) throws ServiceException { try { return service.create(creator); } catch (UniformInterfaceException e) { throw processCatch(new ServiceException(e)); } catch (ClientHandlerException e) { throw processCatch(new ServiceException(e)); } }
java
public static void dump(Node alt, int lv, PrintWriter out) { for (int i = 0; i < lv; i++) out.print(" "); out.println(alt.cs != null ? ('"'+alt.cs.toString()+'"') : "(null)"); if (alt.branches != null) { for (Node br : alt.branches) { dump(br, lv + 1, out); } } }
python
def render_subcommand(args): """Render a subcommand for human-centric viewing""" if args.subcommand == 'delete': return 'delete ' + args.delete_subcommand if args.subcommand in ('wal-prefetch', 'wal-push', 'wal-fetch'): return None return args.subcommand
java
public void reset() { this.getElement().clear(); Grid.driver().findElement(By.tagName("body")).click(); this.calendar = Calendar.getInstance(); this.getElement().click(); }
java
@Deprecated public void addPrimaryKey(String... primaryKeyFieldName) { StringBuilder sb = new StringBuilder(getProp(ConfigurationKeys.EXTRACT_PRIMARY_KEY_FIELDS_KEY, "")); Joiner.on(",").appendTo(sb, primaryKeyFieldName); setProp(ConfigurationKeys.EXTRACT_PRIMARY_KEY_FIELDS_KEY, sb.toString()); }
python
def _clone(self, deepcopy=True, base=None): """Internal clone helper.""" if not base: if self.__explicit_session: base = self._clone_base(self.__session) else: base = self._clone_base(None) values_to_clone = ("spec", "projection", "skip", "limit", "max_time_ms", "max_await_time_ms", "comment", "max", "min", "ordering", "explain", "hint", "batch_size", "max_scan", "manipulate", "query_flags", "modifiers", "collation") data = dict((k, v) for k, v in iteritems(self.__dict__) if k.startswith('_Cursor__') and k[9:] in values_to_clone) if deepcopy: data = self._deepcopy(data) base.__dict__.update(data) return base
java
protected String generateCreateIndexSql(final CreateSpatialIndexStatement statement, final Database database) { final StringBuilder sql = new StringBuilder(); sql.append("CREATE INDEX "); final String schemaName = statement.getTableSchemaName(); final String catalogName = statement.getTableCatalogName(); final String indexName = statement.getIndexName(); sql.append(database.escapeIndexName(catalogName, schemaName, indexName)); sql.append(" ON "); final String tableName = statement.getTableName(); sql.append(database.escapeTableName(catalogName, schemaName, tableName)).append(" ("); final Iterator<String> iterator = Arrays.asList(statement.getColumns()).iterator(); final String column = iterator.next(); sql.append(database.escapeColumnName(catalogName, statement.getTableSchemaName(), tableName, column)); sql.append(") INDEXTYPE IS mdsys.spatial_index"); // Generate and add the optional parameters. final Collection<String> parameters = getParameters(statement); if (parameters != null && !parameters.isEmpty()) { sql.append(" PARAMETERS ('"); sql.append(StringUtils.join(parameters, " ")); sql.append("')"); } return sql.toString(); }
python
def list_public_ips(kwargs=None, call=None): ''' List all available public IPs. CLI Example: .. code-block:: bash salt-cloud -f list_public_ips <provider> To list unavailable (assigned) IPs, use: CLI Example: .. code-block:: bash salt-cloud -f list_public_ips <provider> state=assigned .. versionadded:: 2015.8.0 ''' if kwargs is None: kwargs = {} args = {} if 'state' in kwargs: if kwargs['state'] == 'assigned': args['ip.state'] = 'Assigned' else: args['ip.state'] = 'Unassigned' else: args['ip.state'] = 'Unassigned' args['ip.type'] = 'Public' response = _query('grid', 'ip/list', args=args) ret = {} for item in response['list']: name = item['ip'] ret[name] = item return ret
java
protected void initializeExceptionHandler() { // Initialize the default uncaught exception handler for all other threads Thread.setDefaultUncaughtExceptionHandler(getDefaultUncaughtExceptionHandler()); // Initialize the uncaught exception handler for JavaFX Application Thread JRebirth.runIntoJAT(ATTACH_JAT_UEH.getText(), () -> Thread.currentThread().setUncaughtExceptionHandler(getJatUncaughtExceptionHandler())); // Initialize the uncaught exception handler for JRebirth Internal Thread JRebirth.runIntoJIT(ATTACH_JIT_UEH.getText(), () -> Thread.currentThread().setUncaughtExceptionHandler(getJitUncaughtExceptionHandler())); }
java
public static Expression sanitizedContentOrdainerFunctionForInternalBlocks( SanitizedContentKind kind) { return symbolWithNamespace( NodeContentKinds.getJsImportForOrdainersFunctions(kind), NodeContentKinds.toJsSanitizedContentOrdainerForInternalBlocks(kind)); }
java
protected List<AbstractColumn> getVisibleColumns() { List<AbstractColumn> visibleColums = new ArrayList<AbstractColumn>(getReport().getColumns()); for (DJGroup group : getReport().getColumnsGroups()) { if (group.getLayout().isHideColumn()) { visibleColums.remove(group.getColumnToGroupBy()); } } return visibleColums; }
java
@Override public DMatrixRMaj getR(DMatrixRMaj R, boolean compact) { if( compact ) { R = UtilDecompositons_DDRM.checkZerosLT(R,minLength,numCols); } else { R = UtilDecompositons_DDRM.checkZerosLT(R,numRows,numCols); } for( int j = 0; j < numCols; j++ ) { double colR[] = dataQR[j]; int l = Math.min(j,numRows-1); for( int i = 0; i <= l; i++ ) { double val = colR[i]; R.set(i,j,val); } } return R; }
java
@Override public ValueRange range(ChronoField field) { switch (field) { case DAY_OF_YEAR: return DOY_RANGE; case ALIGNED_WEEK_OF_MONTH: return ALIGNED_WOM_RANGE; case ALIGNED_WEEK_OF_YEAR: return ALIGNED_WOY_RANGE; case PROLEPTIC_MONTH: return PROLEPTIC_MONTH_RANGE; case YEAR_OF_ERA: return YOE_RANGE; case YEAR: return YEAR_RANGE; default: break; } return field.range(); }
python
def re_symlink(input_file, soft_link_name, log=None): """ Helper function: relinks soft symbolic link if necessary """ input_file = os.fspath(input_file) soft_link_name = os.fspath(soft_link_name) if log is None: prdebug = partial(print, file=sys.stderr) else: prdebug = log.debug # Guard against soft linking to oneself if input_file == soft_link_name: prdebug( "Warning: No symbolic link made. You are using " + "the original data directory as the working directory." ) return # Soft link already exists: delete for relink? if os.path.lexists(soft_link_name): # do not delete or overwrite real (non-soft link) file if not os.path.islink(soft_link_name): raise FileExistsError("%s exists and is not a link" % soft_link_name) try: os.unlink(soft_link_name) except OSError: prdebug("Can't unlink %s" % (soft_link_name)) if not os.path.exists(input_file): raise FileNotFoundError("trying to create a broken symlink to %s" % input_file) prdebug("os.symlink(%s, %s)" % (input_file, soft_link_name)) # Create symbolic link using absolute path os.symlink(os.path.abspath(input_file), soft_link_name)
python
def edit_matching_entry(program, arguments): """Edit the matching entry.""" entry = program.select_entry(*arguments) entry.context.execute("pass", "edit", entry.name)
java
public boolean process( List<AssociatedPair> points , FastQueue<DMatrixRMaj> solutions ) { if( points.size() != 7 ) throw new IllegalArgumentException("Must be exactly 7 points. Not "+points.size()+" you gelatinous piece of pond scum."); // reset data structures solutions.reset(); // must normalize for when points are in either pixel or calibrated units // TODO re-evaluate decision to normalize for calibrated case LowLevelMultiViewOps.computeNormalization(points, N1, N2); // extract F1 and F2 from two null spaces createA(points,A); if (!process(A)) return false; // Undo normalization on F PerspectiveOps.multTranA(N2.matrix(),F1,N1.matrix(),F1); PerspectiveOps.multTranA(N2.matrix(),F2,N1.matrix(),F2); // compute polynomial coefficients computeCoefficients(F1, F2, poly.c); // Find polynomial roots and solve for Fundamental matrices computeSolutions( solutions ); return true; }
java
public static List<ForwardedHeader> fromString(String input) { if (input == null || input.trim().isEmpty()) { return emptyList(); } StringBuilder buffer = new StringBuilder(); List<ForwardedHeader> results = new ArrayList<>(); int i = 0; while (i < input.length()) { LinkedHashMap<String, String> extensions = null; State state = State.PARAM_NAME; String paramName = null; String by = null; String forValue = null; String host = null; String proto = null; boolean isQuotedString = false; headerValueLoop: for (; i < input.length(); i++) { char c = input.charAt(i); if (state == State.PARAM_NAME) { if (c == ',' && buffer.length() == 0) { i++; // a semi-colon without an parameter, like "something;" break headerValueLoop; } else if (c == '=') { paramName = buffer.toString(); buffer.setLength(0); state = State.PARAM_VALUE; } else if (ParseUtils.isTChar(c)) { buffer.append(c); } else if (ParseUtils.isOWS(c)) { if (buffer.length() > 0) { throw new IllegalArgumentException("Got whitespace in parameter name while in " + state + " - header was " + buffer); } } else { throw new IllegalArgumentException("Got ascii " + ((int)c) + " while in " + state); } } else { boolean isFirst = !isQuotedString && buffer.length() == 0; if (isFirst && ParseUtils.isOWS(c)) { // ignore it } else if (isFirst && c == '"') { isQuotedString = true; } else { if (isQuotedString) { char lastChar = input.charAt(i - 1); if (c == '\\') { // don't append } else if (lastChar == '\\') { buffer.append(c); } else if (c == '"') { // this is the end, but we'll update on the next go isQuotedString = false; } else { buffer.append(c); } } else { if (c == ';') { String val = buffer.toString(); switch (paramName.toLowerCase()) { case "by": by = val; break; case "for": forValue = val; break; case "host": host = val; break; case "proto": proto = val; break; default: if (extensions == null) { extensions = new LinkedHashMap<>(); // keeps insertion order } extensions.put(paramName, val); break; } buffer.setLength(0); paramName = null; state = State.PARAM_NAME; } else if (c == ',') { i++; break headerValueLoop; } else if (ParseUtils.isVChar(c)) { buffer.append(c); } else if (ParseUtils.isOWS(c)) { // ignore it } else { throw new IllegalArgumentException("Got character code " + ((int) c) + " (" + c + ") while parsing parameter value"); } } } } } switch (state) { case PARAM_VALUE: String val = buffer.toString(); switch (paramName.toLowerCase()) { case "by": by = val; break; case "for": forValue = val; break; case "host": host = val; break; case "proto": proto = val; break; default: if (extensions == null) { extensions = new LinkedHashMap<>(); // keeps insertion order } extensions.put(paramName, val); break; } buffer.setLength(0); break; default: if (buffer.length() > 0) { throw new IllegalArgumentException("Unexpected ending point at state " + state + " for " + input); } } results.add(new ForwardedHeader(by, forValue, host, proto, extensions)); } return results; }
java
public static Variable[] getDeclaredVariables(Class<?> type) { if (!isGeneratedClass(type)) return new Variable[0]; if (type.isInterface()) return getVariables(type); return getVariables(getNewInstance(type)); }
java
public static base_responses update(nitro_service client, systemgroup resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { systemgroup updateresources[] = new systemgroup[resources.length]; for (int i=0;i<resources.length;i++){ updateresources[i] = new systemgroup(); updateresources[i].groupname = resources[i].groupname; updateresources[i].promptstring = resources[i].promptstring; updateresources[i].timeout = resources[i].timeout; } result = update_bulk_request(client, updateresources); } return result; }
python
def update(self, portfolio, date, perfs=None): ''' Actualizes the portfolio universe with the alog state ''' # Make the manager aware of current simulation self.portfolio = portfolio self.perfs = perfs self.date = date
python
def _estimate_label_shape(self): """Helper function to estimate label shape""" max_count = 0 self.reset() try: while True: label, _ = self.next_sample() label = self._parse_label(label) max_count = max(max_count, label.shape[0]) except StopIteration: pass self.reset() return (max_count, label.shape[1])
python
def info(name, root=None): ''' Return user information name User to get the information root Directory to chroot into CLI Example: .. code-block:: bash salt '*' user.info root ''' # If root is provided, we use a less portable solution that # depends on analyzing /etc/passwd manually. Of course we cannot # find users from NIS nor LDAP, but in those cases do not makes # sense to provide a root parameter. # # Please, note that if the non-root /etc/passwd file is long the # iteration can be slow. if root is not None and __grains__['kernel'] != 'AIX': getpwnam = functools.partial(_getpwnam, root=root) else: getpwnam = functools.partial(pwd.getpwnam) try: data = getpwnam(_quote_username(name)) except KeyError: return {} else: return _format_info(data)
java
public static MojoModel readFrom(MojoReaderBackend reader, final boolean readModelDescriptor) throws IOException { try { Map<String, Object> info = parseModelInfo(reader); if (! info.containsKey("algorithm")) throw new IllegalStateException("Unable to find information about the model's algorithm."); String algo = String.valueOf(info.get("algorithm")); ModelMojoReader mmr = ModelMojoFactory.INSTANCE.getMojoReader(algo); mmr._lkv = info; mmr._reader = reader; mmr.readAll(readModelDescriptor); return mmr._model; } finally { if (reader instanceof Closeable) ((Closeable) reader).close(); } }
python
def draw_image(self, ax, image): """Process a matplotlib image object and call renderer.draw_image""" self.renderer.draw_image(imdata=utils.image_to_base64(image), extent=image.get_extent(), coordinates="data", style={"alpha": image.get_alpha(), "zorder": image.get_zorder()}, mplobj=image)
java
public static Object stringToValue(String string) { if ("true".equalsIgnoreCase(string)) { return Boolean.TRUE; } if ("false".equalsIgnoreCase(string)) { return Boolean.FALSE; } if ("null".equalsIgnoreCase(string)) { return JSONObject.NULL; } // If it might be a number, try converting it, first as a Long, and then as a // Double. If that doesn't work, return the string. try { char initial = string.charAt(0); if (initial == '-' || (initial >= '0' && initial <= '9')) { Long value = new Long(string); if (value.toString().equals(string)) { return value; } } } catch (Exception ignore) { try { Double value = new Double(string); if (value.toString().equals(string)) { return value; } } catch (Exception ignoreAlso) { } } return string; }
python
def parameter_names_flat(self, include_fixed=False): """ Return the flattened parameter names for all subsequent parameters of this parameter. We do not include the name for self here! If you want the names for fixed parameters as well in this list, set include_fixed to True. if not hasattr(obj, 'cache'): obj.cache = FunctionCacher() :param bool include_fixed: whether to include fixed names here. """ name_list = [] for p in self.flattened_parameters: name = p.hierarchy_name() if p.size > 1: name_list.extend(["{}[{!s}]".format(name, i) for i in p._indices()]) else: name_list.append(name) name_list = np.array(name_list) if not include_fixed and self._has_fixes(): return name_list[self._fixes_] return name_list
java
public void marshall(GetRegexPatternSetRequest getRegexPatternSetRequest, ProtocolMarshaller protocolMarshaller) { if (getRegexPatternSetRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getRegexPatternSetRequest.getRegexPatternSetId(), REGEXPATTERNSETID_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
java
@Override public int compareTo(YearQuarter other) { int cmp = (year - other.year); if (cmp == 0) { cmp = quarter.compareTo(other.quarter); } return cmp; }
python
def make_srcmap_manifest(self, modelkey, components, data): """Build a yaml file that specfies how to make the srcmap files for a particular model Parameters ---------- modelkey : str Key used to identify this particular model components : list The binning components used in this analysis data : str Path to file containing dataset definition """ try: model_info = self._models[modelkey] except KeyError: model_info = self.make_model_info(modelkey) self._name_factory.update_base_dict(data) outfile = os.path.join('analysis', 'model_%s' % modelkey, 'srcmap_manifest_%s.yaml' % modelkey) manifest = model_info.make_srcmap_manifest( components, self._name_factory) outdir = os.path.dirname(outfile) try: os.makedirs(outdir) except OSError: pass utils.write_yaml(manifest, outfile)
java
private static List<ProjectDefinition> collectProjects(ProjectDefinition def, List<ProjectDefinition> collected) { collected.add(def); for (ProjectDefinition child : def.getSubProjects()) { collectProjects(child, collected); } return collected; }
python
def randomize(length=6, choices=None): """Returns a random string of the given length.""" if type(choices) == str: choices = list(choices) choices = choices or ascii_lowercase return "".join(choice(choices) for _ in range(length))
java
public static Properties fileToProperties(String fileName, Configuration conf) throws IOException, ConfigurationException { PropertiesConfiguration propsConfig = new PropertiesConfiguration(); Path filePath = new Path(fileName); URI fileURI = filePath.toUri(); if (fileURI.getScheme() == null && fileURI.getAuthority() == null) { propsConfig.load(FileSystem.getLocal(conf).open(filePath)); } else { propsConfig.load(filePath.getFileSystem(conf).open(filePath)); } return ConfigurationConverter.getProperties(propsConfig); }
java
public OvhOperation serviceName_output_elasticsearch_alias_aliasId_PUT(String serviceName, String aliasId, String description, String optionId) throws IOException { String qPath = "/dbaas/logs/{serviceName}/output/elasticsearch/alias/{aliasId}"; StringBuilder sb = path(qPath, serviceName, aliasId); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "description", description); addBody(o, "optionId", optionId); String resp = exec(qPath, "PUT", sb.toString(), o); return convertTo(resp, OvhOperation.class); }
java
public Observable<String> deleteAsync(String listId) { return deleteWithServiceResponseAsync(listId).map(new Func1<ServiceResponse<String>, String>() { @Override public String call(ServiceResponse<String> response) { return response.body(); } }); }
python
def create_job(batch_service_client, job_id, pool_id): """Creates a job with the specified ID, associated with the specified pool. :param batch_service_client: A Batch service client. :type batch_service_client: `azure.batch.BatchServiceClient` :param str job_id: The ID for the job. :param str pool_id: The ID for the pool. """ print('Creating job [{}]...'.format(job_id)) job = batch.models.JobAddParameter( id=job_id, pool_info=batch.models.PoolInformation(pool_id=pool_id)) try: batch_service_client.job.add(job) except batchmodels.batch_error.BatchErrorException as err: print_batch_exception(err) raise
python
def foreignKeys(self, *a, **kw): # nopep8 """Executes the SQLForeignKeys function and creates a result set of column names that are foreign keys in the specified table (columns in the specified table that refer to primary keys in other tables) or foreign keys in other tables that refer to the primary key in the specified table. """ fut = self._run_operation(self._impl.foreignKeys, *a, **kw) return fut
python
def get_owner_ids_value(self, obj): """Extract owners' ids.""" return [ user.pk for user in get_users_with_permission(obj, get_full_perm('owner', obj)) ]
python
def need_deployment(): ''' Salt thin needs to be deployed - prep the target directory and emit the delimiter and exit code that signals a required deployment. ''' if os.path.exists(OPTIONS.saltdir): shutil.rmtree(OPTIONS.saltdir) old_umask = os.umask(0o077) # pylint: disable=blacklisted-function try: os.makedirs(OPTIONS.saltdir) finally: os.umask(old_umask) # pylint: disable=blacklisted-function # Verify perms on saltdir if not is_windows(): euid = os.geteuid() dstat = os.stat(OPTIONS.saltdir) if dstat.st_uid != euid: # Attack detected, try again need_deployment() if dstat.st_mode != 16832: # Attack detected need_deployment() # If SUDOing then also give the super user group write permissions sudo_gid = os.environ.get('SUDO_GID') if sudo_gid: try: os.chown(OPTIONS.saltdir, -1, int(sudo_gid)) stt = os.stat(OPTIONS.saltdir) os.chmod(OPTIONS.saltdir, stt.st_mode | stat.S_IWGRP | stat.S_IRGRP | stat.S_IXGRP) except OSError: sys.stdout.write('\n\nUnable to set permissions on thin directory.\nIf sudo_user is set ' 'and is not root, be certain the user is in the same group\nas the login user') sys.exit(1) # Delimiter emitted on stdout *only* to indicate shim message to master. sys.stdout.write("{0}\ndeploy\n".format(OPTIONS.delimiter)) sys.exit(EX_THIN_DEPLOY)
java
public void put(String id, StringWrapper toInsert,Object value) { MyWrapper wrapper = asMyWrapper(toInsert); Token[] tokens = wrapper.getTokens(); for (int i=0; i<tokens.length; i++) { ArrayList stringsWithToken = (ArrayList) index.get(tokens[i]); if (stringsWithToken==null) index.put( tokens[i], (stringsWithToken=new ArrayList()) ); stringsWithToken.add( wrapper ); } map.put( wrapper, value ); if (id!=null) idMap.put( wrapper, id ); distance = null; // mark distance as "out of date" totalEntries++; }
python
def set(self, val, force_set=False): """ Sets an input with a specified value; if force_set=True, will set through javascript if webdriver fails NOTE: if val is None, this function will interpret this to be an empty string @type val: str @param val: string to send to element @type force_set: bool @param force_set: Use javascript if True, webdriver if False """ if val is None: val = "" self.click(force_click=True if force_set else False) self.clear() self.send_keys(val) actual = self.get_attribute('value') if val != actual: if force_set: js_executor = self.driver_wrapper.js_executor def force_set_element(): """ Wrapper to force_set element via javascript if needed """ js_executor.execute_template('setValueTemplate', {'value': val}, self.element) return True self.execute_and_handle_webelement_exceptions(force_set_element, 'set element by javascript') else: self.driver_wrapper.assertion.fail( 'Setting text field failed because final text did not match input value: "{}" != "{}"'.format( actual, val ) ) return self
java
public void setCardinality(double cardinality) { if (cardinality < 0 || Double.isNaN(cardinality)) throw new IllegalArgumentException("Cardinality must be a positive integer or infinity, not " + cardinality); this.cardinality = Math.ceil(cardinality); fixCache(); }
java
public void assign(AbstractIntDoubleMap other) { if (!(other instanceof OpenIntDoubleHashMap)) { super.assign(other); return; } OpenIntDoubleHashMap source = (OpenIntDoubleHashMap) other; OpenIntDoubleHashMap copy = (OpenIntDoubleHashMap) source.copy(); this.values = copy.values; this.table = copy.table; this.state = copy.state; this.freeEntries = copy.freeEntries; this.distinct = copy.distinct; this.lowWaterMark = copy.lowWaterMark; this.highWaterMark = copy.highWaterMark; this.minLoadFactor = copy.minLoadFactor; this.maxLoadFactor = copy.maxLoadFactor; }
java
protected BaseTile getBaseTile (int tx, int ty) { SceneBlock block = getBlock(tx, ty); return (block == null) ? null : block.getBaseTile(tx, ty); }
python
def getCycleData(self, attri, fname, numtype='cycNum'): """ In this method a column of data for the associated cycle attribute is returned. Parameters ---------- attri : string The name of the attribute we are looking for. fname : string The name of the file we are getting the data from or the cycle number found in the filename. numtype : string, optional Determines whether fname is the name of a file or, the cycle number. If it is 'file' it will then interpret it as a file, if it is 'cycNum' it will then interpret it as a cycle number. The default is "cycNum". """ fname=self.findFile(fname,numtype) if self.inputdir == '': self.inputdir = self.sldir # This chunk of code changes into the directory where fname is, os.chdir(self.inputdir) # and appends a '/' to the directory title so it accesses the self.sldir=os.getcwd() + '/' # file correctly f=open(fname,'r') lines=f.readlines() if self.inputdir != './': #This chunk of code changes back into the directory you started in. os.chdir(self.startdir) self.sldir = self.inputdir for i in range(len(lines)): lines[i]=lines[i].strip() for i in range(len(lines)): if lines[i].startswith('#'): lines[i]=lines[i].strip('#') tmp=lines[i].split() tmp1=[] for j in range(len(tmp)): if tmp[j] != '=' or '': tmp1.append(tmp[j]) tmp=tmp1 for j in range(len(tmp)): if tmp[j]== attri: try: if '.' in tmp[j+1]: return float(tmp[j+1]) else: return int(tmp[j+1]) except ValueError: return str(tmp[j+1]) elif lines[i].startswith('H'): continue else: print('This cycle attribute does not exist') print('Returning None') return None
python
def list_all(self): """All items""" return list(set( item for items in self._routes.values() for item in items ))
java
public void append(final Event... events) { if (events != null && events.length > 0) { this.events.addAll(EscSpiUtils.asList(events)); } }
java
protected String toLocaleString(Locale locale) { String language = locale.getLanguage(); if(language.isEmpty()) return ""; String country = locale.getCountry(); if(country.isEmpty()) return language; String variant = locale.getVariant(); if(variant.isEmpty()) { return language + '-' + country; } else { return language + '-' + country + '-' + variant; } }
java
public void setParent(AstNode parent) { if (parent == this.parent) { return; } // Convert position back to absolute. if (this.parent != null) { setRelative(-this.parent.getAbsolutePosition()); } this.parent = parent; if (parent != null) { setRelative(parent.getAbsolutePosition()); } }
java
public static String getCacheName(Method method, String methodCacheName, CacheDefaults cacheDefaultsAnnotation, boolean generate) { assertNotNull(method, "method parameter must not be null"); assertNotNull(methodCacheName, "methodCacheName parameter must not be null"); String cacheName = methodCacheName.trim(); if (cacheName.isEmpty() && cacheDefaultsAnnotation != null) { cacheName = cacheDefaultsAnnotation.cacheName().trim(); } if (cacheName.isEmpty() && generate) { cacheName = getDefaultMethodCacheName(method); } return cacheName; }
java
private void actualRefresh(final ClientMapInfo mapInfo) { if (null == mapInfo) { Log.logError("Cannot find map with id " + id); return; } this.mapInfo = mapInfo; srid = 0; try { int pos = mapInfo.getCrs().indexOf(":"); if (pos >= 0) { srid = Integer.parseInt(mapInfo.getCrs().substring(pos + 1)); } } catch (NumberFormatException nfe) { // warning logged below } if (0 == srid) { Log.logWarn("Cannot parse CRS for map " + id + ", CRS=" + mapInfo.getCrs()); } ScaleConfigurationInfo scaleConfigurationInfo = mapInfo.getScaleConfiguration(); List<Double> realResolutions = new ArrayList<Double>(); for (ScaleInfo scale : scaleConfigurationInfo.getZoomLevels()) { realResolutions.add(1. / scale.getPixelPerUnit()); } mapView.setResolutions(realResolutions); mapView.setMaximumScale(scaleConfigurationInfo.getMaximumScale().getPixelPerUnit()); // replace layers by new layers removeAllLayers(); for (ClientLayerInfo layerInfo : mapInfo.getLayers()) { addLayerWithoutFireEvent(layerInfo); } Bbox maxBounds = new Bbox(mapInfo.getMaxBounds()); Bbox initialBounds = new Bbox(mapInfo.getInitialBounds()); // if the max bounds was not configured, take the union of initial and layer bounds if (maxBounds.isAll()) { for (ClientLayerInfo layerInfo : mapInfo.getLayers()) { maxBounds = (Bbox) initialBounds.clone(); maxBounds = maxBounds.union(new Bbox(layerInfo.getMaxExtent())); } } mapView.setMaxBounds(maxBounds); if (null == mapInfo.getViewBoundsLimitOption()) { mapView.setViewBoundsLimitOption(BoundsLimitOption.COMPLETELY_WITHIN_MAX_BOUNDS); } else { mapView.setViewBoundsLimitOption(mapInfo.getViewBoundsLimitOption()); } }
java
public EClass getIfcApprovalActorRelationship() { if (ifcApprovalActorRelationshipEClass == null) { ifcApprovalActorRelationshipEClass = (EClass) EPackage.Registry.INSTANCE .getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers().get(25); } return ifcApprovalActorRelationshipEClass; }
java
public void untag(Class<?> tagClass) { Iterator<Tag<?>> tagIter = _tags.iterator(); while (tagIter.hasNext()) { Tag<?> tag = tagIter.next(); if (tagClass.isInstance(tag)) { tagIter.remove(); } } }
java
public ReadRecordStatus readRecord(byte[] hostBytes, int processed) throws IOException { int bytesRead = 0; if (getBytesPrefetched() == 0) { bytesRead = readFully(hostBytes, 0, RDW_LEN); if (bytesRead < RDW_LEN) { throw new IOException( "Not enough bytes left for a record descriptor word"); } setBytesPrefetched(RDW_LEN); } int recordLen = getRecordLen(hostBytes); bytesRead += readFully(hostBytes, getBytesPrefetched(), recordLen - getBytesPrefetched() + RDW_LEN); setBytesPrefetched(0); return new ReadRecordStatus(recordLen, bytesRead); }
python
def pprint_thing(thing, _nest_lvl=0, escape_chars=None, default_escapes=False, quote_strings=False, max_seq_items=None): """ This function is the sanctioned way of converting objects to a unicode representation. properly handles nested sequences containing unicode strings (unicode(object) does not) Parameters ---------- thing : anything to be formatted _nest_lvl : internal use only. pprint_thing() is mutually-recursive with pprint_sequence, this argument is used to keep track of the current nesting level, and limit it. escape_chars : list or dict, optional Characters to escape. If a dict is passed the values are the replacements default_escapes : bool, default False Whether the input escape characters replaces or adds to the defaults max_seq_items : False, int, default None Pass thru to other pretty printers to limit sequence printing Returns ------- result - unicode object on py2, str on py3. Always Unicode. """ def as_escaped_unicode(thing, escape_chars=escape_chars): # Unicode is fine, else we try to decode using utf-8 and 'replace' # if that's not it either, we have no way of knowing and the user # should deal with it himself. try: result = six.text_type(thing) # we should try this first except UnicodeDecodeError: # either utf-8 or we replace errors result = str(thing).decode('utf-8', "replace") translate = {'\t': r'\t', '\n': r'\n', '\r': r'\r', } if isinstance(escape_chars, dict): if default_escapes: translate.update(escape_chars) else: translate = escape_chars escape_chars = list(escape_chars.keys()) else: escape_chars = escape_chars or tuple() for c in escape_chars: result = result.replace(c, translate[c]) return six.text_type(result) if (six.PY3 and hasattr(thing, '__next__')) or hasattr(thing, 'next'): return six.text_type(thing) elif (isinstance(thing, dict) and _nest_lvl < options.display.pprint_nest_depth): result = _pprint_dict(thing, _nest_lvl, quote_strings=True, max_seq_items=max_seq_items) elif is_sequence(thing) and _nest_lvl < \ options.display.pprint_nest_depth: result = _pprint_seq(thing, _nest_lvl, escape_chars=escape_chars, quote_strings=quote_strings, max_seq_items=max_seq_items) elif isinstance(thing, six.string_types) and quote_strings: if six.PY3: fmt = "'%s'" else: fmt = "u'%s'" result = fmt % as_escaped_unicode(thing) else: result = as_escaped_unicode(thing) return six.text_type(result)
python
def is_owner(self, user): """ Checks if user is the owner of object Parameters ---------- user: get_user_model() instance Returns ------- bool Author ------ Himanshu Shankar (https://himanshus.com) """ if user.is_authenticated: return self.created_by.id == user.id return False
python
def setQuickColor( self, color ): """ Sets the quick color for the palette to the given color. :param color | <QColor> """ colorset = XPaletteColorSet() colorset.setPalette(QPalette(color)) self.setColorSet(colorset)
python
def cli(env, billing_id, datacenter): """Adds a load balancer given the id returned from create-options.""" mgr = SoftLayer.LoadBalancerManager(env.client) if not formatting.confirm("This action will incur charges on your " "account. Continue?"): raise exceptions.CLIAbort('Aborted.') mgr.add_local_lb(billing_id, datacenter=datacenter) env.fout("Load balancer is being created!")
python
def _validated(self, value): """Format the value or raise a :exc:`ValidationError` if an error occurs.""" if value is None: return None if isinstance(value, bson.ObjectId): return value try: return bson.ObjectId(value) except (ValueError, AttributeError): self.fail('invalid_object_id')
python
def generate_proxy( prefix, base_url='', verify_ssl=True, middleware=None, append_middleware=None, cert=None, timeout=None): """Generate a ProxyClass based view that uses the passed base_url.""" middleware = list(middleware or HttpProxy.proxy_middleware) middleware += list(append_middleware or []) return type('ProxyClass', (HttpProxy,), { 'base_url': base_url, 'reverse_urls': [(prefix, base_url)], 'verify_ssl': verify_ssl, 'proxy_middleware': middleware, 'cert': cert, 'timeout': timeout })
java
static void dataUri( CssFormatter formatter, byte[] bytes, String urlStr, String type ) { if( type == null ) { switch( urlStr.substring( urlStr.lastIndexOf( '.' ) + 1 ) ) { case "gif": type = "image/gif;base64"; break; case "png": type = "image/png;base64"; break; case "jpg": case "jpeg": type = "image/jpeg;base64"; break; default: type = "text/html"; } } else { type = removeQuote( type ); } if( type.endsWith( "base64" ) ) { formatter.append( "url(\"data:" ).append( type ).append( ',' ); formatter.append( toBase64( bytes ) ); formatter.append( "\")" ); } else { formatter.append( "url(\"data:" ).append( type ).append( ',' ); appendEncode( formatter, bytes ); formatter.append( "\")" ); } }
python
def _handle_response(response, **kwargs) -> XMLResponse: """Requests HTTP Response handler. Attaches .html property to class:`requests.Response <requests.Response>` objects. """ if not response.encoding: response.encoding = DEFAULT_ENCODING return response
python
def _http_request(url, headers=None, data=None): ''' Make the HTTP request and return the body as python object. ''' if not headers: headers = _get_headers() session = requests.session() log.debug('Querying %s', url) req = session.post(url, headers=headers, data=salt.utils.json.dumps(data)) req_body = req.json() ret = _default_ret() log.debug('Status code: %d', req.status_code) log.debug('Response body:') log.debug(req_body) if req.status_code != 200: if req.status_code == 500: ret['comment'] = req_body.pop('message', '') ret['out'] = req_body return ret ret.update({ 'comment': req_body.get('error', '') }) return ret ret.update({ 'result': True, 'out': req.json() }) return ret
java
public static Predicate<MonetaryAmount> filterByExcludingCurrency( CurrencyUnit... currencies) { if (Objects.isNull(currencies) || currencies.length == 0) { return m -> true; } return isCurrency(currencies).negate(); }
python
def floating_point( element_name, # type: Text attribute=None, # type: Optional[Text] required=True, # type: bool alias=None, # type: Optional[Text] default=0.0, # type: Optional[float] omit_empty=False, # type: bool hooks=None # type: Optional[Hooks] ): # type: (...) -> Processor """ Create a processor for floating point values. See also :func:`declxml.boolean` """ value_parser = _number_parser(float) return _PrimitiveValue( element_name, value_parser, attribute, required, alias, default, omit_empty, hooks )
python
def ipv6_acl_ipv6_access_list_standard_seq_action(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ipv6_acl = ET.SubElement(config, "ipv6-acl", xmlns="urn:brocade.com:mgmt:brocade-ipv6-access-list") ipv6 = ET.SubElement(ipv6_acl, "ipv6") access_list = ET.SubElement(ipv6, "access-list") standard = ET.SubElement(access_list, "standard") name_key = ET.SubElement(standard, "name") name_key.text = kwargs.pop('name') seq = ET.SubElement(standard, "seq") seq_id_key = ET.SubElement(seq, "seq-id") seq_id_key.text = kwargs.pop('seq_id') action = ET.SubElement(seq, "action") action.text = kwargs.pop('action') callback = kwargs.pop('callback', self._callback) return callback(config)
java
public void pressMenuItem(int index) { if(config.commandLogging){ Log.d(config.commandLoggingTag, "pressMenuItem("+index+")"); } presser.pressMenuItem(index); }
java
public static void encodeDesc(Float value, byte[] dst, int dstOffset) { if (value == null) { DataEncoder.encode(~0x7fffffff, dst, dstOffset); } else { encodeDesc(value.floatValue(), dst, dstOffset); } }
python
def insertComponent(self, index, comp): """Inserts new component *comp* at index""" # new component needs to be wrapped if self.columnCountForRow(index.row()) == 0: self.beginInsertRows(QtCore.QModelIndex(), index.row(), index.row()) self._stim.insertComponent(comp, index.row(), index.column()) self.endInsertRows() else: self._stim.insertComponent(comp, index.row(), index.column()) self.samplerateChanged.emit(self._stim.samplerate())
python
def create_token(key, payload): """Auth token generator payload should be a json encodable data structure """ token = hmac.new(key) token.update(json.dumps(payload)) return token.hexdigest()
java
public static void insertSort(int[] arrays) { for (int i = 1; i < arrays.length; i++) { int currentNumber = arrays[i]; int j = i - 1; while (j >= 0 && arrays[j] > currentNumber) { arrays[j + 1] = arrays[j--]; } arrays[j + 1] = currentNumber; } }
java
public Object[] getAnnotations() { if (annotations == null) { try { annotations = getCtClass().getAvailableAnnotations(); } catch (Exception | Error e) { return new Object[0]; } } return annotations; }
python
def get_short_lambda_body_text(lambda_func): """Return the source of a (short) lambda function. If it's impossible to obtain, returns None. """ try: source_lines, _ = inspect.getsourcelines(lambda_func) except (IOError, TypeError): return None # skip `def`-ed functions and long lambdas if len(source_lines) != 1: return None source_text = os.linesep.join(source_lines).strip() # find the AST node of a lambda definition # so we can locate it in the source code source_ast = ast.parse(source_text) lambda_node = next((node for node in ast.walk(source_ast) if isinstance(node, ast.Lambda)), None) if lambda_node is None: # could be a single line `def fn(x): ...` return None # HACK: Since we can (and most likely will) get source lines # where lambdas are just a part of bigger expressions, they will have # some trailing junk after their definition. # # Unfortunately, AST nodes only keep their _starting_ offsets # from the original source, so we have to determine the end ourselves. # We do that by gradually shaving extra junk from after the definition. lambda_text = source_text[lambda_node.col_offset:] lambda_body_text = source_text[lambda_node.body.col_offset:] min_length = len('lambda:_') # shortest possible lambda expression while len(lambda_text) > min_length: try: # What's annoying is that sometimes the junk even parses, # but results in a *different* lambda. You'd probably have to # be deliberately malicious to exploit it but here's one way: # # bloop = lambda x: False, lambda x: True # get_short_lamnda_source(bloop[0]) # # Ideally, we'd just keep shaving until we get the same code, # but that most likely won't happen because we can't replicate # the exact closure environment. code = compile(lambda_body_text, '<unused filename>', 'eval') # Thus the next best thing is to assume some divergence due # to e.g. LOAD_GLOBAL in original code being LOAD_FAST in # the one compiled above, or vice versa. # But the resulting code should at least be the same *length* # if otherwise the same operations are performed in it. if len(code.co_code) == len(lambda_func.__code__.co_code): # return lambda_text return lambda_body_text except SyntaxError: pass lambda_text = lambda_text[:-1] lambda_body_text = lambda_body_text[:-1] return None
java
public Container getTargetScreen(Container component, Class<?> targetClass, boolean bComponent) { Container container = null; if (bComponent) if (component == this) if (m_parent instanceof Container) { bComponent = false; container = (Container)m_parent; } if (container == null) container = component.getParent(); if (container == null) return null; if (targetClass.isAssignableFrom(container.getClass())) return container; if (container instanceof JBasePanel) return ((JBasePanel)container).getTargetScreen(container, targetClass, true); return this.getTargetScreen(container, targetClass, bComponent); }
python
def pack_data(abi_types, values) -> bytes: """Normalize data and pack them into a byte array""" if len(abi_types) != len(values): raise ValueError( "Length mismatch between provided abi types and values. Got " "{0} types and {1} values.".format(len(abi_types), len(values)), ) normalized_values = map_abi_data([abi_address_to_hex], abi_types, values) return decode_hex(''.join( remove_0x_prefix(hex_encode_abi_type(abi_type, value)) for abi_type, value in zip(abi_types, normalized_values) ))
java
public static policymap[] get(nitro_service service) throws Exception{ policymap obj = new policymap(); policymap[] response = (policymap[])obj.get_resources(service); return response; }
java
public void insertRecord(long recordPointer, long keyPrefix, boolean prefixIsNull) { if (!hasSpaceForAnotherRecord()) { throw new IllegalStateException("There is no space for new record"); } if (prefixIsNull && radixSortSupport != null) { // Swap forward a non-null record to make room for this one at the beginning of the array. array.set(pos, array.get(nullBoundaryPos)); pos++; array.set(pos, array.get(nullBoundaryPos + 1)); pos++; // Place this record in the vacated position. array.set(nullBoundaryPos, recordPointer); nullBoundaryPos++; array.set(nullBoundaryPos, keyPrefix); nullBoundaryPos++; } else { array.set(pos, recordPointer); pos++; array.set(pos, keyPrefix); pos++; } }