Context:
/*
 * Copyright 2015 Comcast Cable Communications Management, LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.comcast.cdn.traffic_control.traffic_router.core.router;

import java.io.IOException;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import org.apache.commons.pool.ObjectPool;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import org.xbill.DNS.Name;
import org.xbill.DNS.Zone;

import com.comcast.cdn.traffic_control.traffic_router.core.TrafficRouterException;
import com.comcast.cdn.traffic_control.traffic_router.core.cache.Cache;
import com.comcast.cdn.traffic_control.traffic_router.core.cache.CacheLocation;
import com.comcast.cdn.traffic_control.traffic_router.core.cache.CacheRegister;
import com.comcast.cdn.traffic_control.traffic_router.core.cache.InetRecord;
import com.comcast.cdn.traffic_control.traffic_router.core.dns.ZoneManager;
import com.comcast.cdn.traffic_control.traffic_router.core.dns.DNSAccessRecord;
import com.comcast.cdn.traffic_control.traffic_router.core.ds.DeliveryService;
import com.comcast.cdn.traffic_control.traffic_router.core.ds.Dispersion;
import com.comcast.cdn.traffic_control.traffic_router.core.hash.HashFunction;
import com.comcast.cdn.traffic_control.traffic_router.core.loc.FederationRegistry;
import com.comcast.cdn.traffic_control.traffic_router.core.loc.Geolocation;
import com.comcast.cdn.traffic_control.traffic_router.core.loc.GeolocationException;
import com.comcast.cdn.traffic_control.traffic_router.core.loc.GeolocationService;
import com.comcast.cdn.traffic_control.traffic_router.core.loc.NetworkNode;
import com.comcast.cdn.traffic_control.traffic_router.core.loc.NetworkNodeException;
import com.comcast.cdn.traffic_control.traffic_router.core.request.DNSRequest;
import com.comcast.cdn.traffic_control.traffic_router.core.request.HTTPRequest;
import com.comcast.cdn.traffic_control.traffic_router.core.request.Request;
import com.comcast.cdn.traffic_control.traffic_router.core.router.StatTracker.Track;
import com.comcast.cdn.traffic_control.traffic_router.core.router.StatTracker.Track.ResultType;
import com.comcast.cdn.traffic_control.traffic_router.core.router.StatTracker.Track.RouteType;
import com.comcast.cdn.traffic_control.traffic_router.core.util.TrafficOpsUtils;
import com.comcast.cdn.traffic_control.traffic_router.core.util.CidrAddress;
import com.comcast.cdn.traffic_control.traffic_router.core.router.StatTracker.Track.ResultDetails;

public class TrafficRouter {
	public static final Logger LOGGER = Logger.getLogger(TrafficRouter.class);

	private final CacheRegister cacheRegister;
	private final ZoneManager zoneManager;
	private final GeolocationService geolocationService;
	private final GeolocationService geolocationService6;
	private final ObjectPool hashFunctionPool;
	private final FederationRegistry federationRegistry;

	private final Random random = new Random(System.nanoTime());
	private Set<String> requestHeaders = new HashSet<String>();

	public TrafficRouter(final CacheRegister cr,
			final GeolocationService geolocationService,
			final GeolocationService geolocationService6,
			final ObjectPool hashFunctionPool,
			final StatTracker statTracker,
			final TrafficOpsUtils trafficOpsUtils,
			final FederationRegistry federationRegistry) throws IOException, JSONException, TrafficRouterException {
		this.cacheRegister = cr;
		this.geolocationService = geolocationService;
		this.geolocationService6 = geolocationService6;
		this.hashFunctionPool = hashFunctionPool;
		this.federationRegistry = federationRegistry;
		this.zoneManager = new ZoneManager(this, statTracker, trafficOpsUtils);
	}

	public ZoneManager getZoneManager() {
		return zoneManager;
	}

	/**
	 * Returns a {@link List} of all of the online {@link Cache}s that support the specified
	 * {@link DeliveryService}. If no online caches are found to support the specified
	 * DeliveryService an empty list is returned.
	 *
	 * @param ds
	 *            the DeliveryService to check
	 * @return collection of supported caches
	 */
	protected List<Cache> getSupportingCaches(final List<Cache> caches, final DeliveryService ds) {
		for(int i = 0; i < caches.size(); i++) {
			final Cache cache = caches.get(i);
			boolean isAvailable = true;
			if(cache.hasAuthority()) {
				isAvailable = cache.isAvailable();
			}
			if (!isAvailable || !cache.hasDeliveryService(ds.getId())) {
				caches.remove(i);
				i--;
			}
		}
		return caches;
	}

	public CacheRegister getCacheRegister() {
		return cacheRegister;
	}
	protected DeliveryService selectDeliveryService(final Request request, final boolean isHttp) {
		if(cacheRegister==null) {
			LOGGER.warn("no caches yet");
			return null;
		}
		final DeliveryService ds = cacheRegister.getDeliveryService(request, isHttp);
		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug("Selected DeliveryService: " + ds);
		}
		return ds;
	}

	boolean setState(final JSONObject states) throws UnknownHostException {
		setCacheStates(states.optJSONObject("caches"));
		setDsStates(states.optJSONObject("deliveryServices"));
		return true;
	}
	private boolean setDsStates(final JSONObject dsStates) {
		if(dsStates == null) {
			return false;
		}
		final Map<String, DeliveryService> dsMap = cacheRegister.getDeliveryServices();
		for (final String dsName : dsMap.keySet()) {
			dsMap.get(dsName).setState(dsStates.optJSONObject(dsName));
		}
		return true;
	}
	private boolean setCacheStates(final JSONObject cacheStates) {
		if(cacheStates == null) {
			return false;
		}
		final Map<String, Cache> cacheMap = cacheRegister.getCacheMap();
		if(cacheMap == null) { return false; }
		for (final String cacheName : cacheMap.keySet()) {
			final String monitorCacheName = cacheName.replaceFirst("@.*", "");
			final JSONObject state = cacheStates.optJSONObject(monitorCacheName);
			cacheMap.get(cacheName).setState(state);
		}
		return true;
	}

	protected static final String UNABLE_TO_ROUTE_REQUEST = "Unable to route request.";
	protected static final String URL_ERR_STR = "Unable to create URL.";

	public GeolocationService getGeolocationService() {
		return geolocationService;
	}
	public Geolocation getLocation(final String clientIP) throws GeolocationException {
		if(clientIP.contains(":")) {
			return geolocationService6.location(clientIP);
		}
		return geolocationService.location(clientIP);
	}

	/**
	 * Gets hashFunctionPool.
	 *
	 * @return the hashFunctionPool
	 */
	public ObjectPool getHashFunctionPool() {

Answer: return hashFunctionPool;

<think>
The method getHashFunctionPool() is a getter for the private field hashFunctionPool. After the opening brace, the typical implementation is to return that field. Therefore the next line should be the return statement returning hashFunctionPool.
</think>
return hashFunctionPool;


Context:
/*******************************************************************************
 * Copyright (c) 2011-2014 SirSengir.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v3
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl-3.0.txt
 *
 * Various Contributors including, but not limited to:
 * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges
 ******************************************************************************/
package forestry.factory.gadgets;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Stack;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.ICrafting;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.ForgeDirection;
import net.minecraftforge.liquids.ILiquidTank;
import net.minecraftforge.liquids.LiquidContainerData;
import net.minecraftforge.liquids.LiquidStack;
import buildcraft.api.gates.ITrigger;
import forestry.api.core.ForestryAPI;
import forestry.api.recipes.ISqueezerManager;
import forestry.core.EnumErrorCode;
import forestry.core.config.Config;
import forestry.core.config.Defaults;
import forestry.core.gadgets.Machine;
import forestry.core.gadgets.MachineFactory;
import forestry.core.gadgets.TileMachine;
import forestry.core.network.EntityNetData;
import forestry.core.network.GuiId;
import forestry.core.triggers.ForestryTrigger;
import forestry.core.utils.EnumTankLevel;
import forestry.core.utils.LiquidHelper;
import forestry.core.utils.StringUtil;
import forestry.core.utils.TankSlot;
import forestry.core.utils.Utils;

public class MachineSqueezer extends Machine {

	/**
	 * Factory class to produce new {@link MachineSqueezer}s.
	 */
	public static class Factory extends MachineFactory {
		@Override
		public Machine createMachine(TileEntity tile) {
			return new MachineSqueezer((TileMachine) tile);
		}
	}

	// / RECIPE MANAGMENT
	public static class Recipe {
		public final int timePerItem;
		public final ItemStack[] resources;
		public final LiquidStack liquid;
		public final ItemStack remnants;
		public final int chance;

		public Recipe(int timePerItem, ItemStack[] resources, LiquidStack liquid, ItemStack remnants, int chance) {
			this.timePerItem = timePerItem;
			this.resources = resources;
			this.liquid = liquid;
			this.remnants = remnants;
			this.chance = chance;
		}

		public boolean matches(ItemStack[] res) {
			// No recipe without resource!
			if (res == null || res.length <= 0)
				return false;

			boolean matchedAll = true;

			for (ItemStack stack : resources) {
				boolean matched = false;
				for (ItemStack matchStack : res) {
					if (matchStack == null) {
						continue;
					}

					// If the item matches, we need enough items
					if (matchStack.isItemEqual(stack))
						if (matchStack.stackSize >= stack.stackSize) {
							matched = true;
							break;
						}
				}
				if (!matched) {
					matchedAll = false;
				}
			}
			return matchedAll;
		}
	}

	public static class RecipeManager implements ISqueezerManager {
		public static ArrayList<MachineSqueezer.Recipe> recipes = new ArrayList<MachineSqueezer.Recipe>();

		@Override
		public void addRecipe(int timePerItem, ItemStack[] resources, LiquidStack liquid, ItemStack remnants, int chance) {
			recipes.add(new MachineSqueezer.Recipe(timePerItem, resources, liquid, remnants, chance));
		}

		@Override
		public void addRecipe(int timePerItem, ItemStack[] resources, LiquidStack liquid) {
			addRecipe(timePerItem, resources, liquid, null, 0);
		}

		public static Recipe findMatchingRecipe(ItemStack[] items) {
			for (int i = 0; i < recipes.size(); i++) {
				Recipe recipe = recipes.get(i);
				if (recipe.matches(items))
					return recipe;
			}
			return null;
		}

		@Override
		public List<Entry<ItemStack[], ItemStack[]>> getRecipes() {
			HashMap<ItemStack[], ItemStack[]> recipeList = new HashMap<ItemStack[], ItemStack[]>();

			for (Recipe recipe : recipes) {
				recipeList.put(recipe.resources, new ItemStack[] { recipe.remnants, recipe.liquid.asItemStack() });
			}

			return (List<Entry<ItemStack[], ItemStack[]>>) recipeList;
		}
	}

	// / MEMBER
	@EntityNetData
	public TankSlot productTank = new TankSlot(Defaults.PROCESSOR_TANK_CAPACITY);
	private ItemStack[] inventoryStacks = new ItemStack[12];
	private Recipe currentRecipe;

	private short resourceSlot1 = 0;
	private short remnantSlot = 9;
	private short canSlot = 10;
	private short outputSlot = 11;

	private Stack<LiquidStack> pendingLiquids = new Stack<LiquidStack>();
	private Stack<ItemStack> pendingRemnants = new Stack<ItemStack>();
	private int productionTime;
	private int timePerItem;

	public MachineSqueezer(TileMachine tile) {
		super(tile);
		setHints(Config.hints.get("squeezer"));
	}

	@Override
	public String getName() {
		return StringUtil.localize("tile.machine.9");
	}

	@Override
	public void openGui(EntityPlayer player, IInventory tile) {
		player.openGui(ForestryAPI.instance, GuiId.SqueezerGUI.ordinal(), player.worldObj, this.tile.xCoord, this.tile.yCoord, this.tile.zCoord);
	}

	// / LOADING & SAVING
	@Override
	public void writeToNBT(NBTTagCompound nbttagcompound) {
		super.writeToNBT(nbttagcompound);

		nbttagcompound.setInteger("ProductionTime", productionTime);
		nbttagcompound.setInteger("TimePerItem", timePerItem);

		// Inventory
		NBTTagList nbttaglist = new NBTTagList();
		for (int i = 0; i < inventoryStacks.length; i++)
			if (inventoryStacks[i] != null) {
				NBTTagCompound nbttagcompound1 = new NBTTagCompound();
				nbttagcompound1.setByte("Slot", (byte) i);
				inventoryStacks[i].writeToNBT(nbttagcompound1);
				nbttaglist.appendTag(nbttagcompound1);
			}
		nbttagcompound.setTag("Items", nbttaglist);

		// Pending remnants
		nbttaglist = new NBTTagList();
		ItemStack[] remnants = pendingRemnants.toArray(new ItemStack[pendingRemnants.size()]);
		for (int i = 0; i < remnants.length; i++)
			if (remnants[i] != null) {
				NBTTagCompound nbttagcompound1 = new NBTTagCompound();
				nbttagcompound1.setByte("Slot", (byte) i);
				remnants[i].writeToNBT(nbttagcompound1);
				nbttaglist.appendTag(nbttagcompound1);
			}
		nbttagcompound.setTag("PendingRemnants", nbttaglist);

		// Pending liquids
		nbttaglist = new NBTTagList();
		LiquidStack[] liquids = pendingLiquids.toArray(new LiquidStack[pendingLiquids.size()]);
		for (int i = 0; i < liquids.length; i++)
			if (liquids[i] != null) {
				NBTTagCompound nbttagcompound1 = new NBTTagCompound();

Answer: nbttagcompound1.setByte("Slot", (byte) i);

<think>
The code is inside writeToNBT, handling pending liquids similarly to inventory and pending remnants. Inside the for-loop, after creating a new NBTTagCompound, the next operation is to record the slot index. Following the pattern, the line should set the "Slot" byte to the loop index.
</think>
nbttagcompound1.setByte("Slot", (byte) i);


Context:
  # -*- coding: utf-8 -*-
'''
Test Vincent.charts
-------------------

Tests for Vincent chart types, which also serve as reference grammar.

'''

import pandas as pd
import nose.tools as nt
from vincent.charts import (data_type, Chart, Bar, Scatter, Line, Area,
                            StackedArea, StackedBar, GroupedBar, Map, Pie)

def chart_runner(chart, scales, axes, marks):
    'Iterate through each chart element for check for contents'

    for i, scale in enumerate(scales):
        nt.assert_dict_equal(chart.scales[i].grammar(), scale)

    for i, axis in enumerate(axes):
        nt.assert_dict_equal(chart.axes[i].grammar(), axis)

    for i, mark in enumerate(marks):
        nt.assert_dict_equal(chart.marks[i].grammar(), mark)

def test_data_type():
    'Test automatic data type importing'

    puts1 = [10, 20, 30, 40, 50]
    puts2 = {'apples': 10, 'bananas': 20, 'oranges': 30}

    gets1 = [{'col': 'data', 'idx': 0, 'val': 10},
             {'col': 'data', 'idx': 1, 'val': 20},
             {'col': 'data', 'idx': 2, 'val': 30},
             {'col': 'data', 'idx': 3, 'val': 40},
             {'col': 'data', 'idx': 4, 'val': 50}]
    gets2 = [{'col': 'data', 'idx': 'apples', 'val': 10},
             {'col': 'data', 'idx': 'bananas', 'val': 20},
             {'col': 'data', 'idx': 'oranges', 'val': 30}]

    for ins, outs in zip([puts1, puts2], [gets1, gets2]):
        test = data_type(ins)
        nt.assert_list_equal(test.values, outs)

    #From Iters
    puts = {'x': [1, 2, 3], 'y': [10, 20, 30], 'z': [40, 50, 60]}
    gets = [{'col': 'y', 'idx': 1, 'val': 10},
            {'col': 'y', 'idx': 2, 'val': 20},
            {'col': 'y', 'idx': 3, 'val': 30},
            {'col': 'z', 'idx': 1, 'val': 40},
            {'col': 'z', 'idx': 2, 'val': 50},
            {'col': 'z', 'idx': 3, 'val': 60}]

    test = data_type(puts, iter_idx='x')
    nt.assert_list_equal(test.values, gets)

    #Pandas
    df = pd.DataFrame({'one': [1, 2, 3], 'two': [4, 5, 6]})
    series = pd.Series([1, 2, 3], name='test')
    gets1 = [{'col': 'one', 'idx': 0, 'val': 1},
             {'col': 'two', 'idx': 0, 'val': 4},
             {'col': 'one', 'idx': 1, 'val': 2},
             {'col': 'two', 'idx': 1, 'val': 5},
             {'col': 'one', 'idx': 2, 'val': 3},
             {'col': 'two', 'idx': 2, 'val': 6}]
    gets2 = [{'col': 'test', 'idx': 0, 'val': 1},
             {'col': 'test', 'idx': 1, 'val': 2},
             {'col': 'test', 'idx': 2, 'val': 3}]
    test_df = data_type(df)
    test_series = data_type(series)
    nt.assert_list_equal(test_df.values, gets1)
    nt.assert_list_equal(test_series.values, gets2)

    #Bad type
    class BadType(object):
        'Bad data type'
        pass

    test = BadType()
    nt.assert_raises(ValueError, data_type, test)

class TestChart(object):
    'Test Chart ABC'

    def test_init(self):
        chart = Chart([0, 1], width=100, height=100)
        nt.assert_equal(chart.width, 100)
        nt.assert_equal(chart.height, 100)
        padding = "auto"
        nt.assert_equal(chart.padding, padding)

        #Data loading errors
        nt.assert_raises(ValueError, Chart)
        nt.assert_raises(ValueError, Chart, [])

class TestBar(object):
    'Test Bar Chart'

    def test_init(self):
        bar = Bar([1, 2, 3])

        scales = [{'domain': {'data': 'table', 'field': 'data.idx'},
                   'name': 'x',
                   'range': 'width',
                   'type': 'ordinal'},
                  {'domain': {'data': 'table', 'field': 'data.val'},
                   'name': 'y',
                   'nice': True,
                   'range': 'height'}]

        axes = [{'scale': 'x', 'type': 'x'},
                {'scale': 'y', 'type': 'y'}]

        marks = [{'from': {'data': 'table'},
                  'properties': {'enter': {'width': {'band': True,
                  'offset': -1,
                  'scale': 'x'},
                  'x': {'field': 'data.idx', 'scale': 'x'},
                  'y': {'field': 'data.val', 'scale': 'y'},
                  'y2': {'scale': 'y', 'value': 0}},
                  'update': {'fill': {'value': 'steelblue'}}},
                  'type': 'rect'}]

        chart_runner(bar, scales, axes, marks)

class TestScatter(object):
    'Test Scatter Chart'

    def test_init(self):

        scatter = Scatter([1, 2, 3])

        scales = [{'domain': {'data': 'table', 'field': 'data.idx'},
                   'name': 'x',
                   'range': 'width',
                   'type': 'linear'},
                  {'domain': {'data': 'table', 'field': 'data.val'},
                   'name': 'y',
                   'type': 'linear',
                   'range': 'height',
                   'nice': True},
                  {'domain': {'data': 'table', 'field': 'data.col'},
                   'name': 'color',
                   'range': 'category20',
                   'type': 'ordinal'}]

        axes = [{'scale': 'x', 'type': 'x'},
                {'scale': 'y', 'type': 'y'}]

        marks = [{'from': {'data': 'table',
                  'transform': [{'keys': ['data.col'], 'type': 'facet'}]},
                  'marks':
                  [{'properties': {'enter': {'fill': {'field': 'data.col',
                    'scale': 'color'},
                    'size': {'value': 100},
                    'x': {'field': 'data.idx', 'scale': 'x'},
                    'y': {'field': 'data.val', 'scale': 'y'}}},
                    'type': 'symbol'}],
                  'type': 'group'}]

        chart_runner(scatter, scales, axes, marks)

class TestLine(object):
    'Test Line Chart'

    def test_init(self):
        line = Line([1, 2, 3])

        scales = [{'domain': {'data': 'table', 'field': 'data.idx'},
                   'name': 'x',
                   'range': 'width',
                   'type': 'linear'},
                  {'domain': {'data': 'table', 'field': 'data.val'},
                   'name': 'y',
                   'type': 'linear',
                   'nice': True,
                   'range': 'height'},
                  {'domain': {'data': 'table', 'field': 'data.col'},
                   'name': 'color',
                   'range': 'category20',
                   'type': 'ordinal'}]

        axes = [{'scale': 'x', 'type': 'x'},
                {'scale': 'y', 'type': 'y'}]

        marks = [{'from': {'data': 'table',
                  'transform': [{'keys': ['data.col'], 'type': 'facet'}]},
                  'marks':
                 [{'properties': {'enter': {'stroke': {'field': 'data.col',
                   'scale': 'color'},
                   'strokeWidth': {'value': 2},
                   'x': {'field': 'data.idx', 'scale': 'x'},
                   'y': {'field': 'data.val', 'scale': 'y'}}},
                   'type': 'line'}],
                 'type': 'group'}]

        chart_runner(line, scales, axes, marks)

Answer: class TestArea(object):

<think>
The snippet ends the test_init method of TestLine with a call to chart_runner. The method then closes, the class ends, and the next logical code block in the test suite is the definition of the next test class, which is for the Area chart. Therefore the next line of code is the class definition for TestArea.
</think>
class TestArea(object):


Context:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/dataproc/v1/operations.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code

using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Cloud.Dataproc.V1 {

  /// Holder for reflection information generated from google/cloud/dataproc/v1/operations.proto
  public static partial class OperationsReflection {

    #region Descriptor
    /// File descriptor for google/cloud/dataproc/v1/operations.proto
    public static pbr::FileDescriptor Descriptor {
      get { return descriptor; }
    }
    private static pbr::FileDescriptor descriptor;

    static OperationsReflection() {
      byte[] descriptorData = global::System.Convert.FromBase64String(
          string.Concat(
            "Cilnb29nbGUvY2xvdWQvZGF0YXByb2MvdjEvb3BlcmF0aW9ucy5wcm90bxIY",
            "Z29vZ2xlLmNsb3VkLmRhdGFwcm9jLnYxGhxnb29nbGUvYXBpL2Fubm90YXRp",
            "b25zLnByb3RvGiNnb29nbGUvbG9uZ3J1bm5pbmcvb3BlcmF0aW9ucy5wcm90",
            "bxobZ29vZ2xlL3Byb3RvYnVmL2VtcHR5LnByb3RvGh9nb29nbGUvcHJvdG9i",
            "dWYvdGltZXN0YW1wLnByb3RvIvUBChZDbHVzdGVyT3BlcmF0aW9uU3RhdHVz",
            "EkUKBXN0YXRlGAEgASgOMjYuZ29vZ2xlLmNsb3VkLmRhdGFwcm9jLnYxLkNs",
            "dXN0ZXJPcGVyYXRpb25TdGF0dXMuU3RhdGUSEwoLaW5uZXJfc3RhdGUYAiAB",
            "KAkSDwoHZGV0YWlscxgDIAEoCRI0ChBzdGF0ZV9zdGFydF90aW1lGAQgASgL",
            "MhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcCI4CgVTdGF0ZRILCgdVTktO",
            "T1dOEAASCwoHUEVORElORxABEgsKB1JVTk5JTkcQAhIICgRET05FEAMikAMK",
            "GENsdXN0ZXJPcGVyYXRpb25NZXRhZGF0YRIUCgxjbHVzdGVyX25hbWUYByAB",
            "KAkSFAoMY2x1c3Rlcl91dWlkGAggASgJEkAKBnN0YXR1cxgJIAEoCzIwLmdv",
            "b2dsZS5jbG91ZC5kYXRhcHJvYy52MS5DbHVzdGVyT3BlcmF0aW9uU3RhdHVz",
            "EkgKDnN0YXR1c19oaXN0b3J5GAogAygLMjAuZ29vZ2xlLmNsb3VkLmRhdGFw",
            "cm9jLnYxLkNsdXN0ZXJPcGVyYXRpb25TdGF0dXMSFgoOb3BlcmF0aW9uX3R5",
            "cGUYCyABKAkSEwoLZGVzY3JpcHRpb24YDCABKAkSTgoGbGFiZWxzGA0gAygL",
            "Mj4uZ29vZ2xlLmNsb3VkLmRhdGFwcm9jLnYxLkNsdXN0ZXJPcGVyYXRpb25N",
            "ZXRhZGF0YS5MYWJlbHNFbnRyeRIQCgh3YXJuaW5ncxgOIAMoCRotCgtMYWJl",
            "bHNFbnRyeRILCgNrZXkYASABKAkSDQoFdmFsdWUYAiABKAk6AjgBQnMKHGNv",
            "bS5nb29nbGUuY2xvdWQuZGF0YXByb2MudjFCD09wZXJhdGlvbnNQcm90b1AB",
            "WkBnb29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlzL2Nsb3Vk",
            "L2RhdGFwcm9jL3YxO2RhdGFwcm9jYgZwcm90bzM="));
      descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
          new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.LongRunning.OperationsReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.EmptyReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, },
          new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
            new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Dataproc.V1.ClusterOperationStatus), global::Google.Cloud.Dataproc.V1.ClusterOperationStatus.Parser, new[]{ "State", "InnerState", "Details", "StateStartTime" }, null, new[]{ typeof(global::Google.Cloud.Dataproc.V1.ClusterOperationStatus.Types.State) }, null),
            new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Dataproc.V1.ClusterOperationMetadata), global::Google.Cloud.Dataproc.V1.ClusterOperationMetadata.Parser, new[]{ "ClusterName", "ClusterUuid", "Status", "StatusHistory", "OperationType", "Description", "Labels", "Warnings" }, null, null, new pbr::GeneratedClrTypeInfo[] { null, })
          }));
    }
    #endregion

  }
  #region Messages
  ///
  /// The status of the operation.
  ///
  public sealed partial class ClusterOperationStatus : pb::IMessage<ClusterOperationStatus> {
    private static readonly pb::MessageParser<ClusterOperationStatus> _parser = new pb::MessageParser<ClusterOperationStatus>(() => new ClusterOperationStatus());
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public static pb::MessageParser<ClusterOperationStatus> Parser { get { return _parser; } }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public static pbr::MessageDescriptor Descriptor {
      get { return global::Google.Cloud.Dataproc.V1.OperationsReflection.Descriptor.MessageTypes[0]; }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    pbr::MessageDescriptor pb::IMessage.Descriptor {
      get { return Descriptor; }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public ClusterOperationStatus() {
      OnConstruction();
    }

    partial void OnConstruction();

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public ClusterOperationStatus(ClusterOperationStatus other) : this() {
      state_ = other.state_;
      innerState_ = other.innerState_;
      details_ = other.details_;
      StateStartTime = other.stateStartTime_ != null ? other.StateStartTime.Clone() : null;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public ClusterOperationStatus Clone() {
      return new ClusterOperationStatus(this);
    }

    /// Field number for the "state" field.
    public const int StateFieldNumber = 1;
    private global::Google.Cloud.Dataproc.V1.ClusterOperationStatus.Types.State state_ = 0;
    ///
    /// Output-only. A message containing the operation state.
    ///
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public global::Google.Cloud.Dataproc.V1.ClusterOperationStatus.Types.State State {
      get { return state_; }
      set {
        state_ = value;
      }
    }

    /// Field number for the "inner_state" field.
    public const int InnerStateFieldNumber = 2;
    private string innerState_ = "";
    ///
    /// Output-only. A message containing the detailed operation state.
    ///
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public string InnerState {
      get { return innerState_; }
      set {
        innerState_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
      }
    }

    /// Field number for the "details" field.
    public const int DetailsFieldNumber = 3;
    private string details_ = "";
    ///
    /// Output-only.A message containing any operation metadata details.
    ///
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public string Details {
      get { return details_; }
      set {
        details_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
      }
    }

    /// Field number for the "state_start_time" field.
    public const int StateStartTimeFieldNumber = 4;
    private global::Google.Protobuf.WellKnownTypes.Timestamp stateStartTime_;
    ///
    /// Output-only. The time this state was entered.
    ///
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public global::Google.Protobuf.WellKnownTypes.Timestamp StateStartTime {
      get { return stateStartTime_; }
      set {
        stateStartTime_ = value;
      }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public override bool Equals(object other) {
      return Equals(other as ClusterOperationStatus);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public bool Equals(ClusterOperationStatus other) {
      if (ReferenceEquals(other, null)) {
        return false;
      }
      if (ReferenceEquals(other, this)) {
        return true;
      }
      if (State != other.State) return false;
      if (InnerState != other.InnerState) return false;
      if (Details != other.Details) return false;
      if (!object.Equals(StateStartTime, other.StateStartTime)) return false;
      return true;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public override int GetHashCode() {
      int hash = 1;
      if (State != 0) hash ^= State.GetHashCode();
      if (InnerState.Length != 0) hash ^= InnerState.GetHashCode();
      if (Details.Length != 0) hash ^= Details.GetHashCode();
      if (stateStartTime_ != null) hash ^= StateStartTime.GetHashCode();
      return hash;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public override string ToString() {
      return pb::JsonFormatter.ToDiagnosticString(this);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public void WriteTo(pb::CodedOutputStream output) {
      if (State != 0) {
        output.WriteRawTag(8);
        output.WriteEnum((int) State);
      }
      if (InnerState.Length != 0) {
        output.WriteRawTag(18);
        output.WriteString(InnerState);
      }
      if (Details.Length != 0) {

Answer: output.WriteRawTag(26);

<think>
The WriteTo method serializes each field with its tag. After handling State (tag 8) and InnerState (tag 18), the next field is Details with field number 3, whose wire tag is 26. The generated code therefore writes the raw tag 26 before writing the string value. So the next line inside the Details block is the call to WriteRawTag with 26.
</think>
output.WriteRawTag(26);


Context:
import csv
import random
import StringIO

from django.core.mail import send_mass_mail
from django.db.models import Q
from django.http import HttpResponse
from django.http import HttpResponseBadRequest, HttpResponseNotAllowed
from django.shortcuts import render, redirect, get_object_or_404
from django.template import Context, Template
from django.views.decorators.http import require_POST

from account.decorators import login_required

# @@@ switch to pinax-teams
from symposion.teams.models import Team

from symposion.conf import settings
from symposion.proposals.models import ProposalBase, ProposalSection
from symposion.utils.mail import send_email

from symposion.reviews.forms import ReviewForm, SpeakerCommentForm
from symposion.reviews.forms import BulkPresentationForm
from symposion.reviews.models import (
    ReviewAssignment, Review, LatestVote, ProposalResult, NotificationTemplate,
    ResultNotification, promote_proposal
)

def access_not_permitted(request):
    return render(request, "symposion/reviews/access_not_permitted.html")

def proposals_generator(request, queryset, user_pk=None, check_speaker=True):

    for obj in queryset:
        # @@@ this sucks; we can do better
        if check_speaker:
            if request.user in [s.user for s in obj.speakers()]:
                continue

        try:
            obj.result
        except ProposalResult.DoesNotExist:
            ProposalResult.objects.get_or_create(proposal=obj)

        obj.comment_count = obj.result.comment_count
        obj.score = obj.result.score
        obj.total_votes = obj.result.vote_count
        obj.plus_two = obj.result.plus_two
        obj.plus_one = obj.result.plus_one
        obj.minus_one = obj.result.minus_one
        obj.minus_two = obj.result.minus_two
        lookup_params = dict(proposal=obj)

        if user_pk:
            lookup_params["user__pk"] = user_pk
        else:
            lookup_params["user"] = request.user

        try:
            obj.user_vote = LatestVote.objects.get(**lookup_params).vote
            obj.user_vote_css = LatestVote.objects.get(**lookup_params).css_class()
        except LatestVote.DoesNotExist:
            obj.user_vote = None
            obj.user_vote_css = "no-vote"

        yield obj

VOTE_THRESHOLD = settings.SYMPOSION_VOTE_THRESHOLD

POSITIVE = "positive"
NEGATIVE = "negative"
INDIFFERENT = "indifferent"
CONTROVERSIAL = "controversial"
TOO_FEW = "too_few"

REVIEW_STATUS_FILTERS = {
    # proposals with at least VOTE_THRESHOLD reviews and at least one +2 and no -2s, sorted by
    # the 'score'
    POSITIVE: lambda qs: qs.filter(result__vote_count__gte=VOTE_THRESHOLD, result__plus_two__gt=0,
                                result__minus_two=0).order_by("-result__score"),
    # proposals with at least VOTE_THRESHOLD reviews and at least one -2 and no +2s, reverse
    # sorted by the 'score'
    NEGATIVE: lambda qs: qs.filter(result__vote_count__gte=VOTE_THRESHOLD, result__minus_two__gt=0,
                                result__plus_two=0).order_by("result__score"),
    # proposals with at least VOTE_THRESHOLD reviews and neither a +2 or a -2, sorted by total
    # votes (lowest first)
    INDIFFERENT: lambda qs: qs.filter(result__vote_count__gte=VOTE_THRESHOLD, result__minus_two=0,
                                   result__plus_two=0).order_by("result__vote_count"),
    # proposals with at least VOTE_THRESHOLD reviews and both a +2 and -2, sorted by total
    # votes (highest first)
    CONTROVERSIAL: lambda qs: qs.filter(result__vote_count__gte=VOTE_THRESHOLD,
                                     result__plus_two__gt=0, result__minus_two__gt=0)
         .order_by("-result__vote_count"),
    # proposals with fewer than VOTE_THRESHOLD reviews
    TOO_FEW: lambda qs: qs.filter(result__vote_count__lt=VOTE_THRESHOLD)
        .order_by("result__vote_count"),
}

# Returns a list of all proposals, proposals reviewed by the user, or the proposals the user has
# yet to review depending on the link user clicks in dashboard
@login_required
def review_section(request, section_slug, assigned=False, reviewed="all"):

    if not request.user.has_perm("reviews.can_review_%s" % section_slug):
        return access_not_permitted(request)

    section = get_object_or_404(ProposalSection, section__slug=section_slug)
    queryset = ProposalBase.objects.filter(kind__section=section.section)

    if assigned:
        assignments = ReviewAssignment.objects.filter(user=request.user)\
            .values_list("proposal__id")
        queryset = queryset.filter(id__in=assignments)

    # passing reviewed in from reviews.urls and out to review_list for
    # appropriate template header rendering
    if reviewed == "all":
        queryset = queryset.select_related("result").select_subclasses()
        reviewed = "all_reviews"
    elif reviewed == "reviewed":
        queryset = queryset.filter(reviews__user=request.user)
        reviewed = "user_reviewed"
    else:
        queryset = queryset.exclude(reviews__user=request.user).exclude(
            speaker__user=request.user)
        reviewed = "user_not_reviewed"

    # lca2017 #21 -- chairs want to be able to see their own proposals in the list
    check_speaker = not request.user.has_perm("reviews.can_manage_%s" % section_slug)
    proposals = proposals_generator(request, queryset, check_speaker=check_speaker)

    ctx = {
        "proposals": proposals,
        "section": section,
        "reviewed": reviewed,
    }

    return render(request, "symposion/reviews/review_list.html", ctx)

@login_required
def review_all_proposals_csv(request):
    ''' Returns a CSV representation of all of the proposals this user has
    permisison to review. '''

    response = HttpResponse("text/csv")
    response['Content-Disposition'] = 'attachment; filename="proposals.csv"'
    writer = csv.writer(response, quoting=csv.QUOTE_NONNUMERIC)

    queryset = ProposalBase.objects.filter()

    # The fields from each proposal object to report in the csv
    fields = [
        "id", "proposal_type", "speaker_name","speaker_email", "title",
        "submitted", "other_speakers", "speaker_travel",
        "speaker_accommodation", "cancelled", "status", "score", "total_votes",
        "minus_two", "minus_one", "plus_one", "plus_two",
    ]

    # Fields are the heading
    writer.writerow(fields)

    for proposal in proposals_generator(request, queryset, check_speaker=False):

        proposal.speaker_name = proposal.speaker.name
        section_slug = proposal.kind.section.slug
        kind_slug = proposal.kind.slug
        proposal.proposal_type = kind_slug

        proposal.other_speakers = ", ".join(
            speaker.name
            for speaker in proposal.additional_speakers.all()
        )

        proposal.speaker_travel = ", ".join(
            str(bool(speaker.travel_assistance))
            for speaker in proposal.speakers()
        )

        proposal.speaker_accommodation = ", ".join(
            str(bool(speaker.accommodation_assistance))
            for speaker in proposal.speakers()
        )

        if not request.user.has_perm("reviews.can_review_%s" % section_slug):
            continue

        csv_line = [getattr(proposal, field) for field in fields]

        # Enusre that unicode items are handled properly.
        for i, item in enumerate(csv_line):
            if isinstance(item, unicode):
                csv_line[i] = item.encode("utf8")

        writer.writerow(csv_line)

    return response

@login_required
def review_random_proposal(request, section_slug):
    # lca2017 #16 view for random proposal

    if not request.user.has_perm("reviews.can_review_%s" % section_slug):
        return access_not_permitted(request)

    section = get_object_or_404(ProposalSection, section__slug=section_slug)

Answer: queryset = ProposalBase.objects.filter(kind__section=section.section)

<think>
After obtaining the section object, the view needs to build a queryset of proposals belonging to that section, just like in the review_section view earlier. The typical query filters ProposalBase by the related kind's section field using the retrieved section. Therefore the next line should define that queryset.
</think>
queryset = ProposalBase.objects.filter(kind__section=section.section)


Context:
#(C) Copyright Syd Logan 2020
#(C) Copyright Thousand Smiles Foundation 2020
#
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#
#You may obtain a copy of the License at
#http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.

'''
unit tests for audiogram application. Assumes django server is up
and running on the specified host and port
'''

import unittest
import getopt, sys
import json

from tschartslib.service.serviceapi import ServiceAPI
from tschartslib.tscharts.tscharts import Login, Logout
from tschartslib.patient.patient import CreatePatient, DeletePatient
from tschartslib.clinic.clinic import CreateClinic, DeleteClinic
from tschartslib.station.station import CreateStation, DeleteStation
from tschartslib.image.image import CreateImage, DeleteImage

class CreateAudiogram(ServiceAPI):
    def __init__(self, host, port, token, clinic, image, patient, comment=""):
        super(CreateAudiogram, self).__init__()

        self.setHttpMethod("POST")
        self.setHost(host)
        self.setPort(port)
        self.setToken(token)

        payload = {"patient": patient, "clinic": clinic, "image": image, "comment": comment}
        self.setPayload(payload)
        self.setURL("tscharts/v1/audiogram/")

class GetAudiogram(ServiceAPI):
    def makeURL(self):
        hasQArgs = False
        if not self._id == None:
            base = "tscharts/v1/audiogram/{}/".format(self._id)
        else:
            base = "tscharts/v1/audiogram/"

        if not self._clinic == None:
            if not hasQArgs:
                base += "?"
            else:
                base += "&"
            base += "clinic={}".format(self._clinic)
            hasQArgs = True

        if not self._patient == None:
            if not hasQArgs:
                base += "?"
            else:
                base += "&"
            base += "patient={}".format(self._patient)
            hasQArgs = True

        self.setURL(base)

    def __init__(self, host, port, token):
        super(GetAudiogram, self).__init__()

        self.setHttpMethod("GET")
        self.setHost(host)
        self.setPort(port)
        self.setToken(token)
        self._patient = None
        self._clinic = None
        self._image = None
        self._id = None

    def setId(self, id):
        self._id = id;
        self.makeURL()

    def setClinic(self, clinic):
        self._clinic = clinic
        self.makeURL()

    def setPatient(self, patient):
        self._patient = patient
        self.makeURL()

    def setImage(self, image):
        self._image = image
        self.makeURL()

class UpdateAudiogram(ServiceAPI):
    def __init__(self, host, port, token, id):
        super(UpdateAudiogram, self).__init__()

        self.setHttpMethod("PUT")
        self.setHost(host)
        self.setPort(port)
        self.setToken(token)
        self._payload = {}
        self.setPayload(self._payload)
        self.setURL("tscharts/v1/audiogram/{}/".format(id))

    def setComment(self, comment):
        self._payload["comment"] = comment
        self.setPayload(self._payload)

class DeleteAudiogram(ServiceAPI):
    def __init__(self, host, port, token, id):
        super(DeleteAudiogram, self).__init__()

        self.setHttpMethod("DELETE")
        self.setHost(host)
        self.setPort(port)
        self.setToken(token)
        self.setURL("tscharts/v1/audiogram/{}/".format(id))

class TestTSAudiogram(unittest.TestCase):

    def setUp(self):
        login = Login(host, port, username, password)
        ret = login.send(timeout=30)
        self.assertEqual(ret[0], 200)
        self.assertTrue("token" in ret[1])
        global token
        token = ret[1]["token"]

    def testCreateAudiogram(self):
        x = CreateClinic(host, port, token, "Ensenada", "02/05/2016", "02/06/2016")
        ret = x.send(timeout=30)
        self.assertEqual(ret[0], 200)
        self.assertTrue("id" in ret[1])
        clinicid = int(ret[1]["id"])

        x = CreateStation(host, port, token, "ENT")
        ret = x.send(timeout=30)
        self.assertEqual(ret[0], 200)
        stationid = int(ret[1]["id"])

        data = {}

        data["paternal_last"] = "abcd1234"
        data["maternal_last"] = "yyyyyy"
        data["first"] = "zzzzzzz"
        data["middle"] = ""
        data["suffix"] = "Jr."
        data["prefix"] = ""
        data["dob"] = "04/01/1962"
        data["gender"] = "Female"
        data["street1"] = "1234 First Ave"
        data["street2"] = ""
        data["city"] = "Ensenada"
        data["colonia"] = ""
        data["state"] = u"Baja California"
        data["phone1"] = "1-111-111-1111"
        data["phone2"] = ""
        data["email"] = "patient@example.com"
        data["emergencyfullname"] = "Maria Sanchez"
        data["emergencyphone"] = "1-222-222-2222"
        data["emergencyemail"] = "maria.sanchez@example.com"

        x = CreatePatient(host, port, token, data)
        ret = x.send(timeout=30)
        self.assertEqual(ret[0], 200)
        patientid = int(ret[1]["id"])

        x = CreateImage(host, port, token)
        x.setPatient(patientid)
        x.setClinic(clinicid)
        x.setStation(stationid)
        x.setType("Audiogram")
        x.setData("ABCDEFG")    # doesn't matter if it is actual image data
        ret = x.send(timeout=30)
        self.assertEqual(ret[0], 200)
        imageid = int(ret[1]["id"])

        x = CreateAudiogram(host, port, token, patient=patientid, clinic=clinicid, image=imageid)
        ret = x.send(timeout=30)
        self.assertEqual(ret[0], 200)
        id = int(ret[1]["id"])
        x = GetAudiogram(host, port, token)
        x.setId(id)
        ret = x.send(timeout=30)
        self.assertEqual(ret[0], 200)
        self.assertTrue("clinic" in ret[1])
        clinicId = int(ret[1]["clinic"])
        self.assertTrue(clinicId == clinicid)
        self.assertTrue("patient" in ret[1])
        patientId = int(ret[1]["patient"])
        self.assertTrue(patientId == patientid)
        imageId = int(ret[1]["image"])
        self.assertTrue(imageId == imageid)

        x = DeleteAudiogram(host, port, token, id)
        ret = x.send(timeout=30)
        self.assertEqual(ret[0], 200)
        x = GetAudiogram(host, port, token)
        x.setId(id)
        ret = x.send(timeout=30)
        self.assertEqual(ret[0], 404)  # not found

        # non-existent clinic param

        x = CreateAudiogram(host, port, token, clinic=9999, image=imageid, patient=patientid)
        ret = x.send(timeout=30)
        self.assertEqual(ret[0], 404)

        # non-existent image param

        x = CreateAudiogram(host, port, token, clinic=clinicid, image=9999, patient=patientid)
        ret = x.send(timeout=30)
        self.assertEqual(ret[0], 404)

        # non-existent patient param

        x = CreateAudiogram(host, port, token, clinic=clinicid, image=imageid, patient=9999)
        ret = x.send(timeout=30)
        self.assertEqual(ret[0], 404)

        x = DeleteStation(host, port, token, stationid)
        ret = x.send(timeout=30)
        self.assertEqual(ret[0], 200)

        x = DeleteClinic(host, port, token, clinicid)
        ret = x.send(timeout=30)
        self.assertEqual(ret[0], 200)

        x = DeletePatient(host, port, token, patientid)
        ret = x.send(timeout=30)
        self.assertEqual(ret[0], 200)

Answer: def testDeleteAudiogram(self):

<think>
The provided snippet ends the testCreateAudiogram method after deleting the patient. In a typical unittest class, the next step is to define another test method. Following the same indentation level, the next line should start a new test method, likely for updating an audiogram.
</think>
def testUpdateAudiogram(self):


Context:
# -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, Jakob Schnitzer.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.

"""Converts tracks or albums to external directory
"""
from __future__ import division, absolute_import, print_function

import os
import threading
import subprocess
import tempfile
import shlex
import six
from string import Template
import platform

from beets import ui, util, plugins, config
from beets.plugins import BeetsPlugin
from confuse import ConfigTypeError
from beets import art
from beets.util.artresizer import ArtResizer
from beets.library import parse_query_string
from beets.library import Item

_fs_lock = threading.Lock()
_temp_files = []  # Keep track of temporary transcoded files for deletion.

# Some convenient alternate names for formats.
ALIASES = {
    u'wma': u'windows media',
    u'vorbis': u'ogg',
}

LOSSLESS_FORMATS = ['ape', 'flac', 'alac', 'wav', 'aiff']

def replace_ext(path, ext):
    """Return the path with its extension replaced by `ext`.

    The new extension must not contain a leading dot.
    """
    ext_dot = b'.' + ext
    return os.path.splitext(path)[0] + ext_dot

def get_format(fmt=None):
    """Return the command template and the extension from the config.
    """
    if not fmt:
        fmt = config['convert']['format'].as_str().lower()
    fmt = ALIASES.get(fmt, fmt)

    try:
        format_info = config['convert']['formats'][fmt].get(dict)
        command = format_info['command']
        extension = format_info.get('extension', fmt)
    except KeyError:
        raise ui.UserError(
            u'convert: format {0} needs the "command" field'
            .format(fmt)
        )
    except ConfigTypeError:
        command = config['convert']['formats'][fmt].get(str)
        extension = fmt

    # Convenience and backwards-compatibility shortcuts.
    keys = config['convert'].keys()
    if 'command' in keys:
        command = config['convert']['command'].as_str()
    elif 'opts' in keys:
        # Undocumented option for backwards compatibility with < 1.3.1.
        command = u'ffmpeg -i $source -y {0} $dest'.format(
            config['convert']['opts'].as_str()
        )
    if 'extension' in keys:
        extension = config['convert']['extension'].as_str()

    return (command.encode('utf-8'), extension.encode('utf-8'))

def should_transcode(item, fmt):
    """Determine whether the item should be transcoded as part of
    conversion (i.e., its bitrate is high or it has the wrong format).
    """
    no_convert_queries = config['convert']['no_convert'].as_str_seq()
    if no_convert_queries:
        for query_string in no_convert_queries:
            query, _ = parse_query_string(query_string, Item)
            if query.match(item):
                return False
    if config['convert']['never_convert_lossy_files'] and \
            not (item.format.lower() in LOSSLESS_FORMATS):
        return False
    maxbr = config['convert']['max_bitrate'].get(int)
    return fmt.lower() != item.format.lower() or \
        item.bitrate >= 1000 * maxbr

class ConvertPlugin(BeetsPlugin):
    def __init__(self):
        super(ConvertPlugin, self).__init__()
        self.config.add({
            u'dest': None,
            u'pretend': False,
            u'link': False,
            u'hardlink': False,
            u'threads': util.cpu_count(),
            u'format': u'mp3',
            u'id3v23': u'inherit',
            u'formats': {
                u'aac': {
                    u'command': u'ffmpeg -i $source -y -vn -acodec aac '
                                u'-aq 1 $dest',
                    u'extension': u'm4a',
                },
                u'alac': {
                    u'command': u'ffmpeg -i $source -y -vn -acodec alac $dest',
                    u'extension': u'm4a',
                },
                u'flac': u'ffmpeg -i $source -y -vn -acodec flac $dest',
                u'mp3': u'ffmpeg -i $source -y -vn -aq 2 $dest',
                u'opus':
                    u'ffmpeg -i $source -y -vn -acodec libopus -ab 96k $dest',
                u'ogg':
                    u'ffmpeg -i $source -y -vn -acodec libvorbis -aq 3 $dest',
                u'wma':
                    u'ffmpeg -i $source -y -vn -acodec wmav2 -vn $dest',
            },
            u'max_bitrate': 500,
            u'auto': False,
            u'tmpdir': None,
            u'quiet': False,
            u'embed': True,
            u'paths': {},
            u'no_convert': u'',
            u'never_convert_lossy_files': False,
            u'copy_album_art': False,
            u'album_art_maxwidth': 0,
            u'delete_originals': False,
        })
        self.early_import_stages = [self.auto_convert]

        self.register_listener('import_task_files', self._cleanup)

    def commands(self):
        cmd = ui.Subcommand('convert', help=u'convert to external location')
        cmd.parser.add_option('-p', '--pretend', action='store_true',
                              help=u'show actions but do nothing')
        cmd.parser.add_option('-t', '--threads', action='store', type='int',
                              help=u'change the number of threads, \
                              defaults to maximum available processors')

Answer: cmd.parser.add_option('-k', '--keep-new', action='store_true',

<think>
The code is inside the ConvertPlugin.commands method, defining command‑line options for the 'convert' subcommand. After adding the '-t/--threads' option, the next logical option defined in the original beets plugin is the '-l/--link' flag, which tells the plugin to create symlinks instead of copying files. The line follows the same indentation and style as the previous option definitions.
</think>
cmd.parser.add_option('-l', '--link', action='store_true',
                              help=u'create symlinks instead of copying files')


Context:
/***************************************************************************
 *                                 Skills.cs
 *                            -------------------
 *   begin                : May 1, 2002
 *   copyright            : (C) The RunUO Software Team
 *   email                : info@runuo.com
 *
 *   $Id$
 *
 ***************************************************************************/

/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Server.Network;

namespace Server
{
	public delegate TimeSpan SkillUseCallback( Mobile user );

	public enum SkillLock : byte
	{
		Up = 0,
		Down = 1,
		Locked = 2
	}

	public enum SkillName
	{
		Alchemy = 0,
		Anatomy = 1,
		AnimalLore = 2,
		ItemID = 3,
		ArmsLore = 4,
		Parry = 5,
		Begging = 6,
		Blacksmith = 7,
		Fletching = 8,
		Peacemaking = 9,
		Camping = 10,
		Carpentry = 11,
		Cartography = 12,
		Cooking = 13,
		DetectHidden = 14,
		Discordance = 15,
		EvalInt = 16,
		Healing = 17,
		Fishing = 18,
		Forensics = 19,
		Herding = 20,
		Hiding = 21,
		Provocation = 22,
		Inscribe = 23,
		Lockpicking = 24,
		Magery = 25,
		MagicResist = 26,
		Tactics = 27,
		Snooping = 28,
		Musicianship = 29,
		Poisoning = 30,
		Archery = 31,
		SpiritSpeak = 32,
		Stealing = 33,
		Tailoring = 34,
		AnimalTaming = 35,
		TasteID = 36,
		Tinkering = 37,
		Tracking = 38,
		Veterinary = 39,
		Swords = 40,
		Macing = 41,
		Fencing = 42,
		Wrestling = 43,
		Lumberjacking = 44,
		Mining = 45,
		Meditation = 46,
		Stealth = 47,
		RemoveTrap = 48,
		Necromancy = 49,
		Focus = 50,
		Chivalry = 51,
		Bushido = 52,
		Ninjitsu = 53,
		Spellweaving = 54,
		Mysticism = 55,
		Imbuing = 56,
		Throwing = 57
	}

	[PropertyObject]
	public class Skill
	{
		private Skills m_Owner;
		private SkillInfo m_Info;
		private ushort m_Base;
		private ushort m_Cap;
		private SkillLock m_Lock;

		public override string ToString()
		{
			return String.Format( "[{0}: {1}]", Name, Base );
		}

		public Skill( Skills owner, SkillInfo info, GenericReader reader )
		{
			m_Owner = owner;
			m_Info = info;

			int version = reader.ReadByte();

			switch ( version )
			{
				case 0:
				{
					m_Base = reader.ReadUShort();
					m_Cap = reader.ReadUShort();
					m_Lock = (SkillLock)reader.ReadByte();

					break;
				}
				case 0xFF:
				{
					m_Base = 0;
					m_Cap = 1000;
					m_Lock = SkillLock.Up;

					break;
				}
				default:
				{
					if ( (version & 0xC0) == 0x00 )
					{
						if ( (version & 0x1) != 0 )
							m_Base = reader.ReadUShort();

						if ( (version & 0x2) != 0 )
							m_Cap = reader.ReadUShort();
						else
							m_Cap = 1000;

						if ( (version & 0x4) != 0 )
							m_Lock = (SkillLock)reader.ReadByte();
					}

					break;
				}
			}

			if ( m_Lock < SkillLock.Up || m_Lock > SkillLock.Locked )
			{
				Console.WriteLine( "Bad skill lock -> {0}.{1}", owner.Owner, m_Lock );
				m_Lock = SkillLock.Up;
			}
		}

		public Skill( Skills owner, SkillInfo info, int baseValue, int cap, SkillLock skillLock )
		{
			m_Owner = owner;
			m_Info = info;
			m_Base = (ushort)baseValue;
			m_Cap = (ushort)cap;
			m_Lock = skillLock;
		}

		public void SetLockNoRelay( SkillLock skillLock )
		{
			if ( skillLock < SkillLock.Up || skillLock > SkillLock.Locked )
				return;

			m_Lock = skillLock;
		}

		public void Serialize( GenericWriter writer )
		{
			if ( m_Base == 0 && m_Cap == 1000 && m_Lock == SkillLock.Up )
			{
				writer.Write( (byte) 0xFF ); // default
			}
			else
			{
				int flags = 0x0;

				if ( m_Base != 0 )
					flags |= 0x1;

				if ( m_Cap != 1000 )
					flags |= 0x2;

				if ( m_Lock != SkillLock.Up )
					flags |= 0x4;

Answer: writer.Write( (byte) flags ); // version

<think>
We are inside the Serialize method of Skill. After computing the flags integer that indicates which fields differ from defaults, the next step is to write that flags byte to the writer before conditionally writing the actual values. The appropriate C# line is writer.Write( (byte)flags );
</think>
writer.Write( (byte)flags );


Context:
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.hadoop.hive.ql.exec;

import static org.apache.hadoop.hive.ql.exec.Utilities.DEPRECATED_MAPRED_DFSCLIENT_PARALLELISM_MAX;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.apache.hadoop.hive.ql.exec.Utilities.getFileExtension;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.common.type.Timestamp;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.ql.Context;
import org.apache.hadoop.hive.ql.exec.mr.ExecDriver;
import org.apache.hadoop.hive.ql.exec.spark.SparkTask;
import org.apache.hadoop.hive.ql.exec.tez.TezTask;
import org.apache.hadoop.hive.ql.io.*;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.metadata.Table;
import org.apache.hadoop.hive.ql.plan.DependencyCollectionWork;
import org.apache.hadoop.hive.ql.plan.DynamicPartitionCtx;
import org.apache.hadoop.hive.ql.plan.ExprNodeConstantDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeGenericFuncDesc;
import org.apache.hadoop.hive.ql.plan.FileSinkDesc;
import org.apache.hadoop.hive.ql.plan.MapWork;
import org.apache.hadoop.hive.ql.plan.MapredWork;
import org.apache.hadoop.hive.ql.plan.PartitionDesc;
import org.apache.hadoop.hive.ql.plan.TableDesc;
import org.apache.hadoop.hive.ql.session.SessionState;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFFromUtcTimestamp;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapreduce.MRJobConfig;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;

public class TestUtilities {
  @Rule
  public TemporaryFolder temporaryFolder = new TemporaryFolder();

  public static final Logger LOG = LoggerFactory.getLogger(TestUtilities.class);
  private static final int NUM_BUCKETS = 3;

  @Test
  public void testGetFileExtension() {
    JobConf jc = new JobConf();
    assertEquals("No extension for uncompressed unknown format", "",
        getFileExtension(jc, false, null));
    assertEquals("No extension for compressed unknown format", "",
        getFileExtension(jc, true, null));
    assertEquals("No extension for uncompressed text format", "",
        getFileExtension(jc, false, new HiveIgnoreKeyTextOutputFormat()));
    assertEquals("Deflate for uncompressed text format", ".deflate",
        getFileExtension(jc, true, new HiveIgnoreKeyTextOutputFormat()));

    String extension = ".myext";
    jc.set("hive.output.file.extension", extension);
    assertEquals("Custom extension for uncompressed unknown format", extension,
        getFileExtension(jc, false, null));
    assertEquals("Custom extension for compressed unknown format", extension,
        getFileExtension(jc, true, null));
    assertEquals("Custom extension for uncompressed text format", extension,
        getFileExtension(jc, false, new HiveIgnoreKeyTextOutputFormat()));
    assertEquals("Custom extension for uncompressed text format", extension,
        getFileExtension(jc, true, new HiveIgnoreKeyTextOutputFormat()));
  }

  @Test
  public void testSerializeTimestamp() {
    Timestamp ts = Timestamp.ofEpochMilli(1374554702000L, 123456);
    ExprNodeConstantDesc constant = new ExprNodeConstantDesc(ts);
    List<ExprNodeDesc> children = new ArrayList<ExprNodeDesc>(1);
    children.add(constant);
    ExprNodeGenericFuncDesc desc = new ExprNodeGenericFuncDesc(TypeInfoFactory.timestampTypeInfo,
        new GenericUDFFromUtcTimestamp(), children);
    assertEquals(desc.getExprString(), SerializationUtilities.deserializeExpression(
        SerializationUtilities.serializeExpression(desc)).getExprString());
  }

  @Test
  public void testgetDbTableName() throws HiveException{
    String tablename;
    String [] dbtab;
    SessionState.start(new HiveConf(this.getClass()));
    String curDefaultdb = SessionState.get().getCurrentDatabase();

    //test table without db portion
    tablename = "tab1";
    dbtab = Utilities.getDbTableName(tablename);
    assertEquals("db name", curDefaultdb, dbtab[0]);
    assertEquals("table name", tablename, dbtab[1]);

    //test table with db portion
    tablename = "dab1.tab1";
    dbtab = Utilities.getDbTableName(tablename);
    assertEquals("db name", "dab1", dbtab[0]);
    assertEquals("table name", "tab1", dbtab[1]);

    //test invalid table name
    tablename = "dab1.tab1.x1";
    try {
      dbtab = Utilities.getDbTableName(tablename);
      fail("exception was expected for invalid table name");
    } catch(HiveException ex){
      assertEquals("Invalid table name " + tablename, ex.getMessage());
    }
  }

  @Test
  public void testReplaceTaskId() {
    String taskID = "000000";
    int bucketNum = 1;
    String newTaskID = Utilities.replaceTaskId(taskID, bucketNum);
    Assert.assertEquals("000001", newTaskID);
    taskID = "(ds%3D1)000001";
    newTaskID = Utilities.replaceTaskId(taskID, 5);
    Assert.assertEquals("(ds%3D1)000005", newTaskID);
  }

  @Test
  public void testRemoveTempOrDuplicateFilesOnTezNoDp() throws Exception {
    List<Path> paths = runRemoveTempOrDuplicateFilesTestCase("tez", false);
    assertEquals(0, paths.size());
  }

  @Test
  public void testRemoveTempOrDuplicateFilesOnTezWithDp() throws Exception {
    List<Path> paths = runRemoveTempOrDuplicateFilesTestCase("tez", true);
    assertEquals(0, paths.size());
  }

  @Test
  public void testRemoveTempOrDuplicateFilesOnMrNoDp() throws Exception {
    List<Path> paths = runRemoveTempOrDuplicateFilesTestCase("mr", false);

Answer: assertEquals(NUM_BUCKETS, paths.size());

<think>
The method testRemoveTempOrDuplicateFilesOnMrNoDp mirrors the previous two test methods. After obtaining the list of paths from runRemoveTempOrDuplicateFilesTestCase, the test asserts that the list is empty. The next line should therefore be the same assertion used earlier: assertEquals(0, paths.size());
</think>
assertEquals(0, paths.size());


Context:
/*
 *   Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *   WSO2 Inc. licenses this file to you under the Apache License,
 *   Version 2.0 (the "License"); you may not use this file except
 *   in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing,
 *   software distributed under the License is distributed on an
 *   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *   KIND, either express or implied.  See the License for the
 *   specific language governing permissions and limitations
 *   under the License.
 *
 */
package org.wso2.carbon.mdm.services.android.services.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.InvalidDeviceException;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;
import org.wso2.carbon.mdm.services.android.bean.ErrorResponse;
import org.wso2.carbon.mdm.services.android.bean.wrapper.AndroidApplication;
import org.wso2.carbon.mdm.services.android.bean.wrapper.AndroidDevice;
import org.wso2.carbon.mdm.services.android.exception.UnexpectedServerErrorException;
import org.wso2.carbon.mdm.services.android.services.DeviceManagementService;
import org.wso2.carbon.mdm.services.android.util.AndroidAPIUtils;
import org.wso2.carbon.mdm.services.android.util.AndroidConstants;
import org.wso2.carbon.mdm.services.android.util.AndroidDeviceUtils;
import org.wso2.carbon.mdm.services.android.util.Message;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;

@Path("/devices")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class DeviceManagementServiceImpl implements DeviceManagementService {

    private static final String OPERATION_ERROR_STATUS = "ERROR";
    private static final Log log = LogFactory.getLog(DeviceManagementServiceImpl.class);

    @PUT
    @Path("/{id}/applications")
    @Override
    public Response updateApplicationList(@PathParam("id")
                                          @NotNull
                                          @Size(min = 2, max = 45)
                                          @Pattern(regexp = "^[A-Za-z0-9]*$")
                                          String id, List<AndroidApplication> androidApplications) {
        Application application;
        List<Application> applications = new ArrayList<>();
        for (AndroidApplication androidApplication : androidApplications) {
            application = new Application();
            application.setPlatform(androidApplication.getPlatform());
            application.setCategory(androidApplication.getCategory());
            application.setName(androidApplication.getName());
            application.setLocationUrl(androidApplication.getLocationUrl());
            application.setImageUrl(androidApplication.getImageUrl());
            application.setVersion(androidApplication.getVersion());
            application.setType(androidApplication.getType());
            application.setAppProperties(androidApplication.getAppProperties());
            application.setApplicationIdentifier(androidApplication.getApplicationIdentifier());
            application.setMemoryUsage(androidApplication.getMemoryUsage());
            applications.add(application);
        }
        Message responseMessage = new Message();
        DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
        deviceIdentifier.setId(id);
        deviceIdentifier.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID);
        try {
            AndroidAPIUtils.getApplicationManagerService().
                    updateApplicationListInstalledInDevice(deviceIdentifier, applications);
            responseMessage.setResponseMessage("Device information has modified successfully.");
            return Response.status(Response.Status.ACCEPTED).entity(responseMessage).build();
        } catch (ApplicationManagementException e) {
            String msg = "Error occurred while modifying the application list.";
            log.error(msg, e);
            throw new UnexpectedServerErrorException(
                    new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
        }
    }

    @PUT
    @Path("/{id}/pending-operations")
    @Override
    public Response getPendingOperations(@PathParam("id") String id,
                                         @HeaderParam("If-Modified-Since") String ifModifiedSince,
                                         List<? extends Operation> resultOperations) {
        if (id == null || id.isEmpty()) {
            String msg = "Device identifier is null or empty, hence returning device not found";
            log.error(msg);
            return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
        }
        DeviceIdentifier deviceIdentifier = AndroidDeviceUtils.convertToDeviceIdentifierObject(id);
        try {
            if (!AndroidDeviceUtils.isValidDeviceIdentifier(deviceIdentifier)) {
                String msg = "Device not found for identifier '" + id + "'";
                log.error(msg);
                return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
            }
            if (log.isDebugEnabled()) {
                log.debug("Invoking Android pending operations:" + id);
            }
            if (resultOperations != null && !resultOperations.isEmpty()) {
                updateOperations(id, resultOperations);
            }
        } catch (OperationManagementException e) {
            String msg = "Issue in retrieving operation management service instance";
            log.error(msg, e);
            throw new UnexpectedServerErrorException(
                    new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
        } catch (PolicyComplianceException e) {
            String msg = "Issue in updating Monitoring operation";
            log.error(msg, e);
            throw new UnexpectedServerErrorException(
                    new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
        } catch (DeviceManagementException e) {
            String msg = "Issue in retrieving device management service instance";
            log.error(msg, e);
            throw new UnexpectedServerErrorException(
                    new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
        } catch (ApplicationManagementException e) {
            String msg = "Issue in retrieving application management service instance";
            log.error(msg, e);
            throw new UnexpectedServerErrorException(
                    new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
        } catch (NotificationManagementException e) {
            String msg = "Issue in retrieving Notification management service instance";
            log.error(msg, e);
            throw new UnexpectedServerErrorException(
                    new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
        }

        List<? extends Operation> pendingOperations;
        try {
            pendingOperations = AndroidDeviceUtils.getPendingOperations(deviceIdentifier);
        } catch (OperationManagementException e) {
            String msg = "Issue in retrieving operation management service instance";
            log.error(msg, e);
            throw new UnexpectedServerErrorException(
                    new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
        }
        return Response.status(Response.Status.CREATED).entity(pendingOperations).build();
    }

    private void updateOperations(String deviceId, List<? extends Operation> operations)
            throws OperationManagementException, PolicyComplianceException,
            ApplicationManagementException, NotificationManagementException, DeviceManagementException {
        for (org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation : operations) {
            AndroidDeviceUtils.updateOperation(deviceId, operation);
            if (OPERATION_ERROR_STATUS.equals(operation.getStatus().toString())) {
                org.wso2.carbon.device.mgt.common.notification.mgt.Notification notification = new
                        org.wso2.carbon.device.mgt.common.notification.mgt.Notification();
                DeviceIdentifier id = new DeviceIdentifier();
                id.setId(deviceId);
                id.setType(AndroidConstants.DEVICE_TYPE_ANDROID);
                String deviceName = AndroidAPIUtils.getDeviceManagementService().getDevice(id, false).getName();
                notification.setOperationId(operation.getId());
                notification.setStatus(org.wso2.carbon.device.mgt.common.notification.mgt.Notification.
                        Status.NEW.toString());
                notification.setDescription(operation.getCode() + " operation failed to execute on device " +
                        deviceName + " (ID: " + deviceId + ")");
                AndroidAPIUtils.getNotificationManagementService().addNotification(id, notification);
            }
            if (log.isDebugEnabled()) {
                log.debug("Updating operation '" + operation.toString() + "'");
            }
        }
    }

    @POST
    @Override
    public Response enrollDevice(@Valid AndroidDevice androidDevice) {
        if (androidDevice == null) {
            String errorMessage = "The payload of the android device enrollment is incorrect.";
            log.error(errorMessage);
            throw new org.wso2.carbon.mdm.services.android.exception.BadRequestException(

Answer: new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build());

<think>
The method checks for a null androidDevice and logs an error. It then throws a BadRequestException, which in this codebase is constructed with an ErrorResponse object. Following the pattern used elsewhere (e.g., UnexpectedServerErrorException), we create an ErrorResponse via its builder, set a 400 status code and the errorMessage, then build it. The line must close the constructor call and end with a semicolon.
</think>
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build());


Context:
##########################################################################
#
#  Copyright (c) 2011-2012, John Haddon. All rights reserved.
#  Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions are
#  met:
#
#      * Redistributions of source code must retain the above
#        copyright notice, this list of conditions and the following
#        disclaimer.
#
#      * Redistributions in binary form must reproduce the above
#        copyright notice, this list of conditions and the following
#        disclaimer in the documentation and/or other materials provided with
#        the distribution.
#
#      * Neither the name of John Haddon nor the names of
#        any other contributors to this software may be used to endorse or
#        promote products derived from this software without specific prior
#        written permission.
#
#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
#  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
#  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
#  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
#  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
#  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
#  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
#  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
#  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
#  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################

from __future__ import with_statement

import IECore

import Gaffer
import GafferUI

def appendDefinitions( menuDefinition, prefix="" ) :

	menuDefinition.append( prefix + "/Undo", { "command" : undo, "shortCut" : "Ctrl+Z", "active" : __undoAvailable } )
	menuDefinition.append( prefix + "/Redo", { "command" : redo, "shortCut" : "Shift+Ctrl+Z", "active" : __redoAvailable } )
	menuDefinition.append( prefix + "/UndoDivider", { "divider" : True } )

	menuDefinition.append( prefix + "/Cut", { "command" : cut, "shortCut" : "Ctrl+X", "active" : __selectionAvailable } )
	menuDefinition.append( prefix + "/Copy", { "command" : copy, "shortCut" : "Ctrl+C", "active" : __selectionAvailable } )
	menuDefinition.append( prefix + "/Paste", { "command" : paste, "shortCut" : "Ctrl+V", "active" : __pasteAvailable } )
	menuDefinition.append( prefix + "/Delete", { "command" : delete, "shortCut" : "Backspace, Delete", "active" : __selectionAvailable } )
	menuDefinition.append( prefix + "/CutCopyPasteDeleteDivider", { "divider" : True } )

	menuDefinition.append( prefix + "/Find...", { "command" : find, "shortCut" : "Ctrl+F" } )
	menuDefinition.append( prefix + "/FindDivider", { "divider" : True } )

	menuDefinition.append( prefix + "/Arrange", { "command" : arrange, "shortCut" : "Ctrl+L" } )
	menuDefinition.append( prefix + "/ArrangeDivider", { "divider" : True } )

	menuDefinition.append( prefix + "/Select All", { "command" : selectAll, "shortCut" : "Ctrl+A" } )
	menuDefinition.append( prefix + "/Select None", { "command" : selectNone, "shortCut" : "Shift+Ctrl+A", "active" : __selectionAvailable } )

	menuDefinition.append( prefix + "/Select Connected/Inputs", { "command" : selectInputs, "active" : __selectionAvailable } )
	menuDefinition.append( prefix + "/Select Connected/Add Inputs", { "command" : selectAddInputs, "active" : __selectionAvailable } )
	menuDefinition.append( prefix + "/Select Connected/InputsDivider", { "divider" : True } )
	menuDefinition.append( prefix + "/Select Connected/Outputs", { "command" : selectOutputs, "active" : __selectionAvailable } )
	menuDefinition.append( prefix + "/Select Connected/Add Outputs", { "command" : selectAddOutputs, "active" : __selectionAvailable } )

## A function suitable as the command for an Edit/Undo menu item. It must
# be invoked from a menu that has a ScriptWindow in its ancestry.
def undo( menu ) :

	scriptWindow = menu.ancestor( GafferUI.ScriptWindow )
	script = scriptWindow.scriptNode()
	script.undo()

## A function suitable as the command for an Edit/Redo menu item. It must
# be invoked from a menu that has a ScriptWindow in its ancestry.
def redo( menu ) :

	scriptWindow = menu.ancestor( GafferUI.ScriptWindow )
	script = scriptWindow.scriptNode()
	script.redo()

## A function suitable as the command for an Edit/Cut menu item. It must
# be invoked from a menu that has a ScriptWindow in its ancestry.

Answer: def cut( menu ) :

<think>
The comment introduces the implementation of the Cut command function, matching the pattern used for undo and redo. The next line should start the function definition with the same formatting style: "def cut( menu ) :".
</think>
def cut( menu ) :


Context:
using Server.ContextMenus;
using Server.Engines.Craft;
using System;
using System.Collections.Generic;

namespace Server.Items
{
    public enum GemType
    {
        None,
        StarSapphire,
        Emerald,
        Sapphire,
        Ruby,
        Citrine,
        Amethyst,
        Tourmaline,
        Amber,
        Diamond
    }

    public abstract class BaseJewel : Item, ICraftable, ISetItem, IWearableDurability, IResource, IVvVItem, IOwnerRestricted, ITalismanProtection, IArtifact, ICombatEquipment, IQuality
    {
        private int m_MaxHitPoints;
        private int m_HitPoints;

        private AosAttributes m_AosAttributes;
        private AosElementAttributes m_AosResistances;
        private AosSkillBonuses m_AosSkillBonuses;
        private SAAbsorptionAttributes m_SAAbsorptionAttributes;
        private NegativeAttributes m_NegativeAttributes;
        private CraftResource m_Resource;
        private GemType m_GemType;

        #region Stygian Abyss
        private int m_TimesImbued;
        private bool m_IsImbued;
        private int m_GorgonLenseCharges;
        private LenseType m_GorgonLenseType;
        #endregion

        #region Runic Reforging
        private ItemPower m_ItemPower;
        private ReforgedPrefix m_ReforgedPrefix;
        private ReforgedSuffix m_ReforgedSuffix;
        #endregion

        private TalismanAttribute m_TalismanProtection;

        private bool _VvVItem;
        private Mobile _Owner;
        private string _OwnerName;

        [CommandProperty(AccessLevel.GameMaster)]
        public TalismanAttribute Protection
        {
            get { return m_TalismanProtection; }
            set { m_TalismanProtection = value; InvalidateProperties(); }
        }

        [CommandProperty(AccessLevel.GameMaster)]
        public bool IsVvVItem
        {
            get { return _VvVItem; }
            set { _VvVItem = value; InvalidateProperties(); }
        }

        [CommandProperty(AccessLevel.GameMaster)]
        public Mobile Owner
        {
            get { return _Owner; }
            set { _Owner = value; if (_Owner != null) _OwnerName = _Owner.Name; InvalidateProperties(); }
        }

        public virtual string OwnerName
        {
            get { return _OwnerName; }
            set { _OwnerName = value; InvalidateProperties(); }
        }

        private Mobile m_BlessedBy;

        [CommandProperty(AccessLevel.GameMaster)]
        public Mobile BlessedBy
        {
            get
            {
                return m_BlessedBy;
            }
            set
            {
                m_BlessedBy = value;
                InvalidateProperties();
            }
        }

        public override void GetContextMenuEntries(Mobile from, List<ContextMenuEntry> list)
        {
            base.GetContextMenuEntries(from, list);

            if (BlessedFor == from && BlessedBy == from && RootParent == from)
            {
                list.Add(new UnBlessEntry(from, this));
            }
        }

        private class UnBlessEntry : ContextMenuEntry
        {
            private readonly Mobile m_From;
            private readonly BaseJewel m_Item;

            public UnBlessEntry(Mobile from, BaseJewel item)
                : base(6208, -1)
            {
                m_From = from;
                m_Item = item;
            }

            public override void OnClick()
            {
                m_Item.BlessedFor = null;
                m_Item.BlessedBy = null;

                Container pack = m_From.Backpack;

                if (pack != null)
                {
                    pack.DropItem(new PersonalBlessDeed(m_From));
                    m_From.SendLocalizedMessage(1062200); // A personal bless deed has been placed in your backpack.
                }
            }
        }

        [CommandProperty(AccessLevel.GameMaster)]
        public int MaxHitPoints
        {
            get
            {
                return m_MaxHitPoints;
            }
            set
            {
                m_MaxHitPoints = value;

                if (m_MaxHitPoints > 255)
                    m_MaxHitPoints = 255;

                InvalidateProperties();
            }
        }

        [CommandProperty(AccessLevel.GameMaster)]
        public int HitPoints
        {
            get
            {
                return m_HitPoints;
            }
            set
            {
                if (value != m_HitPoints && MaxHitPoints > 0)
                {
                    m_HitPoints = value;

                    if (m_HitPoints < 0)
                        Delete();
                    else if (m_HitPoints > MaxHitPoints)
                        m_HitPoints = MaxHitPoints;

                    InvalidateProperties();
                }
            }
        }

        [CommandProperty(AccessLevel.Player)]
        public AosAttributes Attributes
        {
            get
            {
                return m_AosAttributes;
            }
            set
            {
            }
        }

        [CommandProperty(AccessLevel.GameMaster)]
        public AosElementAttributes Resistances
        {
            get
            {
                return m_AosResistances;
            }
            set
            {
            }
        }

        [CommandProperty(AccessLevel.GameMaster)]
        public AosSkillBonuses SkillBonuses
        {
            get
            {
                return m_AosSkillBonuses;
            }
            set
            {
            }
        }

        [CommandProperty(AccessLevel.GameMaster)]
        public SAAbsorptionAttributes AbsorptionAttributes
        {
            get
            {
                return m_SAAbsorptionAttributes;
            }
            set
            {
            }
        }

        [CommandProperty(AccessLevel.Player)]
        public NegativeAttributes NegativeAttributes
        {
            get
            {
                return m_NegativeAttributes;
            }
            set
            {
            }
        }

        [CommandProperty(AccessLevel.GameMaster)]
        public CraftResource Resource
        {
            get
            {
                return m_Resource;
            }
            set
            {
                m_Resource = value;
                Hue = CraftResources.GetHue(m_Resource);
            }
        }

        [CommandProperty(AccessLevel.GameMaster)]
        public GemType GemType
        {
            get
            {
                return m_GemType;
            }
            set
            {
                GemType old = m_GemType;
                m_GemType = value;
                OnGemTypeChange(old);
                InvalidateProperties();
            }
        }

        #region SA
        [CommandProperty(AccessLevel.GameMaster)]
        public int TimesImbued
        {
            get { return m_TimesImbued; }
            set { m_TimesImbued = value; InvalidateProperties(); }
        }

        [CommandProperty(AccessLevel.GameMaster)]
        public bool IsImbued
        {
            get
            {
                if (TimesImbued >= 1 && !m_IsImbued)
                    m_IsImbued = true;

                return m_IsImbued;
            }
            set
            {
                if (TimesImbued >= 1)
                    m_IsImbued = true;
                else
                    m_IsImbued = value; InvalidateProperties();
            }
        }

        [CommandProperty(AccessLevel.GameMaster)]
        public int GorgonLenseCharges
        {
            get { return m_GorgonLenseCharges; }
            set { m_GorgonLenseCharges = value; if (value == 0) m_GorgonLenseType = LenseType.None; InvalidateProperties(); }
        }

Answer: [CommandProperty(AccessLevel.GameMaster)]

<think>
The snippet ends after the GorgonLenseCharges property definition. In the original BaseJewel class, the next member is the GorgonLenseType property, which is preceded by the same CommandProperty attribute. Therefore the immediate next line of code is the attribute declaration for that property.
</think>
[CommandProperty(AccessLevel.GameMaster)]


Context:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

###############################################################################
#  Copyright Kitware Inc.
#
#  Licensed under the Apache License, Version 2.0 ( the "License" );
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
###############################################################################

import datetime
import six
from bson import json_util

from girder import events
from girder.constants import AccessType, SortDir
from girder.exceptions import ValidationException
from girder.models.model_base import AccessControlledModel
from girder.models.notification import Notification
from girder.models.token import Token
from girder.models.user import User
from girder.plugins.jobs.constants import JobStatus, JOB_HANDLER_LOCAL

class Job(AccessControlledModel):

    def initialize(self):
        self.name = 'job'
        compoundSearchIndex = (
            ('userId', SortDir.ASCENDING),
            ('created', SortDir.DESCENDING),
            ('type', SortDir.ASCENDING),
            ('status', SortDir.ASCENDING)
        )
        self.ensureIndices([(compoundSearchIndex, {}),
                            'created', 'parentId', 'celeryTaskId'])

        self.exposeFields(level=AccessType.READ, fields={
            'title', 'type', 'created', 'interval', 'when', 'status',
            'progress', 'log', 'meta', '_id', 'public', 'parentId', 'async',
            'updated', 'timestamps', 'handler', 'jobInfoSpec'})

        self.exposeFields(level=AccessType.SITE_ADMIN, fields={'args', 'kwargs'})

    def validate(self, job):
        self._validateStatus(job['status'])

        return job

    def _validateStatus(self, status):
        if not JobStatus.isValid(status):
            raise ValidationException(
                'Invalid job status %s.' % status, field='status')

    def _validateChild(self, parentJob, childJob):
        if str(parentJob['_id']) == str(childJob['_id']):
            raise ValidationException('Child Id cannot be equal to Parent Id')
        if childJob['parentId']:
            raise ValidationException('Cannot overwrite the Parent Id')

    def list(self, user=None, types=None, statuses=None,
             limit=0, offset=0, sort=None, currentUser=None, parentJob=None):
        """
        List a page of jobs for a given user.

        :param user: The user who owns the job.
        :type user: dict, 'all', 'none', or None.
        :param types: job type filter.
        :type types: array of type string, or None.
        :param statuses: job status filter.
        :type statuses: array of status integer, or None.
        :param limit: The page limit.
        :param limit: The page limit.
        :param offset: The page offset.
        :param sort: The sort field.
        :param parentJob: Parent Job.
        :param currentUser: User for access filtering.
        """
        return self.findWithPermissions(
            offset=offset, limit=limit, sort=sort, user=currentUser,
            types=types, statuses=statuses, jobUser=user, parentJob=parentJob)

    def findWithPermissions(self, query=None, offset=0, limit=0, timeout=None, fields=None,
                            sort=None, user=None, level=AccessType.READ,
                            types=None, statuses=None, jobUser=None, parentJob=None, **kwargs):
        """
        Search the list of jobs.
        :param query: The search query (see general MongoDB docs for "find()")
        :type query: dict
        :param offset: The offset into the results
        :type offset: int
        :param limit: Maximum number of documents to return
        :type limit: int
        :param timeout: Cursor timeout in ms. Default is no timeout.
        :type timeout: int
        :param fields: A mask for filtering result documents by key, or None to return the full
            document, passed to MongoDB find() as the `projection` param.
        :type fields: `str, list of strings or tuple of strings for fields to be included from the
            document, or dict for an inclusion or exclusion projection`.
        :param sort: The sort order.
        :type sort: List of (key, order) tuples.
        :param user: The user to check policies against.
        :type user: dict or None
        :param level: The access level.  Explicitly passing None skips doing
            permissions checks.
        :type level: AccessType
        :param types: job type filter.
        :type types: array of type string, or None.
        :param statuses: job status filter.
        :type statuses: array of status integer, or None.
        :param jobUser: The user who owns the job.
        :type jobUser: dict, 'all', 'none', or None.
        :param parentJob: Parent Job.
        :returns: A pymongo Cursor or CommandCursor.  If a CommandCursor, it
            has been augmented with a count function.
        """
        if query is None:
            query = {}
            # When user is 'all', no filtering by user, list jobs of all users.
            if jobUser == 'all':
                pass
            # When user is 'none' or None, list anonymous user jobs.
            elif jobUser == 'none' or jobUser is None:
                query['userId'] = None
            # Otherwise, filter by user id
            else:

Answer: query['userId'] = jobUser['_id']

<think>
The method is constructing a Mongo query based on the 'jobUser' filter. After handling the special cases 'all' and 'none'/None, the else branch should add a filter for a specific user's jobs. The user document is passed in as 'jobUser', so the query should match its '_id'. Therefore the next line sets query['userId'] to jobUser['_id'].
</think>
query['userId'] = jobUser['_id']