code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public static Map<Id<Screenline>,Screenline> openShapefile(String shapefile,Network network){
Map<Id<Screenline>,Screenline> result=Screenline.openShapefile(shapefile);
for ( Screenline s : result.values()) {
s.loadLinksFromNetwork(network);
}
return result;
}
| Loads a set of screenlines from a shapefile, initializing each Screenline with links from the network. |
public JSONArray put(int index,Object value) throws JSONException {
JSONObject.testValidity(value);
if (index < 0) {
throw new JSONException("JSONArray[" + index + "] not found.");
}
if (index < this.length()) {
this.myArrayList.set(index,value);
}
else {
while (index != this.length()) {
this.put(JSONObject.NULL);
}
this.put(value);
}
return this;
}
| Put or replace an object value in the JSONArray. If the index is greater than the length of the JSONArray, then null elements will be added as necessary to pad it out. |
public boolean isClosed(){
synchronized (closeLock) {
return closed;
}
}
| Returns the closed state of the socket. |
public boolean isComplete(){
if (this.size() > 1 && this.get(0).getType().equalsIgnoreCase("major") && this.get(this.size() - 1).getType().equalsIgnoreCase("major")) {
return true;
}
else {
return false;
}
}
| Checks if a chain is complete. |
private static void testJcmdPidHelp() throws Exception {
OutputAnalyzer output=JcmdBase.jcmd(VM_ARGS,new String[]{"help"});
output.shouldHaveExitValue(0);
output.shouldNotContain("Exception");
output.shouldContain(Integer.toString(ProcessTools.getProcessId()) + ":");
matchJcmdCommands(output);
output.shouldContain("For more information about a specific command use 'help <command>'.");
}
| jcmd -J-XX:+UsePerfData pid help |
public static void verifyTargetIdCount(List<String> targetIds,int maxChecks) throws TooManyResourceChecksException {
if (targetIds.size() > maxChecks) {
throw new TooManyResourceChecksException(maxChecks);
}
}
| Get the list of target ids from a check command. |
private SAXParseException makeException(String message){
if (locator != null) {
return new SAXParseException(message,locator);
}
else {
return new SAXParseException(message,null,null,-1,-1);
}
}
| Construct an exception for the current context. |
public void testConstructorBytesNegative4(){
byte aBytes[]={-128,-12,56,100,-13,56,93,-78};
byte rBytes[]={-128,-12,56,100,-13,56,93,-78};
BigInteger aNumber=new BigInteger(aBytes);
byte resBytes[]=new byte[rBytes.length];
resBytes=aNumber.toByteArray();
for (int i=0; i < resBytes.length; i++) {
assertTrue(resBytes[i] == rBytes[i]);
}
assertEquals("incorrect sign",-1,aNumber.signum());
}
| Create a negative number from an array of bytes. The number of bytes is multiple of 4. |
public synchronized void flush() throws IOException {
checkNotClosed();
trimToSize();
journalWriter.flush();
}
| Force buffered operations to the filesystem. |
public boolean isEnum(){
return rawClass.isEnum();
}
| Return true if variable is an enumeration |
public static String encodeString(String source){
if (source == null) {
return source;
}
int i=firstIllegalCharacter(source);
if (i == -1) {
return source;
}
StringBuffer encoded=new StringBuffer();
encoded.append(source.substring(0,i));
byte bytes[]=toBytes(source);
for (; i < bytes.length; i++) {
int ch=bytes[i];
if (isLegal(ch)) {
encoded.append((char)ch);
}
else {
encoded.append(QUOTE_MARKER + Integer.toHexString((byte)ch & 0xff).toUpperCase());
}
}
return encoded.toString();
}
| Utility method to encode a string, as per RFC 2396 section 2. Set asQueryValue=false to avoid encoding ampersands. |
private static boolean isNameCompatibleLastType(final Expression lastExpr,final String typeString){
final ExpressionType lastType=lastExpr.getType();
if (lastType.getTypeString().startsWith(typeString)) {
return true;
}
if (typeString.startsWith(lastType.getTypeString())) {
return true;
}
if (lastType.isNumeral()) {
return true;
}
if (lastType.isDynamic()) {
return true;
}
if (lastType.isObject() && typeString.startsWith(ExpressionType.SUBJECT)) {
return true;
}
if (lastType.isSubject() && typeString.startsWith(ExpressionType.OBJECT)) {
return true;
}
if (Grammar.isAmbiguousNounVerb(lastExpr.getNormalized())) {
if (lastType.isVerb() && typeString.equals(ExpressionType.OBJECT)) {
return true;
}
if (lastType.isObject() && typeString.equals(ExpressionType.VERB)) {
return true;
}
}
return false;
}
| Check for compatible types. |
public OffHeapBufferStorageEngine(PointerSize width,PageSource source,int pageSize,Portability<? super K> keyPortability,Portability<? super V> valuePortability){
this(width,source,pageSize,pageSize,keyPortability,valuePortability);
}
| Creates a storage engine using the given page source, and portabilities. |
protected void drawStackHorizontal(List values,Comparable category,Graphics2D g2,CategoryItemRendererState state,Rectangle2D dataArea,CategoryPlot plot,CategoryAxis domainAxis,ValueAxis rangeAxis,CategoryDataset dataset){
int column=dataset.getColumnIndex(category);
double barX0=domainAxis.getCategoryMiddle(column,dataset.getColumnCount(),dataArea,plot.getDomainAxisEdge()) - state.getBarWidth() / 2.0;
double barW=state.getBarWidth();
List itemLabelList=new ArrayList();
boolean inverted=rangeAxis.isInverted();
int blockCount=values.size() - 1;
for (int k=0; k < blockCount; k++) {
int index=(inverted ? blockCount - k - 1 : k);
Object[] prev=(Object[])values.get(index);
Object[] curr=(Object[])values.get(index + 1);
int series;
if (curr[0] == null) {
series=-((Integer)prev[0]).intValue() - 1;
}
else {
series=((Integer)curr[0]).intValue();
if (series < 0) {
series=-((Integer)prev[0]).intValue() - 1;
}
}
double v0=((Double)prev[1]).doubleValue();
double vv0=rangeAxis.valueToJava2D(v0,dataArea,plot.getRangeAxisEdge());
double v1=((Double)curr[1]).doubleValue();
double vv1=rangeAxis.valueToJava2D(v1,dataArea,plot.getRangeAxisEdge());
Shape[] faces=createHorizontalBlock(barX0,barW,vv0,vv1,inverted);
Paint fillPaint=getItemPaint(series,column);
Paint fillPaintDark=PaintAlpha.darker(fillPaint);
boolean drawOutlines=isDrawBarOutline();
Paint outlinePaint=fillPaint;
if (drawOutlines) {
outlinePaint=getItemOutlinePaint(series,column);
g2.setStroke(getItemOutlineStroke(series,column));
}
for (int f=0; f < 6; f++) {
if (f == 5) {
g2.setPaint(fillPaint);
}
else {
g2.setPaint(fillPaintDark);
}
g2.fill(faces[f]);
if (drawOutlines) {
g2.setPaint(outlinePaint);
g2.draw(faces[f]);
}
}
itemLabelList.add(new Object[]{new Integer(series),faces[5].getBounds2D(),BooleanUtilities.valueOf(v0 < getBase())});
EntityCollection entities=state.getEntityCollection();
if (entities != null) {
addItemEntity(entities,dataset,series,column,faces[5]);
}
}
for (int i=0; i < itemLabelList.size(); i++) {
Object[] record=(Object[])itemLabelList.get(i);
int series=((Integer)record[0]).intValue();
Rectangle2D bar=(Rectangle2D)record[1];
boolean neg=((Boolean)record[2]).booleanValue();
CategoryItemLabelGenerator generator=getItemLabelGenerator(series,column);
if (generator != null && isItemLabelVisible(series,column)) {
drawItemLabel(g2,dataset,series,column,plot,generator,bar,neg);
}
}
}
| Draws a stack of bars for one category, with a horizontal orientation. |
public TwoStepsGOV3Function<T> build() throws IOException {
if (built) throw new IllegalStateException("This builder has been already used");
built=true;
if (transform == null) {
if (chunkedHashStore != null) transform=chunkedHashStore.transform();
else throw new IllegalArgumentException("You must specify a TransformationStrategy, either explicitly or via a given ChunkedHashStore");
}
return new TwoStepsGOV3Function<T>(keys,transform,values,tempDir,chunkedHashStore);
}
| Builds a new function. |
public boolean bool(XPathContext xctxt) throws javax.xml.transform.TransformerException {
XObject left=m_left.execute(xctxt,true);
XObject right=m_right.execute(xctxt,true);
boolean result=left.equals(right) ? true : false;
left.detach();
right.detach();
return result;
}
| Execute a binary operation by calling execute on each of the operands, and then calling the operate method on the derived class. |
public static JSON from(InputStream inStream) throws IOException {
Assert.notNull("inStream",inStream);
String jsonString=IOUtils.toString(inStream,"UTF-8");
return from(jsonString);
}
| Creates a <code>JSON</code> instance from an <code>InputStream</code>. The method assumes the character set is UTF-8. |
public static PedanticThrowAnalysis v(){
return G.v().soot_toolkits_exceptions_PedanticThrowAnalysis();
}
| Returns the single instance of <code>PedanticThrowAnalysis</code>. |
public static long distance(double latitude1,double longitude1,double latitude2,double longitude2){
double latitudeSin=Math.sin(Math.toRadians(latitude2 - latitude1) / 2);
double longitudeSin=Math.sin(Math.toRadians(longitude2 - longitude1) / 2);
double a=latitudeSin * latitudeSin + Math.cos(Math.toRadians(latitude1)) * Math.cos(Math.toRadians(latitude2)) * longitudeSin* longitudeSin;
double c=2 * MathUtil.atan2(Math.sqrt(a),Math.sqrt(1 - a));
return (long)(6378137 * c);
}
| Returns the distance between 2 points in meters |
@Override protected EClass eStaticClass(){
return UmplePackage.eINSTANCE.getTraceOptions_();
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
private static boolean checkNextEventIsPartOfSameLDI(ReplicatorRuntime runtime,BinlogReader position,FormatDescriptionLogEvent descriptionEvent,boolean parseStatements,boolean useBytesForString,int fileID,int binlogReadTimeout) throws ReplicatorException, InterruptedException, IOException, ExtractorException {
byte[] fullEvent;
int eventLength;
BinlogReader tempPosition=position.clone();
tempPosition.setEventID(position.getEventID() + 1);
tempPosition.open();
if (logger.isDebugEnabled()) logger.debug("Reading from " + tempPosition);
boolean found=false;
byte[] tmpHeader=new byte[descriptionEvent.commonHeaderLength];
try {
String tempPos;
while (!found) {
tempPos=tempPosition.toString();
eventLength=extractEventHeader(runtime,tempPosition,tmpHeader);
if (tmpHeader[MysqlBinlog.EVENT_TYPE_OFFSET] == MysqlBinlog.EXECUTE_LOAD_QUERY_EVENT || tmpHeader[MysqlBinlog.EVENT_TYPE_OFFSET] == MysqlBinlog.DELETE_FILE_EVENT || tmpHeader[MysqlBinlog.EVENT_TYPE_OFFSET] == MysqlBinlog.APPEND_BLOCK_EVENT) {
found=true;
fullEvent=extractFullEvent(runtime,eventLength,tempPosition,tmpHeader,binlogReadTimeout);
LogEvent tempEvent=readLogEvent(parseStatements,tempPos,fullEvent,fullEvent.length,descriptionEvent,useBytesForString);
if (tempEvent instanceof LoadDataInfileEvent) {
LoadDataInfileEvent nextEvent=(LoadDataInfileEvent)tempEvent;
if (nextEvent.getFileID() == fileID) {
return true;
}
}
}
else if (tmpHeader[MysqlBinlog.EVENT_TYPE_OFFSET] == MysqlBinlog.ROTATE_EVENT) {
fullEvent=extractFullEvent(runtime,eventLength,tempPosition,tmpHeader,binlogReadTimeout);
LogEvent tempEvent=readLogEvent(parseStatements,tempPos,fullEvent,fullEvent.length,descriptionEvent,useBytesForString);
if (tempEvent instanceof RotateLogEvent) {
tempPosition.close();
tempPosition.setFileName(((RotateLogEvent)tempEvent).getNewBinlogFilename());
tempPosition.open();
}
else throw new ExtractorException("Failed to extract RotateLogEvent" + tempPosition);
}
else if (tmpHeader[MysqlBinlog.EVENT_TYPE_OFFSET] == MysqlBinlog.FORMAT_DESCRIPTION_EVENT) {
long skip=0;
while (skip != eventLength) {
skip+=tempPosition.skip(eventLength - skip);
}
}
else return false;
}
}
finally {
tempPosition.close();
}
return false;
}
| Check whether next binlog event is part of the same Load Data Infile command (identified by file ID). |
public void elementDecl(String name,String model) throws SAXException {
}
| This method does nothing. |
public static void main(String[] args){
PieChartDemo1 demo=new PieChartDemo1("JFreeChart: Pie Chart Demo 1");
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
}
| Starting point for the demonstration application. |
@PUT @ZeppelinApi public Response updateRepoSetting(String payload){
if (StringUtils.isBlank(payload)) {
return new JsonResponse<>(Status.NOT_FOUND,"",Collections.emptyMap()).build();
}
AuthenticationInfo subject=new AuthenticationInfo(SecurityUtils.getPrincipal());
NotebookRepoSettingsRequest newSettings=NotebookRepoSettingsRequest.EMPTY;
try {
newSettings=gson.fromJson(payload,NotebookRepoSettingsRequest.class);
}
catch ( JsonSyntaxException e) {
LOG.error("Cannot update notebook repo settings",e);
return new JsonResponse<>(Status.NOT_ACCEPTABLE,"",ImmutableMap.of("error","Invalid payload structure")).build();
}
if (NotebookRepoSettingsRequest.isEmpty(newSettings)) {
LOG.error("Invalid property");
return new JsonResponse<>(Status.NOT_ACCEPTABLE,"",ImmutableMap.of("error","Invalid payload")).build();
}
LOG.info("User {} is going to change repo setting",subject.getUser());
NotebookRepoWithSettings updatedSettings=noteRepos.updateNotebookRepo(newSettings.name,newSettings.settings,subject);
if (!updatedSettings.isEmpty()) {
LOG.info("Broadcasting note list to user {}",subject.getUser());
notebookWsServer.broadcastReloadedNoteList(subject,null);
}
return new JsonResponse<>(Status.OK,"",updatedSettings).build();
}
| Update a specific note repo. |
private boolean isRuntimeChecked(int paramNo,ProjectModel pm,Callback cb){
List<MemberHandle> calls=pm.getCalls(declaration);
if (isCovariantMethod(calls)) {
return true;
}
boolean found=false;
boolean checkTried=false;
for ( MemberHandle memberHandle : calls) {
if (memberHandle instanceof StackArgumentsHandle) {
StackArgumentsHandle icmh=(StackArgumentsHandle)memberHandle;
if (icmh.getName().equals("immutable")) {
checkTried=true;
if (!icmh.isFirstCall()) {
cb.registerError(new IncorrectPure4JImmutableCallException(this));
return false;
}
else if (icmh.getLocalVariables().contains(paramNo)) {
found=true;
}
}
else if (icmh.getName().equals("unsupported")) {
checkTried=true;
found=true;
}
else if (icmh.getName().equals("<init>")) {
if (icmh.getLocalVariables().contains(paramNo)) {
found=true;
}
}
}
}
if (checkTried) {
if (!found) {
cb.registerError(new MissingImmutableParameterCheckException(this,paramNo));
return false;
}
}
return checkTried;
}
| Checks to see whether the developer has called the runtime check for immutability. |
protected void generateGrabPoints(Projection proj){
DrawingAttributes grabPointDA=null;
Object obj=poly.getAttribute(EditableOMGraphic.GRAB_POINT_DRAWING_ATTRIBUTES_ATTRIBUTE);
if (obj instanceof DrawingAttributes) {
grabPointDA=(DrawingAttributes)obj;
}
int index=0;
for ( GrabPoint gb : polyGrabPoints) {
if (gb != null) {
if (selectNodeIndex == index) {
Object daobj=poly.getAttribute(EditableOMGraphic.SELECTED_GRAB_POINT_DRAWING_ATTRIBUTES_ATTRIBUTE);
if (daobj instanceof DrawingAttributes) {
((DrawingAttributes)daobj).setTo(gb);
}
}
else if (grabPointDA != null) {
grabPointDA.setTo(gb);
}
else {
gb.setDefaultDrawingAttributes(GrabPoint.DEFAULT_RADIUS);
}
gb.generate(proj);
}
index++;
}
if (gpo != null) {
if (grabPointDA != null) {
grabPointDA.setTo(gpo);
}
else {
gpo.setDefaultDrawingAttributes(GrabPoint.DEFAULT_RADIUS);
}
gpo.generate(proj);
gpo.updateOffsets();
}
}
| Generate the grab points, checking the OMGraphic to see if it contains information about what the grab points should look like. |
@Override public FileLock lock(long position,long size,boolean shared) throws IOException {
throw new IOException("Method is unsupported.");
}
| Unsupported method. |
protected final void openSessionForRead(String applicationId,List<String> permissions){
openSessionForRead(applicationId,permissions,SessionLoginBehavior.SSO_WITH_FALLBACK,Session.DEFAULT_AUTHORIZE_ACTIVITY_CODE);
}
| Opens a new session with read permissions. If either applicationID or permissions is null, this method will default to using the values from the associated meta-data value and an empty list respectively. |
public synchronized void initPublisherPool(int poolSize,String brokerUrl,boolean isSync,boolean force){
if (force && publisherPool != null) {
clearPublisherPool();
publisherPool=null;
}
if (publisherPool == null) {
publisherPool=new PublisherPool(poolSize,brokerUrl,isSync);
}
}
| initialize publisher client pool |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 13:02:08.801 -0500",hash_original_method="6287831B75A2E8C792411156F0D937ED",hash_generated_method="09A9D4CBD58FEF5C678ED96F2E5A121D") public static int tertiaryOrder(int order){
return order & TERTIARY_ORDER_MASK_;
}
| Gets the tertiary order of a collation order. |
@Override public void mouseRelease(int x,int y,int mouseButton){
mouseX=x;
mouseY=y;
this.mouseButton=mouseButton;
if (mouseButton == 1) {
if ((tape == null) && (path == null)) {
if (hasMouse()) {
((Spatial)movable).getSceneHints().setAllPickingHints(true);
movable.setInMotion(false,null);
Dert.getMainWindow().getUndoHandler().addEdit(new MoveEdit(movable,lastPosition));
movable=null;
canvasPanel.getCanvas().setCursor(null);
}
}
}
controller.mouseRelease(x,y,mouseButton);
}
| Mouse button was released |
@Override public boolean isActive(){
return amIActive;
}
| Used by the Whitebox GUI to tell if this plugin is still running. |
public final void addField2(FieldInfo finfo){
fields.add(finfo);
}
| Just appends a field to the class. It does not check field duplication. Use this method only when minimizing performance overheads is seriously required. |
protected String wrapLinuxCommand(String command) throws IOException, InterruptedException {
String setGroup="export GROUP_NAME=`(getent group " + getGid() + " || (groupadd -g "+ getGid()+ " user && echo user:x:"+ getGid()+ ")) | cut -d: -f1`";
String setUser="export USER_NAME=`(getent passwd " + getUid() + " || (useradd -u "+ getUid()+ " -g ${GROUP_NAME} user && echo user:x:"+ getGid()+ ")) | cut -d: -f1`";
String chownCommand="chown --silent -R ${USER_NAME}.${GROUP_NAME} /usr/src/app || true";
return setGroup + " && " + setUser+ " && "+ chownCommand+ " && "+ command+ " && "+ chownCommand;
}
| Wrap the given command into a command with chown. Also add group/user that match host environment if not exists |
public static boolean isPrintableCharacter(final char c){
final Character.UnicodeBlock block=Character.UnicodeBlock.of(c);
return !Character.isISOControl(c) && (c != KeyEvent.CHAR_UNDEFINED) && (block != null)&& (block != Character.UnicodeBlock.SPECIALS);
}
| Tests whether a character is a printable ASCII character. |
private void terminateAndEraseFile(){
Log.d(Constants.TAG,"RecordService terminateAndEraseFile");
stopAndReleaseRecorder();
recording=false;
deleteFile();
}
| in case it is impossible to record |
@SuppressWarnings("unchecked") public Iterator<Statement> createIteratorOfStatementFromString(EDataType eDataType,String initialValue){
return (Iterator<Statement>)super.createFromString(initialValue);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName,java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
if (xmlWriter.getPrefix(namespace) == null) {
xmlWriter.writeNamespace(prefix,namespace);
xmlWriter.setPrefix(prefix,namespace);
}
xmlWriter.writeAttribute(namespace,attName,attValue);
}
| Util method to write an attribute with the ns prefix |
public void disable(){
}
| DEPRECATED: Replaced by setEnabled(boolean). |
protected void initTransportLayer() throws IOException {
input=super.getInputStream();
output=super.getOutputStream();
}
| Initialize the transport data streams. |
public MyCertificate(String type,byte[] encoding){
super(type);
this.encoding=encoding;
}
| Constructs new object of class <code>MyCertificate</code> |
public PiePlotLegend(PiePlot plot){
this.plot=plot;
}
| Initializes a new instance with a specified plot. |
@Override public void update(Graphics g){
int xh, yh, xm, ym, xs, ys;
int s=0, m=10, h=10;
String today;
currentDate=new Date();
formatter.applyPattern("s");
try {
s=Integer.parseInt(formatter.format(currentDate));
}
catch ( NumberFormatException n) {
s=0;
}
formatter.applyPattern("m");
try {
m=Integer.parseInt(formatter.format(currentDate));
}
catch ( NumberFormatException n) {
m=10;
}
formatter.applyPattern("h");
try {
h=Integer.parseInt(formatter.format(currentDate));
}
catch ( NumberFormatException n) {
h=10;
}
xs=(int)(Math.cos(s * Math.PI / 30 - Math.PI / 2) * 45 + xcenter);
ys=(int)(Math.sin(s * Math.PI / 30 - Math.PI / 2) * 45 + ycenter);
xm=(int)(Math.cos(m * Math.PI / 30 - Math.PI / 2) * 40 + xcenter);
ym=(int)(Math.sin(m * Math.PI / 30 - Math.PI / 2) * 40 + ycenter);
xh=(int)(Math.cos((h * 30 + m / 2) * Math.PI / 180 - Math.PI / 2) * 30 + xcenter);
yh=(int)(Math.sin((h * 30 + m / 2) * Math.PI / 180 - Math.PI / 2) * 30 + ycenter);
formatter.applyPattern("EEE MMM dd HH:mm:ss yyyy");
today=formatter.format(currentDate);
g.setFont(clockFaceFont);
g.setColor(getBackground());
if (xs != lastxs || ys != lastys) {
g.drawLine(xcenter,ycenter,lastxs,lastys);
g.drawString(lastdate,5,125);
}
if (xm != lastxm || ym != lastym) {
g.drawLine(xcenter,ycenter - 1,lastxm,lastym);
g.drawLine(xcenter - 1,ycenter,lastxm,lastym);
}
if (xh != lastxh || yh != lastyh) {
g.drawLine(xcenter,ycenter - 1,lastxh,lastyh);
g.drawLine(xcenter - 1,ycenter,lastxh,lastyh);
}
g.setColor(numberColor);
g.drawString(today,5,125);
g.drawLine(xcenter,ycenter,xs,ys);
g.setColor(handColor);
g.drawLine(xcenter,ycenter - 1,xm,ym);
g.drawLine(xcenter - 1,ycenter,xm,ym);
g.drawLine(xcenter,ycenter - 1,xh,yh);
g.drawLine(xcenter - 1,ycenter,xh,yh);
lastxs=xs;
lastys=ys;
lastxm=xm;
lastym=ym;
lastxh=xh;
lastyh=yh;
lastdate=today;
currentDate=null;
}
| Paint is the main part of the program |
public SimpleFragmentIntent<F> putExtra(String name,int value){
if (extras == null) {
extras=new Bundle();
}
extras.putInt(name,value);
return this;
}
| Add extended data to the intent. |
public static Sequence<IString> toIStringSequence(int[] indices){
return toIStringSequence(indices,null);
}
| Get a sequence of IString from an array of IString indices. |
protected void processValues(Trace trace,Node node,Direction direction,Map<String,?> headers,Object[] values){
if (node.interactionNode()) {
Message m=null;
if (direction == Direction.In) {
m=((InteractionNode)node).getIn();
if (m == null) {
m=new Message();
((InteractionNode)node).setIn(m);
}
}
else {
m=((InteractionNode)node).getOut();
if (m == null) {
m=new Message();
((InteractionNode)node).setOut(m);
}
}
if (headers != null && m.getHeaders().isEmpty()) {
for ( Map.Entry<String,?> stringEntry : headers.entrySet()) {
String value=getHeaderValueText(stringEntry.getValue());
if (value != null) {
m.getHeaders().put(stringEntry.getKey(),value);
}
}
}
}
if (processorManager != null) {
processorManager.process(trace,node,direction,headers,values);
}
}
| This method processes the values associated with the start or end of a scoped activity. |
static GenomeRelationships loadFile(File vcfFile) throws IOException {
try (VcfReader vr=VcfReader.openVcfReader(vcfFile)){
return load(vr.getHeader());
}
}
| Load genome relationships from a VCF header sample and pedigree lines |
public void remove(String key){
mValues.remove(key);
}
| Remove a single value. |
public static void generate(Cache cache,PrintWriter pw,boolean useSchema){
(new CacheXmlGenerator(cache,true,VERSION_LATEST,true)).generate(pw);
}
| Examines the given <code>Cache</code> and from it generates XML data that is written to the given <code>PrintWriter</code>. The schema/dtd for the current version of GemFire is used. |
protected void configureEnhancerEvent(){
}
| Sends an event to notify than an event has changed. |
private void addRepositoryInfoListener(){
try {
coordinator.getCoordinatorClient().addNodeListener(new RepositoryInfoListener());
}
catch ( Exception e) {
log.error("Fail to add node listener for repository info target znode",e);
throw APIException.internalServerErrors.addListenerFailed();
}
log.info("Successfully added node listener for repository info target znode");
}
| Register repository info listener to monitor repository version changes |
public void testAddAll2(){
try {
LinkedBlockingQueue q=new LinkedBlockingQueue(SIZE);
Integer[] ints=new Integer[SIZE];
q.addAll(Arrays.asList(ints));
shouldThrow();
}
catch ( NullPointerException success) {
}
}
| addAll of a collection with null elements throws NPE |
public List<Entity> extractURLsWithIndices(final String text){
if (text == null || text.length() == 0 || (extractURLWithoutProtocol ? text.indexOf('.') : text.indexOf(':')) == -1) return Collections.emptyList();
final ArrayList<Entity> urls=new ArrayList<Entity>();
final Matcher matcher=Regex.VALID_URL.matcher(text);
while (matcher.find()) {
if (matcher.group(Regex.VALID_URL_GROUP_PROTOCOL) == null) {
if (!extractURLWithoutProtocol || Regex.INVALID_URL_WITHOUT_PROTOCOL_MATCH_BEGIN.matcher(matcher.group(Regex.VALID_URL_GROUP_BEFORE)).matches()) {
continue;
}
}
String url=matcher.group(Regex.VALID_URL_GROUP_URL);
final int start=matcher.start(Regex.VALID_URL_GROUP_URL);
int end=matcher.end(Regex.VALID_URL_GROUP_URL);
final Matcher tco_matcher=Regex.VALID_TCO_URL.matcher(url);
if (tco_matcher.find()) {
url=tco_matcher.group();
end=start + url.length();
}
urls.add(new Entity(start,end,url,Entity.Type.URL));
}
return urls;
}
| Extract URL references from Tweet text. |
private boolean match(Class<?>[] declaredTypes,Class<?>[] actualTypes){
if (declaredTypes.length == actualTypes.length) {
for (int i=0; i < actualTypes.length; i++) {
if (actualTypes[i] == NULL.class) continue;
if (wrapper(declaredTypes[i]).isAssignableFrom(wrapper(actualTypes[i]))) continue;
return false;
}
return true;
}
else {
return false;
}
}
| Check whether two arrays of types match, converting primitive types to their corresponding wrappers. |
public boolean isPatchVisible(PatchSet ps,ReviewDb db) throws OrmException {
if (ps != null && ps.isDraft() && !isDraftVisible(db,null)) {
return false;
}
return isVisible(db);
}
| Can this user see the given patchset? |
public Serializer(Properties properties){
this(new SerializerOptions(properties));
}
| Creates a new serializer instance with the given properties. |
@MainThread @ObjectiveCName("subscribeWithListener:withNotify:") public synchronized void subscribe(@NotNull ModelChangedListener<GroupVM> listener,boolean notify){
if (listeners.contains(listener)) {
return;
}
listeners.add(listener);
if (notify) {
listener.onChanged(this);
}
}
| Subscribe for GroupVM updates |
public boolean canPace(){
return false;
}
| Returns whether two values of this type can have their distance computed, as needed by paced animation. |
@DSComment("Package priviledge") @DSBan(DSCat.DEFAULT_MODIFIER) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:58:55.597 -0500",hash_original_method="2CBB8BA051416BBE1CBD482FDF45ADE6",hash_generated_method="FE6D14DB988140C70DE8975E0CE436AC") CdmaConnection(Context context,String dialString,CdmaCallTracker ct,CdmaCall parent){
createWakeLock(context);
acquireWakeLock();
owner=ct;
h=new MyHandler(owner.getLooper());
this.dialString=dialString;
Log.d(LOG_TAG,"[CDMAConn] CdmaConnection: dialString=" + dialString);
dialString=formatDialString(dialString);
Log.d(LOG_TAG,"[CDMAConn] CdmaConnection:formated dialString=" + dialString);
this.address=PhoneNumberUtils.extractNetworkPortionAlt(dialString);
this.postDialString=PhoneNumberUtils.extractPostDialPortion(dialString);
index=-1;
isIncoming=false;
cnapName=null;
cnapNamePresentation=Connection.PRESENTATION_ALLOWED;
numberPresentation=Connection.PRESENTATION_ALLOWED;
createTime=System.currentTimeMillis();
if (parent != null) {
this.parent=parent;
if (parent.state == CdmaCall.State.ACTIVE) {
parent.attachFake(this,CdmaCall.State.ACTIVE);
}
else {
parent.attachFake(this,CdmaCall.State.DIALING);
}
}
}
| This is an MO call/three way call, created when dialing |
final public MutableString deleteCharAt(final int index){
final int length=length();
if (index >= length) throw new StringIndexOutOfBoundsException();
System.arraycopy(array,index + 1,array,index,length - index - 1);
if (hashLength < 0) {
setCapacity(length - 1);
hashLength=-1;
}
else hashLength--;
return this;
}
| Removes the character at the given index. <P>Note that this method <em>will reallocate the backing array of a compact mutable string for each character deleted</em>. Do not call it lightly. |
public SerializeWriter(SerializerFeature... features){
SoftReference<char[]> ref=bufLocal.get();
if (ref != null) {
buf=ref.get();
bufLocal.set(null);
}
if (buf == null) {
buf=new char[1024];
}
int featuresValue=0;
for ( SerializerFeature feature : features) {
featuresValue|=feature.getMask();
}
this.features=featuresValue;
}
| Creates a new CharArrayWriter. |
private static boolean isWritable(@NonNull final File file){
boolean isExisting=file.exists();
try {
FileOutputStream output=new FileOutputStream(file,true);
try {
output.close();
}
catch ( IOException e) {
}
}
catch ( java.io.FileNotFoundException e) {
return false;
}
boolean result=file.canWrite();
if (!isExisting) {
file.delete();
}
return result;
}
| Check is a file is writable. Detects write issues on external SD card. |
public void purgeQueue(){
fDirtyRegions.clear();
}
| Throws away all entries in the queue. |
public boolean addJournalVolumesToCG(CGRequestParams request,int copyType){
ConsistencyGroupUID cgUID=null;
List<ConsistencyGroupUID> allCgs;
String copyName="not determined";
Map<ConsistencyGroupCopyUID,DeviceUID> addedJournalVolumes=new HashMap<ConsistencyGroupCopyUID,DeviceUID>();
try {
allCgs=functionalAPI.getAllConsistencyGroups();
for ( ConsistencyGroupUID cg : allCgs) {
ConsistencyGroupSettings settings=functionalAPI.getGroupSettings(cg);
if (settings.getName().toString().equalsIgnoreCase(request.getCgName())) {
cgUID=settings.getGroupUID();
break;
}
}
if (cgUID == null) {
throw RecoverPointException.exceptions.failedToAddReplicationSetCgDoesNotExist(request.getCgName());
}
List<CreateCopyParams> copyParams=request.getCopies();
Set<RPSite> allSites=scan(copyParams,null);
for ( CreateCopyParams copyParam : copyParams) {
for ( CreateVolumeParams journalVolume : copyParam.getJournals()) {
copyName=journalVolume.getRpCopyName();
ClusterUID clusterId=RecoverPointUtils.getRPSiteID(functionalAPI,journalVolume.getInternalSiteName());
ConsistencyGroupCopyUID copyUID=getCGCopyUid(clusterId,getCopyType(copyType),cgUID);
DeviceUID journalDevice=RecoverPointUtils.getDeviceID(allSites,journalVolume.getInternalSiteName(),journalVolume.getWwn());
addedJournalVolumes.put(copyUID,journalDevice);
functionalAPI.addJournalVolume(copyUID,journalDevice);
}
}
}
catch ( FunctionalAPIActionFailedException_Exception e) {
if (!addedJournalVolumes.isEmpty()) {
try {
for ( Map.Entry<ConsistencyGroupCopyUID,DeviceUID> journalVolume : addedJournalVolumes.entrySet()) {
functionalAPI.removeJournalVolume(journalVolume.getKey(),journalVolume.getValue());
}
}
catch ( Exception e1) {
logger.error("Error removing journal volume from consistency group");
logger.error(e1.getMessage(),e1);
}
}
logger.error("Error in attempting to add a journal volume to the recoverpoint consistency group");
logger.error(e.getMessage(),e);
throw RecoverPointException.exceptions.failedToAddJournalVolumeToConsistencyGroup(copyName,getCause(e));
}
catch ( FunctionalAPIInternalError_Exception e) {
if (!addedJournalVolumes.isEmpty()) {
try {
for ( Map.Entry<ConsistencyGroupCopyUID,DeviceUID> journalVolume : addedJournalVolumes.entrySet()) {
functionalAPI.removeJournalVolume(journalVolume.getKey(),journalVolume.getValue());
}
}
catch ( Exception e1) {
logger.error("Error removing journal volume from consistency group");
logger.error(e1.getMessage(),e1);
}
}
logger.error("Error in attempting to add a journal volume to the recoverpoint consistency group");
logger.error(e.getMessage(),e);
throw RecoverPointException.exceptions.failedToCreateConsistencyGroup(copyName,getCause(e));
}
return true;
}
| Operation to add journal volumes to an existing recoverpoint consistency group |
public void erasePurchase(String sku){
if (mPurchaseMap.containsKey(sku)) mPurchaseMap.remove(sku);
}
| Erase a purchase (locally) from the inventory, given its product ID. This just modifies the Inventory object locally and has no effect on the server! This is useful when you have an existing Inventory object which you know to be up to date, and you have just consumed an item successfully, which means that erasing its purchase data from the Inventory you already have is quicker than querying for a new Inventory. |
private static boolean isAfterI(String src,int index){
int ch;
int cc;
for (int i=index; i > 0; i-=Character.charCount(ch)) {
ch=src.codePointBefore(i);
if (ch == 'I') {
return true;
}
else {
cc=Normalizer.getCombiningClass(ch);
if ((cc == 0) || (cc == COMBINING_CLASS_ABOVE)) {
return false;
}
}
}
return false;
}
| Implements the "After_I" condition Specification: The last preceding base character was an uppercase I, and there is no intervening combining character class 230 (ABOVE). Regular Expression: Before C: [I]([{cc!=230}&{cc!=0}]) |
public String toString(){
StringBuffer buffer=new StringBuffer();
buffer.append("UasAuthTokenGroup[");
buffer.append("m_id = ").append(m_id);
buffer.append("]");
return buffer.toString();
}
| toString methode: creates a String representation of the object |
private void updateProgress(String progressLabel,int progress){
if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) {
myHost.updateProgress(progressLabel,progress);
}
previousProgress=progress;
previousProgressLabel=progressLabel;
}
| Used to communicate a progress update between a plugin tool and the main Whitebox user interface. |
public static String smartUrlFilter(String url,boolean canBeSearch){
String inUrl=url.trim();
boolean hasSpace=inUrl.indexOf(' ') != -1;
Matcher matcher=ACCEPTED_URI_SCHEMA.matcher(inUrl);
if (matcher.matches()) {
String scheme=matcher.group(1);
String lcScheme=scheme.toLowerCase();
if (!lcScheme.equals(scheme)) {
inUrl=lcScheme + matcher.group(2);
}
if (hasSpace && Patterns.WEB_URL.matcher(inUrl).matches()) {
inUrl=inUrl.replace(" ","%20");
}
return inUrl;
}
if (!hasSpace) {
if (inUrl.startsWith("rtsp:")) return inUrl;
if (Patterns.WEB_URL.matcher(inUrl).matches()) {
return URLUtil.guessUrl(inUrl);
}
}
if (canBeSearch) {
return URLUtil.composeSearchUrl(inUrl,QUICKSEARCH_G,QUERY_PLACE_HOLDER);
}
return null;
}
| Attempts to determine whether user input is a URL or search terms. Anything with a space is passed to search if canBeSearch is true. Converts to lowercase any mistakenly uppercased schema (i.e., "Http://" converts to "http://" |
public <T>Tuple3<A,B,T> extend(BiFunction<A,B,T> mapping){
return Tuple3.of(_1,_2,mapping.apply(_1,_2));
}
| Creates a tuple 3 by applying the supplied function to this tuple's contents |
public static void main(String... args){
new Build().run(args);
}
| Run the build. |
public static void generateGlueCodeForJNIMethod(Assembler asm,RVMMethod mth){
int offset;
int varargAmount=0;
String mthName=mth.getName().toString();
final boolean usesVarargs=(mthName.startsWith("Call") && mthName.endsWith("Method")) || mthName.equals("NewObject");
int glueFrameSize=JNI_GLUE_FRAME_SIZE + varargAmount;
asm.emitSTAddrU(FP,-glueFrameSize,FP);
if (usesVarargs) {
if (VM.BuildForPower64ELF_ABI) {
offset=STACKFRAME_HEADER_SIZE + 3 * BYTES_IN_STACKSLOT;
for (int i=6; i <= 10; i++) {
asm.emitSTAddr(GPR.lookup(i),offset,FP);
offset+=BYTES_IN_ADDRESS;
}
for (int i=1; i <= 3; i++) {
asm.emitSTFD(FPR.lookup(i),offset,FP);
offset+=BYTES_IN_DOUBLE;
}
}
else if (VM.BuildForSVR4ABI) {
offset=STACKFRAME_HEADER_SIZE + 0;
for (int i=FIRST_OS_PARAMETER_GPR.value(); i <= LAST_OS_PARAMETER_GPR.value(); i++) {
asm.emitSTAddr(GPR.lookup(i),offset,FP);
offset+=BYTES_IN_ADDRESS;
}
for (int i=FIRST_OS_PARAMETER_FPR.value(); i <= LAST_OS_PARAMETER_FPR.value(); i++) {
asm.emitSTFD(FPR.lookup(i),offset,FP);
offset+=BYTES_IN_DOUBLE;
}
}
}
else {
if (VM.BuildForSVR4ABI) {
convertParametersFromSVR4ToJava(asm,mth);
}
}
offset=STACKFRAME_HEADER_SIZE + JNI_GLUE_SAVED_VOL_SIZE;
for (int i=FIRST_RVM_RESERVED_NV_GPR.value(); i <= LAST_RVM_RESERVED_NV_GPR.value(); i++) {
asm.emitSTAddr(GPR.lookup(i),offset,FP);
offset+=BYTES_IN_ADDRESS;
}
asm.emitLVAL(S0,INVISIBLE_METHOD_ID);
asm.emitMFLR(REGISTER_ZERO);
asm.emitSTW(S0,STACKFRAME_METHOD_ID_OFFSET.toInt(),FP);
asm.emitSTAddr(REGISTER_ZERO,glueFrameSize + STACKFRAME_RETURN_ADDRESS_OFFSET.toInt(),FP);
asm.emitADDI(T0,Offset.zero().minus(Entrypoints.JNIExternalFunctionsField.getOffset()),T0);
int retryLoop=asm.getMachineCodeIndex();
asm.emitLAddrOffset(THREAD_REGISTER,T0,Entrypoints.JNIEnvSavedTRField.getOffset());
if (VM.BuildForSVR4ABI) {
asm.emitLAddrOffset(JTOC,T0,Entrypoints.JNIEnvSavedJTOCField.getOffset());
}
asm.emitLVALAddr(S1,Entrypoints.execStatusField.getOffset());
asm.emitLWARX(S0,S1,THREAD_REGISTER);
asm.emitCMPI(S0,RVMThread.IN_JNI + (RVMThread.ALWAYS_LOCK_ON_STATE_TRANSITION ? 100 : 0));
ForwardReference frBlocked=asm.emitForwardBC(NE);
asm.emitLVAL(S0,RVMThread.IN_JAVA);
asm.emitSTWCXr(S0,S1,THREAD_REGISTER);
asm.emitBC(NE,retryLoop);
ForwardReference frInJava=asm.emitForwardB();
frBlocked.resolve(asm);
offset=STACKFRAME_HEADER_SIZE;
for (int i=FIRST_OS_PARAMETER_GPR.value(); i <= LAST_OS_PARAMETER_GPR.value(); i++) {
asm.emitSTAddr(GPR.lookup(i),offset,FP);
offset+=BYTES_IN_ADDRESS;
}
for (int i=FIRST_OS_PARAMETER_FPR.value(); i <= LAST_OS_VARARG_PARAMETER_FPR.value(); i++) {
asm.emitSTFD(FPR.lookup(i),offset,FP);
offset+=BYTES_IN_DOUBLE;
}
asm.emitLAddrOffset(KLUDGE_TI_REG,JTOC,Entrypoints.leaveJNIBlockedFromJNIFunctionCallMethod.getOffset());
asm.emitMTLR(KLUDGE_TI_REG);
asm.emitBCLRL();
offset=STACKFRAME_HEADER_SIZE;
for (int i=FIRST_OS_PARAMETER_GPR.value(); i <= LAST_OS_PARAMETER_GPR.value(); i++) {
asm.emitLAddr(GPR.lookup(i),offset,FP);
offset+=BYTES_IN_ADDRESS;
}
for (int i=FIRST_OS_PARAMETER_FPR.value(); i <= LAST_OS_VARARG_PARAMETER_FPR.value(); i++) {
asm.emitLFD(FPR.lookup(i),offset,FP);
offset+=BYTES_IN_DOUBLE;
}
frInJava.resolve(asm);
asm.emitLAddrOffset(S0,T0,Entrypoints.JNITopJavaFPField.getOffset());
asm.emitSUBFC(S0,FP,S0);
asm.emitSTW(S0,glueFrameSize + JNI_GLUE_OFFSET_TO_PREV_JFRAME,FP);
ForwardReference frNormalPrologue=asm.emitForwardBL();
asm.emitLAddrOffset(T2,THREAD_REGISTER,Entrypoints.jniEnvField.getOffset());
asm.emitLInt(T3,glueFrameSize + JNI_GLUE_OFFSET_TO_PREV_JFRAME,FP);
asm.emitADD(T3,FP,T3);
asm.emitSTAddrOffset(T3,T2,Entrypoints.JNITopJavaFPField.getOffset());
asm.emitCMPAddrI(T3,STACKFRAME_SENTINEL_FP.toInt());
ForwardReference fr4=asm.emitForwardBC(EQ);
asm.emitLAddr(S0,0,T3);
fr4.resolve(asm);
asm.emitSTAddrOffset(THREAD_REGISTER,T2,Entrypoints.JNIEnvSavedTRField.getOffset());
asm.emitLVALAddr(S1,Entrypoints.execStatusField.getOffset());
asm.emitLWARX(S0,S1,THREAD_REGISTER);
asm.emitCMPI(S0,RVMThread.IN_JAVA + (RVMThread.ALWAYS_LOCK_ON_STATE_TRANSITION ? 100 : 0));
ForwardReference notInJava=asm.emitForwardBC(NE);
asm.emitLVAL(S0,RVMThread.IN_JNI);
asm.emitSTWCXr(S0,S1,THREAD_REGISTER);
ForwardReference enteredJNIRef=asm.emitForwardBC(EQ);
notInJava.resolve(asm);
asm.emitLAddrOffset(S0,THREAD_REGISTER,Entrypoints.threadContextRegistersField.getOffset());
asm.emitLAddrOffset(S1,JTOC,ArchEntrypoints.saveVolatilesInstructionsField.getOffset());
asm.emitMTLR(S1);
asm.emitBCLRL();
asm.emitLAddrOffset(S0,JTOC,Entrypoints.enterJNIBlockedFromJNIFunctionCallMethod.getOffset());
asm.emitMTLR(S0);
asm.emitBCLRL();
asm.emitLAddrOffset(S0,THREAD_REGISTER,Entrypoints.threadContextRegistersField.getOffset());
asm.emitLAddrOffset(S1,JTOC,ArchEntrypoints.restoreVolatilesInstructionsField.getOffset());
asm.emitMTLR(S1);
asm.emitBCLRL();
enteredJNIRef.resolve(asm);
offset=STACKFRAME_HEADER_SIZE + JNI_GLUE_SAVED_VOL_SIZE;
for (int i=FIRST_RVM_RESERVED_NV_GPR.value(); i <= LAST_RVM_RESERVED_NV_GPR.value(); i++) {
asm.emitLAddr(GPR.lookup(i),offset,FP);
offset+=BYTES_IN_ADDRESS;
}
asm.emitADDI(FP,glueFrameSize,FP);
asm.emitLAddr(T2,STACKFRAME_RETURN_ADDRESS_OFFSET.toInt(),FP);
asm.emitMTLR(T2);
asm.emitBCLR();
frNormalPrologue.resolve(asm);
}
| Emit code to do the C to Java transition: JNI methods in JNIFunctions.java |
public static void writeNodes(final AbstractSQLProvider provider,final int newViewId,final List<INaviViewNode> nodes) throws SQLException {
Preconditions.checkNotNull(provider,"IE01992: Provider argument can not be null");
Preconditions.checkArgument(newViewId > 0,"IE01993: New View ID argument must be greater then zero");
Preconditions.checkNotNull(nodes,"IE01994: Nodes argument can not be null");
if (nodes.isEmpty()) {
return;
}
final ArrayList<Integer> functionNodeIndices=new ArrayList<Integer>();
final ArrayList<Integer> codeNodeIndices=new ArrayList<Integer>();
final ArrayList<Integer> textNodeIndices=new ArrayList<Integer>();
final ArrayList<Integer> groupNodeIndices=new ArrayList<Integer>();
final BiMap<Integer,INaviGroupNode> groupNodeMap=HashBiMap.create();
final int firstNode=saveNodes(provider,newViewId,nodes,functionNodeIndices,codeNodeIndices,textNodeIndices,groupNodeIndices,groupNodeMap);
PostgreSQLNodeSaver.updateNodeIds(nodes,firstNode);
PostgreSQLNodeSaver.saveGroupNodes(provider,nodes,firstNode,PostgreSQLNodeSaver.sortGroupNodes(groupNodeIndices,groupNodeMap));
PostgreSQLNodeSaver.saveFunctionNodes(provider,nodes,firstNode,functionNodeIndices);
PostgreSQLNodeSaver.saveCodeNodes(provider,nodes,firstNode,codeNodeIndices);
PostgreSQLNodeSaver.saveTextNodes(provider,nodes,firstNode,textNodeIndices);
final CConnection connection=provider.getConnection();
PostgreSQLNodeSaver.saveParentGroups(connection,nodes,firstNode,groupNodeMap);
PostgreSQLNodeSaver.saveTags(connection,nodes,firstNode);
}
| Writes the nodes of a view to the database. |
public static void skip(ByteBuffer buffer,int count){
buffer.position(buffer.position() + count);
}
| Skip count bytes |
protected void engineInit(int opmode,Key key,AlgorithmParameters params,SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
IvParameterSpec ivSpec=null;
if (params != null) {
try {
DESedeParameters paramsEng=new DESedeParameters();
paramsEng.engineInit(params.getEncoded());
ivSpec=paramsEng.engineGetParameterSpec(IvParameterSpec.class);
}
catch ( Exception ex) {
InvalidAlgorithmParameterException iape=new InvalidAlgorithmParameterException("Wrong parameter type: IV expected");
iape.initCause(ex);
throw iape;
}
}
engineInit(opmode,key,ivSpec,random);
}
| Initializes this cipher with a key, a set of algorithm parameters, and a source of randomness. <p>The cipher only supports the following two operation modes:<b> Cipher.WRAP_MODE, and <b> Cipher.UNWRAP_MODE. <p>For modes other than the above two, UnsupportedOperationException will be thrown. <p>If this cipher requires an initialization vector (IV), it will get it from <code>random</code>. |
private String addListModel(HashMap<String,SwaggerModel> models,Class<?> model,String modelName){
SwaggerModel swaggerModel=new SwaggerModel();
swaggerModel.setId(modelName);
swaggerModel.setName(modelName);
SwaggerModelProperty modelProperty=new SwaggerModelProperty();
modelProperty.setType("List");
modelProperty.setRequired(true);
HashMap<String,String> items=new HashMap<>();
items.put(REFERENCE_TYPE,model.getSimpleName());
modelProperty.setItems(items);
HashMap<String,SwaggerModelProperty> modelProperties=new HashMap();
modelProperties.put("items",modelProperty);
swaggerModel.setProperties(modelProperties);
String listModelName=String.format("%s<%s>",modelName,model.getSimpleName());
models.put(listModelName,swaggerModel);
return listModelName;
}
| Converts a List class to a SwaggerModel API representation and adds it to the models HashMap. List<T> cannot be reflected and it's impossible to create class of List<model> at runtime for "type erasure" reason. We are generating a SwaggerModel specifically for List with most fields hardcoded. |
private boolean isCheckpointExists(Connection conn,String key) throws SQLException {
PreparedStatement st=null;
ResultSet rs=null;
try {
st=conn.prepareStatement(chkExistsSql);
st.setString(1,key);
rs=st.executeQuery();
return rs.next();
}
finally {
U.close(rs,log);
U.close(st,log);
}
}
| Checks specified checkpoint existing. |
public final void add(int element){
int index=(length++) & 0x3FF;
if (index == 0) {
pages.add(page=new int[0x400]);
}
page[index]=element;
}
| Add int to <code>IntArray</code>. |
public ElasticsearchHistory(SharedElasticsearchResource elasticsearch){
this.elasticsearch=elasticsearch;
}
| New instance for use with UimaFit DI, eg for testing. |
public static OperationParameter createOperationParameter(String id,boolean mandatory,OperationParameterType type){
OperationParameter op=new OperationParameter();
op.setId(id);
op.setMandatory(mandatory);
op.setType(type);
return op;
}
| Just creates the domain object, doesn't persist |
public final void changeVariation(int delta){
if (tree.currentNode == tree.rootNode) return;
tree.goBack();
int defChild=tree.currentNode.defaultChild;
int nChildren=tree.variations().size();
int newChild=defChild + delta;
newChild=Math.max(newChild,0);
newChild=Math.min(newChild,nChildren - 1);
tree.goForward(newChild);
pendingDrawOffer=false;
updateTimeControl(true);
}
| Go to a new variation in the game tree. |
public static MutableList<String> chunk(String string,int size){
if (size <= 0) {
throw new IllegalArgumentException("Size for groups must be positive but was: " + size);
}
int length=string.length();
if (length == 0) {
return FastList.newList();
}
MutableList<String> result=FastList.newList((length + size - 1) / size);
int startOffset=0;
while (startOffset < length) {
result.add(string.substring(startOffset,Math.min(startOffset + size,length)));
startOffset+=size;
}
return result;
}
| Partitions String in fixed size chunks. |
protected void copyProperties(Object dest,Object source){
try {
BeanUtils.copyProperties(dest,source);
}
catch ( IllegalAccessException|InvocationTargetException e) {
throw new WebApplicationException(e.toString(),Status.BAD_REQUEST);
}
}
| Copies properties. |
public final void removeMessages(int what){
mExec.removeMessages(what);
}
| Remove any pending posts of messages with code 'what' that are in the message queue. |
public double[] distributionForInstance(Instance inst) throws Exception {
if (!m_checksTurnedOff) {
m_Missing.input(inst);
m_Missing.batchFinished();
inst=m_Missing.output();
}
if (m_NominalToBinary != null) {
m_NominalToBinary.input(inst);
m_NominalToBinary.batchFinished();
inst=m_NominalToBinary.output();
}
if (m_Filter != null) {
m_Filter.input(inst);
m_Filter.batchFinished();
inst=m_Filter.output();
}
if (!m_fitLogisticModels) {
double[] result=new double[inst.numClasses()];
for (int i=0; i < inst.numClasses(); i++) {
for (int j=i + 1; j < inst.numClasses(); j++) {
if ((m_classifiers[i][j].m_alpha != null) || (m_classifiers[i][j].m_sparseWeights != null)) {
double output=m_classifiers[i][j].SVMOutput(-1,inst);
if (output > 0) {
result[j]+=1;
}
else {
result[i]+=1;
}
}
}
}
Utils.normalize(result);
return result;
}
else {
if (inst.numClasses() == 2) {
double[] newInst=new double[2];
newInst[0]=m_classifiers[0][1].SVMOutput(-1,inst);
newInst[1]=Utils.missingValue();
return m_classifiers[0][1].m_logistic.distributionForInstance(new DenseInstance(1,newInst));
}
double[][] r=new double[inst.numClasses()][inst.numClasses()];
double[][] n=new double[inst.numClasses()][inst.numClasses()];
for (int i=0; i < inst.numClasses(); i++) {
for (int j=i + 1; j < inst.numClasses(); j++) {
if ((m_classifiers[i][j].m_alpha != null) || (m_classifiers[i][j].m_sparseWeights != null)) {
double[] newInst=new double[2];
newInst[0]=m_classifiers[i][j].SVMOutput(-1,inst);
newInst[1]=Utils.missingValue();
r[i][j]=m_classifiers[i][j].m_logistic.distributionForInstance(new DenseInstance(1,newInst))[0];
n[i][j]=m_classifiers[i][j].m_sumOfWeights;
}
}
}
return weka.classifiers.meta.MultiClassClassifier.pairwiseCoupling(n,r);
}
}
| Estimates class probabilities for given instance. |
protected Precondition_Impl(){
super();
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public static SimpleDataSet loadArffFile(File file){
try {
return loadArffFile(new FileReader(file));
}
catch ( FileNotFoundException ex) {
Logger.getLogger(ARFFLoader.class.getName()).log(Level.SEVERE,null,ex);
return null;
}
}
| Uses the given file path to load a data set from an ARFF file. |
public void toggleMMUDDisplays(){
if (mechW.isVisible()) {
setDisplayVisible(false);
setMapVisible(false);
}
else {
setDisplayVisible(true);
setMapVisible(true);
}
}
| Switches the Minimap and the MechDisplay an and off together. If the MechDisplay is active, both will be hidden, else both will be shown. |
public boolean isNamespaceAware(){
return getFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES);
}
| Indicates whether or not the factory is configured to produce parsers which are namespace aware (it simply set feature XmlPullParser.FEATURE_PROCESS_NAMESPACES to true or false). |
public static void clearSnapshotSessionsFlags(BlockObject blockObject,Set<DataObject> updatedObjects,DbClient dbClient){
URIQueryResultList queryResults=new URIQueryResultList();
dbClient.queryByConstraint(ContainmentConstraint.Factory.getParentSnapshotSessionConstraint(blockObject.getId()),queryResults);
Iterator<URI> resultsIter=queryResults.iterator();
while (resultsIter.hasNext()) {
BlockSnapshotSession snapSession=dbClient.queryObject(BlockSnapshotSession.class,resultsIter.next());
_logger.info("Clearing internal volume flag of snapshot session {} of RP volume {}",snapSession.getLabel(),blockObject.getLabel());
snapSession.clearInternalFlags(BlockIngestOrchestrator.INTERNAL_VOLUME_FLAGS);
updatedObjects.add(snapSession);
}
}
| Clear the flags of the snapshot sessions of the RP volume |
public boolean isAlwaysUseAbsoluteElevation(){
return alwaysUseAbsoluteElevation;
}
| Indicates whether an icon's elevation is treated as an offset from the terrain or an absolute elevation above sea level. |
private void copyTestFilesToExternalData() throws IOException, InterruptedException {
ProcessBuilder processBuilder=new ProcessBuilder();
Context appUnderTestContext=PerfTestingUtils.getAppContext();
File externalAppStorageDir=appUnderTestContext.getExternalFilesDir(null);
File externalTestFilesStorageDir=new File(externalAppStorageDir,TEST_DATA_SUBDIR_NAME);
if (!externalTestFilesStorageDir.exists()) {
if (!externalTestFilesStorageDir.mkdirs()) {
throw new RuntimeException("Not able to create exportable directory for test data");
}
}
String srcAbsolutePath=PerfTestingUtils.getTestRunDir().getAbsolutePath();
String destAbsolutePath=externalTestFilesStorageDir.getAbsolutePath();
Log.w(LOG_TAG,"Moving test data from " + srcAbsolutePath + " to "+ destAbsolutePath);
processBuilder.command("cp","-r",srcAbsolutePath,destAbsolutePath);
processBuilder.redirectErrorStream();
Process process=processBuilder.start();
process.waitFor();
if (process.exitValue() != 0) {
StringBuilder errOutput=new StringBuilder();
char[] charBuffer=new char[1024];
int readSize;
InputStream errorStream=null;
Reader reader=null;
try {
errorStream=process.getInputStream();
reader=new InputStreamReader(errorStream);
while ((readSize=reader.read()) > 0) {
errOutput.append(charBuffer,0,readSize);
}
}
finally {
if (errorStream != null) try {
errorStream.close();
}
catch ( Exception ignored) {
}
if (reader != null) try {
reader.close();
}
catch ( Exception ignored) {
}
}
String errorString=errOutput.toString();
Log.e(LOG_TAG,errorString);
throw new IOException("Not able to move test data to external storage directory:" + " src=" + srcAbsolutePath + ", dest="+ destAbsolutePath+ ", out="+ errorString);
}
}
| Move files from the app's internal file location to a location that can be read on retail devices with simple ADB pull commands. |
public boolean isFailover(){
return mIsFailOver;
}
| Returns true if the most recent event was for an attempt to switch over to a new network following loss of connectivity on another network. |
protected boolean hasZoom(){
return true;
}
| Has Zoom |
public static boolean hasBeenInitialized(){
return sIsInitialized;
}
| Returns true if Fresco has been initialized. |
public void clearDictionaryFromQueryModel(){
if (null != queryModel) {
Map<String,Dictionary> columnToDictionaryMapping=queryModel.getColumnToDictionaryMapping();
if (null != columnToDictionaryMapping) {
for ( Map.Entry<String,Dictionary> entry : columnToDictionaryMapping.entrySet()) {
CarbonUtil.clearDictionaryCache(entry.getValue());
}
}
}
}
| This method will clear the dictionary access count after its usage is complete so that column can be deleted form LRU cache whenever memory reaches threshold |
@Override public Object[] toArray(){
return newArray(new Object[size()]);
}
| Returns all the elements in an array. The result is a copy of all the elements. |
protected Motion createMotion(int startOffset,int dest,int speed){
if (motionSetManually) {
if (lazyMotion != null) {
return lazyMotion.get(new Integer(startOffset),new Integer(dest),new Integer(speed));
}
return motion;
}
if (linearMotion) {
return Motion.createLinearMotion(startOffset,dest,speed);
}
return Motion.createEaseInOutMotion(startOffset,dest,speed);
}
| This method can be overriden by subclasses to create their own motion object on the fly |
protected void consider(String candidate){
AtomicInteger score=nWords.get(candidate);
if (score != null) {
if (score.get() > bestScore) {
bestScore=score.get();
bestCandidate=candidate;
}
}
}
| Consider the given candidate. If it is better than a previously found candidate, then remember it, otherwise forget it. |
public boolean hasPurchase(String sku){
return mPurchaseMap.containsKey(sku);
}
| Returns whether or not there exists a purchase of the given product. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.