code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public static boolean isUnboundedOrSuperBounded(final AnnotatedWildcardType wildcardType){
return ((Type.WildcardType)wildcardType.getUnderlyingType()).isSuperBound();
}
| Returns true if this type is super bounded or unbounded. |
public VolumeShowResponse showVolume(String volumeId) throws Exception {
_log.info("CinderApi - start showVolume");
String showVolumeUri=endPoint.getBaseUri() + String.format(CinderConstants.URI_DELETE_VOLUME,new Object[]{endPoint.getCinderTenantId(),volumeId});
ClientResponse js_response=getClient().get(URI.create(showVolumeUri));
_log.debug("uri {} : Response status {}",showVolumeUri,String.valueOf(js_response.getStatus()));
if (js_response.getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) {
throw CinderException.exceptions.volumeNotFound(volumeId);
}
String jsonString=js_response.getEntity(String.class);
VolumeShowResponse volumeDetails=new Gson().fromJson(SecurityUtils.sanitizeJsonString(jsonString),VolumeShowResponse.class);
_log.info("CinderApi - end showVolume");
return volumeDetails;
}
| Gets the volume information. Its a synchronous operation. |
@Override public void deleteFeature(){
try {
MapLayer layer=openMaps.get(activeMap).getActiveMapArea().getActiveLayer();
if (layer instanceof VectorLayerInfo) {
VectorLayerInfo vli=(VectorLayerInfo)layer;
if (!vli.isActivelyEdited()) {
showFeedback(messages.getString("NotEditingVector") + " \n" + messages.getString("SelectEditVector"));
return;
}
if (vli.getSelectedFeatureNumbers().isEmpty()) {
showFeedback(messages.getString("NoFeaturesSelected"));
return;
}
else {
int n=showFeedback(messages.getString("DeleteFeature") + "?",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
if (n == JOptionPane.YES_OPTION) {
vli.deleteSelectedFeatures();
vli.reloadShapefile();
refreshMap(false);
}
else if (n == JOptionPane.NO_OPTION) {
return;
}
}
}
else {
showFeedback(messages.getString("ActiveLayerNotVector"));
}
}
catch ( Exception e) {
showFeedback(messages.getString("Error") + e.getMessage());
logger.log(Level.SEVERE,"WhiteboxGui.deleteFeature",e);
}
}
| Used to delete a selected vector feature that is actively being edited. |
public void processEvent(SystemEvent event) throws AbortProcessingException {
FacesContext context=FacesContext.getCurrentInstance();
HtmlOutputText outputText=(HtmlOutputText)context.getApplication().createComponent("javax.faces.HtmlOutputText");
outputText.setValue("Dynamic Text");
outputText.setEscape(false);
getChildren().add(1,outputText);
}
| Process the system event. <p> Here we'll add a child in between static text. If dynamic component state saving works properly then upon redisplay it should have first static, then dynamic and then static text. </p> |
private void showFootView(){
if (loadmoreView != null) {
loadmoreView.setVisibility(View.VISIBLE);
}
}
| show footview |
private void returnData(Object ret){
if (myHost != null) {
myHost.returnData(ret);
}
}
| Used to communicate a return object from a plugin tool to the main Whitebox user-interface. |
public static final double feetToMeters(double feet){
return feet * FOOT_TO_METER;
}
| Converts feet to meters. |
int readCorner3(int numRows,int numColumns){
int currentByte=0;
if (readModule(numRows - 1,0,numRows,numColumns)) {
currentByte|=1;
}
currentByte<<=1;
if (readModule(numRows - 1,numColumns - 1,numRows,numColumns)) {
currentByte|=1;
}
currentByte<<=1;
if (readModule(0,numColumns - 3,numRows,numColumns)) {
currentByte|=1;
}
currentByte<<=1;
if (readModule(0,numColumns - 2,numRows,numColumns)) {
currentByte|=1;
}
currentByte<<=1;
if (readModule(0,numColumns - 1,numRows,numColumns)) {
currentByte|=1;
}
currentByte<<=1;
if (readModule(1,numColumns - 3,numRows,numColumns)) {
currentByte|=1;
}
currentByte<<=1;
if (readModule(1,numColumns - 2,numRows,numColumns)) {
currentByte|=1;
}
currentByte<<=1;
if (readModule(1,numColumns - 1,numRows,numColumns)) {
currentByte|=1;
}
return currentByte;
}
| <p>Reads the 8 bits of the special corner condition 3.</p> <p>See ISO 16022:2006, Figure F.5</p> |
public MyHashMap(){
this(DEFAULT_INITIAL_CAPACITY,DEFAULT_MAX_LOAD_FACTOR);
}
| Construct a map with the default capacity and load factor |
private void searchText(){
String query=searchEditText.getText().toString();
presenter.onScrollFinished(query);
}
| Method that retrieves the AutoCompleteTextView's text and passes it to the presenter |
public List<Node> findMb(String targetName){
TetradLogger.getInstance().log("info","target = " + targetName);
numIndTests=0;
long time=System.currentTimeMillis();
pc=new HashMap<>();
trimmed=new HashSet<>();
Node target=getVariableForName(targetName);
List<Node> nodes=mmmb(target);
long time2=System.currentTimeMillis() - time;
TetradLogger.getInstance().log("info","Number of seconds: " + (time2 / 1000.0));
TetradLogger.getInstance().log("info","Number of independence tests performed: " + numIndTests);
return nodes;
}
| Searches for the Markov blanket of the node by the given name. |
public void evaluateExpression(double[] vals) throws Exception {
Stack<Double> operands=new Stack<Double>();
for (int i=0; i < m_postFixExpVector.size(); i++) {
Object nextob=m_postFixExpVector.elementAt(i);
if (nextob instanceof NumericOperand) {
operands.push(new Double(((NumericOperand)nextob).m_numericConst));
}
else if (nextob instanceof AttributeOperand) {
double value=vals[((AttributeOperand)nextob).m_attributeIndex];
if (((AttributeOperand)nextob).m_negative) {
value=-value;
}
operands.push(new Double(value));
}
else if (nextob instanceof Operator) {
char op=((Operator)nextob).m_operator;
if (isUnaryFunction(op)) {
double operand=((Double)operands.pop()).doubleValue();
double result=((Operator)nextob).applyFunction(operand);
operands.push(new Double(result));
}
else {
double second=((Double)operands.pop()).doubleValue();
double first=((Double)operands.pop()).doubleValue();
double result=((Operator)nextob).applyOperator(first,second);
operands.push(new Double(result));
}
}
else {
throw new Exception("Unknown object in postfix vector!");
}
}
if (operands.size() != 1) {
throw new Exception("Problem applying function");
}
Double result=((Double)operands.pop());
if (result.isNaN() || result.isInfinite()) {
vals[vals.length - 1]=Utils.missingValue();
}
else {
vals[vals.length - 1]=result.doubleValue();
}
}
| Evaluate the expression using the supplied array of attribute values. The result is stored in the last element of the array. Assumes that the infix expression has been converted to postfix and stored in m_postFixExpVector |
private void checkStrengthSupport(byte[] ciphersInChallenge) throws IOException {
if (ciphersInChallenge == null) {
throw new SaslException("DIGEST-MD5: server did not specify " + "cipher to use for 'auth-conf'");
}
String cipherOptions=new String(ciphersInChallenge,encoding);
StringTokenizer parser=new StringTokenizer(cipherOptions,", \t\n");
int tokenCount=parser.countTokens();
String token=null;
byte[] serverCiphers={UNSET,UNSET,UNSET,UNSET,UNSET};
String[] serverCipherStrs=new String[serverCiphers.length];
for (int i=0; i < tokenCount; i++) {
token=parser.nextToken();
for (int j=0; j < CIPHER_TOKENS.length; j++) {
if (token.equals(CIPHER_TOKENS[j])) {
serverCiphers[j]|=CIPHER_MASKS[j];
serverCipherStrs[j]=token;
logger.log(Level.FINE,"DIGEST62:Server supports {0}",token);
}
}
}
byte[] clntCiphers=getPlatformCiphers();
byte inter=0;
for (int i=0; i < serverCiphers.length; i++) {
serverCiphers[i]&=clntCiphers[i];
inter|=serverCiphers[i];
}
if (inter == UNSET) {
throw new SaslException("DIGEST-MD5: Client supports none of these cipher suites: " + cipherOptions);
}
negotiatedCipher=findCipherAndStrength(serverCiphers,serverCipherStrs);
if (negotiatedCipher == null) {
throw new SaslException("DIGEST-MD5: Unable to negotiate " + "a strength level for 'auth-conf'");
}
logger.log(Level.FINE,"DIGEST63:Cipher suite: {0}",negotiatedCipher);
}
| Processes the 'cipher' digest-challenge directive. This allows the mechanism to check for client-side support against the list of supported ciphers send by the server. If no match is found, the mechanism aborts. |
public static boolean directoryExists(String dir){
File tmp=new File(dir);
return (tmp.isDirectory() && tmp.exists());
}
| Checks if the directory exists |
private static boolean useCompactFontFormat(Map<String,Object> args,int compatibilityVersion){
String value=(String)args.get(EMBEDASCFF);
boolean useCFF=true;
if (compatibilityVersion < MxmlConfiguration.VERSION_4_0) useCFF=false;
if (value != null) {
useCFF=Boolean.parseBoolean(value.trim());
}
return useCFF;
}
| The CFF flag determines whether font information should be embedded in the Compact Font Format using SWF tag DefineFont4. |
boolean isAlpha(char ch){
return ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'));
}
| Test if a character is alpha (A-Z,a-z). |
public void showStartupDialogs(){
if (!EulaUtils.hasAcceptedEula(this)) {
Fragment fragment=getSupportFragmentManager().findFragmentByTag(EulaDialogFragment.EULA_DIALOG_TAG);
if (fragment == null) {
EulaDialogFragment.newInstance(false).show(getSupportFragmentManager(),EulaDialogFragment.EULA_DIALOG_TAG);
}
}
else {
if (PreferencesUtils.getString(this,R.string.stats_units_key,"").equals("")) {
String statsUnits=getString(Locale.US.equals(Locale.getDefault()) ? R.string.stats_units_imperial : R.string.stats_units_metric);
PreferencesUtils.setString(this,R.string.stats_units_key,statsUnits);
}
checkGooglePlayServices();
}
}
| Shows start up dialogs. |
private boolean isNonCommandLineArgument(String propName){
return propName.equals(EXECUTABLE_NAME_KEY) || propName.equals(EXECUTABLE_PATH_KEY);
}
| Returns true if the property does not belong as a command-line argument |
public void recognize(){
Log.d(TAG,"recognize");
try {
HashMap<String,String> header=new HashMap<String,String>();
header.put("Content-Type",sConfig.audioFormat);
if (sConfig.isAuthNeeded) {
if (this.tokenProvider != null) {
header.put("X-Watson-Authorization-Token",this.tokenProvider.getToken());
Log.d(TAG,"ws connecting with token based authentication");
}
else {
String auth="Basic " + Base64.encodeBytes((this.username + ":" + this.password).getBytes(Charset.forName("UTF-8")));
header.put("Authorization",auth);
Log.d(TAG,"ws connecting with Basic Authentication");
}
}
if (sConfig.learningOptOut) {
header.put("X-Watson-Learning-OptOut","true");
Log.d(TAG,"ws setting X-Watson-Learning-OptOut");
}
String wsURL=getHostURL().toString() + "/v1/recognize" + (this.model != null ? ("?model=" + this.model) : "");
uploader=new WebSocketUploader(wsURL,header,sConfig);
uploader.setDelegate(this.delegate);
this.startRecording();
}
catch ( URISyntaxException e) {
e.printStackTrace();
}
}
| Start recording audio |
public boolean functionAvailable(String ns,String funcName) throws javax.xml.transform.TransformerException {
boolean isAvailable=false;
if (null != ns) {
ExtensionHandler extNS=(ExtensionHandler)m_extensionFunctionNamespaces.get(ns);
if (extNS != null) isAvailable=extNS.isFunctionAvailable(funcName);
}
return isAvailable;
}
| Execute the function-available() function. |
private void doTranslation(float dx,float dy){
mRenderer.matrixTranslate(dx,-dy,0);
}
| Do rotation (plate rotation, not model rotation) |
protected void commandFf(final int flagValue){
flags=new boolean[32];
flags[READONLY_ID]=(flagValue & READONLY_BIT) == READONLY_BIT;
flags[REQUIRED_ID]=(flagValue & REQUIRED_BIT) == REQUIRED_BIT;
flags[NOEXPORT_ID]=(flagValue & NOEXPORT_BIT) == NOEXPORT_BIT;
flags[MULTILINE_ID]=(flagValue & MULTILINE_BIT) == MULTILINE_BIT;
flags[PASSWORD_ID]=(flagValue & PASSWORD_BIT) == PASSWORD_BIT;
flags[NOTOGGLETOOFF_ID]=(flagValue & NOTOGGLETOOFF_BIT) == NOTOGGLETOOFF_BIT;
flags[RADIO_ID]=(flagValue & RADIO_BIT) == RADIO_BIT;
flags[PUSHBUTTON_ID]=(flagValue & PUSHBUTTON_BIT) == PUSHBUTTON_BIT;
flags[COMBO_ID]=(flagValue & COMBO_BIT) == COMBO_BIT;
flags[EDIT_ID]=(flagValue & EDIT_BIT) == EDIT_BIT;
flags[SORT_ID]=(flagValue & SORT_BIT) == SORT_BIT;
flags[FILESELECT_ID]=(flagValue & FILESELECT_BIT) == FILESELECT_BIT;
flags[MULTISELECT_ID]=(flagValue & MULTISELECT_BIT) == MULTISELECT_BIT;
flags[DONOTSPELLCHECK_ID]=(flagValue & DONOTSPELLCHECK_BIT) == DONOTSPELLCHECK_BIT;
flags[DONOTSCROLL_ID]=(flagValue & DONOTSCROLL_BIT) == DONOTSCROLL_BIT;
flags[COMB_ID]=(flagValue & COMB_BIT) == COMB_BIT;
flags[RICHTEXT_ID]=(flagValue & RICHTEXT_BIT) == RICHTEXT_BIT;
flags[RADIOINUNISON_ID]=(flagValue & RADIOINUNISON_BIT) == RADIOINUNISON_BIT;
flags[COMMITONSELCHANGE_ID]=(flagValue & COMMITONSELCHANGE_BIT) == COMMITONSELCHANGE_BIT;
}
| read and setup the form flags for the Ff entry <b>field</b> is the data to be used to setup the Ff flags |
public TableDataException(String string){
super(string);
}
| Construct the exception. |
public static byte[] decode(String s) throws Base64DecoderException {
byte[] bytes=s.getBytes();
return decode(bytes,0,bytes.length);
}
| Decodes data from Base64 notation. |
public JCasId_Type(JCas jcas,Type casType){
super(jcas,casType);
casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType,getFSGenerator());
casFeat_id=jcas.getRequiredFeatureDE(casType,"id","uima.cas.Integer",featOkTst);
casFeatCode_id=(null == casFeat_id) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_id).getCode();
}
| initialize variables to correspond with Cas Type and Features |
protected Link(ElementKey<?,? extends Link> key){
super(key);
}
| Constructs a new instance using the specified element metadata. |
public void start(@NonNull Context context,@NonNull android.support.v4.app.Fragment fragment,int requestCode){
fragment.startActivityForResult(getIntent(context),requestCode);
}
| Send the crop Intent with a custom request code |
NamedBeanHandle<Turnout> loadTurnout(Object o){
Element e=(Element)o;
if (e.getName().equals("turnout")) {
String name=e.getAttribute("systemName").getValue();
Turnout t;
if (e.getAttribute("userName") != null && !e.getAttribute("userName").getValue().equals("")) {
name=e.getAttribute("userName").getValue();
t=InstanceManager.turnoutManagerInstance().getTurnout(name);
}
else {
t=InstanceManager.turnoutManagerInstance().getBySystemName(name);
}
return jmri.InstanceManager.getDefault(jmri.NamedBeanHandleManager.class).getNamedBeanHandle(name,t);
}
else {
String name=e.getText();
try {
Turnout t=InstanceManager.turnoutManagerInstance().provideTurnout(name);
return jmri.InstanceManager.getDefault(jmri.NamedBeanHandleManager.class).getNamedBeanHandle(name,t);
}
catch ( IllegalArgumentException ex) {
log.warn("Failed to provide Turnout \"{}\" in loadTurnout",name);
return null;
}
}
}
| Needs to handle two types of element: turnoutname is new form turnout is old form |
public void connect(final Request request) throws IOException {
this.request=request;
try {
Browser.waitForPageAccess(this,request);
}
catch ( final InterruptedException e) {
throw new IOException("requestIntervalTime Exception");
}
try {
request.connect();
}
finally {
if (this.isDebug()) {
final Logger llogger=this.getLogger();
if (llogger != null) {
try {
llogger.finest("\r\n" + request.printHeaders());
}
catch ( final Throwable e) {
e.printStackTrace();
}
}
}
}
}
| Connects a request. and sets the requests as the browsers latest request |
public Model scale(double x,double y,double z){
for ( Box box : this.modelBoxes) {
for ( Quad quad : box.quads) {
for (int i=0; i < 4; i++) {
Vec3UV vec=quad.vertices[i];
vec.x*=x;
vec.y*=y;
vec.z*=z;
}
}
}
return this;
}
| Scales the model vertices. |
public static boolean isValidType(short type){
return type == TYPE_UNSIGNED_BYTE || type == TYPE_ASCII || type == TYPE_UNSIGNED_SHORT || type == TYPE_UNSIGNED_LONG || type == TYPE_UNSIGNED_RATIONAL || type == TYPE_UNDEFINED || type == TYPE_LONG || type == TYPE_RATIONAL;
}
| Returns true if a given type is a valid tag type. |
public FilenameUtils(){
super();
}
| Instances should NOT be constructed in standard programming. |
public static Response externalException(ExternalException e){
ApiError error=new ApiError(e.getErrorCode(),e.getMessage(),e.getData());
Response.ResponseBuilder builder=Response.status(e.getHttpStatus()).entity(error).type(MediaType.APPLICATION_JSON);
addResponseHeaders(builder);
return builder.build();
}
| return a Response object that reflects the fact that an externally visible exception occurred while processing the request. |
public boolean accept(Json msg){
if (compareAndSetState(State.Proposed,State.Accepted)) {
msg.set(Messages.PERFORMATIVE,Performative.AcceptProposal);
say(msg);
return true;
}
return false;
}
| called by client task when accepting |
private void returnData(Object ret){
if (myHost != null) {
myHost.returnData(ret);
}
}
| Used to communicate a return object from a plugin tool to the main Whitebox user-interface. |
protected ArrayList<FirewallRule> readRulesFromStorage(){
ArrayList<FirewallRule> l=new ArrayList<FirewallRule>();
try {
Map<String,Object> row;
IResultSet resultSet=storageSource.executeQuery(TABLE_NAME,ColumnNames,null,null);
for (Iterator<IResultSet> it=resultSet.iterator(); it.hasNext(); ) {
row=it.next().getRow();
FirewallRule r=new FirewallRule();
if (!row.containsKey(COLUMN_RULEID) || !row.containsKey(COLUMN_DPID)) {
logger.error("skipping entry with missing required 'ruleid' or 'switchid' entry: {}",row);
return l;
}
try {
r.ruleid=Integer.parseInt((String)row.get(COLUMN_RULEID));
r.dpid=DatapathId.of((String)row.get(COLUMN_DPID));
for ( String key : row.keySet()) {
if (row.get(key) == null) {
continue;
}
if (key.equals(COLUMN_RULEID) || key.equals(COLUMN_DPID) || key.equals("id")) {
continue;
}
else if (key.equals(COLUMN_IN_PORT)) {
r.in_port=OFPort.of(Integer.parseInt((String)row.get(COLUMN_IN_PORT)));
}
else if (key.equals(COLUMN_DL_SRC)) {
r.dl_src=MacAddress.of(Long.parseLong((String)row.get(COLUMN_DL_SRC)));
}
else if (key.equals(COLUMN_DL_DST)) {
r.dl_dst=MacAddress.of(Long.parseLong((String)row.get(COLUMN_DL_DST)));
}
else if (key.equals(COLUMN_DL_TYPE)) {
r.dl_type=EthType.of(Integer.parseInt((String)row.get(COLUMN_DL_TYPE)));
}
else if (key.equals(COLUMN_NW_SRC_PREFIX)) {
r.nw_src_prefix_and_mask=IPv4AddressWithMask.of(IPv4Address.of(Integer.parseInt((String)row.get(COLUMN_NW_SRC_PREFIX))),r.nw_src_prefix_and_mask.getMask());
}
else if (key.equals(COLUMN_NW_SRC_MASKBITS)) {
r.nw_src_prefix_and_mask=IPv4AddressWithMask.of(r.nw_src_prefix_and_mask.getValue(),IPv4Address.of(Integer.parseInt((String)row.get(COLUMN_NW_SRC_MASKBITS))));
}
else if (key.equals(COLUMN_NW_DST_PREFIX)) {
r.nw_dst_prefix_and_mask=IPv4AddressWithMask.of(IPv4Address.of(Integer.parseInt((String)row.get(COLUMN_NW_DST_PREFIX))),r.nw_dst_prefix_and_mask.getMask());
}
else if (key.equals(COLUMN_NW_DST_MASKBITS)) {
r.nw_dst_prefix_and_mask=IPv4AddressWithMask.of(r.nw_dst_prefix_and_mask.getValue(),IPv4Address.of(Integer.parseInt((String)row.get(COLUMN_NW_DST_MASKBITS))));
}
else if (key.equals(COLUMN_NW_PROTO)) {
r.nw_proto=IpProtocol.of(Short.parseShort((String)row.get(COLUMN_NW_PROTO)));
}
else if (key.equals(COLUMN_TP_SRC)) {
r.tp_src=TransportPort.of(Integer.parseInt((String)row.get(COLUMN_TP_SRC)));
}
else if (key.equals(COLUMN_TP_DST)) {
r.tp_dst=TransportPort.of(Integer.parseInt((String)row.get(COLUMN_TP_DST)));
}
else if (key.equals(COLUMN_WILDCARD_DPID)) {
r.any_dpid=Boolean.parseBoolean((String)row.get(COLUMN_WILDCARD_DPID));
}
else if (key.equals(COLUMN_WILDCARD_IN_PORT)) {
r.any_in_port=Boolean.parseBoolean((String)row.get(COLUMN_WILDCARD_IN_PORT));
}
else if (key.equals(COLUMN_WILDCARD_DL_SRC)) {
r.any_dl_src=Boolean.parseBoolean((String)row.get(COLUMN_WILDCARD_DL_SRC));
}
else if (key.equals(COLUMN_WILDCARD_DL_DST)) {
r.any_dl_dst=Boolean.parseBoolean((String)row.get(COLUMN_WILDCARD_DL_DST));
}
else if (key.equals(COLUMN_WILDCARD_DL_TYPE)) {
r.any_dl_type=Boolean.parseBoolean((String)row.get(COLUMN_WILDCARD_DL_TYPE));
}
else if (key.equals(COLUMN_WILDCARD_NW_SRC)) {
r.any_nw_src=Boolean.parseBoolean((String)row.get(COLUMN_WILDCARD_NW_SRC));
}
else if (key.equals(COLUMN_WILDCARD_NW_DST)) {
r.any_nw_dst=Boolean.parseBoolean((String)row.get(COLUMN_WILDCARD_NW_DST));
}
else if (key.equals(COLUMN_WILDCARD_NW_PROTO)) {
r.any_nw_proto=Boolean.parseBoolean((String)row.get(COLUMN_WILDCARD_NW_PROTO));
}
else if (key.equals(COLUMN_PRIORITY)) {
r.priority=Integer.parseInt((String)row.get(COLUMN_PRIORITY));
}
else if (key.equals(COLUMN_ACTION)) {
int tmp=Integer.parseInt((String)row.get(COLUMN_ACTION));
if (tmp == FirewallRule.FirewallAction.DROP.ordinal()) {
r.action=FirewallRule.FirewallAction.DROP;
}
else if (tmp == FirewallRule.FirewallAction.ALLOW.ordinal()) {
r.action=FirewallRule.FirewallAction.ALLOW;
}
else {
r.action=null;
logger.error("action not recognized");
}
}
}
}
catch ( ClassCastException e) {
logger.error("skipping rule {} with bad data : " + e.getMessage(),r.ruleid);
}
if (r.action != null) {
l.add(r);
}
}
}
catch ( StorageException e) {
logger.error("failed to access storage: {}",e.getMessage());
}
Collections.sort(l);
return l;
}
| Reads the rules from the storage and creates a sorted arraylist of FirewallRule from them. Similar to getStorageRules(), which only reads contents for REST GET and does no parsing, checking, nor putting into FirewallRule objects |
public PatternFilenameFilter(String patternStr){
this(Pattern.compile(patternStr));
}
| Constructs a pattern file name filter object. |
public void remove(){
iterator.remove();
}
| Remove the current SocketChannel from the iterator |
@EventHandler(priority=EventPriority.HIGH,ignoreCancelled=true) public void onBlockPistonExtend(BlockPistonExtendEvent event){
Match match=Cardinal.getMatch(event.getWorld());
if (match == null) {
return;
}
Collection<AppliedRegion> regions=get(match,ApplyType.BLOCK,ApplyType.BLOCK_PLACE,ApplyType.BLOCK_BREAK);
Block pistonHead=event.getBlock().getRelative(event.getDirection());
for ( AppliedRegion reg : regions) {
if (!reg.getType().equals(ApplyType.BLOCK_BREAK) && reg.contains(pistonHead.getLocation())) {
FilterState result=reg.evaluate(event,Material.PISTON_EXTENSION);
if (!result.toBoolean()) {
event.setCancelled(true);
return;
}
else if (result.hasResult()) {
break;
}
}
}
for ( Block block : event.getBlocks()) {
if (!tryPistonMove(regions,block,event)) {
event.setCancelled(true);
return;
}
}
}
| Filters BlockPistonExtendEvent. <p>Will filter as block removing the old position, and placing a block in the new position.</p> <p>Applies to: block, block place and block break.<p/> |
private double[][] createSampleData1(){
double[][] result=new double[11][2];
result[0][0]=2.00;
result[0][1]=1.60;
result[1][0]=2.25;
result[1][1]=2.00;
result[2][0]=2.60;
result[2][1]=1.80;
result[3][0]=2.65;
result[3][1]=2.80;
result[4][0]=2.80;
result[4][1]=2.10;
result[5][0]=3.10;
result[5][1]=2.00;
result[6][0]=2.90;
result[6][1]=2.65;
result[7][0]=3.25;
result[7][1]=2.25;
result[8][0]=3.30;
result[8][1]=2.60;
result[9][0]=3.60;
result[9][1]=3.00;
result[10][0]=3.25;
result[10][1]=3.10;
return result;
}
| Creates and returns a sample dataset. <P> The data is taken from Table 11.2, page 313 of "Understanding Statistics" by Ott and Mendenhall (Duxbury Press). |
public void expectServerProxyFailed(){
expectedApiCalls.add(new ApiCall(SERVER_PROXY_FAILED));
}
| Expect a server proxy failure. |
public Object runSafely(Catbert.FastStack stack) throws Exception {
Album al=getAlbum(stack);
return (al == null) ? new Integer(0) : new Integer(al.getAirings().length);
}
| Returns the number of tracks that are on this Album |
@Override public void writeStartElement(String localName) throws XMLStreamException {
writeStartElement(null,localName,null);
}
| Writes a start tag to the output. All writeStartElement methods open a new scope in the internal namespace context. Writing the corresponding EndElement causes the scope to be closed |
public Move interpretMove(IGameState gameState,int col,int row,Player player){
TicTacToeState tstate=(TicTacToeState)gameState;
TicTacToeBoard board=tstate.board();
if (col < 0) return null;
if (col >= board.numColumns()) return null;
if (row < 0) return null;
if (row >= board.numRows()) return null;
if (state.getPhase() == PLACE_PHASE) {
if (board.isClear(col,row)) {
return new SlidePlaceMark(col,row,player);
}
return null;
}
Cell empty=getEmptyCell(board);
if (empty == null) return null;
SlideMark sm=new SlideMark(col,row,empty.col,empty.row,player);
if (sm.isValid(gameState)) {
return sm;
}
for (int c=0; c < board.numColumns(); c++) {
for (int r=0; r < board.numRows(); r++) {
sm=new SlideMark(c,r,empty.col,empty.row,player);
if (sm.isValid(gameState)) {
return null;
}
}
}
if (board.isClear(col,row)) {
return new PlaceMark(empty.col,empty.row,player);
}
return null;
}
| Method to determine the type of move that the user has selected. Subclasses should override this method so they will be able to properly construct the appropriate move given the context. |
@Override public void deleteMessage(String msgId){
mImService.tryToDeleteChatMessage(msgId);
}
| Delete a message from its message id from history. Will resolve if the message is one to one or from a group chat. |
public RepeatedRaptorProfileRouter(TransportNetwork network,AnalystClusterRequest clusterRequest,LinkedPointSet targets,TaskStatistics ts){
if (network.streetLayer != targets.streetLayer) {
LOG.error("Transit network and target point set are not linked to the same street layer.");
}
this.network=network;
this.clusterRequest=clusterRequest;
this.targets=targets;
this.request=clusterRequest.profileRequest;
this.ts=ts;
}
| Make a router to use for making ResultEnvelopes. This propagates travel times all the way to the target temporary street vertices, so that average and maximum travel time are correct. Temp vertices are linked to two vertices at the ends of an edge, and it is possible that the average for the sample (as well as the max) is lower than the average or the max at either of the vertices, because it may be that every time the max at one vertex is occurring, a lower value is occurring at the other. This initially seems improbable, but consider the case when there are two parallel transit services running out of phase. It may be that some of the time it makes sense to go out of your house and turn left, and sometimes it makes sense to turn right, depending on which is coming first. |
public void write(Writer out,ELContext ctx) throws ELException, IOException {
out.write(this.literal);
}
| Allow this instance to write to the passed Writer, given the ELContext state |
public static FSExportMap convertUnManagedExportMapToManaged(UnManagedFSExportMap unManagedFSExportMap,StoragePort storagePort,StorageHADomain dataMover){
FSExportMap fsExportMap=new FSExportMap();
if (unManagedFSExportMap == null) {
return fsExportMap;
}
for ( UnManagedFSExport export : unManagedFSExportMap.values()) {
FileExport fsExport=new FileExport();
if (null != export.getIsilonId()) {
fsExport.setIsilonId(export.getIsilonId());
}
if (null != export.getNativeId()) {
fsExport.setNativeId(export.getNativeId());
}
if (null != storagePort) {
fsExport.setStoragePort(storagePort.getPortName());
if ((export.getMountPath() != null) && (export.getMountPath().length() > 0)) {
fsExport.setMountPoint(ExportUtils.getFileMountPoint(storagePort.getPortNetworkId(),export.getMountPath()));
}
else {
fsExport.setMountPoint(ExportUtils.getFileMountPoint(storagePort.getPortNetworkId(),export.getPath()));
}
}
else if (null != export.getStoragePort()) {
fsExport.setStoragePort(export.getStoragePort());
if (null != export.getMountPoint()) {
fsExport.setMountPoint(export.getMountPoint());
}
}
if (null != dataMover) {
fsExport.setStoragePortName(dataMover.getName());
}
else if (null != storagePort) {
fsExport.setStoragePortName(storagePort.getPortName());
}
else if (null != export.getStoragePortName()) {
fsExport.setStoragePortName(export.getStoragePortName());
}
if (null != export.getMountPath()) {
fsExport.setMountPath(export.getMountPath());
}
fsExport.setPath(export.getPath());
fsExport.setPermissions(export.getPermissions());
fsExport.setProtocol(export.getProtocol());
fsExport.setRootUserMapping(export.getRootUserMapping());
fsExport.setSecurityType(export.getSecurityType());
fsExport.setClients(export.getClients());
fsExportMap.put(fsExport.getFileExportKey(),fsExport);
}
return fsExportMap;
}
| extract value from a String Set This method is used, to get value from a StringSet of size 1. |
public float lengthOfPath(){
return pathLength.lengthOfPath();
}
| Returns the total length of the path. |
public String next(){
seq+=inc;
if (seq >= maxSeq) {
randomizePrefix();
resetSequential();
}
char[] b=new char[totalLen];
System.arraycopy(pre,0,b,0,preLen);
int i=b.length;
for (long l=seq; i > preLen; l/=base) {
i--;
b[i]=digits[(int)(l % base)];
}
return new String(b);
}
| Generate the next NUID string from this instance. |
public boolean isNearlyEqualTo(DoubleVector v,double tolerance){
return Math.abs(v.x - x) < tolerance && Math.abs(v.y - y) < tolerance && Math.abs(v.z - z) < tolerance;
}
| Checks if this vector is nearly equals to the vector v, with some tolerance. |
public static void main(String[] args) throws OAuthException, IOException, ServiceException {
if (args.length != 3) {
System.out.println("Usage: unshare_profile <consumerKey> <consumerSecret> <adminEmail>");
}
else {
String consumerKey=args[0];
String consumerSecret=args[1];
String adminEmail=args[2];
ProfilesManager manager=new ProfilesManager(consumerKey,consumerSecret,adminEmail);
BatchResult result=manager.unshareProfiles();
System.out.println("Success: " + result.getSuccess() + " - Error: "+ result.getError());
for ( ContactEntry entry : result.getErrorEntries()) {
BatchStatus status=BatchUtils.getBatchStatus(entry);
System.out.println(" > Failed to update " + entry.getId() + ": ("+ status.getCode()+ ") "+ status.getReason());
}
}
}
| Run the sample app with the provided arguments. |
private void countResetFeedsAndCategories(){
final SQLiteDatabase db=getOpenHelper().getWritableDatabase();
try {
db.beginTransaction();
final ContentValues cv=new ContentValues(1);
cv.put(COL_UNREAD,0);
db.update(TABLE_FEEDS,cv,null,null);
db.update(TABLE_CATEGORIES,cv,null,null);
db.setTransactionSuccessful();
}
finally {
db.endTransaction();
}
}
| First of all, reset all feeds and all categories to unread=0. |
public static StaticMethodExpression staticMethod(String className,String method,Expression... parameters){
return new StaticMethodExpression(className,method,parameters);
}
| Static method invocation. |
public static Set<String> readStopwordsFile(File file,boolean lowercase) throws IOException {
return readStopwordsPath(file.toPath(),lowercase);
}
| Read a file containing stopwords (one per line). <p> Empty lines and lines starting with ("#") are filtered out. |
protected void clearEvents(){
sCInterface.clearEvents();
}
| This method resets the incoming events (time events included). |
public void testLargeMessage(){
String methodName="testLargeMessage";
IMqttAsyncClient mqttClient=null;
try {
mqttClient=new MqttAndroidClient(mContext,mqttServerURI,"testLargeMessage");
IMqttToken connectToken;
IMqttToken subToken;
IMqttToken unsubToken;
IMqttDeliveryToken pubToken;
MqttV3Receiver mqttV3Receiver=new MqttV3Receiver(mqttClient,null);
mqttClient.setCallback(mqttV3Receiver);
connectToken=mqttClient.connect(null,null);
connectToken.waitForCompletion(waitForCompletionTime);
int largeSize=1000;
String[] topicNames=new String[]{"testLargeMessage" + "/Topic"};
int[] topicQos={0};
byte[] message=new byte[largeSize];
java.util.Arrays.fill(message,(byte)'s');
subToken=mqttClient.subscribe(topicNames,topicQos,null,null);
subToken.waitForCompletion(waitForCompletionTime);
unsubToken=mqttClient.unsubscribe(topicNames,null,null);
unsubToken.waitForCompletion(waitForCompletionTime);
subToken=mqttClient.subscribe(topicNames,topicQos,null,null);
subToken.waitForCompletion(waitForCompletionTime);
pubToken=mqttClient.publish(topicNames[0],message,0,false,null,null);
pubToken.waitForCompletion(waitForCompletionTime);
boolean ok=mqttV3Receiver.validateReceipt(topicNames[0],0,message);
if (!ok) {
fail("Receive failed");
}
}
catch ( Exception exception) {
fail("Failed to instantiate:" + methodName + " exception="+ exception);
}
finally {
try {
IMqttToken disconnectToken;
disconnectToken=mqttClient.disconnect(null,null);
disconnectToken.waitForCompletion(waitForCompletionTime);
mqttClient.close();
}
catch ( Exception exception) {
}
}
}
| Test client pubSub using very large messages |
public static PGPPublicKey mergeSignatures(PGPPublicKey targetKey,PGPPublicKey sourceKey) throws PGPException {
if (!Objects.deepEquals(targetKey.getFingerprint(),sourceKey.getFingerprint())) {
throw new IllegalArgumentException("Signature merge can be done for different instances of the same public key only");
}
return copySignatures(targetKey,sourceKey);
}
| Returns a public key containing signatures of two keys. |
public void test_setDoubleLjava_lang_ObjectID(){
double[] x={0};
boolean thrown=false;
try {
Array.setDouble(x,0,1);
}
catch ( Exception e) {
fail("Exception during get test : " + e.getMessage());
}
assertEquals("Get returned incorrect value",1,Array.getDouble(x,0),0.0);
try {
Array.setDouble(new Object(),0,9);
}
catch ( IllegalArgumentException e) {
thrown=true;
}
if (!thrown) {
fail("Passing non-array failed to throw exception");
}
thrown=false;
try {
Array.setDouble(x,4,9);
}
catch ( ArrayIndexOutOfBoundsException e) {
thrown=true;
}
if (!thrown) {
fail("Invalid index failed to throw exception");
}
thrown=false;
try {
Array.setDouble(null,0,0);
}
catch ( NullPointerException e) {
thrown=true;
}
if (!thrown) {
fail("Null argument failed to throw NPE");
}
}
| java.lang.reflect.Array#setDouble(java.lang.Object, int, double) |
public Context(){
map(this);
}
| Creates a new empty context. |
private Object readResolve() throws ObjectStreamException {
return ctx.grid().scheduler();
}
| Reconstructs object on unmarshalling. |
public static IDownloaderService CreateProxy(Messenger msg){
return new Proxy(msg);
}
| Returns a proxy that will marshall calls to IDownloaderService methods |
public Cursor fetchLangGameWords(){
return mDb.query(TABLE_LEXIS,new String[]{_ROWID,KEY_LANG_ROOTWORD,KEY_LANG_LANGUAGE,KEY_LANG_ENGLISHTRANS,KEY_GAME_DIFFICULTY},null,null,null,null,null);
}
| Fetch All Language Game Words |
public static void enterSearchQuery(Activity activity,String query){
EspressoTestUtils.clickMenuItem(activity,activity.getString(R.string.action_search),R.id.action_search);
onView(isAssignableFrom(AutoCompleteTextView.class)).perform(click(),typeText(query),clearFocus());
Espresso.closeSoftKeyboard();
}
| Clicks on the search menu item and enters the given search query |
public boolean hasLabels(){
return hasRepeatingExtension(Label.class);
}
| Returns whether it has the labels. |
@Override public String id(){
return id;
}
| The id of the indexed document. |
private void generateSourceCode(final String name){
final Fingerprint fingerprint=getFingerprintByName(name);
final ClassTemplate clazz=getClassTemplateByName(name);
final List<Fingerprint.Filter> filters=fingerprint.getFilter();
final List<Fingerprint.Payload> payloads=fingerprint.getPayload();
final String javaName=Template.asJavaIdentifier(name);
final Integer index=javaName.hashCode();
final VariableDeclaration indexVariable=new VariableDeclaration(Integer.class,"INDEX",index.toString()).setIsStatic(true);
clazz.addVariable(indexVariable).setImplementingClass(FunctionalFingerprint.class).setClassPackage(getPackage()).setClassDirectives("public").setClassImports(getImports()).setClassName(javaName);
clazz.addInitialVariable(new Variable(int.class,"offset")).addInitialVariable(new Variable(int.class,"length")).addInitialVariable(new Variable(int.class,"location")).addInitialVariable(new Variable(String.class,"string")).addInitialVariable(new Variable(Matcher.class,"matcher")).addInitialVariable(new Variable(this.returnType,"ret"));
Function<String,String> mathodNameTransform=null;
final List<String> codePaths=payloads.stream().map(null).map(null).map(null).distinct().collect(Collectors.toList());
codePaths.stream().map(null).forEach(null);
}
| Generates source code for a Fingerprint which has already been added to the Template4. |
public void actionPerformed(ActionEvent e){
JTextComponent target=getTextComponent(e);
if (target != null) {
int offs=target.getCaretPosition();
Element elem=Utilities.getParagraphElement(target,offs);
offs=elem.getStartOffset();
if (select) {
target.moveCaretPosition(offs);
}
else {
target.setCaretPosition(offs);
}
}
}
| The operation to perform when this action is triggered. |
@Override public Enumeration<Option> listOptions(){
Vector<Option> result=new Vector<Option>();
result.addElement(new Option("\tThe Omega parameter.\n" + "\t(default: 1.0)","O",1,"-O <num>"));
result.addElement(new Option("\tThe Sigma parameter.\n" + "\t(default: 1.0)","S",1,"-S <num>"));
result.addAll(Collections.list(super.listOptions()));
return result.elements();
}
| Returns an enumeration describing the available options. |
@Override public List<ReilInstruction> translate(final ITranslationEnvironment environment,final InstructionType instruction,final List<ITranslationExtension<InstructionType>> extensions) throws InternalTranslationException {
Preconditions.checkNotNull(environment,"Error: Argument environment can't be null");
Preconditions.checkNotNull(instruction,"Error: Argument instruction can't be null");
final IAddress offset=ReilHelpers.toReilAddress(instruction.getAddress());
final String mnemonic=instruction.getMnemonic();
final ReilOperand firstOperand=convert(instruction.getOperands().get(0));
final ReilOperand secondOperand=convert(instruction.getOperands().get(1));
final ReilOperand thirdOperand=convert(instruction.getOperands().get(2));
return Lists.newArrayList(new ReilInstruction(offset,mnemonic,firstOperand,secondOperand,thirdOperand));
}
| Translates a REIL instruction to REIL code |
private int countFrames(int first,int last){
int numElements=0;
if (!VM.BuildForOptCompiler) {
numElements=last - first + 1;
}
else {
for (int i=first; i <= last; i++) {
CompiledMethod compiledMethod=getCompiledMethod(i);
if ((compiledMethod == null) || (compiledMethod.getCompilerType() != CompiledMethod.OPT)) {
numElements++;
}
else {
Offset instructionOffset=Offset.fromIntSignExtend(instructionOffsets[i]);
OptCompiledMethod optInfo=(OptCompiledMethod)compiledMethod;
OptMachineCodeMap map=optInfo.getMCMap();
int iei=map.getInlineEncodingForMCOffset(instructionOffset);
if (iei < 0) {
numElements++;
}
else {
int[] inlineEncoding=map.inlineEncoding;
for (; iei >= 0; iei=OptEncodedCallSiteTree.getParent(iei,inlineEncoding)) {
numElements++;
}
}
}
}
}
return numElements;
}
| Count number of stack frames including those inlined by the opt compiler |
private void assertRoleCount(UserAssignmentDetails details,int expectedRoleCount){
assertEquals(expectedRoleCount,details.getRoleKeys().size());
}
| Assert the number of the role assignment details |
public static int putVarInt(int val,byte[] buf,int off){
assert val >= 0;
while (val > 0x7f) {
buf[off++]=(byte)((val & 0x7f) | 0x80);
val>>=7;
}
buf[off++]=(byte)val;
return off;
}
| Inserts the protobuf varint into the array at the requested offset. |
public static String convertPackageToResourcePath(final Class clazz){
final String packageName=clazz.getPackage().getName();
return String.format("/%s/",packageName.replaceAll("\\.","\\/"));
}
| Takes a class and converts its package name to a path that can be used to access a resource in that package. |
public Polygon2D(double[] xs,double[] ys){
points=new ArrayList<Point2D>();
for (int i=0; i < xs.length; i++) points.add(new Point2D(xs[i],ys[i]));
}
| Creates a new polygon according to a list of coordinates <b>pre: </b> xs.length=ys.length |
public String foldsTipText(){
return "Set the number of folds for cross validation.";
}
| Returns a string for this option suitable for display in the gui as a tip text |
public String toString(){
String returnString;
returnString=opName + "(";
if (hasArgument) {
returnString=returnString + argument;
}
returnString=returnString + ")";
return returnString;
}
| Returns a string representation of this object, e.g. if opName = "addFront" and argument = 10, this method would return "addFront(10)" |
public static boolean convertKFPuzzle(InputStream is,DataOutputStream os,String title,String author,String copyright,Date date){
Puzzle puz=new Puzzle();
Scanner scanner=new Scanner(new InputStreamReader(is,new MacRoman()));
if (!scanner.hasNextLine()) {
System.err.println("File empty.");
return false;
}
String line=scanner.nextLine();
if (!line.startsWith("{") || !scanner.hasNextLine()) {
System.err.println("First line format incorrect.");
return false;
}
line=scanner.nextLine();
while (!line.startsWith("{")) {
if (!scanner.hasNextLine()) {
System.err.println("Unexpected EOF - Grid information.");
return false;
}
line=scanner.nextLine();
}
List<char[]> solGrid=new ArrayList<char[]>();
line=line.substring(1,line.length() - 2);
String[] rowString=line.split(" ");
int width=rowString.length;
do {
if (line.endsWith(" |")) {
line=line.substring(0,line.length() - 2);
}
rowString=line.split(" ");
if (rowString.length != width) {
System.err.println("Not a square grid.");
return false;
}
char[] row=new char[width];
for (int x=0; x < width; x++) {
row[x]=rowString[x].charAt(0);
}
solGrid.add(row);
if (!scanner.hasNextLine()) {
System.err.println("Unexpected EOF - Solution grid.");
return false;
}
line=scanner.nextLine();
}
while (!line.startsWith("{"));
int height=solGrid.size();
puz.setWidth(width);
puz.setHeight(height);
Box[][] boxes=new Box[height][width];
for (int x=0; x < height; x++) {
char[] row=solGrid.get(x);
for (int y=0; y < width; y++) {
if (row[y] != '#') {
boxes[x][y]=new Box();
boxes[x][y].setSolution(row[y]);
boxes[x][y].setResponse(' ');
}
}
}
puz.setBoxes(boxes);
Map<Integer,String> acrossNumToClueMap=new HashMap<Integer,String>();
line=line.substring(1);
int clueNum;
do {
if (line.endsWith(" |")) {
line=line.substring(0,line.length() - 2);
}
clueNum=0;
int i=0;
while (line.charAt(i) != '.') {
if (clueNum != 0) {
clueNum*=10;
}
clueNum+=line.charAt(i) - '0';
i++;
}
String clue=line.substring(i + 2).trim();
acrossNumToClueMap.put(clueNum,clue);
if (!scanner.hasNextLine()) {
System.err.println("Unexpected EOF - Across clues.");
return false;
}
line=scanner.nextLine();
}
while (!line.startsWith("{"));
int maxClueNum=clueNum;
Map<Integer,String> downNumToClueMap=new HashMap<Integer,String>();
line=line.substring(1);
boolean finished=false;
do {
if (line.endsWith(" |")) {
line=line.substring(0,line.length() - 2);
}
else {
finished=true;
}
clueNum=0;
int i=0;
while (line.charAt(i) != '.') {
if (clueNum != 0) {
clueNum*=10;
}
clueNum+=line.charAt(i) - '0';
i++;
}
String clue=line.substring(i + 2).trim();
downNumToClueMap.put(clueNum,clue);
if (!finished) {
if (!scanner.hasNextLine()) {
System.err.println("Unexpected EOF - Down clues.");
return false;
}
line=scanner.nextLine();
}
}
while (!finished);
maxClueNum=clueNum > maxClueNum ? clueNum : maxClueNum;
int numberOfClues=acrossNumToClueMap.size() + downNumToClueMap.size();
puz.setNumberOfClues(numberOfClues);
String[] rawClues=new String[numberOfClues];
int i=0;
for (clueNum=1; clueNum <= maxClueNum; clueNum++) {
if (acrossNumToClueMap.containsKey(clueNum)) {
rawClues[i]=acrossNumToClueMap.get(clueNum);
i++;
}
if (downNumToClueMap.containsKey(clueNum)) {
rawClues[i]=downNumToClueMap.get(clueNum);
i++;
}
}
puz.setRawClues(rawClues);
puz.setTitle(title);
puz.setAuthor(author);
puz.setDate(date);
puz.setCopyright(copyright);
puz.setVersion(IO.VERSION_STRING);
puz.setNotes("");
try {
IO.saveNative(puz,os);
}
catch ( IOException e) {
System.err.println("Unable to dump puzzle to output stream.");
return false;
}
return true;
}
| Take an InputStream containing a plaintext puzzle to a DataOutputStream containing the generated .puz file. Returns true if the process succeeded, or false if it fails (for example, if the plaintext file is not in a valid format). |
private void createVao(){
this.vao=glGenVertexArrays();
int vbo=glGenBuffers();
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER,vbo);
ByteBuffer bb=BufferUtils.createByteBuffer(4 * 2 * 6);
FloatBuffer fv=bb.asFloatBuffer();
fv.put(-1.0f).put(-1.0f);
fv.put(1.0f).put(-1.0f);
fv.put(1.0f).put(1.0f);
fv.put(1.0f).put(1.0f);
fv.put(-1.0f).put(1.0f);
fv.put(-1.0f).put(-1.0f);
glBufferData(GL_ARRAY_BUFFER,bb,GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0,2,GL_FLOAT,false,0,0L);
glBindBuffer(GL_ARRAY_BUFFER,0);
glBindVertexArray(0);
}
| Simple fullscreen quad. |
public static boolean isDirectory(byte flags){
return hasFlag(flags,FLAG_DIR);
}
| Check whether passed flags represent directory. |
private void defineRootPanes(UIDefaults d){
String c=PAINTER_PREFIX + "FrameAndRootPainter";
String p="RootPane";
d.put(p + ".States","Enabled,WindowFocused,NoFrame");
d.put(p + ".contentMargins",new InsetsUIResource(0,0,0,0));
d.put(p + ".opaque",Boolean.FALSE);
d.put(p + ".NoFrame",new RootPaneNoFrameState());
d.put(p + ".WindowFocused",new RootPaneWindowFocusedState());
d.put(p + "[Enabled+NoFrame].backgroundPainter",new LazyPainter(c,FrameAndRootPainter.Which.BACKGROUND_ENABLED_NOFRAME));
d.put(p + "[Enabled].backgroundPainter",new LazyPainter(c,FrameAndRootPainter.Which.BACKGROUND_ENABLED));
d.put(p + "[Enabled+WindowFocused].backgroundPainter",new LazyPainter(c,FrameAndRootPainter.Which.BACKGROUND_ENABLED_WINDOWFOCUSED));
}
| Initialize the root pane settings. |
public byte[] canonicalizeSubtree(Node node) throws CanonicalizationException {
return canonicalizerSpi.engineCanonicalizeSubTree(node);
}
| Canonicalizes the subtree rooted by <CODE>node</CODE>. |
private void updateElements(){
comboboxElements.clear();
comboboxElements.add(new CDebuggerTemplateWrapper(null));
for ( final DebuggerTemplate template : debuggerContainer.getDebuggers()) {
comboboxElements.add(new CDebuggerTemplateWrapper(template));
}
}
| Updates the elements of the combobox after relevant changes to the debugger container. |
@Beta public static String toString(byte x){
return toString(x,10);
}
| Returns a string representation of x, where x is treated as unsigned. |
private CloneThread(final CGraphWindow parent,final INaviView view,final IViewContainer container){
m_parent=Preconditions.checkNotNull(parent,"IE02387: parent argument can not be null");
m_view=Preconditions.checkNotNull(view,"IE02388: view argument can not be null");
m_container=Preconditions.checkNotNull(container,"IE02389: container argument can not be null");
}
| Creates a new thread object. |
public static void main(String[] args){
LoggingConfiguration.setStatistics();
double[][] data=new double[1000][2];
for (int i=0; i < data.length; i++) {
for (int j=0; j < data[i].length; j++) {
data[i][j]=Math.random();
}
}
DatabaseConnection dbc=new ArrayAdapterDatabaseConnection(data);
Database db=new StaticArrayDatabase(dbc,null);
db.initialize();
Relation<NumberVector> rel=db.getRelation(TypeUtil.NUMBER_VECTOR_FIELD);
DBIDRange ids=(DBIDRange)rel.getDBIDs();
SquaredEuclideanDistanceFunction dist=SquaredEuclideanDistanceFunction.STATIC;
RandomlyGeneratedInitialMeans init=new RandomlyGeneratedInitialMeans(RandomFactory.DEFAULT);
KMeansLloyd<NumberVector> km=new KMeansLloyd<>(dist,3,0,init);
Clustering<KMeansModel> c=km.run(db);
int i=0;
for ( Cluster<KMeansModel> clu : c.getAllClusters()) {
System.out.println("#" + i + ": "+ clu.getNameAutomatic());
System.out.println("Size: " + clu.size());
System.out.println("Center: " + clu.getModel().getPrototype().toString());
System.out.print("Objects: ");
for (DBIDIter it=clu.getIDs().iter(); it.valid(); it.advance()) {
final int offset=ids.getOffset(it);
System.out.print(" " + offset);
}
System.out.println();
++i;
}
}
| Main method |
SIPTransactionErrorEvent(SIPTransaction sourceTransaction,int transactionErrorID){
super(sourceTransaction);
errorID=transactionErrorID;
}
| Creates a transaction error event. |
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
| Process Post Request (handled by get) |
protected boolean isBefore(int x,int y,Rectangle innerAlloc){
if (majorAxis == View.X_AXIS) {
return (x < innerAlloc.x);
}
else {
return (y < innerAlloc.y);
}
}
| Determines if a point falls before an allocated region. |
@Override public String toString(){
return mediaType;
}
| Returns the encoded media type, like "text/plain; charset=utf-8", appropriate for use in a Content-Type header. |
@AfterClass public static void tearDownAfterClass() throws Exception {
}
| Method tearDownAfterClass. |
public ProviderMismatchException(){
}
| Constructs an instance of this class. |
public Matrix transpose(){
Matrix X=new Matrix(n,m);
double[][] C=X.getArray();
for (int i=0; i < m; i++) {
for (int j=0; j < n; j++) {
C[j][i]=A[i][j];
}
}
return X;
}
| Matrix transpose. |
private void updateProgress(int progress){
if (myHost != null && progress != previousProgress) {
myHost.updateProgress(progress);
}
previousProgress=progress;
}
| Used to communicate a progress update between a plugin tool and the main Whitebox user interface. |
private DownloadJob createDownloadJob(String name,URL siteUrl,UpdateSiteToken token){
if (siteUrl == null) {
CorePluginLog.logError("Could not " + name + "becuase the update site was not found in the "+ "downloaded compositeArtifacts.xml");
return null;
}
try {
final File temp=FeatureUpdateManager.createTmpFile();
temp.deleteOnExit();
DownloadJob newDownloadJob=new DownloadJob(name,siteUrl,temp);
newDownloadJob.addJobChangeListener(getSiteDownloadJobChangeListener(temp,token));
return newDownloadJob;
}
catch ( IOException e) {
CorePluginLog.logError(e);
return null;
}
}
| Creates a download job and adds it to the download jobs list in the featureUpdateManager. |
public boolean isStripOriginalVlan(){
return stripOriginalVlan;
}
| Gets the value of the stripOriginalVlan property. |
@Nullable public static URI toUri(@NonNls @NotNull String uri){
int index=uri.indexOf("://");
if (index < 0) {
try {
return new URI(uri);
}
catch ( URISyntaxException e) {
LOG.debug(e);
return null;
}
}
if (SystemInfo.isWindows && uri.startsWith(LocalFileSystem.PROTOCOL_PREFIX)) {
int firstSlashIndex=index + "://".length();
if (uri.charAt(firstSlashIndex) != '/') {
uri=LocalFileSystem.PROTOCOL_PREFIX + '/' + uri.substring(firstSlashIndex);
}
}
try {
return new URI(uri);
}
catch ( URISyntaxException e) {
LOG.debug("uri is not fully encoded",e);
try {
int fragmentIndex=uri.lastIndexOf('#');
String path=uri.substring(index + 1,fragmentIndex > 0 ? fragmentIndex : uri.length());
String fragment=fragmentIndex > 0 ? uri.substring(fragmentIndex + 1) : null;
return new URI(uri.substring(0,index),path,fragment);
}
catch ( URISyntaxException e1) {
LOG.debug(e1);
return null;
}
}
}
| uri - may be incorrect (escaping or missed "/" before disk name under windows), may be not fully encoded, may contains query and fragment |
public static boolean intersects(double lat1,double lon1,double lat2,double lon2,double lat3,double lon3,double lat4,double lon4){
double[] llp=getSegIntersection(lat1,lon1,lat2,lon2,lat3,lon3,lat4,lon4);
return (llp[0] != Double.MAX_VALUE && llp[1] != Double.MAX_VALUE) || (llp[2] != Double.MAX_VALUE && llp[3] != Double.MAX_VALUE);
}
| Returns true if the two segs intersect in at least one point. All lat-lon values are in degrees. lat1,lon1-lat2,lon2 make up one segment, lat3,lon3-lat4,lon4 make up the other segment. |
public Author(String name,URI uri,String email){
super(KEY,name,uri,email);
}
| Constructs a new author instance with the given name, uri, and email. |
private void tred2(){
for (int j=0; j < n; j++) d[j]=V.get(n - 1,j);
for (int i=n - 1; i > 0; i--) {
double scale=0.0;
double h=0.0;
for (int k=0; k < i; k++) {
scale=scale + abs(d[k]);
}
if (scale == 0.0) {
e[i]=d[i - 1];
for (int j=0; j < i; j++) {
d[j]=V.get(i - 1,j);
V.set(i,j,0.0);
V.set(j,i,0.0);
}
}
else {
for (int k=0; k < i; k++) {
d[k]/=scale;
h+=d[k] * d[k];
}
double f=d[i - 1];
double g=sqrt(h);
if (f > 0) g=-g;
e[i]=scale * g;
h-=f * g;
d[i - 1]=f - g;
Arrays.fill(e,0,i,0.0);
for (int j=0; j < i; j++) {
f=d[j];
V.set(j,i,f);
g=e[j] + V.get(j,j) * f;
for (int k=j + 1; k <= i - 1; k++) {
g+=V.get(k,j) * d[k];
e[k]+=V.get(k,j) * f;
}
e[j]=g;
}
f=0.0;
for (int j=0; j < i; j++) {
e[j]/=h;
f+=e[j] * d[j];
}
double hh=f / (h + h);
for (int j=0; j < i; j++) {
e[j]-=hh * d[j];
}
for (int j=0; j < i; j++) {
f=d[j];
g=e[j];
for (int k=j; k <= i - 1; k++) {
V.increment(k,j,-(f * e[k] + g * d[k]));
}
d[j]=V.get(i - 1,j);
V.set(i,j,0.0);
}
}
d[i]=h;
}
for (int i=0; i < n - 1; i++) {
V.set(n - 1,i,V.get(i,i));
V.set(i,i,1.0);
double h=d[i + 1];
if (h != 0.0) {
for (int k=0; k <= i; k++) {
d[k]=V.get(k,i + 1) / h;
}
for (int j=0; j <= i; j++) {
double g=0.0;
for (int k=0; k <= i; k++) {
g+=V.get(k,i + 1) * V.get(k,j);
}
RowColumnOps.addMultCol(V,j,0,i + 1,-g,d);
}
}
RowColumnOps.fillCol(V,i + 1,0,i + 1,0.0);
}
for (int j=0; j < n; j++) {
d[j]=V.get(n - 1,j);
V.set(n - 1,j,0.0);
}
V.set(n - 1,n - 1,1.0);
e[0]=0.0;
}
| Symmetric Householder reduction to tridiagonal form. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.