code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public boolean supportsCatalogsInIndexDefinitions() throws SQLException {
return false;
}
| Can a catalog name be used in an index definition statement? |
public void releaseMemory(){
corpus=null;
realTokens=null;
originalTokens=null;
tokenToNodeMap=null;
originalTokenToNodeMap=null;
tokenToListInfo=null;
wsClassifier=null;
hposClassifier=null;
}
| Free anything we can to reduce memory footprint after a format(). keep analysis, testDoc as they are used for results. |
public synchronized final Map<K,V> snapshot(){
return new LinkedHashMap<K,V>(map);
}
| Returns a copy of the current contents of the cache, ordered from least recently accessed to most recently accessed. |
public AffinityUuid(Object affKey){
super(IgniteUuid.randomUuid(),affKey);
}
| Constructs unique affinity UUID based on affinity key. |
static char randomChar(){
return (char)TestUtil.nextInt(random(),'a','z');
}
| returns random character (a-z) |
void done(){
summary.remove(this);
}
| Part of the internal implementation; not for general use. Common internal end-time processing |
public GridCacheAffinityRoutingSelfTest(){
super(false);
}
| Constructs test. |
@Override public void run(){
amIActive=true;
boolean image1Bool=false;
boolean image2Bool=false;
double constant1=0;
double constant2=0;
if (args.length < 3) {
showFeedback("Plugin parameters have not been set properly.");
return;
}
String inputHeader1=args[0];
File file=new File(inputHeader1);
image1Bool=file.exists();
if (image1Bool) {
constant1=-1;
}
else {
constant1=Double.parseDouble(file.getName().replace(".dep",""));
}
file=null;
String inputHeader2=args[1];
file=new File(inputHeader2);
image2Bool=file.exists();
if (image2Bool) {
constant2=-1;
}
else {
constant2=Double.parseDouble(file.getName().replace(".dep",""));
}
file=null;
String outputHeader=args[2];
if ((inputHeader1 == null) || (inputHeader2 == null) || (outputHeader == null)) {
showFeedback("One or more of the input parameters have not been set properly.");
return;
}
try {
int row, col;
double z1, z2;
int progress, oldProgress=-1;
double[] data1;
double[] data2;
if (image1Bool && image2Bool) {
WhiteboxRaster inputFile1=new WhiteboxRaster(inputHeader1,"r");
WhiteboxRaster inputFile2=new WhiteboxRaster(inputHeader2,"r");
int rows=inputFile1.getNumberRows();
int cols=inputFile1.getNumberColumns();
double noData1=inputFile1.getNoDataValue();
double noData2=inputFile2.getNoDataValue();
if ((inputFile2.getNumberRows() != rows) || (inputFile2.getNumberColumns() != cols)) {
showFeedback("The input images must have the same dimensions and coordinates. Operation cancelled.");
return;
}
WhiteboxRaster outputFile=new WhiteboxRaster(outputHeader,"rw",inputHeader1,WhiteboxRaster.DataType.INTEGER,noData1);
outputFile.setPreferredPalette("black_white.pal");
for (row=0; row < rows; row++) {
data1=inputFile1.getRowValues(row);
data2=inputFile2.getRowValues(row);
for (col=0; col < cols; col++) {
z1=data1[col];
z2=data2[col];
if ((z1 != noData1) && (z2 != noData2)) {
if (z1 >= z2) {
outputFile.setValue(row,col,1);
}
else {
outputFile.setValue(row,col,0);
}
}
else {
outputFile.setValue(row,col,noData1);
}
}
progress=(int)(100f * row / (rows - 1));
if (progress != oldProgress) {
oldProgress=progress;
updateProgress((int)progress);
if (cancelOp) {
cancelOperation();
return;
}
}
}
outputFile.addMetadataEntry("Created by the " + getDescriptiveName() + " tool.");
outputFile.addMetadataEntry("Created on " + new Date());
inputFile1.close();
inputFile2.close();
outputFile.close();
}
else if (image1Bool) {
WhiteboxRaster inputFile1=new WhiteboxRaster(inputHeader1,"r");
int rows=inputFile1.getNumberRows();
int cols=inputFile1.getNumberColumns();
double noData=inputFile1.getNoDataValue();
WhiteboxRaster outputFile=new WhiteboxRaster(outputHeader,"rw",inputHeader1,WhiteboxRaster.DataType.INTEGER,noData);
outputFile.setPreferredPalette("black_white.pal");
for (row=0; row < rows; row++) {
data1=inputFile1.getRowValues(row);
for (col=0; col < cols; col++) {
z1=data1[col];
if (z1 != noData) {
if (z1 >= constant2) {
outputFile.setValue(row,col,1);
}
else {
outputFile.setValue(row,col,0);
}
}
}
progress=(int)(100f * row / (rows - 1));
if (progress != oldProgress) {
oldProgress=progress;
updateProgress((int)progress);
if (cancelOp) {
cancelOperation();
return;
}
}
}
outputFile.addMetadataEntry("Created by the " + getDescriptiveName() + " tool.");
outputFile.addMetadataEntry("Created on " + new Date());
inputFile1.close();
outputFile.close();
}
else if (image2Bool) {
WhiteboxRaster inputFile2=new WhiteboxRaster(inputHeader2,"r");
int rows=inputFile2.getNumberRows();
int cols=inputFile2.getNumberColumns();
double noData=inputFile2.getNoDataValue();
WhiteboxRaster outputFile=new WhiteboxRaster(outputHeader,"rw",inputHeader2,WhiteboxRaster.DataType.INTEGER,noData);
outputFile.setPreferredPalette("black_white.pal");
for (row=0; row < rows; row++) {
data2=inputFile2.getRowValues(row);
for (col=0; col < cols; col++) {
z2=data2[col];
if (z2 != noData) {
if (z2 >= constant1) {
outputFile.setValue(row,col,1);
}
else {
outputFile.setValue(row,col,0);
}
}
}
progress=(int)(100f * row / (rows - 1));
if (progress != oldProgress) {
oldProgress=progress;
updateProgress((int)progress);
if (cancelOp) {
cancelOperation();
return;
}
}
}
outputFile.addMetadataEntry("Created by the " + getDescriptiveName() + " tool.");
outputFile.addMetadataEntry("Created on " + new Date());
inputFile2.close();
outputFile.close();
}
else {
showFeedback("At least one of the inputs must be a raster image.");
}
returnData(outputHeader);
}
catch ( OutOfMemoryError oe) {
myHost.showFeedback("An out-of-memory error has occurred during operation.");
}
catch ( Exception e) {
myHost.showFeedback("An error has occurred during operation. See log file for details.");
myHost.logException("Error in " + getDescriptiveName(),e);
}
finally {
updateProgress("Progress: ",0);
amIActive=false;
myHost.pluginComplete();
}
}
| Used to execute this plugin tool. |
@Override public void flush() throws IOException {
if (_isDisableFlush || _source == null) {
return;
}
int len=_writeLength;
if (len > 0) {
_writeLength=0;
_source.write(_writeBuffer,0,len,false);
_position+=len;
_isFlushRequired=true;
}
if (_source != null && _isFlushRequired) {
_isFlushRequired=false;
_source.flush();
}
}
| Flushes the buffer to the source. |
private void markCacheComplete(){
NodeVector nv=getVector();
if (nv != null) {
m_cache.setCacheComplete(true);
}
}
| If this NodeSequence has a cache, mark that it is complete. This method should be called after the iterator is exhausted. |
private void updateText(){
if (!currentTextVisibility) {
return;
}
double act=neuron.getActivation();
activationText.setScale(1);
setActivationTextPosition();
priorityText.setScale(1);
setPriorityTextPosition();
priorityText.setText("" + neuron.getUpdatePriority());
if (java.lang.Double.isNaN(neuron.getActivation())) {
activationText.setText("NaN");
activationText.scale(.7);
activationText.translate(-4,3);
}
else if ((act > 0) && (neuron.getActivation() < 1)) {
activationText.setFont(NEURON_FONT_BOLD);
String text=Utils.round(act,1);
if (text.startsWith("0.")) {
text=text.replaceAll("0.",".");
if (text.equals(".0")) {
text="0";
}
}
else {
text=text.replaceAll(".0$","");
}
activationText.setText(text);
}
else if ((act > -1) && (act < 0)) {
activationText.setFont(NEURON_FONT_BOLD);
activationText.setText(Utils.round(act,1).replaceAll("^-0*","-").replaceAll(".0$",""));
}
else {
activationText.setFont(NEURON_FONT_BOLD);
if (Math.abs(act) < 10) {
activationText.scale(.9);
}
else if (Math.abs(act) < 100) {
activationText.scale(.8);
activationText.translate(1,1);
}
else {
activationText.scale(.7);
activationText.translate(-1,2);
}
activationText.setText(String.valueOf((int)Math.round(act)));
}
}
| Determine what font to use for this neuron based in its activation level. TODO: Redo by scaling the text object. |
private void write(double duration_home_work_min,double distance_home_work_meter,double duration_work_home_min,double distance_work_home_meter,String mode,Person p){
UrbanSimPersonCSVWriter.write(p.getId().toString(),duration_home_work_min,distance_home_work_meter,duration_work_home_min,distance_work_home_meter,mode);
}
| writing agent performances to csv file |
public static DataType userDefinedType(String qualifiedName){
return new DataType(qualifiedName,qualifiedName,Types.OTHER,-1,-1,null,0);
}
| Obtain the data type for a user-defined or fully-qualified type name. |
@DSComment("From safe class list") @DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:57:40.043 -0500",hash_original_method="DB9408C548BB70BC9C2AC261FCDA28D9",hash_generated_method="1962DC9CA9457658A119FC983749DA2B") public static void fill(double[] array,double value){
for (int i=0; i < array.length; i++) {
array[i]=value;
}
}
| Fills the specified array with the specified element. |
private SchemaVersionDAO createSchemaVersionDAO(){
SchemaVersionDAO metaDataTable=mock(SchemaVersionDAO.class);
when(metaDataTable.findAppliedMigrations()).thenReturn(new ArrayList<AppliedMigration>());
return metaDataTable;
}
| Creates a metadata table for testing. |
@RequestProcessing(value="/member/{userName}/comments",method=HTTPRequestMethod.GET) @Before(adviceClass={StopwatchStartAdvice.class,AnonymousViewCheck.class,UserBlockCheck.class}) @After(adviceClass=StopwatchEndAdvice.class) public void showHomeComments(final HTTPRequestContext context,final HttpServletRequest request,final HttpServletResponse response,final String userName) throws Exception {
final JSONObject user=(JSONObject)request.getAttribute(User.USER);
request.setAttribute(Keys.TEMAPLTE_DIR_NAME,Symphonys.get("skinDirName"));
final AbstractFreeMarkerRenderer renderer=new SkinRenderer();
context.setRenderer(renderer);
renderer.setTemplateName("/home/comments.ftl");
final Map<String,Object> dataModel=renderer.getDataModel();
filler.fillHeaderAndFooter(request,response,dataModel);
String pageNumStr=request.getParameter("p");
if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) {
pageNumStr="1";
}
final int pageNum=Integer.valueOf(pageNumStr);
final int pageSize=Symphonys.getInt("userHomeCmtsCnt");
final int windowSize=Symphonys.getInt("userHomeCmtsWindowSize");
fillHomeUser(dataModel,user);
avatarQueryService.fillUserAvatarURL(user);
final String followingId=user.optString(Keys.OBJECT_ID);
dataModel.put(Follow.FOLLOWING_ID,followingId);
final boolean isLoggedIn=(Boolean)dataModel.get(Common.IS_LOGGED_IN);
JSONObject currentUser=null;
if (isLoggedIn) {
currentUser=(JSONObject)dataModel.get(Common.CURRENT_USER);
final String followerId=currentUser.optString(Keys.OBJECT_ID);
final boolean isFollowing=followQueryService.isFollowing(followerId,followingId);
dataModel.put(Common.IS_FOLLOWING,isFollowing);
}
user.put(UserExt.USER_T_CREATE_TIME,new Date(user.getLong(Keys.OBJECT_ID)));
final List<JSONObject> userComments=commentQueryService.getUserComments(user.optString(Keys.OBJECT_ID),pageNum,pageSize,currentUser);
dataModel.put(Common.USER_HOME_COMMENTS,userComments);
final int commentCnt=user.optInt(UserExt.USER_COMMENT_COUNT);
final int pageCount=(int)Math.ceil((double)commentCnt / (double)pageSize);
final List<Integer> pageNums=Paginator.paginate(pageNum,pageSize,pageCount,windowSize);
if (!pageNums.isEmpty()) {
dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM,pageNums.get(0));
dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM,pageNums.get(pageNums.size() - 1));
}
dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM,pageNum);
dataModel.put(Pagination.PAGINATION_PAGE_COUNT,pageCount);
dataModel.put(Pagination.PAGINATION_PAGE_NUMS,pageNums);
}
| Shows user home comments page. |
public int resizePartWidth(){
if (!frame.isResizable()) {
return 0;
}
return FrameBorder.BORDER_SIZE;
}
| Returns the width of the InternalFrameBorder's resize controls, appearing along the InternalFrameBorder's bottom border. Clicking and dragging within these controls lets the user change both the InternalFrame's width and height, while dragging between the controls constrains resizing to just the vertical dimension. Override this method if you implement your own bottom border painting and use a resize control with a different size. |
public void testRandomStrings() throws Exception {
checkRandomData(random(),analyzer,1000 * RANDOM_MULTIPLIER);
}
| blast some random strings through the analyzer |
@Override public String toString(){
return this.getClass().getName() + '(' + getName()+ ':'+ getTypeInternal()+ ')';
}
| Returns a string containing a concise, human-readable description of this field descriptor. |
@RpcMethod public void ping() throws InterruptedException, RpcException {
SyncHandler<Object,AgentControl.AsyncClient.ping_call> syncHandler=new SyncHandler<>();
ping(syncHandler);
syncHandler.await();
}
| This method performs a synchronous Thrift call to ping the host. |
public ChangedFolderNode(String name,NodesResources nodesResources){
this.name=name;
this.nodesResources=nodesResources;
}
| Create instance of ChangedFolderNode. |
public String toStringShort(){
return AbstractFormatter.shape(this);
}
| Returns a string representation of the receiver's shape. |
public LoggingPermission(String name,String actions) throws IllegalArgumentException {
super(name);
if (!name.equals("control")) {
throw new IllegalArgumentException("name: " + name);
}
if (actions != null && actions.length() > 0) {
throw new IllegalArgumentException("actions: " + actions);
}
}
| Creates a new LoggingPermission object. |
protected SVGOMAnimationElement(){
}
| Creates a new SVGOMAnimationElement. |
public ModbusTCPListener(int poolsize){
threadPool=new ThreadPool(poolsize);
try {
address=InetAddress.getByAddress(new byte[]{0,0,0,0});
}
catch ( UnknownHostException ex) {
}
}
| / Constructs a ModbusTCPListener instance. This interface is created to listen on the wildcard address (0.0.0.0), which will accept TCP packets on all available adapters/interfaces |
private void drawText(int x1,int y1,int s,boolean e_or_n,Graphics g){
Color oldColor=g.getColor();
g.setPaintMode();
if (m_FontColor == null) {
g.setColor(Color.black);
}
else {
g.setColor(m_FontColor);
}
String st;
if (e_or_n) {
Edge e=m_edges[s].m_edge;
for (int noa=0; (st=e.getLine(noa)) != null; noa++) {
g.drawString(st,(m_edges[s].m_width - m_fontSize.stringWidth(st)) / 2 + x1,y1 + (noa + 1) * m_fontSize.getHeight());
}
}
else {
Node e=m_nodes[s].m_node;
for (int noa=0; (st=e.getLine(noa)) != null; noa++) {
g.drawString(st,(m_nodes[s].m_width - m_fontSize.stringWidth(st)) / 2 + x1,y1 + (noa + 1) * m_fontSize.getHeight());
}
}
g.setColor(oldColor);
}
| Draws the text for either an Edge or a Node. |
public void paintToolBarDragWindowBorder(SynthContext context,Graphics g,int x,int y,int w,int h){
paintBorder(context,g,x,y,w,h,null);
}
| Paints the border of the window containing the tool bar when it has been detached from it's primary frame. |
private void addBasicBlock(BasicBlock newBB){
int blocknum=newBB.getBlockNumber();
if (blocknum >= basicBlocks.length) {
int currentSize=basicBlocks.length;
int newSize=15;
if (currentSize != 2) {
if (currentSize == 15) {
newSize=bytelength >> 4;
}
else {
newSize=currentSize + currentSize >> 3;
}
if (newSize <= blocknum) {
newSize=blocknum + 20;
}
}
BasicBlock[] biggerBlocks=new BasicBlock[newSize];
for (int i=0; i < currentSize; i++) {
biggerBlocks[i]=basicBlocks[i];
}
basicBlocks=biggerBlocks;
}
basicBlocks[blocknum]=newBB;
}
| Adds a basic block. |
public String toKeyString(){
return (nodeId.toString() + "|" + portId.toString());
}
| API to return a String value formed wtih NodeID and PortID The portID is a 16-bit field, so mask it as an integer to get full positive value |
public static Font[] filterMonospaced(Font... fonts){
List<Font> result=new ArrayList<Font>(fonts.length);
for ( Font font : fonts) {
if (isFontMonospaced(font)) {
result.add(font);
}
}
return result.toArray(new Font[result.size()]);
}
| Given an array of fonts, returns another array with only the ones that are monospaced. The fonts in the result will have the same order as in which they came in. A font is considered monospaced if the width of 'i' and 'W' is the same. |
@Override public void flushData(){
recordMethodCounts();
if (emitBounds()) {
Range bounds=traces.getBounds();
recordGaugeValue("cpu.trace." + bounds.getLeft(),bounds.getLeft());
recordGaugeValue("cpu.trace." + bounds.getRight(),bounds.getRight());
}
}
| Flush methodCounts data on shutdown |
public DagToPag(Graph dag){
this.dag=dag;
}
| Constructs a new FCI search for the given independence test and background knowledge. |
public static BigInteger calculateGx(BigInteger p,BigInteger g,BigInteger x){
return g.modPow(x,p);
}
| Calculate g^x mod p as done in round 1. |
public boolean hasMoreElements(){
if (curindex < length) return true;
return false;
}
| <i>true</i> if the entire string hasn't been enumerated yet. |
public boolean equals(Object anObj){
if (anObj == null) {
return false;
}
if (anObj.getClass().getName().equals(this.getClass().getName())) {
NewPortfolio np=(NewPortfolio)anObj;
if (!np.name.equals(this.name) || (np.id != this.id) || !np.type.equals(this.type)|| !np.status.equals(this.status)) {
return false;
}
if (np.positions == null) {
if (this.positions != null) {
return false;
}
}
else {
if (np.positions.size() != this.positions.size()) {
return false;
}
else {
Iterator itr=np.positions.values().iterator();
Position pos;
while (itr.hasNext()) {
pos=(Position)itr.next();
if (!this.positions.containsValue(pos)) {
return false;
}
}
}
}
}
else {
return false;
}
return true;
}
| To enable the comparison. |
public void receiveFA(int faDataType,String xml){
ByteArrayInputStream inputSource=null;
try {
inputSource=new ByteArrayInputStream(xml.getBytes("utf-8"));
switch (faDataType) {
case EClientSocket.ALIASES:
{
_log.debug("Aliases: /n" + xml);
final TWSAccountAliasRequest request=new TWSAccountAliasRequest();
final Aspects aspects=(Aspects)request.fromXML(inputSource);
for ( Aspect aspect : aspects.getAspect()) {
Account item=(Account)aspect;
Account account=m_tradePersistentModel.findAccountByNumber(item.getAccountNumber());
if (null == account) {
account=new Account(item.getAccountNumber(),item.getAccountNumber(),Currency.USD,AccountType.INDIVIDUAL);
}
account.setAlias(item.getAlias());
account.setLastUpdateDate(TradingCalendar.getDateTimeNowMarketTimeZone());
m_tradePersistentModel.persistAspect(account);
}
m_client.requestFA(EClientSocket.GROUPS);
break;
}
case EClientSocket.PROFILES:
{
_log.debug("Profiles: /n" + xml);
final TWSAllocationRequest request=new TWSAllocationRequest();
final Aspects aspects=(Aspects)request.fromXML(inputSource);
for ( Aspect aspect : aspects.getAspect()) {
m_tradePersistentModel.persistPortfolio((Portfolio)aspect);
}
this.fireFAAccountsCompleted();
break;
}
case EClientSocket.GROUPS:
{
_log.debug("Groups: /n" + xml);
final TWSGroupRequest request=new TWSGroupRequest();
final Aspects aspects=(Aspects)request.fromXML(inputSource);
for ( Aspect aspect : aspects.getAspect()) {
m_tradePersistentModel.persistPortfolio((Portfolio)aspect);
}
m_client.requestFA(EClientSocket.PROFILES);
break;
}
default :
{
_log.debug("receiveFA: /n" + xml);
}
}
}
catch (Exception ex) {
error(faDataType,3235,ex.getMessage());
}
finally {
try {
if (null != inputSource) inputSource.close();
}
catch (IOException ex) {
error(faDataType,3236,ex.getMessage());
}
}
}
| Method receiveFA. |
public FractionAtom(Atom num,Atom den,boolean rule){
this(num,den,!rule,TeXConstants.UNIT_PIXEL,0f);
}
| Uses the default thickness for the fraction line |
public static boolean isAlpha(String str){
if (str == null) {
return false;
}
int sz=str.length();
for (int i=0; i < sz; i++) {
if (Character.isLetter(str.charAt(i)) == false) {
return false;
}
}
return true;
}
| <p> Checks if the String contains only unicode letters. </p> <p/> <p> <code>null</code> will return <code>false</code>. An empty String will return <code>true</code>. </p> |
public void writeText(char text) throws IOException {
closeStartIfNecessary();
if (dontEscape) {
writer.write(text);
}
else {
charHolder[0]=text;
HtmlUtils.writeText(writer,true,true,buffer,charHolder);
}
}
| <p>Write a properly escaped single character, If there is an open element that has been created by a call to <code>startElement()</code>, that element will be closed first.</p> <p/> <p>All angle bracket occurrences in the argument must be escaped using the &gt; &lt; syntax.</p> |
public JSONObject increment(String key) throws JSONException {
Object value=this.opt(key);
if (value == null) {
this.put(key,1);
}
else if (value instanceof Integer) {
this.put(key,(Integer)value + 1);
}
else if (value instanceof Long) {
this.put(key,(Long)value + 1);
}
else if (value instanceof Double) {
this.put(key,(Double)value + 1);
}
else if (value instanceof Float) {
this.put(key,(Float)value + 1);
}
else {
throw new JSONException("Unable to increment [" + quote(key) + "].");
}
return this;
}
| Increment a property of a JSONObject. If there is no such property, create one with a value of 1. If there is such a property, and if it is an Integer, Long, Double, or Float, then add one to it. |
public boolean hasPayloads(){
return storePayloads;
}
| Returns true if any payloads exist for this field. |
public void print(java.io.PrintWriter out){
new Printer(this,out).print();
}
| Prints this stack map. |
public static String wordShape(String inStr,int wordShaper,Collection<String> knownLCWords){
if (knownLCWords != null && dontUseLC(wordShaper)) {
knownLCWords=null;
}
switch (wordShaper) {
case NOWORDSHAPE:
return inStr;
case WORDSHAPEDAN1:
return wordShapeDan1(inStr);
case WORDSHAPECHRIS1:
return wordShapeChris1(inStr);
case WORDSHAPEDAN2:
return wordShapeDan2(inStr,knownLCWords);
case WORDSHAPEDAN2USELC:
return wordShapeDan2(inStr,knownLCWords);
case WORDSHAPEDAN2BIO:
return wordShapeDan2Bio(inStr,knownLCWords);
case WORDSHAPEDAN2BIOUSELC:
return wordShapeDan2Bio(inStr,knownLCWords);
case WORDSHAPEJENNY1:
return wordShapeJenny1(inStr,knownLCWords);
case WORDSHAPEJENNY1USELC:
return wordShapeJenny1(inStr,knownLCWords);
case WORDSHAPECHRIS2:
return wordShapeChris2(inStr,false,knownLCWords);
case WORDSHAPECHRIS2USELC:
return wordShapeChris2(inStr,false,knownLCWords);
case WORDSHAPECHRIS3:
return wordShapeChris2(inStr,true,knownLCWords);
case WORDSHAPECHRIS3USELC:
return wordShapeChris2(inStr,true,knownLCWords);
case WORDSHAPECHRIS4:
return wordShapeChris4(inStr,false,knownLCWords);
default :
throw new IllegalStateException("Bad WordShapeClassifier");
}
}
| Specify the string and the int identifying which word shaper to use and this returns the result of using that wordshaper on the String. |
@DSComment("Package priviledge") @DSBan(DSCat.DEFAULT_MODIFIER) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:32:45.171 -0500",hash_original_method="DFC23EFD31E5C4FF40E98CE1A64FD5ED",hash_generated_method="DFC23EFD31E5C4FF40E98CE1A64FD5ED") void pauseLoad(boolean pause){
if (mRequestHandle != null) {
mRequestHandle.pauseRequest(pause);
}
}
| Pause the load. For example, if a plugin is unable to accept more data, we pause reading from the request. Called directly from the WebCore thread. |
protected byte[] last() throws IOException, SpaceExceededException {
assert (this.index != null) : "index == null; closeDate=" + this.closeDate + ", now="+ new Date();
if (this.index == null) {
log.severe("this.index == null in last(); closeDate=" + this.closeDate + ", now="+ new Date()+ this.heapFile == null ? "" : (" file = " + this.heapFile.toString()));
return null;
}
synchronized (this.index) {
byte[] key=this.index.largestKey();
if (key == null) return null;
return get(key);
}
}
| find a special blob in the heap: one that has the largest key this method is useful if the entries are ordered using their keys. then the key with the largest key denotes the last entry |
private String obtainGateway(String token) throws ParseException {
String s=null;
try {
s=((String)((JSONObject)JSON_PARSER.parse(Requests.GET.makeRequest("https://discordapp.com/api/gateway",new BasicNameValuePair("authorization",token)))).get("url")).replaceAll("wss","ws");
}
catch ( HTTP403Exception e) {
Discord4J.logger.error("Received 403 error attempting to get gateway; is your login correct?");
}
Discord4J.logger.debug("Obtained gateway {}.",s);
return s;
}
| Gets the WebSocket gateway |
public static void tweakTipEditorPane(JEditorPane textArea){
if (UIManager.getLookAndFeel().getName().equals("Nimbus")) {
Color selBG=textArea.getSelectionColor();
Color selFG=textArea.getSelectedTextColor();
textArea.setUI(new javax.swing.plaf.basic.BasicEditorPaneUI());
textArea.setSelectedTextColor(selFG);
textArea.setSelectionColor(selBG);
}
textArea.setEditable(false);
textArea.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
textArea.getCaret().setSelectionVisible(true);
textArea.setBackground(TipUtil.getToolTipBackground());
Font font=UIManager.getFont("Label.font");
if (font == null) {
font=new Font("SansSerif",Font.PLAIN,12);
}
HTMLDocument doc=(HTMLDocument)textArea.getDocument();
doc.getStyleSheet().addRule("body { font-family: " + font.getFamily() + "; font-size: "+ font.getSize()+ "pt; }");
}
| Tweaks a <code>JEditorPane</code> so it can be used to render the content in a focusable pseudo-tool tip. It is assumed that the editor pane is using an <code>HTMLDocument</code>. |
public void close() throws IOException {
}
| Closing a <tt>StringWriter</tt> has no effect. The methods in this class can be called after the stream has been closed without generating an <tt>IOException</tt>. |
public static LazyPQueueX<Long> rangeLong(long start,long end){
return fromStreamS(ReactiveSeq.rangeLong(start,end));
}
| Create a LazyPStackX that contains the Longs between start and end |
private void zzScanError(int errorCode){
String message;
try {
message=ZZ_ERROR_MSG[errorCode];
}
catch ( ArrayIndexOutOfBoundsException e) {
message=ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
}
throw new Error(message);
}
| Reports an error that occured while scanning. In a wellformed scanner (no or only correct usage of yypushback(int) and a match-all fallback rule) this method will only be called with things that "Can't Possibly Happen". If this method is called, something is seriously wrong (e.g. a JFlex bug producing a faulty scanner etc.). Usual syntax/scanner level error handling should be done in error fallback rules. |
private WebEmbed handleNotRendered(Element e){
if (!e.getAttribute("class").contains("twitter-tweet")) {
return null;
}
NodeList<Element> anchors=e.getElementsByTagName("a");
if (anchors.getLength() == 0) {
return null;
}
AnchorElement tweetAnchor=AnchorElement.as(anchors.getItem(anchors.getLength() - 1));
if (!DomUtil.hasRootDomain(tweetAnchor.getHref(),"twitter.com")) {
return null;
}
String path=tweetAnchor.getPropertyString("pathname");
String id=getTweetIdFromPath(path);
if (id == null) {
return null;
}
return new WebEmbed(e,"twitter",id,null);
}
| Handle a Twitter embed that has not yet been rendered. |
@Override protected void finalize() throws Throwable {
close();
super.finalize();
}
| Invoke close, which will be harmless if we are already closed. |
public void unbox(final Type type){
Type t=NUMBER_TYPE;
Method sig=null;
switch (type.getSort()) {
case Type.VOID:
return;
case Type.CHAR:
t=CHARACTER_TYPE;
sig=CHAR_VALUE;
break;
case Type.BOOLEAN:
t=BOOLEAN_TYPE;
sig=BOOLEAN_VALUE;
break;
case Type.DOUBLE:
sig=DOUBLE_VALUE;
break;
case Type.FLOAT:
sig=FLOAT_VALUE;
break;
case Type.LONG:
sig=LONG_VALUE;
break;
case Type.INT:
case Type.SHORT:
case Type.BYTE:
sig=INT_VALUE;
}
if (sig == null) {
checkCast(type);
}
else {
checkCast(t);
invokeVirtual(t,sig);
}
}
| Generates the instructions to unbox the top stack value. This value is replaced by its unboxed equivalent on top of the stack. |
public static String ItThey(final int quantity){
return makeUpperCaseWord(itthey(quantity));
}
| "It" or "They", depending on the quantity. |
@SuppressWarnings("unchecked") private void mergeAt(int i){
assert stackSize >= 2;
assert i >= 0;
assert i == stackSize - 2 || i == stackSize - 3;
int base1=runBase[i];
int len1=runLen[i];
int base2=runBase[i + 1];
int len2=runLen[i + 1];
assert len1 > 0 && len2 > 0;
assert base1 + len1 == base2;
runLen[i]=len1 + len2;
if (i == stackSize - 3) {
runBase[i + 1]=runBase[i + 2];
runLen[i + 1]=runLen[i + 2];
}
stackSize--;
int k=gallopRight((Comparable<Object>)a[base2],a,base1,len1,0);
assert k >= 0;
base1+=k;
len1-=k;
if (len1 == 0) return;
len2=gallopLeft((Comparable<Object>)a[base1 + len1 - 1],a,base2,len2,len2 - 1);
assert len2 >= 0;
if (len2 == 0) return;
if (len1 <= len2) mergeLo(base1,len1,base2,len2);
else mergeHi(base1,len1,base2,len2);
}
| Merges the two runs at stack indices i and i+1. Run i must be the penultimate or antepenultimate run on the stack. In other words, i must be equal to stackSize-2 or stackSize-3. |
public mxCellMarker(mxGraphComponent graphComponent,Color validColor,Color invalidColor){
this(graphComponent,validColor,invalidColor,mxConstants.DEFAULT_HOTSPOT);
}
| Constructs a new marker for the given graph component. |
public static byte[] toByteArrayForPBE(char[] chars){
byte[] out=new byte[chars.length];
for (int i=0; i < chars.length; i++) {
out[i]=(byte)chars[i];
}
int length=out.length * 2;
byte[] ret=new byte[length + 2];
int j=0;
for (int i=0; i < out.length; i++) {
j=i * 2;
ret[j]=0;
ret[j + 1]=out[i];
}
ret[length]=0;
ret[length + 1]=0;
return ret;
}
| Convert the given char array into a byte array for use with PBE encryption. |
public ByteBuffer buildPacket(int encap,short destUdp,short srcUdp){
ByteBuffer result=ByteBuffer.allocate(MAX_LENGTH);
InetAddress destIp=mBroadcast ? Inet4Address.ALL : mYourIp;
InetAddress srcIp=mBroadcast ? Inet4Address.ANY : mSrcIp;
fillInPacket(encap,destIp,srcIp,destUdp,srcUdp,result,DHCP_BOOTREPLY,mBroadcast);
result.flip();
return result;
}
| Fills in a packet with the specified OFFER attributes. |
public int compare(IMove o1,IMove o2){
JumpMove j1=(JumpMove)o1;
JumpMove j2=(JumpMove)o2;
int sc1=weights[j1.from] + weights[j1.over] + weights[j1.to];
int sc2=weights[j2.from] + weights[j2.over] + weights[j2.to];
return sc2 - sc1;
}
| If moves are assigned scores representing the pegs at play, then we can select moves that are near the "center" which suggest that game try to keep things moving without heading into off-beat tangents. |
public boolean isMultiSelection(){
return m_multiSelection;
}
| Single Selection Table |
public ConnectionConfig(jmri.jmrix.SerialPortAdapter p){
super(p);
}
| Ctor for an object being created during load process; Swing init is deferred. |
public Object runSafely(Catbert.FastStack stack) throws Exception {
if (stack.getUIComponent() != null) return stack.getUIComponent().getWidget();
else return null;
}
| Returns the Widget for the corresponding UI component that this execution originated from. For 'green' process chains; this will correspond to the UI component that received the event. For 'blue' UI chains; this will correspond to the UI component who's conditionality is being determined or who's data is being evaluated. This will be null if there is no UI context; such as for non-UI hooks and calls made from Java directly. |
@Path("propdel") @POST @Consumes(MediaType.APPLICATION_JSON) @Produces({MediaType.APPLICATION_JSON,MediaType.TEXT_PLAIN}) @RolesAllowed("workspace/developer") public CLIOutputResponse propdel(final PropertyDeleteRequest request) throws ServerException, IOException {
request.setProjectPath(getRealPath(request.getProjectPath()));
return this.subversionApi.propdel(request);
}
| Delete property from specified path or target. |
public boolean equals(Object obj){
if (!(obj instanceof EvenPortAttribute)) return false;
if (obj == this) return true;
EvenPortAttribute att=(EvenPortAttribute)obj;
if (att.getAttributeType() != getAttributeType() || att.getDataLength() != getDataLength() || att.rFlag != rFlag) return false;
return true;
}
| Compares two STUN Attributes. Attributes are considered equal when their type, length, and all data are the same. |
public boolean isChapAuthSettable(){
return chapAuthSettable;
}
| Gets the value of the chapAuthSettable property. |
public static void seek(final long position){
if (musicPlaybackService != null) {
try {
musicPlaybackService.seek(position);
}
catch ( final RemoteException ignored) {
}
}
}
| Seeks the current track to a desired position |
public synchronized Relationship addRelationship(Vertex type,Vertex target,int index,boolean internal){
BasicRelationship relationship=new BasicRelationship(this,type,target);
relationship.setIndex(index);
return addRelationship(relationship,internal,false,0.5f);
}
| Add the relation of the relationship type to the target vertex. Only increment the correctness if not internal. |
public DelphiProject(String projName){
name=projName;
}
| C-tor, initializes project with name and empty files and definitions |
public static void main(final String[] args){
DOMTestCase.doMain(elementsetattributenodens02.class,args);
}
| Runs this test from the command line. |
public OperationNotPermittedException(String message){
super(message);
}
| Constructs a new exception with the specified detail message. The cause is not initialized. |
private void closeConnection() throws IOException {
if (this.clientOutput != null) this.clientOutput.close();
if (this.clientInput != null) this.clientInput.close();
if (this.ControlSocket != null) this.ControlSocket.close();
if (this.DataSocketActive != null) this.DataSocketActive.close();
if (this.DataSocketPassive != null) this.DataSocketPassive.close();
}
| close all sockets |
private static void addActionByClsID(Action action,String clsID,int regLevel) throws RegisterFailedException {
String verb=action.getVerb();
String desc=action.getDescription();
String cmd=action.getCommand();
String clsIDKey=getClsIDKey(clsID,regLevel);
String shellKey=clsIDKey + "\\" + KN_SHELL;
String verbKey=shellKey + "\\" + verb;
String cmdKey=verbKey + "\\" + KN_COMMAND;
if (cmdKey != null) {
regCreateKeyEx(cmdKey,regLevel);
if (cmd != null) {
setDefaultValue(cmdKey,cmd,regLevel);
if ((desc != null) && (verbKey != null)) {
setDefaultValue(verbKey,desc,regLevel);
}
}
}
}
| Writes an action into the registry table (From the specified registry folder). |
public BufferedImage buildBufferedImage(Dimension size){
return new BufferedImage(size.width,size.height,BufferedImage.TYPE_INT_ARGB);
}
| This method creates a BufferedImage with an alpha channel, as this is supported by Base64. |
private Images(){
}
| This utility class cannot be instantiated |
public XCalDocument(InputStream in) throws SAXException, IOException {
this(XmlUtils.toDocument(in));
}
| Parses an xCal document from an input stream. |
private static String[] parseHierarchy(String cRealm,String sRealm){
String[] cComponents=cRealm.split("\\.");
String[] sComponents=sRealm.split("\\.");
int cPos=cComponents.length;
int sPos=sComponents.length;
boolean hasCommon=false;
for (sPos--, cPos--; sPos >= 0 && cPos >= 0 && sComponents[sPos].equals(cComponents[cPos]); sPos--, cPos--) {
hasCommon=true;
}
LinkedList<String> path=new LinkedList<>();
for (int i=0; i <= cPos; i++) {
path.addLast(subStringFrom(cComponents,i));
}
if (hasCommon) {
path.addLast(subStringFrom(cComponents,cPos + 1));
}
for (int i=sPos; i >= 0; i--) {
path.addLast(subStringFrom(sComponents,i));
}
path.removeLast();
return path.toArray(new String[path.size()]);
}
| Build a list of realm that can be traversed to obtain credentials from the initiating realm cRealm for a service in the target realm sRealm. |
private void initializeUserDirectives(){
userDirectives=new ArrayList<>();
IEclipsePreferences preferences=VelocityCorePlugin.getPreferences();
String directives=preferences.get(IPreferencesConstants.VELOCITY_USER_DIRECTIVES,"");
StringTokenizer st=new StringTokenizer(directives,",\n\r");
while (st.hasMoreElements()) {
String directive=(String)st.nextElement();
String name=directive.substring(0,directive.indexOf(' '));
int type=(directive.endsWith("[Block]") ? Directive.BLOCK : Directive.LINE);
userDirectives.add('#' + name);
addDirective(new VelocityDirective(name,type));
}
}
| This methods initializes all user directives. |
@Override public int read(byte b[],int off,int len) throws IOException {
if (markerFound) {
return -1;
}
int count=0;
if (segment.isEntropyCoded()) {
for (; count < len; count++) {
int data=read();
if (data == -1) {
if (count == 0) return -1;
break;
}
b[off + count]=(byte)data;
}
}
else {
long available=segment.length - offset + segment.offset;
if (available <= 0) {
return -1;
}
if (available < len) {
len=(int)available;
}
count=in.read(b,off,len);
if (count != -1) {
offset+=count;
}
}
return count;
}
| Reads up to <code>len</code> b of data from this input stream into an array of b. This method blocks until some input is available. <p> This method simply performs <code>in.read(b, off, len)</code> and returns the result. |
public void testDrainToSelfN(){
LinkedBlockingDeque q=populatedDeque(SIZE);
try {
q.drainTo(q,0);
shouldThrow();
}
catch ( IllegalArgumentException success) {
}
}
| drainTo(this, n) throws IAE |
public void waitDbRingRebuildDone(String vdcShortId,int vdcHosts){
String prefix=new StringBuilder("Waiting for DB rebuild to finish for vdc with shortId '").append(vdcShortId).append("' and ").append(vdcHosts).append(" hosts...").toString();
log.info(prefix);
DbJmxClient geoInstance=getJmxClient(LOCALHOST);
int quorum=vdcHosts / 2 + 1;
long start=System.currentTimeMillis();
while (System.currentTimeMillis() - start < DB_RING_TIMEOUT) {
try {
List<String> fullOwners=geoInstance.getDcNodeFullOwnership(vdcShortId);
if (fullOwners.size() >= quorum) {
log.info("Full owner nodes: {}",fullOwners.toString());
return;
}
else {
log.info("db {} rebuild not finish yet",vdcShortId);
}
TimeUnit.SECONDS.sleep(WAIT_INTERVAL_IN_SEC);
}
catch ( InterruptedException ex) {
}
catch ( Exception ex) {
log.error("Exception checking DB cluster status",ex);
}
}
log.info("{} Timed out",prefix);
throw new IllegalStateException(String.format("%s : Timed out",prefix));
}
| Wait for db ring rebuild finished in a vdc. Quorum nodes owns full data, rebuild may need a long time |
private boolean check(@NonNull String text,char key){
char[] chars=text.toCharArray();
boolean bool=true;
for (int i=0; i < chars.length; i++) {
bool&=(chars[i] == key);
if (!bool) {
break;
}
}
return bool;
}
| check whether it's the same character |
public int[] numVerticesDetected(Set<? extends SampledVertex> vertices){
int it=-1;
TIntIntHashMap map=new TIntIntHashMap();
for ( SampledVertex v : vertices) {
if (v.isDetected()) {
map.adjustOrPutValue(v.getIterationDetected(),1,1);
it=Math.max(it,v.getIterationDetected());
}
}
int[] list=new int[it + 1];
for (int i=0; i <= it; i++) {
list[i]=map.get(i);
}
list[0]+=map.get(-1);
return list;
}
| Returns an array with the number of detected vertices per iteration. |
public void incMarkerEventsConflated(){
this._stats.incLong(_markerEventsConflatedId,1);
}
| Increments the "markerEventsConflated" stat by 1. |
public static boolean isWellFormedAddress(String p_address){
if (p_address == null) {
return false;
}
String address=p_address.trim();
int addrLength=address.length();
if (addrLength == 0 || addrLength > 255) {
return false;
}
if (address.startsWith(".") || address.startsWith("-")) {
return false;
}
int index=address.lastIndexOf('.');
if (address.endsWith(".")) {
index=address.substring(0,index).lastIndexOf('.');
}
if (index + 1 < addrLength && isDigit(p_address.charAt(index + 1))) {
char testChar;
int numDots=0;
for (int i=0; i < addrLength; i++) {
testChar=address.charAt(i);
if (testChar == '.') {
if (!isDigit(address.charAt(i - 1)) || (i + 1 < addrLength && !isDigit(address.charAt(i + 1)))) {
return false;
}
numDots++;
}
else if (!isDigit(testChar)) {
return false;
}
}
if (numDots != 3) {
return false;
}
}
else {
char testChar;
for (int i=0; i < addrLength; i++) {
testChar=address.charAt(i);
if (testChar == '.') {
if (!isAlphanum(address.charAt(i - 1))) {
return false;
}
if (i + 1 < addrLength && !isAlphanum(address.charAt(i + 1))) {
return false;
}
}
else if (!isAlphanum(testChar) && testChar != '-') {
return false;
}
}
}
return true;
}
| Determine whether a string is syntactically capable of representing a valid IPv4 address or the domain name of a network host. A valid IPv4 address consists of four decimal digit groups separated by a '.'. A hostname consists of domain labels (each of which must begin and end with an alphanumeric but may contain '-') separated & by a '.'. See RFC 2396 Section 3.2.2. |
public Stack<IMove> solution(){
if (moveStack == null) {
return new Stack<IMove>();
}
return moveStack;
}
| Combine all stacks into one move sequence. <p> If no solution, then empty stack returned. |
public void removeListener(Listener<ComplexBuffer> listener){
synchronized (mComplexBufferBroadcaster) {
mComplexBufferBroadcaster.removeListener(listener);
if (!mComplexBufferBroadcaster.hasListeners()) {
mBufferProcessor.stop();
}
}
}
| Removes the sample listener. If this is the last registered listener, shuts down the buffer processing thread. |
public HttpMethod process(HttpServletRequest request,String url) throws HttpException {
HttpMethodBase method=null;
if (request.getMethod().equalsIgnoreCase("GET")) {
method=new GetMethod(url);
}
else if (request.getMethod().equalsIgnoreCase("HEAD")) {
method=new HeadMethod(url);
}
else if (request.getMethod().equalsIgnoreCase("DELETE")) {
method=new DeleteMethod(url);
}
else {
return null;
}
setHeaders(method,request);
return method;
}
| Will only set the headers. |
protected void clearEvents(){
}
| This method resets the incoming events (time events included). |
@Override public boolean isActive(){
return amIActive;
}
| Used by the Whitebox GUI to tell if this plugin is still running. |
Node[] genObjs(int nobjs){
Node[] objs=new Node[nobjs];
for (int i=0; i < nobjs; i++) objs[i]=new Node();
return objs;
}
| Generate objects. |
@Override public boolean isCellEditable(int row,int col){
return false;
}
| Editable state must be set in ctor. |
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. |
public static String toString(Object val){
if (val instanceof String) {
return trimLeadingSlash((String)val);
}
else if (val instanceof InetAddress) {
return ((InetAddress)val).getHostAddress();
}
else {
return trimLeadingSlash(val.toString());
}
}
| Returns a string version of InetAddress which can be converted back to an InetAddress later. Essentially any leading slash is trimmed. |
private int measureShort(int measureSpec){
int result;
int specMode=MeasureSpec.getMode(measureSpec);
int specSize=MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
result=specSize;
}
else {
result=(int)(2 * mRadius + getPaddingTop() + getPaddingBottom() + 1);
if (specMode == MeasureSpec.AT_MOST) {
result=Math.min(result,specSize);
}
}
return result;
}
| Determines the height of this view |
public static long nextLong(){
synchronized (random) {
return random.nextLong();
}
}
| Access a default instance of this class, access is synchronized |
public PrefixSearchTupleSet(boolean caseSensitive){
m_trie=new Trie(caseSensitive);
}
| Creates a new KeywordSearchFocusSet with the indicated case sensitivity. |
public T caseExecutionSlot(ExecutionSlot object){
return null;
}
| Returns the result of interpreting the object as an instance of '<em>Execution Slot</em>'. <!-- begin-user-doc --> This implementation returns null; returning a non-null result will terminate the switch. <!-- end-user-doc --> |
public static Region createLocalRegion(String regionName) throws RegionExistsException {
AttributesFactory attr=new AttributesFactory();
attr.setScope(Scope.LOCAL);
Region localRegion=createCache().createRegion(regionName,attr.create());
return localRegion;
}
| This method creates a local region with all the default values. The cache created is a loner, so this is only suitable for single VM tests. |
public int compareTo(Object o){
return compareTo((MutableDouble)o);
}
| Compares this <code>MutableDouble</code> object to another object. If the object is an <code>MutableDouble</code>, this function behaves like <code>compareTo(MutableDouble)</code>. Otherwise, it throws a <code>ClassCastException</code> (as <code>MutableDouble</code> objects are only comparable to other <code>MutableDouble</code> objects). |
public void testNodeDocumentFragmentNormalize1() throws Throwable {
Document doc;
DocumentFragment docFragment;
String nodeValue;
Text txtNode;
Node retval;
doc=(Document)load("hc_staff",builder);
docFragment=doc.createDocumentFragment();
txtNode=doc.createTextNode("foo");
retval=docFragment.appendChild(txtNode);
txtNode=doc.createTextNode("bar");
retval=docFragment.appendChild(txtNode);
docFragment.normalize();
txtNode=(Text)docFragment.getFirstChild();
nodeValue=txtNode.getNodeValue();
assertEquals("normalizedNodeValue","foobar",nodeValue);
retval=txtNode.getNextSibling();
assertNull("singleChild",retval);
}
| Runs the test case. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.