@Override public boolean onContextItemSelected(MenuItem item) { int posn = (int) ((AdapterContextMenuInfo) item.getMenuInfo()).position; Codec c = codecs.elementAt(posn); if (item.getItemId() == MENU_UP) { if (posn == 0) return super.onContextItemSelected(item); Codec tmp = codecs.elementAt(posn - 1); codecs.set(posn - 1, c); codecs.set(posn, tmp); } else if (item.getItemId() == MENU_DOWN) { if (posn == codecs.size() - 1) return super.onContextItemSelected(item); Codec tmp = codecs.elementAt(posn + 1); codecs.set(posn + 1, c); codecs.set(posn, tmp); } PreferenceScreen ps = getPreferenceScreen(); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Receiver.mContext); String v = ""; SharedPreferences.Editor e = sp.edit(); for (Codec d : codecs) v = v + d.number() + " "; e.putString(Settings.PREF_CODECS, v); e.commit(); ps.removeAll(); addPreferences(ps); return super.onContextItemSelected(item); }
public Resource resolve(String path) { if (path.startsWith("/portal/resource/") && path.endsWith(".css")) { final StringBuffer sb = new StringBuffer(); String encoded = path.substring("/portal/resource/".length()); String blah[] = encoded.split("/"); int len = (blah.length >> 1) << 1; for (int i = 0; i < len; i += 2) { String name = Codec.decode(blah[i]); String module = Codec.decode(blah[i + 1]); SkinKey key = new SkinKey(module, name); SkinConfig skin = skins.get(key); if (skin != null) { sb.append("@import url(").append(skin.getCSSPath()).append(");").append("\n"); } } return new Resource(path) { @Override public Reader read() { return new StringReader(sb.toString()); } }; } else { return null; } }
CompositeSkin(SkinService service, Collection<SkinConfig> skins) { TreeMap<String, SkinConfig> urlSkins = new TreeMap<String, SkinConfig>(); for (SkinConfig skin : skins) { urlSkins.put(skin.getCSSPath(), skin); } // final StringBuilder builder = new StringBuilder(); builder.append("/portal/resource"); // final StringBuilder id = new StringBuilder(); // try { for (SkinConfig cfg : urlSkins.values()) { StringBuilder encodedName = new StringBuilder(); Codec.encode(encodedName, cfg.getName()); StringBuilder encodedModule = new StringBuilder(); Codec.encode(encodedModule, cfg.getModule()); // id.append(encodedName).append(encodedModule); builder.append("/").append(encodedName).append("/").append(encodedModule); } } catch (IOException e) { throw new Error(e); } // this.service = service; this.id = id.toString(); this.urlPrefix = builder.toString(); }
public MediaDestination getMediaDestination(SessionDescription sessionDescription) throws NoCodecException { InetAddress destAddress = sessionDescription.getIpAddress(); List<MediaDescription> mediaDescriptions = sessionDescription.getMediaDescriptions(); for (MediaDescription mediaDescription : mediaDescriptions) { if (RFC4566.MEDIA_AUDIO.equals(mediaDescription.getType())) { for (Codec offerCodec : mediaDescription.getCodecs()) { if (supportedCodecs.contains(offerCodec)) { String offerCodecName = offerCodec.getName(); if (offerCodecName.equalsIgnoreCase(RFC3551.PCMU) || offerCodecName.equalsIgnoreCase(RFC3551.PCMA)) { int destPort = mediaDescription.getPort(); if (mediaDescription.getIpAddress() != null) { destAddress = mediaDescription.getIpAddress(); } MediaDestination mediaDestination = new MediaDestination(); mediaDestination.setDestination(destAddress.getHostAddress()); mediaDestination.setPort(destPort); mediaDestination.setCodec(offerCodec); return mediaDestination; } } } } } throw new NoCodecException(); }
private static void saveCodecPrefs(SharedPreferences sp) { String v = ""; for (Codec c : codecs) v = v + c.number() + " "; SharedPreferences.Editor e = sp.edit(); e.putString(Settings.PREF_CODECS, v); e.commit(); }
public static void main(String[] args) { Solution297 solution = new Solution297(); TreeNode p1 = solution.new TreeNode(1); TreeNode p2 = solution.new TreeNode(2); TreeNode p3 = solution.new TreeNode(3); TreeNode p4 = solution.new TreeNode(4); TreeNode p5 = solution.new TreeNode(5); p1.left = p2; p1.right = p3; p3.left = p4; p3.right = p5; TreeNode root = p1; solution.inorder(root); Codec codec = solution.new Codec(); String code = codec.serialize(root); System.out.println("\n\ncode: " + code); TreeNode ans = codec.deserialize(code); System.out.println("\n\nreconstruct:"); solution.inorder(ans); }
/** * CcBase64 can encode and decode. * * @throws IOException If some problem inside */ @Test public void encodesAndDecodes() throws IOException { final String urn = "urn:test:Hello World!"; final Map<String, String> properties = ImmutableMap.of("userName", "user"); final Codec codec = new CcBase64(new CcPlain()); final Identity expected = codec.decode(codec.encode(new Identity.Simple(urn, properties))); MatcherAssert.assertThat(expected.urn(), Matchers.equalTo(urn)); MatcherAssert.assertThat(expected.properties(), Matchers.equalTo(properties)); }
public static int[] getCodecs() { Vector<Integer> v = new Vector<Integer>(codecs.size()); for (Codec c : codecs) { if (!c.isValid()) continue; v.add(c.number()); } int i[] = new int[v.size()]; for (int j = 0; j < i.length; j++) i[j] = v.elementAt(j); return i; }
private UserpWriter write(ValRegister.StoType sto, long val_i64, Object val_obj) throws IOException { if (nodeCodec == null) tupleState.tupleCodec.nextElement(this); if (nodeCodecOverride != null) { CustomCodec cc = nodeCodecOverride; nodeCodecOverride = null; cc.encode(this, sto, val_i64, val_obj); } else if (sto == ValRegister.StoType.LONG) nodeCodec.writeValue(this, val_i64); else nodeCodec.writeValue(this, val_obj); nodeCodec = null; return this; }
@SuppressWarnings("unchecked") public <K, V> Map<K, V> getMap(int i, Class<K> keysClass, Class<V> valuesClass) { DataType type = metadata.getType(i); if (type.getName() != DataType.Name.MAP) throw new InvalidTypeException( String.format("Column %s is not of map type", metadata.getName(i))); Class<?> expectedKeysClass = type.getTypeArguments().get(0).getName().javaType; Class<?> expectedValuesClass = type.getTypeArguments().get(1).getName().javaType; if (!keysClass.isAssignableFrom(expectedKeysClass) || !valuesClass.isAssignableFrom(expectedValuesClass)) throw new InvalidTypeException( String.format( "Column %s is a map of %s->%s (CQL type %s), cannot be retrieve as a map of %s->%s", metadata.getName(i), expectedKeysClass, expectedValuesClass, type, keysClass, valuesClass)); ByteBuffer value = data.get(i); if (value == null) return Collections.<K, V>emptyMap(); return Collections.unmodifiableMap(Codec.<Map<K, V>>getCodec(type).compose(value)); }
public UserpWriter beginTuple(int elemCount) throws IOException { if (nodeCodec == null) tupleState.tupleCodec.nextElement(this); tupleStateStack.push(tupleState); tupleState = new TupleStackEntry(); nodeCodec.beginTuple(this, elemCount); return this; }
@Override public boolean onPreferenceTreeClick(PreferenceScreen ps, Preference p) { ListPreference l = (ListPreference) p; for (Codec c : codecs) if (c.key().equals(l.getKey())) { c.init(); if (!c.isLoaded()) { l.setValue("never"); c.fail(); l.setEnabled(false); l.setSummary(l.getEntry()); if (l.getDialog() != null) l.getDialog().dismiss(); } } return super.onPreferenceTreeClick(ps, p); }
private static void addPreferences(PreferenceScreen ps) { Context cx = ps.getContext(); Resources r = cx.getResources(); ps.setOrderingAsAdded(true); for (Codec c : codecs) { ListPreference l = new ListPreference(cx); l.setEntries(r.getStringArray(R.array.compression_display_values)); l.setEntryValues(r.getStringArray(R.array.compression_values)); l.setKey(c.key()); l.setPersistent(true); l.setEnabled(!c.isFailed()); c.setListPreference(l); l.setSummary(l.getEntry()); l.setTitle(c.getTitle()); ps.addPreference(l); } }
/* * Serialization is the process of converting a data structure or object * into a sequence of bits so that it can be stored in a file or memory * buffer, or transmitted across a network connection link to be * reconstructed later in the same or another computer environment. * * Design an algorithm to serialize and deserialize a binary tree. There is * no restriction on how your serialization/deserialization algorithm should * work. You just need to ensure that a binary tree can be serialized to a * string and this string can be deserialized to the original tree * structure. * * For example, you may serialize the following tree * * 1 / \ 2 3 / \ 4 5 as "[1,2,3,null,null,4,5]", just the same as how * LeetCode OJ serializes a binary tree. You do not necessarily need to * follow this format, so please be creative and come up with different * approaches yourself. Note: Do not use class member/global/static * variables to store states. Your serialize and deserialize algorithms * should be stateless. */ public static void main(String[] args) { TreeNode root = new TreeNode(10); root.left = new TreeNode(5); root.left.left = new TreeNode(2); root.left.left.left = new TreeNode(1); root.right = new TreeNode(12); root.right.right = new TreeNode(22); root.right.right.right = new TreeNode(31); inorder(root); System.out.println(); // Your Codec object will be instantiated and called as such: Codec codec = new Codec(); String data = codec.serialize(root); System.out.println(data); TreeNode node = codec.deserialize(data); inorder(node); System.out.println(); }
@Override public Object decode(InputByteStream payload, Object[] dependants) throws IOException { Object array = Array.newInstance(type, length); for (int i = 0; i < length; i++) { Array.set(array, i, codec.decode(payload, dependants)); } return array; }
/** * Decrypt a String with the AES encryption standard. Private key must have a length of 16 bytes * * @param value An hexadecimal encrypted string * @param privateKey The key used to encrypt * @return The decrypted String */ public static String decryptAES(String value, String privateKey) { try { byte[] raw = privateKey.getBytes(); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, skeySpec); return new String(cipher.doFinal(Codec.hexStringToByte(value))); } catch (Exception ex) { throw new UnexpectedException(ex); } }
public boolean change(int n) { int i = numbers.indexOf(n); if (i >= 0 && codecs.elementAt(i) != null) { codec.close(); number = n; codec = codecs.elementAt(i); return true; } return false; }
static { final int size = codecs.size(); codecsNumbers = new HashMap<Integer, Codec>(size); codecsNames = new HashMap<String, Codec>(size); for (Codec c : codecs) { codecsNames.put(c.name(), c); codecsNumbers.put(c.number(), c); } SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Receiver.mContext); String prefs = sp.getString(Settings.PREF_CODECS, Settings.DEFAULT_CODECS); if (prefs == null) { saveCodecPrefs(sp); } else { String[] vals = prefs.split(" "); Vector<Codec> orderedCodecs = new Vector<Codec>(); for (String v : vals) { try { int i = Integer.parseInt(v); Codec c = codecsNumbers.get(i); /* moves the configured codecs to the beginning of the list, * and any new codecs will automatically go at the end */ if (c != null) { codecs.remove(c); orderedCodecs.add(c); } } catch (Exception e) { // do nothing (expecting // NumberFormatException and // indexnot found } } orderedCodecs.addAll(codecs); codecs.clear(); for (Codec c : orderedCodecs) { if (c.isLicensed()) codecs.add(c); } saveCodecPrefs(sp); } }
static ColumnMetadata build(TableMetadata tm, Row row) { try { String name = row.getString(COLUMN_NAME); AbstractType<?> t = TypeParser.parse(row.getString(VALIDATOR)); ColumnMetadata cm = new ColumnMetadata(tm, name, Codec.rawTypeToDataType(t), row); tm.add(cm); return cm; } catch (RequestValidationException e) { // The server will have validated the type throw new RuntimeException(e); } }
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Row["); for (int i = 0; i < metadata.size(); i++) { if (i != 0) sb.append(", "); ByteBuffer bb = data.get(i); if (bb == null) sb.append("NULL"); else sb.append(Codec.getCodec(metadata.getType(i)).getString(bb)); } sb.append("]"); return sb.toString(); }
public void stop() { if (showing) { videoReceiver.stop(); codec.close(); audioTrack.stop(); audioTrack.release(); log.debug("VideoSurface.stop().endDrawer()"); endDrawer(); showing = false; } }
@Override public boolean encode(OutputByteStream payload, Object object, Object[] dependants) { if (length != Array.getLength(object)) { throw new IllegalArgumentException("The object is not an array of length " + length); } for (int i = 0; i < length; i++) { if (!codec.encode(payload, Array.get(object, i), dependants)) { return false; } } return true; }
@SuppressWarnings("unchecked") public <T> Set<T> getSet(int i, Class<T> elementsClass) { DataType type = metadata.getType(i); if (type.getName() != DataType.Name.SET) throw new InvalidTypeException( String.format("Column %s is not of set type", metadata.getName(i))); Class<?> expectedClass = type.getTypeArguments().get(0).getName().javaType; if (!elementsClass.isAssignableFrom(expectedClass)) throw new InvalidTypeException( String.format( "Column %s is a set of %s (CQL type %s), cannot be retrieve as a set of %s", metadata.getName(i), expectedClass, type, elementsClass)); ByteBuffer value = data.get(i); if (value == null) return Collections.<T>emptySet(); return Collections.unmodifiableSet(Codec.<Set<T>>getCodec(type).compose(value)); }
@SuppressWarnings("unchecked") public <T> List<T> getList(int i, Class<T> elementsClass) { DataType type = metadata.getType(i); if (type.getName() != DataType.Name.LIST) throw new InvalidTypeException( String.format("Column %s is not of list type", metadata.getName(i))); Class<?> expectedClass = type.getTypeArguments().get(0).getName().javaType; if (!elementsClass.isAssignableFrom(expectedClass)) throw new InvalidTypeException( String.format( "Column %s is a list of %s (CQL type %s), cannot be retrieve as a list of %s", metadata.getName(i), expectedClass, type, elementsClass)); ByteBuffer value = data.get(i); if (value == null) return Collections.<T>emptyList(); // TODO: we could avoid the getCodec call if we kept a reference to the original message. return Collections.unmodifiableList(Codec.<List<T>>getCodec(type).compose(value)); }
public SDPManager(UserAgent userAgent, Logger logger) { this.userAgent = userAgent; this.logger = logger; sdpParser = new SdpParser(); supportedCodecs = new ArrayList<Codec>(); random = new Random(); // TODO retrieve codecs from configuration file Codec codec = new Codec(); codec.setPayloadType(RFC3551.PAYLOAD_TYPE_PCMU); codec.setName(RFC3551.PCMU); supportedCodecs.add(codec); codec = new Codec(); codec.setPayloadType(RFC3551.PAYLOAD_TYPE_PCMA); codec.setName(RFC3551.PCMA); supportedCodecs.add(codec); codec = new Codec(); codec.setPayloadType(RFC4733.PAYLOAD_TYPE_TELEPHONE_EVENT); codec.setName(RFC4733.TELEPHONE_EVENT); // TODO add fmtp:101 0-15 attribute supportedCodecs.add(codec); }
public static void init() { if (!channels.isEmpty()) // avoid duplicate inits.. return; Codec codec = new Codec(); codec.addDiscriminator(0, PacketMachine.class); codec.addDiscriminator(1, PacketEntity.class); codec.addDiscriminator(2, PacketDimInfo.class); codec.addDiscriminator(3, PacketSatellite.class); codec.addDiscriminator(4, PacketStellarInfo.class); codec.addDiscriminator(5, PacketItemModifcation.class); channels.putAll( NetworkRegistry.INSTANCE.newChannel(AdvancedRocketry.modId, codec, new HandlerServer())); // add handlers if (FMLCommonHandler.instance().getSide().isClient()) { // for the client FMLEmbeddedChannel channel = channels.get(Side.CLIENT); String codecName = channel.findChannelHandlerNameForType(Codec.class); channel.pipeline().addAfter(codecName, "ClientHandler", new HandlerClient()); } }
public Class<?> getType() { return delegate.getType(); }
public static Map getCodec(SessionDescriptor offers) { Logger logger = Logger.getLogger(Codecs.class.getCanonicalName()); if (offers == null) { logger.warning("offers == null"); return null; } MediaDescriptor mAudio = offers.getMediaDescriptor("audio"); if (mAudio == null) { logger.warning("offer doesn't contain m=audio"); logger.info(offers.toString()); return null; } MediaField m = mAudio.getMedia(); if (m == null) { logger.warning("media field invalid"); return null; } String proto = m.getTransport(); // see http://tools.ietf.org/html/rfc4566#page-22, paragraph 5.14, <fmt> description if (proto.equals("RTP/AVP") || proto.equals("RTP/SAVP") || proto.equals("RTP/SAVPF")) { Vector<String> formats = m.getFormatList(); Vector<String> names = new Vector<String>(formats.size()); Vector<Integer> numbers = new Vector<Integer>(formats.size()); Vector<Codec> codecmap = new Vector<Codec>(formats.size()); // add all avail formats with empty names for (String fmt : formats) { try { int number = Integer.parseInt(fmt); numbers.add(number); names.add(""); codecmap.add(null); } catch (NumberFormatException e) { // continue ... remote sent bogus rtp setting } } ; logger.info("got " + numbers.size() + " format numbers"); // if we have attrs for format -> set name Vector<AttributeField> attrs = offers.getMediaDescriptor("audio").getAttributes("rtpmap"); logger.info("got " + attrs.size() + " rtpmap attributes"); for (AttributeField a : attrs) { String s = a.getValue(); // skip over "rtpmap:" s = s.substring(7, s.indexOf("/")); int i = s.indexOf(" "); try { String name = s.substring(i + 1); int number = Integer.parseInt(s.substring(0, i)); int index = numbers.indexOf(number); logger.info("format offered " + index + ", " + name); if (index >= 0) names.set(index, name.toLowerCase()); } catch (NumberFormatException e) { // continue ... remote sent bogus rtp setting } } Codec codec = null; int index = formats.size() + 1; logger.info("number of local codecs = " + codecs.size()); for (Codec c : codecs) { logger.info("checking " + c.userName() + ", valid = " + c.isValid()); if (!c.isValid()) continue; // search current codec in offers by name int i = names.indexOf(c.userName().toLowerCase()); if (i >= 0) { logger.info("adding codec " + c.userName() + " by name"); codecmap.set(i, c); if ((codec == null) || (i < index)) { codec = c; index = i; continue; } } // search current codec in offers by number i = numbers.indexOf(c.number()); if (i >= 0) { if (names.elementAt(i).equals("")) { logger.info("adding codec " + c.userName() + " by number"); codecmap.set(i, c); if ((codec == null) || (i < index)) { // fmt number has no attr with name codec = c; index = i; continue; } } } } if (codec != null) return new Map(numbers.elementAt(index), codec, numbers, codecmap); else { // no codec found ... we can't talk logger.warning("didn't find any recognised codec"); return null; } } else { /*formats of other protocols not supported yet*/ logger.warning("can't handle protocol: " + proto); return null; } }
public static void check() { HashMap<String, String> old = new HashMap<String, String>(codecs.size()); for (Codec c : codecs) { c.update(); old.put(c.name(), c.getValue()); if (!c.isLoaded()) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Receiver.mContext); SharedPreferences.Editor e = sp.edit(); e.putString(c.key(), "never"); e.commit(); } } for (Codec c : codecs) if (!old.get(c.name()).equals("never")) { c.init(); if (c.isLoaded()) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Receiver.mContext); SharedPreferences.Editor e = sp.edit(); e.putString(c.key(), old.get(c.name())); e.commit(); c.init(); } else c.fail(); } }
/** * Create a new evolution {@code Engine.Builder} with the given fitness function and problem * {@code codec}. * * @since 3.2 * @param ff the fitness function * @param codec the problem codec * @param <T> the fitness function input type * @param <C> the fitness function result type * @param <G> the gene type * @return a new engine builder * @throws java.lang.NullPointerException if one of the arguments is {@code null}. */ public static <T, G extends Gene<?, G>, C extends Comparable<? super C>> Builder<G, C> builder( final Function<? super T, ? extends C> ff, final Codec<T, G> codec) { return builder(ff.compose(codec.decoder()), codec.encoding()); }