hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
ec36cc93ae04f29c16d731b3fc8975b8d396cf24
4,048
package com.cerner.ccl.parser.text.documentation.parser; import com.cerner.ccl.parser.data.EnumeratedValue; import com.cerner.ccl.parser.exception.InvalidDocumentationException; import com.google.code.jetm.reporting.ext.PointFactory; import etm.core.monitor.EtmPoint; /** * A parser that produces {@link EnumeratedValue} objects out of the given line. * * @author Joshua Hyde * */ public class EnumeratedValueParser extends AbstractMultiTagParser<EnumeratedValue> { @Override protected boolean isParseable(final String line) { return line.startsWith("@value"); } @Override protected EnumeratedValue parseElement(final String line) { final EtmPoint point = PointFactory.getPoint(getClass(), "parseElement(String)"); try { final int firstSpace = line.indexOf(' '); if (firstSpace < 0) { throw new InvalidDocumentationException("No space found in value definition: " + line); } final int secondSpace = line.indexOf(' ', firstSpace + 1); // No documentation, just the value if (secondSpace < 0) { return new EnumeratedValue(decodeFieldValue(line.substring(firstSpace + 1))); } // If it's a string value, then find the location of the very last quotation mark if (line.charAt(firstSpace + 1) == '"') { return getStringValue(firstSpace + 1, line); } final String fieldValue = decodeFieldValue(line.substring(firstSpace + 1, secondSpace)); final String description = line.substring(secondSpace + 1); return new EnumeratedValue(fieldValue, description); } finally { point.collect(); } } /** * Remove any encoding or escaping of data from the given value. * * @param value * The line to be decoded. * @return The given value, decoded. */ private String decodeFieldValue(final String value) { return value.replaceAll("\"\"", "\""); } /** * If the actual enumerated value is a string value in quotes, parse out the value. * * @param startingPos * The position within the given line at which parsing should begin. * @param line * The string out of which the value is to be parsed. * @return An {@link EnumeratedValue} representing the parsed value. * @throws InvalidDocumentationException * If the string enumerated value does not have a closing quotation mark. */ private EnumeratedValue getStringValue(final int startingPos, final String line) { int endingPos = -1; for (int i = startingPos + 1, size = line.length(); i < size; i++) { if (line.charAt(i) == '"') { /* * Make sure that this isn't escaping another quotation. If it's at the end of the line, then it's got * to be the closing quotation or the next character is not a " character, then this really is the close * of the value. */ if (i == size - 1) { endingPos = i; break; } /* * If the next character is a quote, skip its consideration - this current character is merely escaping * it */ if (line.charAt(i + 1) == '"') { i++; continue; } endingPos = i; break; } } if (endingPos < 0) { throw new InvalidDocumentationException("Unable to find closing quotation of field value: " + line); } final String value = decodeFieldValue(line.substring(startingPos + 1, endingPos)); return endingPos + 2 >= line.length() ? new EnumeratedValue(value) : new EnumeratedValue(value, line.substring(endingPos + 2)); } }
36.8
120
0.578557
796acc37692e50006e819aab6250190b59d8120d
2,183
/* * Copyright 2020 the original author or authors. * * 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 * * https://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.springframework.amqp.rabbit.annotation; import org.springframework.amqp.rabbit.connection.SingleConnectionFactory; import org.springframework.amqp.rabbit.core.RabbitAdmin; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; /** * This test is an extension of {@link RabbitListenerAnnotationBeanPostProcessorTests} * in order to guarantee the compatibility of MultiRabbit with previous use cases. This * ensures that multirabbit does not break single rabbit applications. * * @author Wander Costa */ class MultiRabbitListenerAnnotationBeanPostProcessorCompatibilityTests extends RabbitListenerAnnotationBeanPostProcessorTests { @Override protected Class<?> getConfigClass() { return MultiConfig.class; } @Configuration @PropertySource("classpath:/org/springframework/amqp/rabbit/annotation/queue-annotation.properties") static class MultiConfig extends RabbitListenerAnnotationBeanPostProcessorTests.Config { @Bean @Override public MultiRabbitListenerAnnotationBeanPostProcessor postProcessor() { MultiRabbitListenerAnnotationBeanPostProcessor postProcessor = new MultiRabbitListenerAnnotationBeanPostProcessor(); postProcessor.setEndpointRegistry(rabbitListenerEndpointRegistry()); postProcessor.setContainerFactoryBeanName("testFactory"); return postProcessor; } @Bean public RabbitAdmin defaultRabbitAdmin() { return new RabbitAdmin(new SingleConnectionFactory()); } } }
36.383333
101
0.802565
58c938c570aa6da4132d6aab1da4c62b021b84a1
852
package java004; import java.util.Scanner; public class A01 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String text = sc.nextLine(); String textLow = text.toLowerCase(); String textResult = textLow.replaceAll(" ", ""); int consonant = 0, vowel = 0; for (int i = 0; i < textResult.length(); i++) { if ((textResult.charAt(i) == 'a') || (textResult.charAt(i) == 'e') || (textResult.charAt(i) == 'i') || (textResult.charAt(i) == 'o') || (textResult.charAt(i) == 'u')) { vowel++; } else if ((textResult.charAt(i) != 'a') || (textResult.charAt(i) != 'e') || (textResult.charAt(i) != 'i') || (textResult.charAt(i) != 'o') || (textResult.charAt(i) != 'u')){ consonant++; } } System.out.println("Consonant : " + consonant); System.out.println("Vowel : " + vowel); } }
29.37931
107
0.579812
0a7cff14cbf515389e83476bd1ac3d62235882e3
6,800
package com.mapswithme.maps.routing; import android.annotation.SuppressLint; import android.app.Dialog; import android.content.DialogInterface; import android.graphics.drawable.ColorDrawable; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AlertDialog; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.ExpandableListAdapter; import android.widget.ExpandableListView; import android.widget.TextView; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.mapswithme.maps.R; import com.mapswithme.maps.adapter.DisabledChildSimpleExpandableListAdapter; import com.mapswithme.maps.base.BaseMwmDialogFragment; import com.mapswithme.maps.downloader.CountryItem; import com.mapswithme.maps.downloader.MapManager; import com.mapswithme.util.StringUtils; import com.mapswithme.util.UiUtils; abstract class BaseRoutingErrorDialogFragment extends BaseMwmDialogFragment { static final String EXTRA_MISSING_MAPS = "MissingMaps"; private static final String GROUP_NAME = "GroupName"; private static final String GROUP_SIZE = "GroupSize"; private static final String COUNTRY_NAME = "CountryName"; final List<CountryItem> mMissingMaps = new ArrayList<>(); String[] mMapsArray; private boolean mCancelRoute = true; boolean mCancelled; void beforeDialogCreated(AlertDialog.Builder builder) {} void bindGroup(View view) {} private Dialog createDialog(AlertDialog.Builder builder) { View view = (mMissingMaps.size() == 1 ? buildSingleMapView(mMissingMaps.get(0)) : buildMultipleMapView()); builder.setView(view); return builder.create(); } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { parseArguments(); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()) .setCancelable(true) .setNegativeButton(android.R.string.cancel, null); beforeDialogCreated(builder); return createDialog(builder); } @Override public void onStart() { super.onStart(); AlertDialog dlg = (AlertDialog) getDialog(); dlg.getButton(DialogInterface.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mCancelled = true; dismiss(); } }); } @Override public void onDismiss(DialogInterface dialog) { if (mCancelled && mCancelRoute) RoutingController.get().cancel(); super.onDismiss(dialog); } void parseArguments() { Bundle args = getArguments(); mMapsArray = args.getStringArray(EXTRA_MISSING_MAPS); for (String map : mMapsArray) mMissingMaps.add(CountryItem.fill(map)); } View buildSingleMapView(CountryItem map) { @SuppressLint("InflateParams") final View countryView = View.inflate(getActivity(), R.layout.dialog_missed_map, null); ((TextView) countryView.findViewById(R.id.tv__title)).setText(map.name); final TextView szView = (TextView) countryView.findViewById(R.id.tv__size); szView.setText(MapManager.nativeIsLegacyMode() ? "" : StringUtils.getFileSizeString(map.totalSize)); ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) szView.getLayoutParams(); lp.rightMargin = 0; szView.setLayoutParams(lp); return countryView; } View buildMultipleMapView() { @SuppressLint("InflateParams") final View countriesView = View.inflate(getActivity(), R.layout.dialog_missed_maps, null); final ExpandableListView listView = (ExpandableListView) countriesView.findViewById(R.id.items_frame); if (mMissingMaps.isEmpty()) { mCancelRoute = false; UiUtils.hide(listView); UiUtils.hide(countriesView.findViewById(R.id.divider_top)); UiUtils.hide(countriesView.findViewById(R.id.divider_bottom)); return countriesView; } listView.setAdapter(buildAdapter()); listView.setChildDivider(new ColorDrawable(getResources().getColor(android.R.color.transparent))); UiUtils.waitLayout(listView, new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { final int width = listView.getWidth(); final int indicatorWidth = UiUtils.dimen(R.dimen.margin_quadruple); listView.setIndicatorBounds(width - indicatorWidth, width); if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) listView.setIndicatorBounds(width - indicatorWidth, width); else listView.setIndicatorBoundsRelative(width - indicatorWidth, width); } }); return countriesView; } private ExpandableListAdapter buildAdapter() { List<Map<String, String>> countries = new ArrayList<>(); long size = 0; boolean legacy = MapManager.nativeIsLegacyMode(); for (CountryItem item: mMissingMaps) { Map<String, String> data = new HashMap<>(); data.put(COUNTRY_NAME, item.name); countries.add(data); if (!legacy) size += item.totalSize; } Map<String, String> group = new HashMap<>(); group.put(GROUP_NAME, getString(R.string.maps) + " (" + mMissingMaps.size() + ") "); group.put(GROUP_SIZE, (legacy ? "" : StringUtils.getFileSizeString(size))); List<Map<String, String>> groups = new ArrayList<>(); groups.add(group); List<List<Map<String, String>>> children = new ArrayList<>(); children.add(countries); return new DisabledChildSimpleExpandableListAdapter(getActivity(), groups, R.layout.item_missed_map_group, R.layout.item_missed_map, new String[] { GROUP_NAME, GROUP_SIZE }, new int[] { R.id.tv__title, R.id.tv__size }, children, R.layout.item_missed_map, new String[] { COUNTRY_NAME }, new int[] { R.id.tv__title }) { @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { View res = super.getGroupView(groupPosition, isExpanded, convertView, parent); bindGroup(res); return res; } }; } }
33.830846
106
0.655294
c1b4bbf42ca628b87e150ddb6271f7b8f62891bb
2,981
import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; /** * * @author yahao.sun * */ public class Question2 { public List<String> getDirectFriendsForUser(String user) { return new ArrayList<String>(); } public List<String> getAttendedCoursesForUser(String user) { return new ArrayList<String>(); } public List<String> getRankedCourses(String user) { // the spacial complexity of the algorithm is // O(socialNetworkSize*courseListSize), hard to predict // assume the two external methods consumes constant time, // the time complexity is O(nlogn) where n is // socialNetworkSize*courseListSize // set to store the user's social network of 2nd-level link Set<String> socialSet = new HashSet<String>(); // get the first level contact list for user List<String> firstContactList = this.getDirectFriendsForUser(user); socialSet.addAll(firstContactList); // get the 2nd level contact list for user for (String firstFriend : firstContactList) { socialSet.addAll(this.getDirectFriendsForUser(firstFriend)); } // remove user itself, now we get a complete set for user's social // network socialSet.remove(user); // a map to store the courses and the attend times of which the user's // social network attended Map<String, Integer> courseMap = new HashMap<String, Integer>(); for (String nu : socialSet) { List<String> courses = this.getAttendedCoursesForUser(nu); for (String c : courses) { if (courseMap.containsKey(c)) { courseMap.put(c, courseMap.get(c) + 1); } else { courseMap.put(c, 1); } } } // remove the courses that user itself attended List<String> attendedCourses = this.getAttendedCoursesForUser(user); for (String ac : attendedCourses) { courseMap.remove(ac); } // use a TreeMap to get the reverse order of <attendTimes,courseName> Map<Integer, String> courseOrderMap = new TreeMap<Integer, String>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { if (o2 > o1) { return 1; } else if (o1 > o2) { return -1; } else { return 0; } } }); for (String c : courseMap.keySet()) { courseOrderMap.put(courseMap.get(c), c); } // return the ordered values(course names) return new ArrayList<String>(courseOrderMap.values()); } public static void main(String[] args) { } }
34.662791
102
0.591412
fc4fee7e2f4cfbad4e23c320eb2679ce29b1067e
2,216
package com.example.demo.controller; import com.example.demo.model.User; import com.example.demo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import javax.servlet.http.HttpServletRequest; import java.util.List; @Controller public class FollowController { @Autowired private UserService userService; /* the following method, which will be called whenever we make a post request to /follow/{username} */ @PostMapping(value = "/follow/{username}") public String follow(@PathVariable(value="username") String username, HttpServletRequest request) { /* call the UserService to get the currently logged in user as well as the user we want to follow */ User loggedInUser = userService.getLoggedInUser(); User userToFollow = userService.findByUsername(username); /* get all of the userToFollow's current followers, add the currently logged in user to the list, and then reassign the updated list to userToFollow */ List<User> followers = userToFollow.getFollowers(); followers.add(loggedInUser); userToFollow.setFollowers(followers); /* save userToFollow to flush our changes to the database and redirect to the last page */ userService.save(userToFollow); return "redirect:" + request.getHeader("Referer"); } @PostMapping(value = "/unfollow/{username}") public String unfollow(@PathVariable(value="username") String username, HttpServletRequest request) { User loggedInUser = userService.getLoggedInUser(); User userToUnfollow = userService.findByUsername(username); List<User> followers = userToUnfollow.getFollowers(); followers.remove(loggedInUser); userToUnfollow.setFollowers(followers); userService.save(userToUnfollow); return "redirect:" + request.getHeader("Referer"); } }//end FollowController class
36.327869
105
0.697653
dd82cbda53fb6b559c90514cefc27c718159da07
12,244
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can obtain * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt. * Sun designates this particular file as subject to the "Classpath" exception * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * Header, with the fields enclosed by brackets [] replaced by your own * identifying information: "Portions Copyrighted [year] * [name of copyright owner]" * * Contributor(s): * * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ /* * Copyright (c) 2004, Mikael Grev, MiG InfoCom AB. (base64 @ miginfocom . com) * All rights reserved. */ package org.more.util.io.input; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; /** * <p>A slight spin on the standard ByteArrayInputStream. This * one accepts only a Base64 encoded String in the constructor argument</p> * which decodes into a <code>byte[]</code> to be read from by * other stream.</p> */ public class Base64InputStream extends InputStream { private static final int[] IA = new int[256]; private static final char[] CA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray(); static { Arrays.fill(Base64InputStream.IA, -1); for (int i = 0, iS = Base64InputStream.CA.length; i < iS; i++) { Base64InputStream.IA[Base64InputStream.CA[i]] = i; } Base64InputStream.IA['='] = 0; } /** * An array of bytes that was provided * by the creator of the stream. Elements <code>buf[0]</code> * through <code>buf[count-1]</code> are the * only bytes that can ever be read from the * stream; element <code>buf[pos]</code> is * the next byte to be read. */ protected byte buf[]; /** * The index of the next character to read from the input stream buffer. * This value should always be nonnegative * and not larger than the value of <code>count</code>. * The next byte to be read from the input stream buffer * will be <code>buf[pos]</code>. */ protected int pos; /** * The currently marked position in the stream. * ByteArrayInputStream objects are marked at position zero by * default when constructed. They may be marked at another * position within the buffer by the <code>mark()</code> method. * The current buffer position is set to this point by the * <code>reset()</code> method. * <p/> * If no mark has been set, then the value of mark is the offset * passed to the constructor (or 0 if the offset was not supplied). * * @since JDK1.1 */ protected int mark = 0; /** * The index one greater than the last valid character in the input * stream buffer. * This value should always be nonnegative * and not larger than the length of <code>buf</code>. * It is one greater than the position of * the last byte within <code>buf</code> that * can ever be read from the input stream buffer. */ protected int count; /** * Creates a <code>Base64InputStream</code>. * * @param encodedString the Base64 encoded String */ public Base64InputStream(final String encodedString) { this.buf = this.decode(encodedString); this.pos = 0; this.count = this.buf.length; } /** * Reads the next byte of data from this input stream. The value * byte is returned as an <code>int</code> in the range * <code>0</code> to <code>255</code>. If no byte is available * because the end of the stream has been reached, the value * <code>-1</code> is returned. * <p/> * This <code>read</code> method * cannot block. * * @return the next byte of data, or <code>-1</code> if the end of the * stream has been reached. */ @Override public int read() { return this.pos < this.count ? this.buf[this.pos++] & 0xff : -1; } /** * Reads up to <code>len</code> bytes of data into an array of bytes * from this input stream. * If <code>pos</code> equals <code>count</code>, * then <code>-1</code> is returned to indicate * end of file. Otherwise, the number <code>k</code> * of bytes read is equal to the smaller of * <code>len</code> and <code>count-pos</code>. * If <code>k</code> is positive, then bytes * <code>buf[pos]</code> through <code>buf[pos+k-1]</code> * are copied into <code>b[off]</code> through * <code>b[off+k-1]</code> in the manner performed * by <code>System.arraycopy</code>. The * value <code>k</code> is added into <code>pos</code> * and <code>k</code> is returned. * <p/> * This <code>read</code> method cannot block. * * @param b the buffer into which the data is read. * @param off the start offset of the data. * @param len the maximum number of bytes read. * * @return the total number of bytes read into the buffer, or * <code>-1</code> if there is no more data because the end of * the stream has been reached. */ @Override public int read(final byte b[], final int off, int len) { if (b == null) { throw new NullPointerException(); } else if (off < 0 || off > b.length || len < 0 || off + len > b.length || off + len < 0) { throw new IndexOutOfBoundsException(); } if (this.pos >= this.count) { return -1; } if (this.pos + len > this.count) { len = this.count - this.pos; } if (len <= 0) { return 0; } System.arraycopy(this.buf, this.pos, b, off, len); this.pos += len; return len; } /** * Skips <code>n</code> bytes of input from this input stream. Fewer * bytes might be skipped if the end of the input stream is reached. * The actual number <code>k</code> * of bytes to be skipped is equal to the smaller * of <code>n</code> and <code>count-pos</code>. * The value <code>k</code> is added into <code>pos</code> * and <code>k</code> is returned. * * @param n the number of bytes to be skipped. * * @return the actual number of bytes skipped. */ @Override public long skip(long n) { if (this.pos + n > this.count) { n = this.count - this.pos; } if (n < 0) { return 0; } this.pos += n; return n; } /** * Returns the number of bytes that can be read from this input * stream without blocking. * The value returned is * <code>count&nbsp;- pos</code>, * which is the number of bytes remaining to be read from the input buffer. * * @return the number of bytes that can be read from the input stream * without blocking. */ @Override public int available() { return this.count - this.pos; } /** * Tests if this <code>InputStream</code> supports mark/reset. The * <code>markSupported</code> method of <code>ByteArrayInputStream</code> * always returns <code>true</code>. * * @since JDK1.1 */ @Override public boolean markSupported() { return true; } /** * Set the current marked position in the stream. * ByteArrayInputStream objects are marked at position zero by * default when constructed. They may be marked at another * position within the buffer by this method. * <p/> * If no mark has been set, then the value of the mark is the * offset passed to the constructor (or 0 if the offset was not * supplied). * <p/> * <p> Note: The <code>readAheadLimit</code> for this class * has no meaning. * * @since JDK1.1 */ @Override public void mark(final int readAheadLimit) { this.mark = this.pos; } /** * Resets the buffer to the marked position. The marked position * is 0 unless another position was marked or an offset was specified * in the constructor. */ @Override public void reset() { this.pos = this.mark; } /** * Closing a <tt>ByteArrayInputStream</tt> has no effect. The methods in * this class can be called after the stream has been closed without * generating an <tt>IOException</tt>. * <p/> */ @Override public void close() throws IOException { } /** * <p>Base64 decodes the source string. NOTE: This method doesn't * consider line breaks</p> * @param source a Base64 encoded string * @return the bytes of the decode process */ private byte[] decode(final String source) { // Check special case int sLen = source.length(); if (sLen == 0) { return new byte[0]; } int sIx = 0, eIx = sLen - 1; // Start and end index after trimming. // Trim illegal chars from start while (sIx < eIx && Base64InputStream.IA[source.charAt(sIx) & 0xff] < 0) { sIx++; } // Trim illegal chars from end while (eIx > 0 && Base64InputStream.IA[source.charAt(eIx) & 0xff] < 0) { eIx--; } // get the padding count (=) (0, 1 or 2) int pad = source.charAt(eIx) == '=' ? source.charAt(eIx - 1) == '=' ? 2 : 1 : 0; // Count '=' at end. int cCnt = eIx - sIx + 1; // Content count including possible separators int sepCnt = sLen > 76 ? (source.charAt(76) == '\r' ? cCnt / 78 : 0) << 1 : 0; int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes byte[] dArr = new byte[len]; // Preallocate byte[] of exact length // Decode all but the last 0 - 2 bytes. int d = 0; for (int eLen = len / 3 * 3; d < eLen; ) { // Assemble three bytes into an int from four "valid" characters. int i = Base64InputStream.IA[source.charAt(sIx++)] << 18 | Base64InputStream.IA[source.charAt(sIx++)] << 12 | Base64InputStream.IA[source.charAt(sIx++)] << 6 | Base64InputStream.IA[source.charAt(sIx++)]; // Add the bytes dArr[d++] = (byte) (i >> 16); dArr[d++] = (byte) (i >> 8); dArr[d++] = (byte) i; } if (d < len) { // Decode last 1-3 bytes (incl '=') into 1-3 bytes int i = 0; for (int j = 0; sIx <= eIx - pad; j++) { i |= Base64InputStream.IA[source.charAt(sIx++)] << 18 - j * 6; } for (int r = 16; d < len; r -= 8) { dArr[d++] = (byte) (i >> r); } } return dArr; } // Test Case: com.sun.faces.io.TestIO } // END Base64InputStream
39.118211
215
0.605766
fef3ae98a40c0e8341857fa4602b46642e225ce5
317
package fabuco.performer; public interface PerformerCall<P extends PerformerParameter<R>, R> { PerformerCallState getState(); boolean isSucceeded(); boolean isExpired(); P getParameter(); R getResult(); boolean isRecoverableError(); String getFaultCode(); Throwable getRecoverableError(); }
14.409091
68
0.731861
59a558e762d86a9ec8f38c0480095318ab103d9c
1,061
package videosTest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import org.openqa.selenium.By; import org.openqa.selenium.chrome.ChromeDriver; public class Test { private static ChromeDriver driver; public static void main(String[] args) throws IOException, InterruptedException { // TODO Auto-generated method stub System.setProperty("webdriver.chrome.driver", "C:\\Users\\vd180005d\\Downloads\\chromedriver_win32\\chromedriver.exe"); driver=new ChromeDriver(); driver.get("http://www.bing.com"); System.out.println("Loaded BING homepage"); System.out.println("Search for some term and then press ENTER"); Scanner s=new Scanner(System.in); String search=s.nextLine(); System.out.println(search); System.out.println("Clicking on the first link ..."); driver.findElement(By.id("sb_form_q")).sendKeys(search); driver.findElement(By.className("search")).click(); driver.findElement(By.tagName("h2")).click(); Thread.sleep(3000); driver.quit(); } }
29.472222
121
0.747408
ec5d22bc4b7e608bff42876bbb912d0f5f534fd1
758
package com.mapi.docadm.dto; import java.io.Serializable; import org.springframework.data.domain.Page; import com.mapi.docadm.entities.Funcionario; public class FuncionarioDto implements Serializable { private static final long serialVersionUID = 1L; private Long id; private String nome; public FuncionarioDto() { } public FuncionarioDto(Funcionario entity) { id = entity.getId(); nome = entity.getNome(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public static Page<FuncionarioDto> converter(Page<Funcionario> funcionarios) { return funcionarios.map(FuncionarioDto::new); } }
17.227273
79
0.726913
5e25fbfc61e9e4bc48cae26908afacb12ad861a1
904
package info.ericlin.redditnow.recyclerview; import android.content.Context; import android.view.View; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.List; import org.greenrobot.eventbus.EventBus; public abstract class RedditViewHolder<T extends RedditListItem> extends RecyclerView.ViewHolder { @NonNull private final EventBus eventBus; public RedditViewHolder(@NonNull View itemView, @NonNull EventBus eventBus) { super(itemView); this.eventBus = eventBus; } @NonNull protected final EventBus getEventBus() { return eventBus; } protected final Context getContext() { return itemView.getContext(); } protected abstract void bind(@NonNull T item); protected void bind(@NonNull T item, @NonNull List<Object> payloads) { // fallback to bind bind(item); } protected abstract void unbind(); }
23.789474
98
0.754425
0084e576a10b11205574ccd4c8769b10509672e0
166
package com.forgottenartsstudios.networking.packets; /** * Created by forgo on 10/15/2017. */ public class SendTryAttack extends Packet { public int index; }
16.6
52
0.73494
02d9bfe2909e2913bf009ba863f05178fae450bd
1,922
/* * Copyright 2017-2021 original authors * * 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 * * https://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 io.micronaut.coherence.annotation; import io.micronaut.context.annotation.Executable; import java.lang.annotation.*; /** * <p>An {@link Executable} advice annotation that allows listening for Coherence events.</p> * <p>The method will ultimately be wrapped in either an {@link com.tangosol.net.events.EventInterceptor} * or a {@link com.tangosol.util.MapListener}. * Various qualifier annotations can also be applied to further qualify the types of events and the target event source * for a specific listener method. Listener methods can have any name but must take a single parameter that extends either * {@link com.tangosol.net.events.Event} or {@link com.tangosol.util.MapEvent} and return {@code void}.</p> * * <p>For example:</p> * <p>The following method will receive a {@link com.tangosol.net.events.partition.cache.CacheLifecycleEvent} event every * time a map or cache is created or destroyed.</p> * * <pre><code> * {@literal @}CoherenceEventListener * public void onEvent(CacheLifecycleEvent event) { * } * </code></pre> * * @author Jonathan Knight * @since 1.0 */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.ANNOTATION_TYPE, ElementType.TYPE, ElementType.METHOD}) @Executable(processOnStartup = true) public @interface CoherenceEventListener { }
39.22449
122
0.75078
bed9edf540f9cbce93b206d3d2eec9abe47a6f0e
12,349
package co.mide.kanjiunlock; import android.content.SharedPreferences; import android.graphics.PixelFormat; import android.os.Bundle; import android.provider.Settings; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.WindowManager; import android.widget.RelativeLayout; import android.widget.TextView; import org.xdump.android.zinnia.ModelDoesNotExistException; import org.xdump.android.zinnia.Zinnia; import fr.castorflex.android.verticalviewpager.VerticalViewPager; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.TimeZone; public class Unlock extends FragmentActivity implements KeyPressedCallback{ private boolean isPreview = false; public static boolean locked = false; private CustomViewGroup wrapperView = null; private RelativeLayout wrapperView1 = null; private TextView dateText = null; private TextView timeText = null; private TextView amPmText = null; private DateFormat dateFormat; private DateFormat timeFormat; private DateFormat amPmFormat; private VerticalViewPager pager; private long recognizer; private Zinnia zin; private MyPagerAdapter pageAdapter; private static Unlock unlock; private SharedPreferences preferences; private int origTimeout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); origTimeout = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, -1); Log.d("Timeout", origTimeout + ""); setContentView(R.layout.activity_unlock); dateFormat = new SimpleDateFormat("EEE, MMM d"); timeFormat = new SimpleDateFormat("h:mm"); amPmFormat = new SimpleDateFormat("a"); dateFormat.setTimeZone(TimeZone.getDefault()); timeFormat.setTimeZone(TimeZone.getDefault()); amPmFormat.setTimeZone(TimeZone.getDefault()); preferences = getSharedPreferences(AppConstants.PREF_NAME, MODE_PRIVATE); setupActivity(); zin = new Zinnia(this); try { recognizer = zin.zinnia_recognizer_new("handwriting-ja.model"); }catch (ModelDoesNotExistException e){ Log.e("Zinnia model", "Model does not exist"); } unlock = this; } public static Unlock getUnlock(){ return unlock; } public void updateTime(){ Date date = new Date(System.currentTimeMillis()); if(timeText != null){ //update timeText timeText.setText(timeFormat.format(date)); } if(dateText != null){ //update dateText regardless dateText.setText(dateFormat.format(date)); } if(amPmText != null){ //update am/pm if need be amPmText.setText(amPmFormat.format(date)); } } public void addStroke(long character, int strokeNum, int x, int y){ zin.zinnia_character_add(character, strokeNum, x, y); } private void setCharacterSize(long character, int width, int height){ zin.zinnia_character_set_width(character, width); zin.zinnia_character_set_height(character, height); } private List<Fragment> getFragments(){ List<Fragment> fragmentList = new ArrayList<>(); fragmentList.add(MyVerticalFragment.newInstance(1)); fragmentList.add(MyVerticalFragment.newInstance(2)); return fragmentList; } public boolean verifyCharacter(char character, long zinniaCharacter){ boolean returnValue = false; long result = zin.zinnia_recognizer_classify(recognizer, zinniaCharacter, 10); if (result == 0) { Log.e("Zinnia", String.format("%s", zin.zinnia_recognizer_strerror(recognizer))); }else { for (int i = 0; i < zin.zinnia_result_size(result); i++) { Log.v("Zinnia", String.format("%s\t%f\n", zin.zinnia_result_value(result, i), zin.zinnia_result_score(result, i))); if(zin.zinnia_result_value(result, i).equals(Character.toString(character))){ returnValue = true; unlock(); }else if(JapCharacter.isKana(character)){//This is because zinnia doesn't play well with ten ten if(JapCharacter.isVoiced(character)){ char voicelessCharacter = JapCharacter.getVoiceless(character); if(zin.zinnia_result_value(result, i).equals(Character.toString(voicelessCharacter))){ returnValue = true; unlock(); } } } } } return returnValue; } public long createCharacter(int width, int height){ long character = zin.zinnia_character_new(); setCharacterSize(character, width, height); return character; } @Override public void onDestroy(){ WindowManager winManager = ((WindowManager)getApplicationContext().getSystemService(WINDOW_SERVICE)); if(winManager != null) { if (wrapperView1 != null) { winManager.removeView(wrapperView1); wrapperView1.removeAllViews(); } else { Log.d("Destroy", "wrapperView1 is null"); } if (wrapperView != null) { winManager.removeView(wrapperView); wrapperView.removeAllViews(); } else { Log.d("Destroy", "wrapperView is null"); } } try { zin.zinnia_recognizer_destroy(recognizer); }catch (Exception e){ //do nothing } Log.v("Unlock", "Unlocked"); unlock = null; locked = false; super.onDestroy(); } @Override public void onPause(){ super.onPause(); if (origTimeout != -1) { Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, origTimeout); Log.v("timeout", "Timeout set to: orig timeout: " + origTimeout); } } @Override public void onStop(){ if(!isPreview) overridePendingTransition(0, 0); super.onStop(); } public void onBackKeyPressed(){ Log.d("Back", "back pressed"); if(!isPreview && (pager.getCurrentItem() == 0)) ((MyVerticalFragment)pageAdapter.getItem(0)).onBackPressed(); } public void onBackKeyLongPressed(){ Log.d("Back", "back long pressed"); if(!isPreview && (pager.getCurrentItem() == 0)) ((MyVerticalFragment)pageAdapter.getItem(0)).onBackLongPressed(); } @Override public void onAttachedToWindow() { super.onAttachedToWindow(); if(locked) getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); } @Override public void onResume(){ super.onResume(); if(!isPreview) { overridePendingTransition(0, 0); Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, AppConstants.FIVE_SECONDS); Log.v("timeout", "timeout set to Fiveseconds"); } if(isPreview) locked = false; } public boolean verifyPin(String pinString){ int pin = preferences.getInt(AppConstants.PIN, 0); if(Integer.parseInt(pinString) == pin) unlock(); return Integer.parseInt(pinString) == pin; } private void setupActivity(){ View view; if(getIntent().getBooleanExtra(AppConstants.IS_ACTUALLY_LOCKED, false) && !locked){ //just to still be able to pick up onback pressed isPreview = false; locked = true; getWindow().setType(2004); getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); WindowManager.LayoutParams localLayoutParams1 = new WindowManager.LayoutParams(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); WindowManager winManager = ((WindowManager)getApplicationContext().getSystemService(WINDOW_SERVICE)); wrapperView1 = new RelativeLayout(getBaseContext()); getWindow().setAttributes(localLayoutParams1); winManager.addView(wrapperView1, localLayoutParams1); view = View.inflate(this, R.layout.activity_unlock, wrapperView1); RelativeLayout unlockLayout = (RelativeLayout)view.findViewById(R.id.unlock_layout); dateText = (TextView)view.findViewById(R.id.date); timeText = (TextView)view.findViewById(R.id.time); amPmText = (TextView)view.findViewById(R.id.am_pm); getSupportFragmentManager().setViewGroup(unlockLayout); view.findViewById(R.id.previewText).setVisibility(View.INVISIBLE); pageAdapter = new MyPagerAdapter(getSupportFragmentManager(), getFragments()); pager = (VerticalViewPager)view.findViewById(R.id.vertical_pager); pager.setAdapter(pageAdapter); WindowManager.LayoutParams localLayoutParams = new WindowManager.LayoutParams(); localLayoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR; localLayoutParams.gravity = Gravity.TOP; localLayoutParams.flags = //WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE| // this is to enable the notification to recieve touch events WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | // Draws over status bar WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN; localLayoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; localLayoutParams.height = (int) (50 * getResources() .getDisplayMetrics().scaledDensity); localLayoutParams.format = PixelFormat.TRANSPARENT; wrapperView = new CustomViewGroup(this); wrapperView.registerCallback(this); winManager.addView(wrapperView, localLayoutParams); wrapperView.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { Log.d("Back", "item: " + pager.getCurrentItem()); if ((keyCode == KeyEvent.KEYCODE_BACK) && (pager.getCurrentItem() == 0)) { ((MyVerticalFragment) pageAdapter.getItem(0)).onBackPressed(); return true; } return false; } }); Log.v("Unlock", "Locked"); }else if(!getIntent().getBooleanExtra(AppConstants.IS_ACTUALLY_LOCKED, false)){ setContentView(R.layout.activity_unlock); pageAdapter = new MyPagerAdapter(getSupportFragmentManager(), getFragments()); pager = (VerticalViewPager)findViewById(R.id.vertical_pager); Log.v("pager", pager.getId() + ""); pager.setAdapter(pageAdapter); isPreview = true; locked = false; getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); findViewById(R.id.previewText).setVisibility(View.VISIBLE); dateText = (TextView)findViewById(R.id.date); timeText = (TextView)findViewById(R.id.time); amPmText = (TextView)findViewById(R.id.am_pm); } updateTime(); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); pager.setPageTransformer(true, new MyPageTransformer()); } // public void unlockPhone(View v){ // //Unlock Phone here // if(v.getId() == R.id.unlock_button) // unlock(); // } private void unlock() { Log.d("Unlock", "Unlock function"); finish(); if (!isPreview) overridePendingTransition(0, 0); locked = false; } }
39.328025
137
0.630334
69a7e4bbde61e844a8f4f11aef5c424757a7f934
341
package com.thinkgem.jeesite.modules.sys.utils; public class AccessUtils { private static final ThreadLocal accessInfo = new ThreadLocal(); public static AccessInfo getAccessInfo() { return (AccessInfo) accessInfo.get(); } public static void setAccessInfo(AccessInfo info) { accessInfo.set(info); } }
22.733333
68
0.70088
357f0b2570c58d0c55f54ce403d481a24eb7869b
4,724
/* * 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 WARRANTIESOR 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.aries.blueprint.itests; import static org.apache.aries.blueprint.itests.Helper.mvnBundle; import static org.junit.Assert.assertNotNull; import static org.ops4j.pax.exam.CoreOptions.composite; import static org.ops4j.pax.exam.CoreOptions.junitBundles; import static org.ops4j.pax.exam.CoreOptions.systemProperty; import static org.ops4j.pax.exam.CoreOptions.vmOption; import static org.ops4j.pax.exam.CoreOptions.when; import java.io.InputStream; import java.util.Hashtable; import org.apache.aries.itest.AbstractIntegrationTest; import org.apache.aries.itest.RichBundleContext; import org.junit.runner.RunWith; import org.ops4j.pax.exam.CoreOptions; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.options.MavenArtifactProvisionOption; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.osgi.service.blueprint.container.BlueprintContainer; import org.osgi.service.cm.Configuration; import org.osgi.service.cm.ConfigurationAdmin; /** * Base class for Pax Exam 1.2.x based unit tests * * Contains the injection point and various utilities used in most tests */ @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public abstract class AbstractBlueprintIntegrationTest extends AbstractIntegrationTest { public static final long DEFAULT_TIMEOUT = 15000; protected BlueprintContainer startBundleBlueprint(String symbolicName) throws BundleException { Bundle b = context().getBundleByName(symbolicName); assertNotNull("Bundle " + symbolicName + " not found", b); b.start(); BlueprintContainer beanContainer = Helper.getBlueprintContainerForBundle(context(), symbolicName); assertNotNull(beanContainer); return beanContainer; } public Option baseOptions() { String localRepo = System.getProperty("maven.repo.local"); if (localRepo == null) { localRepo = System.getProperty("org.ops4j.pax.url.mvn.localRepository"); } return composite( junitBundles(), systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("DEBUG"), when(localRepo != null).useOptions(vmOption("-Dorg.ops4j.pax.url.mvn.localRepository=" + localRepo)), mvnBundle("org.ops4j.pax.logging", "pax-logging-api"), mvnBundle("org.ops4j.pax.logging", "pax-logging-service") ); } public InputStream getResource(String path) { InputStream is = this.getClass().getClassLoader().getResourceAsStream(path); if (is == null) { throw new IllegalArgumentException("Resource not found " + path); } return is; } protected void applyCommonConfiguration(BundleContext ctx) throws Exception { ConfigurationAdmin ca = (new RichBundleContext(ctx)).getService(ConfigurationAdmin.class); Configuration cf = ca.getConfiguration("blueprint-sample-placeholder", null); Hashtable<String, String> props = new Hashtable<String, String>(); props.put("key.b", "10"); cf.update(props); } protected Bundle getSampleBundle() { Bundle bundle = context().getBundleByName("org.apache.aries.blueprint.sample"); assertNotNull(bundle); return bundle; } protected MavenArtifactProvisionOption sampleBundleOption() { return CoreOptions.mavenBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.sample").versionAsInProject(); } protected void startBlueprintBundles() throws BundleException, InterruptedException { context().getBundleByName("org.apache.aries.blueprint.core").start(); context().getBundleByName("org.apache.aries.blueprint.cm").start(); Thread.sleep(2000); } }
41.438596
121
0.740686
f162c86b22f8d5bee13de3a1b4bb2e5cf0c93a02
14,460
package main; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Objects; import java.util.Random; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.ScrollPaneConstants; import javax.swing.SwingUtilities; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.AttributeSet; import javax.swing.text.Document; import javax.swing.text.JTextComponent; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import javax.swing.text.StyleContext; import enums.Stat; import simpleconcepts.Unit; /** * @author InfuriatedBrute */ public final class BattleTester extends BattleController { Battle b; public static String ls = System.lineSeparator(); private JTextArea attackerTextArea, defenderTextArea, seedTextArea; private JTextField attackerLabel, defenderLabel, seedLabel, attackerCostDisplayArea, defenderCostDisplayArea; private JFrame frame; private JTextPane resultPane = new JTextPane(); boolean lastTurn = false; int results = -999; Random random = new Random(); WindowAdapter exitOnClose = new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }; ActionListener attackerRandomListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setRandomArmy(true); } }; ActionListener attackerBlankListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setBlankArmy(true); } }; ActionListener defenderRandomListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setRandomArmy(false); } }; ActionListener defenderBlankListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setBlankArmy(false); } }; ActionListener runListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { run(); } }; public static void main(String[] args) { new BattleTester(); } private BattleTester() { inputPopup(); } private void run() { String[] attackerArmy = attackerTextArea.getText().split(ls); String s = isValidArmy(attackerArmy); if (!s.equals("")) { errorBox(s); return; } String[] defenderArmy = defenderTextArea.getText().split(ls); s = isValidArmy(defenderArmy); if (!s.equals("")) { errorBox(s); return; } Long RNGseed; try { RNGseed = Long.parseLong(seedTextArea.getText()); } catch (NumberFormatException e) { errorBox("The string in the seed box must be a number between " + Long.MIN_VALUE + " and " + Long.MAX_VALUE + "." + ls + "No commas, no decimals, etc."); return; } b = new Battle(attackerArmy, defenderArmy, RNGseed, this); frame.dispose(); results = b.simulate(); lastTurn = true; try { endOfTurn(); } catch (Exception e) { throw new RuntimeException(); } } public static void errorBox(String infoMessage) { JOptionPane.showMessageDialog(null, infoMessage, "Error", JOptionPane.ERROR_MESSAGE); } /** * * @param army * the army to check whether is valid * @return a string for a reason the army isn't valid, or the empty string if it * is valid */ private String isValidArmy(String[] army) { if (army.length != Constants.START_AREA_HEIGHT) return "An army is the wrong height. Please keep the armies the same height as the default and try again."; for (String line : army) if (line.length() != Constants.START_AREA_WIDTH) return "An army is the wrong width. Please keep the armies the same width as the default and try again."; for (String line : army) for (char c : line.toCharArray()) { if (c != ls.toCharArray()[0] && c != Constants.BLANK_SPACE_CHAR) { if (Unit.getTypes().get(c) == null) return "A character is not recognized. Please try again. Keep in mind the input is case-sensitive."; } } return ""; } @Override public void endOfTurn() throws Exception { if (b.actionPerformedThisTurn || b.turn == 1 || lastTurn) { if (lastTurn) { String victory; switch (results) { case 1: victory = "N ATTACKER VICTORY!"; break; case 0: victory = " STALEMATE."; break; case -1: victory = " DEFENDER VICTORY!"; break; default: throw new RuntimeException(); } appendToPane(resultPane, (ls + ls + ls + "BATTLE ENDED ON TURN " + (b.turn - 1) + " WITH A" + victory + ls), Color.BLACK); } else appendToPane(resultPane, (ls + ls + ls + "Turn " + b.turn + ":" + ls), Color.BLACK); for (int row = 0; row < Constants.MAP_HEIGHT; row++) { appendToPane(resultPane, ls, Color.BLACK); for (int col = 0; col < Constants.MAP_WIDTH; col++) { if (b.grid[row][col] != null) { float howHurt = (1 - ((float) b.grid[row][col].get(Stat.CURRENTHP) / (float) b.grid[row][col].get(Stat.MAXHP))); Color color = new Color(howHurt, howHurt / 2.0f, howHurt / 2.0f); if (b.grid[row][col].attacker == 1) { appendToPane(resultPane, String.valueOf(b.grid[row][col].getChar()), color, true); } else { appendToPane(resultPane, String.valueOf(b.grid[row][col].getChar()), color); } } else { appendToPane(resultPane, String.valueOf(Constants.BLANK_SPACE_CHAR), Color.BLACK); } } } } if (lastTurn) { try { resultsPopup(); } catch (Exception e) { e.printStackTrace(); } } } private void appendToPane(JTextPane tp, String msg, Color c) { appendToPane(tp, msg, c, false); } private void appendToPane(JTextPane tp, String msg, Color c, boolean italic) { StyleContext sc = StyleContext.getDefaultStyleContext(); AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c); aset = sc.addAttribute(aset, StyleConstants.FontFamily, Constants.FONT); aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED); aset = sc.addAttribute(aset, StyleConstants.Italic, italic); int len = tp.getDocument().getLength(); tp.setCaretPosition(len); tp.setCharacterAttributes(aset, false); tp.replaceSelection(msg); } private void inputPopup() { attackerTextArea = new JTextArea(); attackerCostDisplayArea = new JTextField(); attackerLabel = new JTextField(); defenderTextArea = new JTextArea(); defenderCostDisplayArea = new JTextField(); defenderLabel = new JTextField(); seedTextArea = new JTextArea(); seedLabel = new JTextField(); Font font = new Font(Constants.FONT, Font.PLAIN, 18); attackerCostDisplayArea.setEditable(false); defenderCostDisplayArea.setEditable(false); attackerLabel.setEditable(false); defenderLabel.setEditable(false); seedLabel.setEditable(false); attackerTextArea.setFont(font); attackerCostDisplayArea.setFont(font); attackerLabel.setFont(font); defenderTextArea.setFont(font); defenderCostDisplayArea.setFont(font); defenderLabel.setFont(font); seedTextArea.setFont(font); seedLabel.setFont(font); setRandomArmy(true); attackerLabel.setText("Attacker"); updateCost(true); setRandomArmy(false); updateCost(false); defenderLabel.setText("Defender"); seedTextArea.setText(String.valueOf(new Random().nextLong())); seedLabel.setText("Seed"); JButton doneButton = new JButton("Done"); doneButton.addActionListener(runListener); JButton attackerBlankButton = new JButton("Blank"); attackerBlankButton.addActionListener(attackerBlankListener); JButton attackerRandomButton = new JButton("Random"); attackerRandomButton.addActionListener(attackerRandomListener); JButton defenderBlankButton = new JButton("Blank"); defenderBlankButton.addActionListener(defenderBlankListener); JButton defenderRandomButton = new JButton("Random"); defenderRandomButton.addActionListener(defenderRandomListener); JPanel armyPanel = new JPanel(), seedPanel = new JPanel(), donePanel = new JPanel(), attackerPanel = new JPanel(), defenderPanel = new JPanel(), attackerButtonPanel = new JPanel(), defenderButtonPanel = new JPanel(); attackerPanel.setLayout(new BoxLayout(attackerPanel, BoxLayout.Y_AXIS)); attackerPanel.add(attackerLabel); attackerPanel.add(attackerCostDisplayArea); attackerPanel.add(attackerTextArea); attackerButtonPanel.add(attackerBlankButton); attackerButtonPanel.add(attackerRandomButton); attackerPanel.add(attackerButtonPanel); defenderPanel.setLayout(new BoxLayout(defenderPanel, BoxLayout.Y_AXIS)); defenderPanel.add(defenderLabel); defenderPanel.add(defenderCostDisplayArea); defenderPanel.add(defenderTextArea); defenderButtonPanel.add(defenderBlankButton); defenderButtonPanel.add(defenderRandomButton); defenderPanel.add(defenderButtonPanel); seedPanel.setLayout((new BoxLayout(seedPanel, BoxLayout.Y_AXIS))); seedPanel.add(seedLabel); seedPanel.add(seedTextArea); donePanel.add(doneButton); addChangeListener(attackerTextArea, e -> updateCost(true)); addChangeListener(defenderTextArea, e -> updateCost(false)); armyPanel.add(attackerPanel); armyPanel.add(defenderPanel); JPanel mainPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS)); mainPanel.add(armyPanel); mainPanel.add(seedPanel); mainPanel.add(donePanel); frame = new JFrame(); frame.add(mainPanel); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); frame.addWindowListener(exitOnClose); } private void setRandomArmy(boolean attacker) { if (attacker) { attackerTextArea.setText(randomArmy()); } else { defenderTextArea.setText(randomArmy()); } } private String randomArmy() { String toReturn = ""; Object[] cs = Unit.getTypes().keySet().toArray(); for (int row = 0; row < Constants.START_AREA_HEIGHT; row++) { for (int col = 0; col < Constants.START_AREA_WIDTH; col++) { if (random.nextDouble() < 0.1) { toReturn += cs[random.nextInt(cs.length)]; } else { toReturn += Constants.BLANK_SPACE_CHAR; } } if (row < Constants.START_AREA_HEIGHT - 1) toReturn += ls; } return toReturn; } private void updateCost(boolean attacker) { if (attacker) attackerCostDisplayArea.setText(String.valueOf(Battle.getCost(attackerTextArea.getText().split(ls)))); else defenderCostDisplayArea.setText(String.valueOf(Battle.getCost(defenderTextArea.getText().split(ls)))); } private void setBlankArmy(boolean attacker) { String blankArmy = blankArmy(); if (attacker) { attackerTextArea.setText(blankArmy); } else { defenderTextArea.setText(blankArmy); } } private String blankArmy() { String toReturn = ""; for (int row = 0; row < Constants.START_AREA_HEIGHT; row++) { for (int col = 0; col < Constants.START_AREA_WIDTH; col++) toReturn += Constants.BLANK_SPACE_CHAR; if (row < Constants.START_AREA_HEIGHT - 1) toReturn += ls; } return toReturn; } private void resultsPopup() { JPanel middlePanel = new JPanel(); JScrollPane scroll = new JScrollPane(resultPane); resultPane.setFont(new Font(Constants.FONT, Font.PLAIN, 18)); scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); scroll.setPreferredSize(new Dimension(800, 800)); middlePanel.add(scroll); JFrame frame = new JFrame(); frame.add(middlePanel); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); frame.addWindowListener(exitOnClose); } // https://stackoverflow.com/questions/3953208/value-change-listener-to-jtextfield /** * Installs a listener to receive notification when the text of any * {@code JTextComponent} is changed. Internally, it installs a * {@link DocumentListener} on the text component's {@link Document}, and a * {@link PropertyChangeListener} on the text component to detect if the * {@code Document} itself is replaced. * * @param text * any text component, such as a {@link JTextField} or * {@link JTextArea} * @param changeListener * a listener to receieve {@link ChangeEvent}s when the text is * changed; the source object for the events will be the text * component * @throws NullPointerException * if either parameter is null */ public static void addChangeListener(JTextComponent text, ChangeListener changeListener) { Objects.requireNonNull(text); Objects.requireNonNull(changeListener); DocumentListener dl = new DocumentListener() { private int lastChange = 0, lastNotifiedChange = 0; @Override public void insertUpdate(DocumentEvent e) { changedUpdate(e); } @Override public void removeUpdate(DocumentEvent e) { changedUpdate(e); } @Override public void changedUpdate(DocumentEvent e) { lastChange++; SwingUtilities.invokeLater(() -> { if (lastNotifiedChange != lastChange) { lastNotifiedChange = lastChange; changeListener.stateChanged(new ChangeEvent(text)); } }); } }; text.addPropertyChangeListener("document", (PropertyChangeEvent e) -> { Document d1 = (Document) e.getOldValue(); Document d2 = (Document) e.getNewValue(); if (d1 != null) d1.removeDocumentListener(dl); if (d2 != null) d2.addDocumentListener(dl); dl.changedUpdate(null); }); Document d = text.getDocument(); if (d != null) d.addDocumentListener(dl); } }
32.714932
136
0.694537
921fda0cbb9b410c94cd9f2d135304684f24b7fa
148
package org.nanotek.entities.immutables; import java.io.Serializable; public interface ArtistCreditNameEntity<K> { K getArtistCreditName(); }
14.8
44
0.790541
31c5b9ba90a55bf9e420c43afbc400f1a1311646
5,251
package org.treez.javafxd3.d3.scales; import org.treez.javafxd3.d3.arrays.ArrayUtils; import org.treez.javafxd3.d3.core.Value; import org.treez.javafxd3.d3.time.TimeScale; import org.treez.javafxd3.d3.core.JsEngine; import org.treez.javafxd3.d3.core.JsObject; /** * {@link QuantitativeScale} with a continuous range: * <ul> * <li>{@link LinearScale} have a linear interpolator * <li>{@link LogScale} have apply a log function to the domain * <li>{@link PowScale} * <li>{@link IdentityScale} * <li>{@link TimeScale} are linear scale for timestamp * </ul> * * * @param <S> * */ public abstract class ContinuousQuantitativeScale<S extends ContinuousQuantitativeScale<S>> extends QuantitativeScale<S> { //#region CONSTRUCTORS /** * Constructor * * @param engine * @param wrappedJsObject */ public ContinuousQuantitativeScale(JsEngine engine, JsObject wrappedJsObject) { super(engine, wrappedJsObject); } //#end region //#region METHODS // =========== rangeRound ========== /** * Sets the scale's output range to the specified array of values, while * also setting the scale's interpolator to D3#interpolateRound(). * <p> * This is a convenience routine for when the values output by the scale * should be exact integers, such as to avoid antialiasing artifacts. It is * also possible to round the output values manually after the scale is * applied. * <p> * * @param values * the array of values. * @param callingScale * @return the current scale for chaining */ public S rangeRound(JsObject values) { JsObject result = call("rangeRound", values); S resultScale = createScale(engine, result); return resultScale; } /** * Factory method for creating a new scale * @param engine * @param result * @return */ public abstract S createScale(JsEngine engine, JsObject result); /** * See #rangeRound(JsObject). * * @param numbers * @return the current scale for chaining */ public final S rangeRound(final double... numbers) { String arrayString = ArrayUtils.createArrayString(numbers); String command = "this.rangeRound(" + arrayString + ")"; JsObject result = evalForJsObject(command); S resultScale = createScale(engine, result); return resultScale; } /** * See #rangeRound(JavaScriptObject). * * @return the current scale for chaining */ public final S rangeRound(final String... strings) { String arrayString = ArrayUtils.createArrayString(strings); String command = "this.rangeRound(" + arrayString + ")"; JsObject result = evalForJsObject(command); S resultScale = createScale(engine, result); return resultScale; } // =========== invert ========== /** * Returns the value in the input domain x for the corresponding value in * the output range y. * <p> * This represents the inverse mapping from range to domain. For a valid * value y in the output range, apply(scale.invert(y)) equals y; similarly, * for a valid value x in the input domain, scale.invert(apply(x)) equals x. * <p> * Equivalently, you can construct the invert operator by building a new * scale while swapping the domain and range. The invert operator is * particularly useful for interaction, say to determine the value in the * input domain that corresponds to the pixel location under the mouse. * <p> * Note: the invert operator is only supported if the output range is * numeric! D3 allows the output range to be any type; under the hood, * d3.interpolate or a custom interpolator of your choice is used to map the * normalized parameter t to a value in the output range. Thus, the output * range may be colors, strings, or even arbitrary objects. As there is no * facility to "uninterpolate" arbitrary types, the invert operator is * currently supported only on numeric ranges. * @param d * * @return */ public Value invert(double d){ String command = "this.invert(" + d + ")"; Object result = eval(command); if (result==null){ return null; } Value value = Value.create(engine, result); return value; } // =========== clamp ========== /** * returns whether or not the scale currently clamps values to within the * output range. * * @return true if clamping is enabled, false otherwise. */ public boolean clamp() { Boolean result = callForBoolean("clamp"); return result; } /** * Enables or disables clamping accordingly. * <p> * By default, clamping is disabled, such that if a value outside the input * domain is passed to the scale, the scale may return a value outside the * output range through linear extrapolation. * <p> * For example, with the default domain and range of [0,1], an input value * of 2 will return an output value of 2. * <p> * If clamping is enabled, the normalized domain parameter t is clamped to * the range [0,1], such that the return value of the scale is always within * the scale's output range. * <p> * @param clamping * * @return the current scale for chaining */ public S clamp(boolean clamping) { JsObject result = call("clamp", clamping); S resultScale = createScale(engine, result); return resultScale; } //#end region }
28.851648
91
0.691106
265c7559adf24057dba2f3e371603a2627a1467e
698
package com.dingdong.party.serviceBase.common.api; import io.swagger.annotations.ApiModelProperty; import java.util.List; /** * 为了契合前端的数据处理, 从而生成这个 无用的类 * * @author retraci */ public class CommonList<T> { @ApiModelProperty("列表数据") private CommonPage<T> list; /** * 封装一个 CommonPage */ public static <T> CommonList<T> restList(List<T> list) { CommonPage<T> restPage = CommonPage.restPage(list); CommonList<T> result = new CommonList<>(); result.setList(restPage); return result; } public CommonPage<T> getList() { return list; } public void setList(CommonPage<T> list) { this.list = list; } }
18.864865
60
0.627507
8b320966057c646eeec61fb536868daa89a3fd8d
15,021
package cs555RS.nodes; import cs555RS.transport.TCPConnection; import cs555RS.transport.TCPSender; import cs555RS.util.Protocol; import cs555RS.wireformats.ChunkServerMajorHeartbeat; import cs555RS.wireformats.ChunkServerMinorHeartbeat; import cs555RS.wireformats.ChunkServerRegistration; import cs555RS.wireformats.ClientChunkName; import cs555RS.wireformats.ClientRead; import cs555RS.wireformats.ClientRegistration; import cs555RS.wireformats.ControllerClientChunkservers; import cs555RS.wireformats.ControllerClientRegistrationStatus; import cs555RS.wireformats.ControllerReadReply; import cs555RS.wireformats.ControllerRegistrationStatus; import cs555RS.wireformats.EventFactory; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; 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.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; public class Controller extends Thread implements Node { private static Controller controller; public Map<String, TCPConnection> tempCache = new HashMap(); public Map<Integer, TCPConnection> connectionCache = new HashMap(); private AtomicInteger numNodes = new AtomicInteger(0); public Map<Integer, Integer> listeningPortCache = new HashMap<>(); private AtomicInteger numChunkSrvrs = new AtomicInteger(0); Set<Integer> chunkServers = new HashSet<>(); Map<String, Map<Integer, Map<Integer, Integer>>> dataStructure = new HashMap<>(); public static Controller getController() { return controller; } private Controller(int port) throws IOException { ServerSocket controllerSocket = new ServerSocket(port); System.out.println("[INFO] Controller Started."); while (true) { Socket s = controllerSocket.accept(); TCPConnection conn = new TCPConnection(s, this); addtoTempCache(conn); } } public static void main(String[] args) throws IOException { int port = Protocol.PORT; if (args.length == 1) { port = Integer.parseInt(args[0]); } controller = new Controller(port); } public void onEvent(byte[] data, Socket s) throws IOException { EventFactory eventFactory = EventFactory.getInstance(); switch (data[0]) { case Protocol.CHUNKSERVER_REGISTRATION: // ServerReg reg = new ServerReg(data, s); // Thread serverRegThread = new Thread(reg); // serverRegThread.start(); ChunkServerRegistration registration = new ChunkServerRegistration(data); // int nodeID = addToDepository(registration.getIp(), registration.getPort(), s); int nodeID = numNodes.incrementAndGet(); numChunkSrvrs.incrementAndGet(); int listeningPort = registration.getPort(); synchronized (chunkServers) { chunkServers.add(nodeID); } System.out.println("[INFO] Chunk Server with id: " + nodeID + " connected"); addConnectiontoCache(nodeID, s); ControllerRegistrationStatus crs = (ControllerRegistrationStatus) eventFactory.createEvent(Protocol.CONTROLLER_REGISTRATION_STATUS); crs.setNodeID(nodeID); crs.setInfo("Registration Request Succesfull"); TCPConnection conn; synchronized (connectionCache) { conn = (TCPConnection) connectionCache.get(nodeID); } // System.out.println("-conn " + conn); conn.getSender().sendData(crs.getByte()); synchronized (listeningPortCache) { listeningPortCache.put(nodeID, listeningPort); } break; case Protocol.CHUNKSERVER_MINOR_HEARTBEAT: ChunkServerMinorHeartbeat minor = new ChunkServerMinorHeartbeat(data); int minorNodeID = minor.getNodeID(); // Map<String, MetaData> metaDataCache = minor.getMetaDataCache(); break; case Protocol.CHUNKSERVER_MAJOR_HEARTBEAT: ChunkServerMajorHeartbeat major = new ChunkServerMajorHeartbeat(data); int majorNodeID = major.getNodeID(); break; case Protocol.CLIENT_REGISTRATION: ClientRegistration cr = new ClientRegistration(data); // int cNodeID = addToDepository(cr.getIp(), cr.getPort(), s); int cNodeID = numNodes.incrementAndGet(); int cListeningPort = cr.getPort(); System.out.println("[INFO] Client with id: " + cNodeID + " connected"); if (cNodeID >= 0) { addConnectiontoCache(cNodeID, s); } synchronized (listeningPortCache) { listeningPortCache.put(cNodeID, cListeningPort); } ControllerClientRegistrationStatus ccrs = (ControllerClientRegistrationStatus) eventFactory.createEvent(Protocol.CONTROLLER_CLIENT_REGISTRATION_STATUS); ccrs.setNodeID(cNodeID); ccrs.setInfo("Registration Request Succesfull"); TCPConnection cconn; // cconn = getfromTempCache(s); TCPSender sender = new TCPSender(s); sender.sendData(ccrs.getByte()); break; case Protocol.CLIENT_CHUNK_NAME: System.out.println("[INFO] Client store request recieved"); ClientChunkName ccn = new ClientChunkName(data); int clientNodeID = ccn.getNodeID(); byte[] cn = ccn.getData(); String ChunkName = new String(cn); // System.out.println("-chunkName-: "+ChunkName); int[] nodes = determineCS(); // System.out.println("-nodes- " + nodes[0] + " "+ nodes[1] + " "+ nodes[2] + " "+ nodes[3] + " "+ nodes[4] + " "+ nodes[5] + " "+ nodes[6] + " "+ nodes[7] + " "+ nodes[8] + " "); addToStructure(ChunkName, nodes); // System.out.println("-nodes: " + nodes[0]+" "+nodes[1]+" "+nodes[2]); ControllerClientChunkservers ccc = (ControllerClientChunkservers) eventFactory.createEvent(Protocol.CONTROLLER_CLIENT_CHUNKSERVERS); ccc.setNodeID(clientNodeID); ccc.setChunkName(cn); TCPConnection tconn; Map<Integer, Map<Integer, String>> nodeAddr = new HashMap<>(); for (int i = 0; i < 9; i++) { Map<Integer, String> nodeMap = new HashMap<>(); synchronized (connectionCache) { tconn = (TCPConnection) this.connectionCache.get(nodes[i]); } String ip = tconn.getSocket().getInetAddress().getHostAddress(); int port; synchronized (listeningPortCache) { port = listeningPortCache.get(nodes[i]); } String ipport = ip + ":" + port; nodeMap.put(nodes[i], ipport); nodeAddr.put(i + 1, nodeMap); } ccc.setChunkServers(nodeAddr); // System.out.println("-nodeAddr-" + nodeAddr); // System.out.println("-ip: " + new String(ns[0].getIp()) + ":" + ns[0].getPort()); TCPSender sender1 = new TCPSender(s); try { sender1.sendData(ccc.getByte()); } catch (Exception ex) { Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex); } break; case Protocol.CLIENT_READ: ClientRead cread = new ClientRead(data); System.out.println("[INFO] Read Request Received"); // System.out.println("-datastructure- \n" + dataStructure); int clientread = cread.getClientID(); String requestedFileName = new String(cread.getFileName()); Map<Integer, Map<Integer, String>> finalMapToSendToClient = new HashMap<>(); synchronized (dataStructure) { // System.out.println("-datastructure-"); Set<Integer> chunks = dataStructure.get(requestedFileName).keySet(); Map<Integer, Map<Integer, Integer>> chunkCache = dataStructure.get(requestedFileName); for (Integer chunkNo : chunks) { Map<Integer, Integer> shardCache = chunkCache.get(chunkNo); Map<Integer, String> shardLoc = new HashMap<>(); for (Map.Entry<Integer, Integer> entrySet : shardCache.entrySet()) { int shardNo = entrySet.getKey(); int destID = entrySet.getValue(); TCPConnection tconn1; synchronized (connectionCache) { tconn1 = (TCPConnection) this.connectionCache.get(destID); } byte[] ip1 = tconn1.getSocket().getInetAddress().getHostName().getBytes(); int port1; synchronized (listeningPortCache) { port1 = listeningPortCache.get(destID); } String ipport = new String(ip1) + ":" + port1; shardLoc.put(shardNo, ipport); } finalMapToSendToClient.put(chunkNo, shardLoc); } } ControllerReadReply crr = (ControllerReadReply) eventFactory.createEvent(Protocol.CONTROLLER_READ_REPLY); crr.setClientID(clientread); crr.setFileName(requestedFileName.getBytes()); crr.setFinalMapToSendToClient(finalMapToSendToClient); TCPSender senderr = new TCPSender(s); try { senderr.sendData(crr.getByte()); } catch (Exception ex) { Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex); } break; } } private void addConnectiontoCache(int nodeId, Socket s) { TCPConnection tempObj = getfromTempCache(s); if (tempObj != null) { synchronized (connectionCache) { this.connectionCache.put(nodeId, tempObj); } } } private void addtoTempCache(TCPConnection connection) { int idbyPort = connection.getSocket().getPort(); String idbyIP = connection.getSocket().getInetAddress().getHostAddress(); String id = idbyIP + ":" + idbyPort; // System.out.println("-ret- " + id); synchronized (tempCache) { this.tempCache.put(id, connection); // System.out.println("-temp cache-" + tempCache); } } private TCPConnection getfromTempCache(Socket s) { TCPConnection tempObj; synchronized (tempCache) { int idbyPort = s.getPort(); String idbyIP = s.getInetAddress().getHostAddress(); String id = idbyIP + ":" + idbyPort; tempObj = (TCPConnection) this.tempCache.get(id); } return tempObj; } private int[] determineCS() { int[] nodes = new int[9]; int numchnksrvrs; synchronized (numChunkSrvrs) { numchnksrvrs = numChunkSrvrs.get(); } if (numchnksrvrs > 9) { for (int i = 0; i < 9; i++) { nodes[i] = randomNodeID(numchnksrvrs); } } else { synchronized (chunkServers) { List<Integer> temp = new ArrayList<>(chunkServers); int[] tmp = new int[temp.size()]; for (int j = 0; j < temp.size(); j++) { tmp[j] = temp.get(j); } int i = 0; int size = tmp.length; for (int j = 0; j < 9; j++) { nodes[j] = tmp[i]; i++; if (i >= size) { i = 0; } } } } return nodes; } private int getChunkNumber(String s) { StringBuffer buff = new StringBuffer(s); String lastToken = buff.substring(buff.lastIndexOf("k") + 1); int number = Integer.parseInt(lastToken); return number; } private void addToStructure(String shardName, int[] node) { AddToDataStructure as; as = new AddToDataStructure(shardName, node); Thread t = new Thread(as); t.start(); } private int randomNodeID(int numchnksrvrs) { int item = new Random().nextInt(numchnksrvrs); int j = 0; synchronized (chunkServers) { for (Integer nodeID : chunkServers) { if (j == item) { return nodeID; } j = j + 1; } } return -1; } private class AddToDataStructure implements Runnable { String fileName; int chunkNum; int[] nodes; private AddToDataStructure(String shardName, int[] nodes) { this.fileName = shardName.substring(0, shardName.lastIndexOf("_")); this.chunkNum = getChunkNumber(shardName); this.nodes = nodes; } @Override public void run() { synchronized (dataStructure) { if (!dataStructure.containsKey(fileName)) { dataStructure.put(fileName, new HashMap<>()); } Map<Integer, Map<Integer, Integer>> t1 = dataStructure.get(fileName); if (t1 == null) { t1 = new HashMap<>(); } t1.put(chunkNum, new HashMap<>()); Map<Integer, Integer> t2 = t1.get(chunkNum); if (t2 == null) { t2 = new HashMap<>(); } for (int i = 0; i < 9; i++) { t2.put(i + 1, nodes[i]); } } } } }
41.494475
195
0.534319
edacf3c494350998fb8a0a43abdcb34bfddd516e
152
package rosetta; public class MDC_DIM_X_INTL_UNIT_PER_MIN { public static final String VALUE = "MDC_DIM_X_INTL_UNIT_PER_MIN"; }
16.888889
69
0.703947
f882bf38c7dfd5473afeea0997aa69b51cf858c0
869
package io.nosqlbench.activitytype.cqlverify; public enum DiffType { /// Verify that fields named in the row are present in the reference map. rowfields(0x1), /// Verify that fields in the reference map are present in the row data. reffields(0x1<<1), /// Verify that all fields present in either the row or the reference data /// are also present in the other. fields(0x1|0x1<<1), /// Verify that all values of the same named field are equal, according to /// {@link Object#equals(Object)}}. values(0x1<<2), /// Cross-verify all fields and field values between the reference data and /// the actual data. all(0x1|0x1<<1|0x1<<2); public int bitmask; DiffType(int bit) { this.bitmask = bit; } public boolean is(DiffType option) { return (bitmask & option.bitmask) > 0; } }
25.558824
79
0.650173
6667ad77004cbaaf29761197a71c5fec1908c279
1,187
package gmlviewer.gis.style; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.Stroke; import java.awt.BasicStroke; import gmlviewer.gis.model.Project; public class StrokeStyle extends Style { protected StrokeStyle(Color lineColor, float width, float [] dash ) { this.lineColor = lineColor; this.stroke = new BasicStroke( width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, dash, 0 ); } public void draw(Graphics2D g2, Shape shape) { if ( lineColor != null ) { g2.setColor(lineColor); if( stroke != null ) { g2.setStroke( stroke ); } g2.draw(shape); } } public void fill(Graphics2D g2, Shape shape) { } public void paint(Graphics2D g2, gmlviewer.gis.model.Shape shape, Project proj ) { java.awt.Shape ashape = shape.getShape( proj ); if( ashape != null ) { this.draw( g2, ashape ); } } // member protected Color lineColor; protected Stroke stroke; // static method public static StrokeStyle getStyle(Color lineColor, float width, float [] dash ) { return new StrokeStyle(lineColor, width, dash ); } }
24.729167
87
0.655434
98c4100bf91bb2a8d9bbbceca6179bebdc0b7802
829
package com.moqbus.app.service; import com.moqbus.app.service.mqtt.ControlProxy; public class QueryAndSubscribeThread extends Thread { private static ChildThreadExceptionHandler exceptionHandler; static { exceptionHandler = new ChildThreadExceptionHandler(); } public static class ChildThreadExceptionHandler implements Thread.UncaughtExceptionHandler { public void uncaughtException(Thread t, Throwable e) { System.out.println(String.format("handle exception in child thread. %s", e)); } } @Override public void run() { Thread.currentThread().setUncaughtExceptionHandler(exceptionHandler); System.out.println("QueryAndSubscribeThread run before"); ControlProxy.queryAndSubscribeService(); System.out.println("QueryAndSubscribeThread run after"); } }
27.633333
96
0.750302
411a3750423bae1fc91f09e4fddbb2bdf49a245f
2,771
package com.hmsoft.pentaxgallery.ui.camera; import android.content.Intent; import android.os.Bundle; import android.view.Display; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.Surface; import android.view.WindowManager; import com.hmsoft.pentaxgallery.R; import com.hmsoft.pentaxgallery.camera.Camera; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.FragmentActivity; import androidx.fragment.app.FragmentTransaction; public class CameraActivity extends AppCompatActivity { private static final String TAG = "CameraActivity"; private CameraFragment fragment; public static void start(FragmentActivity activity) { Intent i = new Intent(activity, CameraActivity.class); activity.startActivity(i); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); fragment = (CameraFragment) getSupportFragmentManager().findFragmentByTag(TAG); if (fragment == null) { final FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); fragment = new CameraFragment(); ft.add(android.R.id.content, fragment, TAG); ft.commit(); } setTitle(Camera.instance.getCameraData().getDisplayName()); Display display = ((WindowManager)getSystemService(WINDOW_SERVICE)).getDefaultDisplay(); int rotation = display.getRotation(); if(rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); final ActionBar actionBar = getSupportActionBar(); if(actionBar != null) { actionBar.hide(); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.camera_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if(super.onOptionsItemSelected(item)) { return true; } return fragment != null && fragment.onOptionsItemSelected(item); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (super.onKeyDown(keyCode, event)) { return true; } if(fragment == null) { return false; } switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_DOWN: fragment.shoot(); return true; case KeyEvent.KEYCODE_VOLUME_UP: fragment.focus(); return true; } return false; } }
30.119565
96
0.656442
b3f8f1688ce5ffed583c5181e79729a2a9113e6b
4,602
/* * Copyright 2010-2019 Australian Signals Directorate * * 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 au.gov.asd.tac.constellation.views.conversationview.state; import au.gov.asd.tac.constellation.graph.Attribute; import au.gov.asd.tac.constellation.graph.GraphReadMethods; import au.gov.asd.tac.constellation.graph.GraphWriteMethods; import au.gov.asd.tac.constellation.graph.io.providers.AbstractGraphIOProvider; import au.gov.asd.tac.constellation.graph.io.providers.GraphByteReader; import au.gov.asd.tac.constellation.graph.io.providers.GraphByteWriter; import au.gov.asd.tac.constellation.graph.utilities.ImmutableObjectCache; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonNode; import java.io.IOException; import java.util.Iterator; import java.util.Map; import org.openide.util.lookup.ServiceProvider; /** * The ConversationStateIOProvider supports saving and loading of the * ConversationState when the graph is saved and loaded. * * @author sirius */ @ServiceProvider(service = AbstractGraphIOProvider.class) public class ConversationStateIOProvider extends AbstractGraphIOProvider { private static final String HIDDEN_CONTRIBUTION_PROVIDERS_TAG = "hiddenContributionProviders"; private static final String SENDER_ATTRIBUTES_TAG = "senderAttributes"; @Override public String getName() { return ConversationViewConcept.MetaAttribute.CONVERSATION_VIEW_STATE.getAttributeType(); } @Override public void readObject(int attributeId, int elementId, JsonNode jnode, GraphWriteMethods graph, Map<Integer, Integer> vertexMap, Map<Integer, Integer> transactionMap, GraphByteReader byteReader, ImmutableObjectCache cache) throws IOException { if (!jnode.isNull()) { final ConversationState state = new ConversationState(); JsonNode hiddenContributionProvidersArray = jnode.get(HIDDEN_CONTRIBUTION_PROVIDERS_TAG); Iterator<JsonNode> hiddenContributionProviderIterator = hiddenContributionProvidersArray.iterator(); while (hiddenContributionProviderIterator.hasNext()) { JsonNode hiddenContributionProvider = hiddenContributionProviderIterator.next(); state.getHiddenContributionProviders().add(hiddenContributionProvider.asText()); } JsonNode senderAttributesArray = jnode.get(SENDER_ATTRIBUTES_TAG); Iterator<JsonNode> senderAttributesIterator = senderAttributesArray.iterator(); while (senderAttributesIterator.hasNext()) { JsonNode senderAttribute = senderAttributesIterator.next(); state.getSenderAttributes().add(senderAttribute.asText()); } graph.setObjectValue(attributeId, elementId, state); } } @Override public void writeObject(Attribute attribute, int elementId, JsonGenerator jsonGenerator, GraphReadMethods graph, GraphByteWriter byteWriter, boolean verbose) throws IOException { if (verbose || !graph.isDefaultValue(attribute.getId(), elementId)) { final ConversationState state = (ConversationState) graph.getObjectValue(attribute.getId(), elementId); if (state == null) { jsonGenerator.writeNullField(attribute.getName()); } else { jsonGenerator.writeObjectFieldStart(attribute.getName()); jsonGenerator.writeArrayFieldStart(HIDDEN_CONTRIBUTION_PROVIDERS_TAG); for (String hiddenContributionProvider : state.getHiddenContributionProviders()) { jsonGenerator.writeString(hiddenContributionProvider); } jsonGenerator.writeEndArray(); jsonGenerator.writeArrayFieldStart(SENDER_ATTRIBUTES_TAG); for (String senderAttribute : state.getSenderAttributes()) { jsonGenerator.writeString(senderAttribute); } jsonGenerator.writeEndArray(); jsonGenerator.writeEndObject(); } } } }
46.959184
247
0.726641
a2b87edf887f542164650c98f232394a6e2a791f
1,400
package com.linkedbear.spring.transaction.dao; import com.linkedbear.spring.transaction.util.JdbcUtils; import org.springframework.stereotype.Repository; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; @Repository public class FinanceDao { public void addMoney(Long id, int money) { try { Connection connection = JdbcUtils.getConnection(); PreparedStatement preparedStatement = connection .prepareStatement("update tbl_employee set salary = salary + ? where id = ?"); preparedStatement.setInt(1, money); preparedStatement.setLong(2, id); preparedStatement.executeUpdate(); preparedStatement.close(); connection.close(); } catch (SQLException e) { throw new RuntimeException(e); } } public void subtractMoney(Long id, int money) { try { Connection connection = JdbcUtils.getConnection(); PreparedStatement preparedStatement = connection .prepareStatement("update tbl_employee set salary = salary - ? where id = ?"); preparedStatement.setInt(1, money); preparedStatement.setLong(2, id); preparedStatement.executeUpdate(); } catch (SQLException e) { throw new RuntimeException(e); } } }
34.146341
98
0.64
4f7a01cd37b9631f9d7b7caefad27c3c23748ef3
2,578
package io.github.putrasattvika.jrmcremote.utils.request; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import org.w3c.dom.Document; import org.xml.sax.InputSource; import java.io.ByteArrayInputStream; import java.io.StringReader; import java.net.URL; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; /** * Created by Sattvika on 17-Jan-17. */ public class ResourceRequestUtil { public static Bitmap requestBitmap(URL url) throws ExecutionException, InterruptedException { List<ByteArrayInputStream> bitmapInputStreams = null; Bitmap bitmap = null; try { ByteArrayAsyncRequest asyncRequest = new ByteArrayAsyncRequest(); bitmapInputStreams = asyncRequest.execute(url).get(2000, TimeUnit.MILLISECONDS); } catch (TimeoutException ignore) {} try { bitmap = BitmapFactory.decodeStream(bitmapInputStreams.get(0)); } catch (Exception ignore) {} return bitmap; } public static Document requestDocument(URL url) throws ExecutionException, InterruptedException { try { StringAsyncRequest asyncRequest = new StringAsyncRequest(); List<String> documentStrings = asyncRequest.execute(url).get(); Document doc = null; try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); doc = dBuilder.parse(new InputSource(new StringReader(documentStrings.get(0)))); } catch (Exception e) { e.printStackTrace(); } return doc; } catch (Exception e) { return null; } } public static String requestString(URL url) throws ExecutionException, InterruptedException { try { StringAsyncRequest asyncRequest = new StringAsyncRequest(); List<String> strings = asyncRequest.execute(url).get(); return strings.get(0); } catch (Exception e) { return null; } } public static void request(URL url) throws ExecutionException, InterruptedException { try { StringAsyncRequest asyncRequest = new StringAsyncRequest(); asyncRequest.execute(url); } catch (Exception ignore) {} } }
31.82716
101
0.66796
6f609f4729418d79a6133cc89b315844bd9315e4
6,892
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.omnibox; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; /** * Structured representation of the JSON payload of a suggestion with an answer. An answer has * exactly two image lines, so called because they are a combination of text and an optional * image. Each image line has 0 or more text fields, each of which is required to contain a string * and an integer type. The text fields are contained in a list and two optional named properties, * referred to as "additional text" and "status text". The image, if present, contains a single * string, which may be a URL or base64-encoded image data. * * When represented in the UI, these elements should be styled and layed out according to the * specification at http://goto.google.com/ais_api. */ public class SuggestionAnswer { private static final String TAG = "SuggestionAnswer"; private ImageLine mFirstLine; private ImageLine mSecondLine; private static final String ANSWERS_JSON_LINE = "l"; private static final String ANSWERS_JSON_IMAGE_LINE = "il"; private static final String ANSWERS_JSON_TEXT = "t"; private static final String ANSWERS_JSON_ADDITIONAL_TEXT = "at"; private static final String ANSWERS_JSON_STATUS_TEXT = "st"; private static final String ANSWERS_JSON_TEXT_TYPE = "tt"; private static final String ANSWERS_JSON_IMAGE = "i"; private static final String ANSWERS_JSON_IMAGE_DATA = "d"; private static final String ANSWERS_JSON_NUMBER_OF_LINES = "ln"; private SuggestionAnswer() { } /** * Parses the JSON representation of an answer and constructs a SuggestionAnswer from the * contents. * * @param answerContents The JSON representation of an answer. * @return A SuggestionAnswer with the answer contents or null if the contents are malformed or * missing required elements. */ public static SuggestionAnswer parseAnswerContents(String answerContents) { SuggestionAnswer answer = new SuggestionAnswer(); try { JSONObject jsonAnswer = new JSONObject(answerContents); JSONArray jsonLines = jsonAnswer.getJSONArray(ANSWERS_JSON_LINE); if (jsonLines.length() != 2) { Log.e(TAG, "Answer JSON doesn't contain exactly two lines: " + jsonAnswer); return null; } answer.mFirstLine = new SuggestionAnswer.ImageLine( jsonLines.getJSONObject(0).getJSONObject(ANSWERS_JSON_IMAGE_LINE)); answer.mSecondLine = new SuggestionAnswer.ImageLine( jsonLines.getJSONObject(1).getJSONObject(ANSWERS_JSON_IMAGE_LINE)); } catch (JSONException e) { Log.e(TAG, "Problem parsing answer JSON: " + e.getMessage()); return null; } return answer; } /** * Returns the first of the two required image lines. */ public ImageLine getFirstLine() { return mFirstLine; } /** * Returns the second of the two required image lines. */ public ImageLine getSecondLine() { return mSecondLine; } /** * Represents a single line of an answer, containing any number of typed text fields and an * optional image. */ public static class ImageLine { private final List<TextField> mTextFields; private final TextField mAdditionalText; private final TextField mStatusText; private final String mImage; ImageLine(JSONObject jsonLine) throws JSONException { mTextFields = new ArrayList<TextField>(); JSONArray textValues = jsonLine.getJSONArray(ANSWERS_JSON_TEXT); for (int i = 0; i < textValues.length(); i++) { mTextFields.add(new TextField(textValues.getJSONObject(i))); } mAdditionalText = jsonLine.has(ANSWERS_JSON_ADDITIONAL_TEXT) ? new TextField(jsonLine.getJSONObject(ANSWERS_JSON_ADDITIONAL_TEXT)) : null; mStatusText = jsonLine.has(ANSWERS_JSON_STATUS_TEXT) ? new TextField(jsonLine.getJSONObject(ANSWERS_JSON_STATUS_TEXT)) : null; mImage = jsonLine.has(ANSWERS_JSON_IMAGE) ? jsonLine.getJSONObject(ANSWERS_JSON_IMAGE).getString(ANSWERS_JSON_IMAGE_DATA) : null; } /** * Return an unnamed list of text fields. These represent the main content of the line. */ public List<TextField> getTextFields() { return mTextFields; } /** * Returns true if the line contains an "additional text" field. */ public boolean hasAdditionalText() { return mAdditionalText != null; } /** * Return the "additional text" field. */ public TextField getAdditionalText() { return mAdditionalText; } /** * Returns true if the line contains an "status text" field. */ public boolean hasStatusText() { return mStatusText != null; } /** * Return the "status text" field. */ public TextField getStatusText() { return mStatusText; } /** * Returns true if the line contains an image. */ public boolean hasImage() { return mImage != null; } /** * Return the optional image (URL or base64-encoded image data). */ public String getImage() { return mImage; } } /** * Represents one text field of an answer, containing a integer type and a string. */ public static class TextField { private final int mType; private final String mText; private final int mNumLines; TextField(JSONObject jsonTextField) throws JSONException { mType = jsonTextField.getInt(ANSWERS_JSON_TEXT_TYPE); mText = jsonTextField.getString(ANSWERS_JSON_TEXT); mNumLines = jsonTextField.has(ANSWERS_JSON_NUMBER_OF_LINES) ? jsonTextField.getInt(ANSWERS_JSON_NUMBER_OF_LINES) : -1; } public int getType() { return mType; } public String getText() { return mText; } public boolean hasNumLines() { return mNumLines != -1; } public int getNumLines() { return mNumLines; } } }
33.619512
99
0.627249
8650158e675dda7909f9f26a3058dfff1933433f
489
package com.example.bootiful_restaurant_reviews.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToOne; import java.io.Serializable; @Data @NoArgsConstructor @AllArgsConstructor @Entity(name = "users_roles") public class UserRole implements Serializable { @Id @ManyToOne private User user; @Id @ManyToOne private Role role; }
20.375
54
0.785276
c4843c6f5997a49befdce12f50147935b31f0678
3,890
package org.apache.ofbiz.shipment.receipt; import lombok.experimental.FieldNameConstants; import java.io.Serializable; import lombok.Getter; import lombok.Setter; import java.sql.Timestamp; import java.math.BigDecimal; import org.apache.ofbiz.entity.GenericValue; import java.util.List; import java.util.ArrayList; /** * Shipment Receipt */ @FieldNameConstants public class ShipmentReceipt implements Serializable { public static final long serialVersionUID = 6954476232143128576L; public static final String NAME = "ShipmentReceipt"; /** * Receipt Id */ @Getter @Setter private String receiptId; /** * Inventory Item Id */ @Getter @Setter private String inventoryItemId; /** * Product Id */ @Getter @Setter private String productId; /** * Shipment Id */ @Getter @Setter private String shipmentId; /** * Shipment Item Seq Id */ @Getter @Setter private String shipmentItemSeqId; /** * Shipment Package Seq Id */ @Getter @Setter private String shipmentPackageSeqId; /** * Order Id */ @Getter @Setter private String orderId; /** * Order Item Seq Id */ @Getter @Setter private String orderItemSeqId; /** * Return Id */ @Getter @Setter private String returnId; /** * Return Item Seq Id */ @Getter @Setter private String returnItemSeqId; /** * Rejection Id */ @Getter @Setter private String rejectionId; /** * Received By User Login Id */ @Getter @Setter private String receivedByUserLoginId; /** * Datetime Received */ @Getter @Setter private Timestamp datetimeReceived; /** * Item Description */ @Getter @Setter private String itemDescription; /** * Quantity Accepted */ @Getter @Setter private BigDecimal quantityAccepted; /** * Quantity Rejected */ @Getter @Setter private BigDecimal quantityRejected; /** * Last Updated Stamp */ @Getter @Setter private Timestamp lastUpdatedStamp; /** * Last Updated Tx Stamp */ @Getter @Setter private Timestamp lastUpdatedTxStamp; /** * Created Stamp */ @Getter @Setter private Timestamp createdStamp; /** * Created Tx Stamp */ @Getter @Setter private Timestamp createdTxStamp; public ShipmentReceipt(GenericValue value) { receiptId = (String) value.get(FIELD_RECEIPT_ID); inventoryItemId = (String) value.get(FIELD_INVENTORY_ITEM_ID); productId = (String) value.get(FIELD_PRODUCT_ID); shipmentId = (String) value.get(FIELD_SHIPMENT_ID); shipmentItemSeqId = (String) value.get(FIELD_SHIPMENT_ITEM_SEQ_ID); shipmentPackageSeqId = (String) value .get(FIELD_SHIPMENT_PACKAGE_SEQ_ID); orderId = (String) value.get(FIELD_ORDER_ID); orderItemSeqId = (String) value.get(FIELD_ORDER_ITEM_SEQ_ID); returnId = (String) value.get(FIELD_RETURN_ID); returnItemSeqId = (String) value.get(FIELD_RETURN_ITEM_SEQ_ID); rejectionId = (String) value.get(FIELD_REJECTION_ID); receivedByUserLoginId = (String) value .get(FIELD_RECEIVED_BY_USER_LOGIN_ID); datetimeReceived = (Timestamp) value.get(FIELD_DATETIME_RECEIVED); itemDescription = (String) value.get(FIELD_ITEM_DESCRIPTION); quantityAccepted = (BigDecimal) value.get(FIELD_QUANTITY_ACCEPTED); quantityRejected = (BigDecimal) value.get(FIELD_QUANTITY_REJECTED); lastUpdatedStamp = (Timestamp) value.get(FIELD_LAST_UPDATED_STAMP); lastUpdatedTxStamp = (Timestamp) value.get(FIELD_LAST_UPDATED_TX_STAMP); createdStamp = (Timestamp) value.get(FIELD_CREATED_STAMP); createdTxStamp = (Timestamp) value.get(FIELD_CREATED_TX_STAMP); } public static ShipmentReceipt fromValue( org.apache.ofbiz.entity.GenericValue value) { return new ShipmentReceipt(value); } public static List<ShipmentReceipt> fromValues(List<GenericValue> values) { List<ShipmentReceipt> entities = new ArrayList<>(); for (GenericValue value : values) { entities.add(new ShipmentReceipt(value)); } return entities; } }
21.731844
76
0.734447
e35bbd5939a1922a972854b7c819eb3aee820c7f
3,286
import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class XMLParser { public static void main(String[] args) throws FileNotFoundException, XMLStreamException { List<Employee> employees = null; Employee empl = null; String text = null; XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader reader = factory.createXMLStreamReader(new FileInputStream( new File("./tests.rdf"))); while (reader.hasNext()) { System.out.println(reader.next()); // int Event = reader.next(); // switch (Event) { // case XMLStreamConstants.START_ELEMENT: { // if ("Employee".equals(reader.getLocalName())) { // empl = new Employee(); // empl.setID(reader.getAttributeValue(0)); // } // if ("Employees".equals(reader.getLocalName())) // employees = new ArrayList<>(); // break; // } // case XMLStreamConstants.CHARACTERS: { // text = reader.getText().trim(); // break; // } // case XMLStreamConstants.END_ELEMENT: { // switch (reader.getLocalName()) { // case "Employee": { // employees.add(empl); // break; // } // case "Firstname": { // empl.setFirstname(text); // break; // } // case "Lastname": { // empl.setLastname(text); // break; // } // case "Age": { // empl.setAge(Integer.parseInt(text)); // break; // } // case "Salary": { // empl.setSalary(Double.parseDouble(text)); // break; // } // } // break; // } // } } // Print all employees. for (Employee employee : employees) System.out.println(employee.toString()); } }
39.590361
93
0.400183
d91ac8542d91653360a8ca2303fe48d79fb82670
287
package com.yizhiteamo.ufood.entity; import lombok.Data; /** * @author Ralts */ @Data public class Order { private Integer id; private String orderTime; private String userInfo; private String orderContent; private String createTime; private String status; }
16.882353
36
0.710801
9b8b3306c1f99abeed575a10a62b87df629174c2
605
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: compiler/ir/serialization.common/src/KotlinIr.proto package org.jetbrains.kotlin.backend.common.serialization.proto; public interface IrErrorDeclarationOrBuilder extends // @@protoc_insertion_point(interface_extends:org.jetbrains.kotlin.backend.common.serialization.proto.IrErrorDeclaration) org.jetbrains.kotlin.protobuf.MessageLiteOrBuilder { /** * <code>required int64 coordinates = 1;</code> */ boolean hasCoordinates(); /** * <code>required int64 coordinates = 1;</code> */ long getCoordinates(); }
33.611111
125
0.757025
3139506499380f9877fd4c76fa38d301721eee91
2,834
package scraper.hooks; import scraper.annotations.ArgsCommand; import scraper.annotations.NotNull; import scraper.annotations.node.NodePlugin; import scraper.api.di.DIContainer; import scraper.api.plugin.Hook; import scraper.api.specification.ScrapeInstance; import scraper.api.specification.ScrapeSpecification; import scraper.utils.StringUtil; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintWriter; import java.nio.file.Path; import java.util.HashSet; import java.util.Map; import java.util.Set; import static java.lang.System.Logger.Level.DEBUG; import static java.lang.System.Logger.Level.INFO; /** * Hook to generate a node dependency file for the currently parsed workflow specifications */ @ArgsCommand( value = "ndep", doc = "Generated a node dependency file for all parsed scrape specifications", example = "scraper app.scrape ndep exit" ) public class NodeDependencyGeneratorHook implements Hook { private static final System.Logger log = System.getLogger("NodeVersioning"); @Override public void execute(@NotNull final DIContainer dependencies, @NotNull final String[] args, @NotNull final Map<ScrapeSpecification, ScrapeInstance> jobs) throws Exception { // == // node dependency generation // == String createNodeDependencies = StringUtil.getArgument(args, "ndep"); if(createNodeDependencies != null) { log.log(DEBUG, "Generating node dependencies"); for (ScrapeSpecification job : jobs.keySet()) { Path path; if(createNodeDependencies.isEmpty()) path = Path.of(job.getScrapeFile().toString()+".ndep"); else path = Path.of(createNodeDependencies, job.getName()+".ndep"); log.log(DEBUG, "Creating node dependencies file at {0}", path.toString()); generateNodeDependencies(jobs.get(job), path.toString()); } } } private void generateNodeDependencies(ScrapeInstance scrapeInstance, String path) throws FileNotFoundException { File f = new File(path); Set<String> nodes = new HashSet<>(); scrapeInstance.getRoutes().forEach(((address, nodeContainer) -> { String type = nodeContainer.getC().getClass().getSimpleName(); String version = nodeContainer.getC().getClass().getDeclaredAnnotation(NodePlugin.class).value(); nodes.add(type+":"+version); })); try(PrintWriter pw = new PrintWriter(new FileOutputStream(f))) { for (String node : nodes) { pw.println(node); } } } @Override public String toString() { return "NodeDependencyGenerator"; } }
36.333333
116
0.667255
4558fdfb84fa0232eb73ef66836d78d936057cf5
851
package com.phaosoft.android.popularmovies.model; /** * Trailers data model module */ public class Trailer { private String key = null; private String name = null; private String videoUrl = null; private String pictureUrl = null; public Trailer() {} public Trailer(String key, String name, String videoUrl, String pictureUrl) { this.key = key; this.name = name; this.videoUrl = videoUrl; this.pictureUrl = pictureUrl; } public String getKey() { return key; } public String getName() { return name; } public String getVideoUrl() { return videoUrl; } public String getPictureUrl() { return pictureUrl; } @Override public String toString() { return this.key + ":" + this.name + ":" + pictureUrl; } }
20.261905
81
0.60047
2d6ab170a4ea34e8bb79474647e125ab506a8dcd
973
package ar.com.ada3d.frontend; import com.ibm.xsp.extlib.tree.impl.BasicLeafTreeNode; import com.ibm.xsp.extlib.tree.impl.BasicNodeList; public class LayoutTitleBarActions extends BasicNodeList { private static final long serialVersionUID = 1L; public LayoutTitleBarActions() { addLeaf("Nuevo Gasto", "btnClose"); addLeaf("Alta de Proveedor", "btnSave"); addLeaf("Pagar", "btnPagar"); addLeaf("Recalcular", "btnClose"); } private void addLeaf(String label, String boton) { BasicLeafTreeNode node = new BasicLeafTreeNode(); node.setLabel(label); //node.setHref("/Project_View.xsp" ); //node.setOnClick("alert('On Click');"); //String script = "window.open(\"" + url.toString() + "\");"; //String script = "$(\"[id$='#{id:btnClose}']\").get(0).click()" ; String script = "dojo.query(\"[id$='" + boton + "']\")[0].click();"; node.setOnClick(script); //node.setOnClick("XSP.getElementById('#{id:btnClose}').click()"); addChild(node); } }
30.40625
69
0.677287
32bd673a13e3e897c69099aecce41387f1162d6e
1,688
package workerManagerResourceSpotAllocation; import java.util.HashMap; import bwapi.Unit; /** * RefineryManager.java --- {@link ResourceManager} for refineries. The * {@link GatheringSource}s that this Class holds are all the currently existing * / constructed refineries on the map of the Player. * * @author P H - 03.09.2017 * */ class RefineryManager<T extends GatheringSource> extends ResourceManager<GatheringSource> { private HashMap<Unit, RefineryWrapper> mappedRefineries = new HashMap<>(); public RefineryManager(WorkerManagerResourceSpotAllocation workerManagerResourceSpotAllocation) { super(workerManagerResourceSpotAllocation); } // -------------------- Functions /** * Function for adding a refinery to the ones that are being managed by this * instance and considered in the accessible gathering sources. * * @param unit * the refinery that is going to be managed by this Class. */ public void addRefinery(Unit unit) { RefineryWrapper refineryWrapper = new RefineryWrapper(unit, this); this.gatheringSources.add(refineryWrapper); this.mappedRefineries.put(unit, refineryWrapper); } /** * Function for removing a refinery from the accessible gathering sources. * * @param unit * the refinery that is going to be removed from the List of * managed gathering sources. */ public void removeRefinery(Unit unit) { GatheringSource refineryWrapper = this.mappedRefineries.get(unit); // Remove the mapped entries (List before HashMap!). this.gatheringSources.remove(refineryWrapper); this.mappedRefineries.remove(unit); } }
30.690909
99
0.710308
5a3f5d5b505dd50bbd7b1c51e34a2b76510ceeed
2,007
import java.util.HashMap; import java.util.Map; public class TabIdent { private int nbVar; private int nbParam; private HashMap<String,IdFunct> table_globaux; private HashMap<String,Ident> table_locaux; public TabIdent() { this.nbVar = 0; this.nbParam = 0; this.table_locaux = new HashMap<String, Ident>(); this.table_globaux = new HashMap<String, IdFunct>(); } public Ident chercheIdent(String clef){ return table_locaux.get(clef); } public IdFunct chercheFonction(String clef) { return table_globaux.get(clef); } public boolean existeIdent(String clef){ return table_locaux.containsKey(clef); } public void rangeIdent(String clef, IdConst id){ if(table_locaux.containsKey(clef) || table_globaux.containsKey(clef)) { Yaka.yvm.ecrireErreur("Error : Ident '"+clef+"' already exists."); } table_locaux.put(clef, id); } public void rangeIdent(String clef, IdVar id){ if(table_locaux.containsKey(clef) || table_globaux.containsKey(clef)) { Yaka.yvm.ecrireErreur("Error : Ident '"+clef+"' already exists."); } id.setValue((nbVar+1)*(-2)); table_locaux.put(clef, id); this.nbVar++; } public int getNbParam() { return nbParam; } public int getNbVar() { return nbVar; } public void rangeParam(String clef, IdVar id) { this.nbParam++; id.setValue(nbParam); table_locaux.put(clef, id); } public void rangeIdent(String clef, IdFunct id) { if(table_locaux.containsKey(clef) || table_globaux.containsKey(clef)) { Yaka.yvm.ecrireErreur("Error : Ident '"+clef+"' already exists."); } table_globaux.put(clef, id); } public void initLocaux() { this.table_locaux.clear(); this.nbParam = 0; this.nbVar = 0; } public String toString() { String ret = ""; for (Map.Entry<String, Ident> entry : table_locaux.entrySet()) { ret += "(" + entry.getKey() + " : " + entry.getValue() + ")\n"; } return ret; } public HashMap<String, Ident> gettable_locaux() { return table_locaux; } }
20.90625
71
0.678127
21433ab4de7ebe1660bcaf07ebaa8364e3d0b575
2,398
package top.zhogjianhao; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.*; @Slf4j @DisplayName("集合工具类测试") public class CollectionUtilsTest { private void println(Object source) { System.out.println(source); } @DisplayName("isEmpty:是否为 null 或没有元素") @Test void isEmpty() { List<String> list = new ArrayList<>(); println("空列表:" + CollectionUtils.isEmpty(list)); list.add(null); println("[0] 为 null 的列表:" + CollectionUtils.isEmpty(list)); } @DisplayName("sizeIsEmpty:是否为 null 或没有元素") @Test void sizeIsEmpty() { List<String> list = new ArrayList<>(); println("空列表:" + CollectionUtils.sizeIsEmpty(list)); list.add(null); println("[0] = null 的列表:" + CollectionUtils.sizeIsEmpty(list)); Map<String, Object> map = new HashMap<>(); println("空键值对:" + CollectionUtils.sizeIsEmpty(map)); map.put(null, null); println("{null, null} 的键值对:" + CollectionUtils.sizeIsEmpty(map)); // TODO …… } @DisplayName("isAllEmpty:是否所有元素都为 null") @Test void isAllEmpty() { List<String> list = new ArrayList<>(); list.add(null); println("[0] 为 null 的列表:" + CollectionUtils.isAllEmpty(list)); Map<String, Object> map = new HashMap<>(); map.put("", null); println("{\"\", null} 的键值对:" + CollectionUtils.isAllEmpty(map)); println("[null] 的数组:" + CollectionUtils.isAllEmpty(new Object[]{null})); println("[0] 为 null 的迭代器(Iterator):" + CollectionUtils.isAllEmpty(list.iterator())); Vector<String> vector = new Vector<>(); vector.add(null); println("[0] 为 null 的枚举:" + CollectionUtils.isAllEmpty(vector.elements())); } @DisplayName("isAnyEmpty:是否任意元素为 null") @Test void isAnyEmpty() { List<String> list = new ArrayList<>(); list.add(null); list.add(""); println("[0] 为 null 的列表:" + CollectionUtils.isAnyEmpty(list)); Map<String, Object> map = new HashMap<>(); map.put("", null); println("{\"\", null} 的键值对:" + CollectionUtils.isAnyEmpty(map)); println("[null] 的数组:" + CollectionUtils.isAnyEmpty(new Object[]{null, 1})); println("[0] 为 null 的迭代器(Iterator):" + CollectionUtils.isAnyEmpty(list.iterator())); Vector<String> vector = new Vector<>(); vector.add(null); vector.add(""); println("[0] 为 null 的枚举:" + CollectionUtils.isAnyEmpty(vector.elements())); } }
32.405405
88
0.651376
8d85846c989a9ce8e48ef3b7945a9415521add59
1,409
/** * Created by mt on 11/10/2015. */ package socketex.core; import java.net.Inet4Address; import java.net.UnknownHostException; public class HostName { String ip; int port; public HostName(String ip, int port) { if(ip.equals("127.0.0.1") || ip.equals("localhost")) { try { ip = Inet4Address.getLocalHost().getHostAddress(); // try to get the real IP } catch (UnknownHostException e) { } } this.ip = ip; this.port = port; } public static HostName valueOf(String s) { if(StringEx.isNullOrWhiteSpace(s)) throw new IllegalArgumentException("String is not HostName"); String []parts = s.split(":"); if(parts.length != 2) throw new IllegalArgumentException("String is not HostName"); return new HostName(parts[0], Integer.valueOf(parts[1])); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; HostName h = (HostName)obj; return ip.equals(h.ip) && port == h.port; } @Override public int hashCode() { return ip.hashCode() ^ port; } @Override public String toString() { return ip + ":" + port; } }
25.160714
92
0.551455
6ebdfcdcdf87fcae1c36704b4c00e2a31d8c09e7
766
package org.scaffoldeditor.scaffold.io; import java.io.IOException; import java.io.InputStream; import org.scaffoldeditor.nbt.schematic.Structure; import net.querz.nbt.io.NBTDeserializer; import net.querz.nbt.tag.CompoundTag; public class StructureAsset extends BlockCollectionAsset<Structure> { public StructureAsset() { super(Structure.class); } public static void register() { AssetLoaderRegistry.registry.put("nbt", new StructureAsset()); } @Override public Structure loadAsset(InputStream in) throws IOException { CompoundTag map = (CompoundTag) new NBTDeserializer(true).fromStream(in).getTag(); if (map == null) { throw new IOException("Improperly formatted structure file!"); } return Structure.fromCompoundMap(map); } }
23.212121
84
0.761097
abc7079c38fe35027fb80a24efc9e8d974100e3c
2,471
/** * <p>Copyright: Copyright (c) 2019</p> * * <h3>License</h3> * * Copyright (c) 2019 by Jonatan Gomez-Perdomo. <br> * All rights reserved. <br> * * <p>Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * <ul> * <li> Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * <li> 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. * <li> Neither the name of the copyright owners, their employers, nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * </ul> * <p>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 OWNERS 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. * * * * @author <A HREF="http://disi.unal.edu.co/profesores/jgomezpe"> Jonatan Gomez-Perdomo </A> * (E-mail: <A HREF="mailto:[email protected]">[email protected]</A> ) * @version 1.0 */ package speco.list; /** * <p>A list node. The list is double linked</p> * @param <T> Type of elements stored by the Node */ public class Node<T> { /** * The next node in the list */ protected Node<T> next = null; /** * The previous node in the list */ protected Node<T> prev = null; /** * The object stored in the node */ protected T data = null; /** * Constructor: Creates a node with the given data. The next attribute is set to null * @param data The object stored by the node */ public Node(T data) { this.data = data; } protected Node(){} }
36.338235
92
0.719951
5b569b682503bbf839baccedec6cb830788e6b3d
651
package HW2_Copy_List_with_Random_Pointer_138; import java.util.HashMap; // 138. Copy List with Random Pointer. // first define a Node class public class Solution { public Node copyRandomList(Node head){ HashMap<Node, Node> map = new HashMap<>(); Node curr = head; while(curr != null){ map.put(curr, new Node(curr.val)); curr = curr.next; } curr = head; while(curr != null){ map.get(curr).next = map.get(curr.next); map.get(curr).random = map.get(curr.random); curr = curr.next; } return map.get(head); } }
25.038462
56
0.557604
0b5e7da1be0cb3a9a2067c081b189ce1d65fcf74
5,736
package de.citec.sc.sentence.preprocessing.sparql; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.jena.query.Query; import org.apache.jena.query.QueryExecution; import org.apache.jena.query.QueryExecutionFactory; import org.apache.jena.query.QueryFactory; import org.apache.jena.query.QuerySolution; import org.apache.jena.query.ResultSet; public class Sparql { public static List<String> retrieveEntities(String endpoint, String uri, String language){ List<String> entities = new ArrayList<String>(); /* * If label is given, this is the case for the dbpedia object property */ entities.addAll(getValues(endpoint, getQueryLabel(language,uri),language,uri)); /* * if no label is found try to get everything from the right side, e.g. if datatype property is given */ if (entities.size()==0){ entities.addAll(getValues(endpoint, getQueryData(language,uri),language,uri)); } return entities; } private static String getQueryLabel(String language, String uri){ String query = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> " + "SELECT DISTINCT ?y ?subj ?obj ?x WHERE {" + "?y <"+uri+"> ?x." + "{?y rdfs:label ?subj. FILTER (lang(?subj) = '"+language+"')} UNION" + "{?y rdfs:label ?subj. FILTER (lang(?subj) = 'en')}" + "{?x rdfs:label ?obj. FILTER (lang(?obj) = '"+language+"')} UNION" + "{?x rdfs:label ?obj. FILTER (lang(?obj) = 'en')}" + "}"; return query; } private static String getQueryData(String language, String uri){ String query = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> " + "SELECT DISTINCT ?y ?subj ?obj WHERE " + "{?y <"+uri+"> ?obj. " + "{?y rdfs:label ?subj. FILTER (lang(?subj) = '"+language+"')} UNION" + "{?y rdfs:label ?subj. FILTER (lang(?subj) = 'en')}" + "}"; return query; } private static List<String> getValues(String endpoint, String queryString, String language, String uri){ //System.out.println(queryString); int number_entityPairs = getNumberEntityPairs(uri,endpoint); List<String> entities = new ArrayList<String>(); if(number_entityPairs<10000) entities.addAll(executeQuery(queryString,endpoint,language)); else{ int limit = 2000; int offset = 0; for(int i = 0; i<number_entityPairs/2000;i++){ offset = i*2000; String tmp_query = queryString+" LIMIT "+limit+" OFFSET "+offset; entities.addAll(executeQuery(tmp_query,endpoint,language)); } if((offset+limit)<number_entityPairs){ String tmp_query = queryString+" OFFSET "+offset; entities.addAll(executeQuery(tmp_query,endpoint,language)); } } return entities; } private static int getNumberEntityPairs(String property, String endpoint) { int numbers = 0; String queryString = "SELECT (COUNT(DISTINCT *) as ?count) WHERE{?x <"+property+"> ?y}"; System.out.println(queryString); Query query = QueryFactory.create(queryString); QueryExecution qexec = QueryExecutionFactory.sparqlService(endpoint, query); ResultSet results = qexec.execSelect(); while ( results.hasNext() ) { QuerySolution qs = results.next(); numbers = Integer.valueOf(qs.get("?count").toString().replace("^^http://www.w3.org/2001/XMLSchema#integer","")); } return numbers; } private static List<String> executeQuery(String queryString, String endpoint, String language) { // System.out.println(queryString); Query query = QueryFactory.create(queryString); List<String> entities = new ArrayList<String>(); QueryExecution qexec = QueryExecutionFactory.sparqlService(endpoint, query); try { ResultSet results = qexec.execSelect(); while ( results.hasNext() ) { QuerySolution qs = results.next(); try{ String subj = qs.get("?subj").toString(); String subj_uri = qs.get("?y").toString(); String obj_uri = ""; try{ obj_uri = qs.get("?x").toString(); } catch(Exception e){ obj_uri = qs.get("?obj").toString(); } String obj = qs.get("?obj").toString(); String entityPair = subj_uri+"\t"+subj+"\t"+obj+"\t"+obj_uri; entityPair = entityPair.replace("@en", ""); entityPair = entityPair.replace("@"+language, ""); //System.out.println("entityPair:"+entityPair); entities.add(entityPair); } catch(Exception e){ e.printStackTrace(); //ignore those without Frequency TODO:Check Source of Error } } } catch(Exception e){ e.printStackTrace(); //ignore those without Frequency TODO:Check Source of Error } return entities; } }
42.176471
125
0.537308
4da5d0cabeba2368f173dc4db24380e820423306
4,718
/* * Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved. * * 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.hazelcast.sql.impl.exec.scan; import com.hazelcast.internal.serialization.Data; import com.hazelcast.internal.util.Clock; import com.hazelcast.map.impl.MapContainer; import com.hazelcast.map.impl.record.Record; import com.hazelcast.map.impl.recordstore.RecordStore; import com.hazelcast.spi.exception.RetryableHazelcastException; import com.hazelcast.sql.SqlErrorCode; import com.hazelcast.sql.impl.QueryException; import java.util.Iterator; import java.util.Map; /** * Iterator over map partitions. */ @SuppressWarnings("rawtypes") public class MapScanExecIterator implements KeyValueIterator { private final MapContainer map; private final Iterator<Integer> partsIterator; private final long now = Clock.currentTimeMillis(); private RecordStore currentRecordStore; private Iterator<Map.Entry<Data, Record<Object>>> currentRecordStoreIterator; private Data currentKey; private Object currentValue; private Data nextKey; private Object nextValue; public MapScanExecIterator(MapContainer map, Iterator<Integer> partsIterator) { this.map = map; this.partsIterator = partsIterator; advance0(); } @Override public boolean tryAdvance() { if (!done()) { currentKey = nextKey; currentValue = nextValue; advance0(); return true; } else { return false; } } @Override public boolean done() { return nextKey == null; } /** * Get the next key/value pair from the store. */ @SuppressWarnings("unchecked") private void advance0() { while (true) { // Move to the next record store if needed. if (currentRecordStoreIterator == null) { if (!partsIterator.hasNext()) { nextKey = null; nextValue = null; return; } else { int nextPart = partsIterator.next(); boolean isOwned = map.getMapServiceContext().getOwnedPartitions().contains(nextPart); if (!isOwned) { throw QueryException.error( SqlErrorCode.PARTITION_NOT_OWNED, "Partition is not owned by member: " + nextPart ).withInvalidate(); } currentRecordStore = map.getMapServiceContext().getRecordStore(nextPart, map.getName()); if (currentRecordStore == null) { // RecordStore might be missing if the associated partition is empty. Just skip it. continue; } try { currentRecordStore.checkIfLoaded(); } catch (RetryableHazelcastException e) { throw QueryException.error(SqlErrorCode.MAP_LOADING_IN_PROGRESS, "Map loading is in progress: " + map.getName(), e); } currentRecordStoreIterator = currentRecordStore.getStorage().mutationTolerantIterator(); } } assert currentRecordStoreIterator != null; // Move to the next valid entry inside the record store. while (currentRecordStoreIterator.hasNext()) { Map.Entry<Data, Record<Object>> entry = currentRecordStoreIterator.next(); if (!currentRecordStore.isExpired(entry.getValue(), now, false)) { nextKey = entry.getKey(); nextValue = entry.getValue().getValue(); return; } } // No matching entries in this store, move to the next one. currentRecordStore = null; currentRecordStoreIterator = null; } } @Override public Object getKey() { return currentKey; } @Override public Object getValue() { return currentValue; } }
31.878378
119
0.597923
a7de6053c28695bb6fd9bef616af64b8330f83c0
351
package org.gameontext.iotboard.provider.browser; import java.util.ArrayList; import java.util.List; public class DeviceList { private List<String> devices = new ArrayList<String>(); public void add(String deviceId) { devices.add(deviceId); } public List<String> getDevices() { return devices; } }
17.55
59
0.65812
7a03cc340e19c906db2e3dbbe522a58b91e2582a
2,635
/** * Copyright 2007 Cordys R&D B.V. * * This file is part of the Cordys Email IO Connector. * * 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.cordys.coe.ac.emailio.method; import com.cordys.coe.ac.emailio.config.IEmailIOConfiguration; import com.cordys.coe.ac.emailio.exception.EmailIOException; import com.eibus.soap.BodyBlock; /** * This class is the base class for handling specific methods. * * @author pgussow */ public abstract class BaseMethod { /** * Holds the request bodyblock. */ private BodyBlock m_bbRequest; /** * Holds the response bodyblock. */ private BodyBlock m_bbResponse; /** * Holds the configuration of the connector. */ private IEmailIOConfiguration m_iecConfig; /** * Constructor. * * @param bbRequest The request bodyblock. * @param bbResponse The response bodyblock. * @param iecConfig The configuration of the connector. */ public BaseMethod(BodyBlock bbRequest, BodyBlock bbResponse, IEmailIOConfiguration iecConfig) { m_bbRequest = bbRequest; m_bbResponse = bbResponse; m_iecConfig = iecConfig; } /** * This method executed the requested SOAP method. * * @throws EmailIOException In case of any processing errors. */ public abstract void execute() throws EmailIOException; /** * This method gets the configuration for the connector. * * @return The configuration for the connector. */ public IEmailIOConfiguration getConfiguration() { return m_iecConfig; } /** * This method gets the request bodyblock. * * @return The request bodyblock. */ public BodyBlock getRequest() { return m_bbRequest; } /** * This method gets the response bodyblock. * * @return The response bodyblock. */ public BodyBlock getResponse() { return m_bbResponse; } }
26.616162
98
0.632258
ee93365aeab72cdf3bd4d37f9b3e1b7cc26aced8
4,678
/* * See LICENSE file in distribution for copyright and licensing information. */ package org.yecht; /** * * @author <a href="mailto:[email protected]">Ola Bini</a> */ public class YAML { public final static int BLOCK_FOLD = 10; public final static int BLOCK_LIT = 20; public final static int BLOCK_PLAIN = 30; public final static int NL_CHOMP = 40; public final static int NL_KEEP = 50; public final static int YAML_MAJOR = 1; public final static int YAML_MINOR = 0; public final static String YECHT_VERSION = "0.0.2"; public final static String DOMAIN = "yaml.org,2002"; public final static int ALLOC_CT = 8; public final static int BUFFERSIZE = 4096; public final static String DEFAULT_ANCHOR_FORMAT = "id%03d"; /* specify list of bytecodes */ public final static byte BYTE_FINISH = (byte) 0; public final static byte BYTE_DOCUMENT = (byte)'D'; public final static byte BYTE_DIRECTIVE = (byte)'V'; public final static byte BYTE_PAUSE = (byte)'P'; public final static byte BYTE_MAPPING = (byte)'M'; public final static byte BYTE_SEQUENCE = (byte)'Q'; public final static byte BYTE_END_BRANCH = (byte)'E'; public final static byte BYTE_SCALAR = (byte)'S'; public final static byte BYTE_CONTINUE = (byte)'C'; public final static byte BYTE_NEWLINE = (byte)'N'; public final static byte BYTE_NULLCHAR = (byte)'Z'; public final static byte BYTE_ANCHOR = (byte)'A'; public final static byte BYTE_ALIAS = (byte)'R'; public final static byte BYTE_TRANSFER = (byte)'T'; /* formatting bytecodes */ public final static byte BYTE_COMMENT = (byte)'c'; public final static byte BYTE_INDENT = (byte)'i'; public final static byte BYTE_STYLE = (byte)'s'; /* other bytecodes */ public final static byte BYTE_LINE_NUMBER = (byte)'#'; public final static byte BYTE_WHOLE_SCALAR = (byte)'<'; public final static byte BYTE_NOTICE = (byte)'!'; public final static byte BYTE_SPAN = (byte)')'; public final static byte BYTE_ALLOC = (byte)'@'; /* second level style bytecodes, ie "s>" */ public final static byte BYTE_FLOW = (byte)'>'; public final static byte BYTE_LITERAL = (byte)'|'; public final static byte BYTE_BLOCK = (byte)'b'; public final static byte BYTE_PLAIN = (byte)'p'; public final static byte BYTE_INLINE_MAPPING = (byte)'{'; public final static byte BYTE_INLINE_SEQUENCE = (byte)'['; public final static byte BYTE_SINGLE_QUOTED = (byte)39; public final static byte BYTE_DOUBLE_QUOTED = (byte)'"'; public static byte[] realloc(byte[] input, int size) { byte[] newArray = new byte[size]; System.arraycopy(input, 0, newArray, 0, input.length); return newArray; } public static long[] realloc(long[] input, int size) { long[] newArray = new long[size]; System.arraycopy(input, 0, newArray, 0, input.length); return newArray; } public static Level[] realloc(Level[] input, int size) { Level[] newArray = new Level[size]; System.arraycopy(input, 0, newArray, 0, input.length); return newArray; } public static Object[] realloc(Object[] input, int size) { Object[] newArray = new Object[size]; System.arraycopy(input, 0, newArray, 0, input.length); return newArray; } // syck_yaml2byte public static byte[] yaml2byte(byte[] yamlstr) { Parser parser = Parser.newParser(); parser.str(Pointer.create(yamlstr, 0), null); parser.handler(new BytecodeNodeHandler()); parser.errorHandler(null); parser.implicitTyping(true); parser.taguriExpansion(true); Bytestring sav = (Bytestring)parser.parse(); if(null == sav) { return null; } else { byte[] ret = new byte[Bytestring.strlen(sav.buffer) + 2]; ret[0] = 'D'; ret[1] = '\n'; System.arraycopy(sav.buffer, 0, ret, 2, ret.length-2); return ret; } } public static void main(String[] args) throws Exception { byte[] yaml = "test: 1\nand: \"with new\\nline\\n\"\nalso: &3 three\nmore: *3".getBytes("ISO-8859-1"); System.out.println("--- # YAML "); System.out.print(new String(yaml, "ISO-8859-1")); System.out.print("\n...\n"); System.out.print(new String(yaml2byte(yaml), "ISO-8859-1")); } }
39.644068
110
0.609876
62d5d3e5ebd6e1b5d4e4609fc92a82783f31706c
5,310
package com.planet_ink.coffee_mud.Abilities.Druid; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2000-2010 Bo Zimmerman 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. */ @SuppressWarnings("unchecked") public class Chant_Shillelagh extends Chant { public String ID() { return "Chant_Shillelagh"; } public String name(){ return "Shillelagh";} public String displayText(){return "(Shillelagh)";} public int classificationCode(){return Ability.ACODE_CHANT|Ability.DOMAIN_PLANTCONTROL;} public int abstractQuality(){return Ability.QUALITY_INDIFFERENT;} protected int canAffectCode(){return CAN_ITEMS;} protected int canTargetCode(){return CAN_ITEMS;} public void affectEnvStats(Environmental affected, EnvStats affectableStats) { super.affectEnvStats(affected,affectableStats); if(affected==null) return; affectableStats.setDisposition(affectableStats.disposition()|EnvStats.IS_BONUS); if(affected instanceof Item) affectableStats.setAbility(affectableStats.ability()+4); } public void unInvoke() { // undo the affects of this spell if(canBeUninvoked()) { if(((affected!=null)&&(affected instanceof Item)) &&((((Item)affected).owner()!=null) &&(((Item)affected).owner() instanceof MOB))) ((MOB)((Item)affected).owner()).tell("The enchantment on "+((Item)affected).name()+" fades."); } super.unInvoke(); } public int castingQuality(MOB mob, Environmental target) { if(mob!=null) { if((mob.fetchWieldedItem() instanceof Weapon) &&((((Weapon)mob.fetchWieldedItem()).material()&RawMaterial.MATERIAL_MASK)!=RawMaterial.MATERIAL_WOODEN) &&((((Weapon)mob.fetchWieldedItem()).material()&RawMaterial.MATERIAL_MASK)!=RawMaterial.MATERIAL_VEGETATION) &&(mob.fetchWieldedItem().fetchEffect(ID())==null)) return super.castingQuality(mob, target,Ability.QUALITY_BENEFICIAL_SELF); } return super.castingQuality(mob,target); } public boolean invoke(MOB mob, Vector commands, Environmental givenTarget, boolean auto, int asLevel) { Item target=getTarget(mob,mob.location(),givenTarget,commands,Wearable.FILTER_ANY); if(target==null) { if((mob.isMonster()) &&(mob.fetchWieldedItem() instanceof Weapon) &&((((Weapon)mob.fetchWieldedItem()).material()&RawMaterial.MATERIAL_MASK)!=RawMaterial.MATERIAL_WOODEN) &&((((Weapon)mob.fetchWieldedItem()).material()&RawMaterial.MATERIAL_MASK)!=RawMaterial.MATERIAL_VEGETATION)) target=mob.fetchWieldedItem(); else return false; } if(!(target instanceof Weapon)) { mob.tell("You can only enchant weapons."); return false; } if(((((Weapon)target).material()&RawMaterial.MATERIAL_MASK)!=RawMaterial.MATERIAL_WOODEN) &&((((Weapon)target).material()&RawMaterial.MATERIAL_MASK)!=RawMaterial.MATERIAL_VEGETATION)) { mob.tell("You cannot enchant this foreign material."); return false; } if(((Weapon)target).fetchEffect(this.ID())!=null) { mob.tell(target.name()+" is already enchanted."); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; boolean success=proficiencyCheck(mob,0,auto); if(success) { // it worked, so build a copy of this ability, // and add it to the affects list of the // affected MOB. Then tell everyone else // what happened. CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"<T-NAME> appear(s) enchanted!":"^S<S-NAME> chant(s) to <T-NAMESELF>.^?"); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); beneficialAffect(mob,target,asLevel,0); mob.location().show(mob,target,CMMsg.MSG_OK_VISUAL,"<T-NAME> glow(s)!"); target.recoverEnvStats(); mob.recoverEnvStats(); } } else return beneficialWordsFizzle(mob,target,"<S-NAME> chant(s) to <T-NAMESELF>, but nothing happens."); // return whether it worked return success; } }
38.201439
156
0.702637
c2e1dff3b7f345b14c55f5cea16a206657ff41f0
1,449
package support.actions.plugin; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; public class CreateIgnore { public Boolean UpdateIgnore(String ignoreName, ArrayList<String> localPaths) { // String fileName=ignoreName; PrintWriter out = null; ReadIgnore ri = new ReadIgnore(); if (ri.Read(ignoreName)) { try { out = new PrintWriter(new BufferedWriter(new FileWriter(ignoreName, true))); for (int i = 0; i < localPaths.size(); i++) { if (!ri.filesIgnore.containsKey(localPaths.get(i))) { out.println(localPaths.get(i)); } } out.close(); } catch (IOException e) { System.out.println("DEN YPARXEI"); } } else { try { out = new PrintWriter(new BufferedWriter(new FileWriter(ignoreName, true))); for (int i = 0; i < localPaths.size(); i++) { if (!ri.filesIgnore.containsKey(localPaths.get(i))) { out.println(localPaths.get(i)); } } out.close(); } catch (IOException e) { System.out.println("DEN YPARXEI"); } } return null; } public Boolean CreateNew(String ignoreName, ArrayList<String> localPaths) { try { PrintWriter in = new PrintWriter(ignoreName, "UTF-8"); for (int i = 0; i < localPaths.size(); i++) { in.println(localPaths.get(i)); } in.close(); return true; } catch (IOException e) { return false; } } }
22.292308
80
0.646653
2a9bf052844f8a5e4d2e78bcc0e083562f34662e
375
package com.ilargia.games.logicbrick.component; import com.badlogic.gdx.math.Vector2; import com.ilargia.games.entitas.api.IComponent; import com.ilargia.games.entitas.Component; @Component(pools = {"Core"}) public class Motion implements IComponent { public Vector2 velocity; public Motion(float x, float y) { this.velocity = new Vector2(x, y); } }
22.058824
48
0.730667
52c5319f0a908ac758c79749c1b6eacb08b707b2
4,660
/* * Copyright (c) 2015-2021, Antonio Gabriel Muñoz Conejo <antoniogmc at gmail dot com> * Distributed under the terms of the MIT License */ package com.github.tonivade.resp.protocol; import static com.github.tonivade.purefun.Precondition.checkNonNull; import static java.nio.charset.StandardCharsets.UTF_8; import java.nio.Buffer; import java.nio.ByteBuffer; import com.github.tonivade.purefun.data.Sequence; import com.github.tonivade.resp.protocol.AbstractRedisToken.ArrayRedisToken; import com.github.tonivade.resp.protocol.AbstractRedisToken.ErrorRedisToken; import com.github.tonivade.resp.protocol.AbstractRedisToken.IntegerRedisToken; import com.github.tonivade.resp.protocol.AbstractRedisToken.StatusRedisToken; import com.github.tonivade.resp.protocol.AbstractRedisToken.StringRedisToken; import io.netty.util.Recycler; public class RedisSerializer { private static final Recycler<ByteBufferBuilder> RECYCLER = new Recycler<ByteBufferBuilder>() { protected ByteBufferBuilder newObject(Recycler.Handle<ByteBufferBuilder> handle) { return new ByteBufferBuilder(handle); } }; private static final byte ARRAY = '*'; private static final byte ERROR = '-'; private static final byte INTEGER = ':'; private static final byte SIMPLE_STRING = '+'; private static final byte BULK_STRING = '$'; private static final byte[] DELIMITER = new byte[] { '\r', '\n' }; public static byte[] encodeToken(RedisToken msg) { try (ByteBufferBuilder builder = RECYCLER.get()) { encodeToken(builder, msg); return builder.toArray(); } } private static void encodeToken(ByteBufferBuilder builder, RedisToken msg) { switch (msg.getType()) { case ARRAY: Sequence<RedisToken> array = ((ArrayRedisToken) msg).getValue(); if (array != null) { builder.append(ARRAY).append(array.size()).append(DELIMITER); for (RedisToken token : array) { encodeToken(builder, token); } } else { builder.append(ARRAY).append(0).append(DELIMITER); } break; case STRING: SafeString string = ((StringRedisToken) msg).getValue(); if (string != null) { builder.append(BULK_STRING).append(string.length()).append(DELIMITER).append(string); } else { builder.append(BULK_STRING).append(-1); } builder.append(DELIMITER); break; case STATUS: String status = ((StatusRedisToken) msg).getValue(); builder.append(SIMPLE_STRING).append(status).append(DELIMITER); break; case INTEGER: Integer integer = ((IntegerRedisToken) msg).getValue(); builder.append(INTEGER).append(integer).append(DELIMITER); break; case ERROR: String error = ((ErrorRedisToken) msg).getValue(); builder.append(ERROR).append(error).append(DELIMITER); break; case UNKNOWN: throw new IllegalArgumentException(msg.toString()); } } private static class ByteBufferBuilder implements AutoCloseable { private static final int INITIAL_CAPACITY = 1024; private ByteBuffer buffer = ByteBuffer.allocate(INITIAL_CAPACITY); private final Recycler.Handle<ByteBufferBuilder> handle; private ByteBufferBuilder(Recycler.Handle<ByteBufferBuilder> handle) { this.handle = checkNonNull(handle); } public void close() { if (buffer.capacity() > INITIAL_CAPACITY) { buffer = ByteBuffer.allocate(INITIAL_CAPACITY); } else { buffer.clear(); } handle.recycle(this); } private ByteBufferBuilder append(int i) { append(String.valueOf(i)); return this; } private ByteBufferBuilder append(String str) { append(str.getBytes(UTF_8)); return this; } private ByteBufferBuilder append(SafeString str) { append(str.getBytes()); return this; } private ByteBufferBuilder append(byte[] buf) { ensureCapacity(buf.length); buffer.put(buf); return this; } public ByteBufferBuilder append(byte b) { ensureCapacity(1); buffer.put(b); return this; } private void ensureCapacity(int len) { if (buffer.remaining() < len) { growBuffer(len); } } private void growBuffer(int len) { int capacity = buffer.capacity() + Math.max(len, INITIAL_CAPACITY); buffer = ByteBuffer.allocate(capacity).put(toArray()); } public byte[] toArray() { byte[] array = new byte[buffer.position()]; ((Buffer) buffer).rewind(); buffer.get(array); return array; } } }
31.486486
97
0.66824
e9d0130fdd3eef1be08786bddb4cb0a4646a7db5
3,028
package Vinkkitietokanta.DAO; import Vinkkitietokanta.Attribuutit; import Vinkkitietokanta.Formaatit; import Vinkkitietokanta.LukuStatus; import Vinkkitietokanta.Vinkki; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; /** * * @author rokka */ abstract public class ProtoDAO { protected Connection conn = null; public ProtoDAO(Connection conn){ this.conn = conn; } protected boolean suoritaKomento(String vinkkiID, Vinkki vinkki, List<Attribuutit> attribuutit, String sql, String func){ String query = sql; try { PreparedStatement komento = conn.prepareStatement(query); int indx = 0; for(Attribuutit attr : attribuutit){ komento.setString(++indx, vinkki.haeOminaisuus(attr)); } komento.setInt(++indx, Integer.parseInt(vinkkiID)); komento.executeUpdate(); komento.close(); return true; } catch (SQLException e) { System.err.println(func+e.getMessage()); } return false; } protected List<Vinkki> suoritaKomento2(Formaatit formaatti,LukuStatus status, List<Vinkki> list, HashMap<Attribuutit,String> attribuutit, String sql, String func){ return suoritaKomento3(formaatti,status, list, attribuutit, sql, func, ""); } protected List<Vinkki> suoritaKomento3(Formaatit formaatti,LukuStatus status, List<Vinkki> list, HashMap<Attribuutit,String> attribuutit, String sql, String func, String vinkkiID){ String query = sql; try { PreparedStatement komento = conn.prepareStatement(query); if(!vinkkiID.isEmpty()) komento.setInt(1, Integer.parseInt(vinkkiID)); ResultSet rs = komento.executeQuery(); while (rs.next()) { int luettu = Integer.parseInt(rs.getString("luettu")); if (luettu == status.getValue() || status == LukuStatus.KAIKKI) { Vinkki vinkki = new Vinkki(rs.getString("otsikko"), formaatti); if (luettu == 0) { vinkki.merkitseLukemattomaksi(); } else { vinkki.merkitseLuetuksi(); } vinkki.lisaaTekijat(rs.getString("tekijat")); vinkki.lisaaTagit(rs.getString("tagit")); for (Map.Entry<Attribuutit, String> attr : attribuutit.entrySet()){ vinkki.lisaaOminaisuus((Attribuutit)attr.getKey(), rs.getString(attr.getValue())); } list.add(vinkki); } } komento.close(); return list; } catch (SQLException e) { System.err.println(func+e.getMessage()); } return null; } }
36.047619
167
0.587517
24ad30ad5a4802023a23a0a8c3f50a632589bd72
1,716
/* * JFLAP - Formal Languages and Automata Package * * * Susan H. Rodger * Computer Science Department * Duke University * August 27, 2009 * Copyright (c) 2002-2009 * All rights reserved. * JFLAP is open source software. Please see the LICENSE for terms. * */ package edu.duke.cs.jflap.gui.editor; import edu.duke.cs.jflap.automata.State; import edu.duke.cs.jflap.automata.Transition; import edu.duke.cs.jflap.automata.vdg.VDGTransition; import edu.duke.cs.jflap.gui.viewer.AutomatonPane; /** * This is a transition creator for variable dependency graphs. * * @author Thomas Finley */ public class VDGTransitionCreator extends TransitionCreator { /** * Instantiates a transition creator. * * @param parent * the parent object that any dialogs or windows brought up by * this creator should be the child of */ public VDGTransitionCreator(final AutomatonPane parent) { super(parent); } /** * Creates a transition with user interaction and returns it. * * @return returns the variable dependency transition */ @Override public Transition createTransition(final State from, final State to) { final VDGTransition t = new VDGTransition(from, to); getParent().getDrawer().getAutomaton().addTransition(t); return null; } /** * Edits a given transition. Ideally this should use the same interface as * that given by <CODE>createTransition</CODE>. * * @param transition * the transition to edit * @return <CODE>false</CODE> if the user decided to not edit a transition, * <CODE>true</CODE> if the edit was "approved" */ @Override public boolean editTransition(final Transition transition) { return false; } }
25.61194
76
0.710373
57f570bd6bc78e735992bca0f647c441a508df55
1,321
package leetcode.stringbinarytree; /** * https://leetcode.com/problems/construct-string-from-binary-tree/description/ */ class Solution { public String tree2str(final TreeNode root) { if (root == null) { return ""; } // 1 // / // 2 // -> 1(2) // 1 // \ // 2 // -> 1()(2) // If left node is absent, we print '()'. // If right node is absent, we print nothing. // If a node having no children, simply print (val). final StringBuilder stringBuilder = convertToString(root); stringBuilder.deleteCharAt(0); stringBuilder.deleteCharAt(stringBuilder.length() - 1); return stringBuilder.toString(); } private StringBuilder convertToString(final TreeNode root) { final StringBuilder strings = new StringBuilder(); strings.append('(').append(root.val); if (root.left != null || root.right != null) { if (root.left == null) { strings.append("()"); } else { strings.append(convertToString(root.left).toString()); } if (root.right != null) { strings.append(convertToString(root.right).toString()); } } return strings.append(")"); } static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } }
22.775862
79
0.588948
68db4cbdaa9d93560212e7e2754de6910faf8496
2,018
// This file is auto-generated, don't edit it. Thanks. package com.antgroup.antchain.openapi.acm.models; import com.aliyun.tea.*; public class UpdateOperatorRequest extends TeaModel { // OAuth模式下的授权token @NameInMap("auth_token") public String authToken; // 邮箱 @NameInMap("email") public String email; // 手机号 @NameInMap("mobile") public String mobile; // 操作员昵称 @NameInMap("nickname") public String nickname; // 操作员唯一ID @NameInMap("operator_id") @Validation(required = true) public String operatorId; // 操作员真实姓名 @NameInMap("real_name") public String realName; public static UpdateOperatorRequest build(java.util.Map<String, ?> map) throws Exception { UpdateOperatorRequest self = new UpdateOperatorRequest(); return TeaModel.build(map, self); } public UpdateOperatorRequest setAuthToken(String authToken) { this.authToken = authToken; return this; } public String getAuthToken() { return this.authToken; } public UpdateOperatorRequest setEmail(String email) { this.email = email; return this; } public String getEmail() { return this.email; } public UpdateOperatorRequest setMobile(String mobile) { this.mobile = mobile; return this; } public String getMobile() { return this.mobile; } public UpdateOperatorRequest setNickname(String nickname) { this.nickname = nickname; return this; } public String getNickname() { return this.nickname; } public UpdateOperatorRequest setOperatorId(String operatorId) { this.operatorId = operatorId; return this; } public String getOperatorId() { return this.operatorId; } public UpdateOperatorRequest setRealName(String realName) { this.realName = realName; return this; } public String getRealName() { return this.realName; } }
23.465116
94
0.645689
01e11d3ace1047e020867ce8928b5b610316cfff
294
package net.minecraft.world.inventory; import net.minecraft.world.item.ItemStack; public interface ContainerListener { void slotChanged(AbstractContainerMenu p_39315_, int p_39316_, ItemStack p_39317_); void dataChanged(AbstractContainerMenu p_150524_, int p_150525_, int p_150526_); }
32.666667
86
0.823129
746d24d661b518b809e390ef865bdeb3a27b41bd
714
package uk.gov.hmcts.reform.sscs.common; import static com.google.common.io.Resources.getResource; import com.google.common.io.Resources; import java.io.IOException; import java.net.URL; import org.apache.commons.codec.Charsets; public class TestHelper { public static final String TEST_SERVICE_AUTH_TOKEN = "testServiceAuth"; public static final String TEST_USER_AUTH_TOKEN = "testUserAuth"; public static final String TEST_USER_ID = "1234"; private TestHelper() { //Utility class } public static String exceptionRecord(String fileName) throws IOException { URL url = getResource(fileName); return Resources.toString(url, Charsets.toCharset("UTF-8")); } }
29.75
78
0.740896
5e2a4edb3ae099afb949d329504f087cf79ecbdc
5,729
/* * Copyright (C) 2016 The Android Open Source Project * * 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.example.miwokbuild; import android.content.Context; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import androidx.appcompat.app.AppCompatActivity; import java.util.ArrayList; public class PhrasesActivity extends AppCompatActivity { private MediaPlayer mMediaPlayer; private AudioManager mAudioManager; AudioManager.OnAudioFocusChangeListener mOnAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() { public void onAudioFocusChange(int focusChange) { if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT || focusChange==AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) { mMediaPlayer.pause(); mMediaPlayer.seekTo(0); } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) { mMediaPlayer.start(); } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) { releaseMediaPlayer(); } } }; private MediaPlayer.OnCompletionListener mCompletionListener = new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { releaseMediaPlayer(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.word_list); mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); //creating array final ArrayList<Word> words = new ArrayList<Word>(); // objects words.add(new Word("Hello","Namaskara",R.raw.greeting_hello)); words.add(new Word("Good Morning","Shubha dina",R.raw.greeting_goodmorning)); words.add(new Word("Good Night","Shuba ratri",R.raw.greeting_night)); words.add(new Word("How are you?","Eer encha ullar?",R.raw.greeting_howareyou)); words.add(new Word("What is that?","Au jadhoo?",R.raw.greeting_whatisthat)); words.add(new Word("What is your name?","Eeno pudar dado?",R.raw.greeting_whatisyourname)); words.add(new Word("What is your number","Eena number jadhoo?",R.raw.greeting_whatisyournumber)); words.add(new Word("How was your day?","Eena dina encha ithane?",R.raw.greeting_howwasyourday)); words.add(new Word("Please come in!","Ulaye bale!",R.raw.greeting_comeinside)); words.add(new Word("I am fine","Yan ushaar ulle",R.raw.greeting_iamfine)); words.add(new Word("My name Ram","Yenna pudar Ram",R.raw.greeting_mynameisram)); words.add(new Word("I am from India","Yan India daalu",R.raw.greeting_iamfromindia)); words.add(new Word("Don't mention it","Malle athe",R.raw.greeting_dontmentionit)); words.add(new Word("Never mind","Malle iddi",R.raw.greeting_nevermind)); words.add(new Word("I will meet you there","Yan eereg aul thikue",R.raw.greeting_iwillmeetyou)); words.add(new Word("Yes","Anth",R.raw.greeting_yes)); words.add(new Word("No","Edhi",R.raw.greeting_no)); words.add(new Word("Ok then","Auu anchanda",R.raw.greeting_bye)); words.add(new Word("OK","Auu",R.raw.greeting_ok)); //add bye WordAdapter adapter = new WordAdapter(this, words,R.color.category_phrases); ListView listView = (ListView) findViewById(R.id.list); listView.setAdapter(adapter);listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long l) { Word word= words.get(position); releaseMediaPlayer(); int result = mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT); if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { mMediaPlayer = MediaPlayer.create(PhrasesActivity.this,word.getAudioResourceId()); mMediaPlayer.start(); mMediaPlayer.setOnCompletionListener(mCompletionListener); } } }); } @Override protected void onStop() { super.onStop(); releaseMediaPlayer(); } /*Clean up the media player by releasing its resources. */ private void releaseMediaPlayer() { // If the media player is not null, then it may be currently playing a sound. if (mMediaPlayer != null) { // Regardless of the current state of the media player, release its resources // because we no longer need it. mMediaPlayer.release(); // Set the media player back to null. For our code, we've decided that // setting the media player to null is an easy way to tell that the media player // is not configured to play an audio file at the moment. mAudioManager.abandonAudioFocus(mOnAudioFocusChangeListener); } } }
41.514493
157
0.676732
10c303547054bbca6aa157970e592b997f23efaa
1,068
/** * Copyright (C) 2014 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.sesame.credit.market; import com.opengamma.financial.analytics.isda.credit.CreditCurveDataKey; import com.opengamma.util.result.Result; /** * Implements mapping logic for {@link CreditCurveDataKey}. This function adds * a level of indirection when resolving credit curves. The input key is * inferred directly from the security being priced. The output key will be a * reference to the target credit curve. This allows generic curves to be * used for pricing specified credit securities. */ public interface CreditKeyMapperFn { /** * Map the input key to a target key to be used for credit curve resolution. * * A result will always be returned. If no mapping exists in the underlying * implementation, the input key will be returned. * * @param key a credit key * @return a credit key result */ Result<CreditCurveDataKey> getMapping(CreditCurveDataKey key); }
33.375
86
0.742509
df10edb1b8fe6f87979216636a3d7989afa82338
630
package com.scottlogic.deg.generator.outputs; import com.scottlogic.deg.generator.inputs.RuleInformation; import java.util.stream.Stream; public class TestCaseDataSet { public final RuleInformation violation; private final Stream<GeneratedObject> rows; public TestCaseDataSet(RuleInformation violation, GeneratedObject... rows) { this(violation, Stream.of(rows)); } public TestCaseDataSet(RuleInformation violation, Stream<GeneratedObject> rows) { this.rows = rows; this.violation = violation; } public Stream<GeneratedObject> stream() { return this.rows; } }
26.25
85
0.722222
afa559ceaeed0989e312a40b656ef78fbe8f61c8
1,837
package Props; import java.io.*; /* Entidade de Usuarios. */ public class Usuario implements Registro{ private int id; private String nome; private String email; private byte[] senha; private byte[] salt; public Usuario(){ this(-1,"","",new byte[32],new byte[32]); }//end of void constructor public Usuario(int id,String nome,String email,byte[] senha,byte[] salt){ this.id = id; this.nome = nome; this.email = email; this.senha = senha; this.salt = salt; }//end of full constructor public void setID(int id){ this.id = id; }//end of setID public int getID(){ return this.id; }//end of getID public String getNome(){ return this.nome; }//end of getNome public byte[] getSenha(){ return this.senha; }//end of getSenha public byte[] getSalt(){ return this.salt; }//end of getSalt public String chaveSecundaria(){ return this.email; }//end of chaveSecundaria public byte[] toByteArray() throws IOException{ ByteArrayOutputStream data = new ByteArrayOutputStream(); DataOutputStream saida = new DataOutputStream(data); saida.writeInt(this.id); saida.writeUTF(this.nome); saida.writeUTF(this.email); saida.write(this.senha); saida.write(this.salt); return data.toByteArray(); }//end of toByteArray public void fromByteArray(byte[] ba) throws IOException{ ByteArrayInputStream data = new ByteArrayInputStream(ba); DataInputStream saida = new DataInputStream(data); this.id = saida.readInt(); this.nome = saida.readUTF(); this.email = saida.readUTF(); saida.read(senha); saida.read(salt); }//end of fromByteArray public String toString(){ return "Nome........: " + this.nome + "\n" + "E-mail......: " + this.email + "\n" + "Senha.......: " + " Essa não pode mostrar né kkk"; }//end of toString }//end of class
24.171053
74
0.670114
ca266347d228954a87fbdf6557f89140fcf1007d
3,396
package com.koch.ambeth.xml; /*- * #%L * jambeth-test * %% * Copyright (C) 2017 Koch Softwaredevelopment * %% * 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. * #L% */ import java.util.List; import org.junit.Assert; import org.junit.Test; import com.koch.ambeth.ioc.annotation.Autowired; import com.koch.ambeth.security.SecurityContext; import com.koch.ambeth.security.SecurityContextType; import com.koch.ambeth.testutil.AbstractInformationBusTest; import com.koch.ambeth.testutil.TestModule; import com.koch.ambeth.xml.ioc.XmlModule; @TestModule({XmlModule.class}) public class CyclicXmlReaderTest extends AbstractInformationBusTest { public static class MyEntity { private String myValue; private boolean myValueSpecified; private String myValue2; private boolean myValue2Specified; public String getMyValue() { return myValue; } public void setMyValue(String myValue) { this.myValue = myValue; setMyValueSpecified(true); } public String getMyValue2() { return myValue2; } public void setMyValue2(String myValue2) { this.myValue2 = myValue2; setMyValue2Specified(true); } public boolean isMyValue2Specified() { return myValue2Specified; } public void setMyValue2Specified(boolean myValue2Specified) { this.myValue2Specified = myValue2Specified; } public boolean isMyValueSpecified() { return myValueSpecified; } public void setMyValueSpecified(boolean myValueSpecified) { this.myValueSpecified = myValueSpecified; } } @Autowired(XmlModule.CYCLIC_XML_HANDLER) protected ICyclicXMLHandler cyclicXmlHandler; @SecurityContext(SecurityContextType.NOT_REQUIRED) public void test() { } @SuppressWarnings("unchecked") @Test public void cyclicTestReadMetaData() { String xml = "<root><l i=\"1\" s=\"2\" ti=\"2\" n=\"Object\"><o i=\"3\" ti=\"4\" n=\"com.koch.ambeth.merge.transfer.EntityMetaDataTransfer\" m=\"AlternateIdMemberIndicesInPrimitives AlternateIdMemberNames CreatedByMemberName CreatedOnMemberName EntityType IdMemberName MergeRelevantNames PrimitiveMemberNames RelationMemberNames TypesRelatingToThis TypesToCascadeDelete UpdatedByMemberName UpdatedOnMemberName VersionMemberName\"><n/><n/><n/><n/><n/><n/><n/><n/><n/><n/><n/><n/><n/><n/></o><r i=\"1\"/></l></root>"; List<Object> list = (List<Object>) cyclicXmlHandler.read(xml); Assert.assertNotNull(list); Assert.assertEquals(2, list.size()); } @Test public void readUnspecified() { MyEntity obj1 = new MyEntity(); obj1.setMyValue("hello"); String xml = cyclicXmlHandler.write(obj1); MyEntity obj2 = (MyEntity) cyclicXmlHandler.read(xml); Assert.assertEquals(obj1.getMyValue(), obj2.getMyValue()); Assert.assertEquals(obj1.getMyValue2(), obj2.getMyValue2()); Assert.assertEquals(obj1.isMyValueSpecified(), obj2.isMyValueSpecified()); Assert.assertEquals(obj1.isMyValue2Specified(), obj2.isMyValue2Specified()); } }
29.789474
506
0.7553
436d0d56018a544ae42bc5360aa3cbc12e7c8c60
2,050
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package modelo; import java.util.Date; /** * * @author Vik-t */ public class Renta { private int idrenta; private String fechainicio; private String fechafin; private double deposito; private double monto; private int idcliente; private int idinmueble; public Renta() { } public Renta(int idrenta, String fechainicio, String fechafin, double deposito, double monto, int idcliente, int idinmueble) { this.idrenta = idrenta; this.fechainicio = fechainicio; this.fechafin = fechafin; this.deposito = deposito; this.monto = monto; this.idcliente = idcliente; this.idinmueble = idinmueble; } public int getIdrenta() { return idrenta; } public void setIdrenta(int idrenta) { this.idrenta = idrenta; } public String getFechainicio() { return fechainicio; } public void setFechainicio(String fechainicio) { this.fechainicio = fechainicio; } public String getFechafin() { return fechafin; } public void setFechafin(String fechafin) { this.fechafin = fechafin; } public double getDeposito() { return deposito; } public void setDeposito(double deposito) { this.deposito = deposito; } public double getMonto() { return monto; } public void setMonto(double monto) { this.monto = monto; } public int getIdcliente() { return idcliente; } public void setIdcliente(int idcliente) { this.idcliente = idcliente; } public int getIdinmueble() { return idinmueble; } public void setIdinmueble(int idinmueble) { this.idinmueble = idinmueble; } }
21.578947
131
0.599512
8338f2ccf6420549080e123eb6ff510d859bccfe
1,525
package com.example.ruolan.cainiaogo.adapter; import android.support.v7.widget.RecyclerView; import android.util.SparseArray; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; /** * Created by ruolan on 2015/11/13. */ public class BaseViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{ //定义一个数组用来存放View对象 private SparseArray<View> views; protected BaseAdapter.OnItemClickListener mListener; public BaseViewHolder(View itemView,BaseAdapter.OnItemClickListener listener) { super(itemView); views = new SparseArray<View>(); this.mListener = listener; itemView.setOnClickListener(this); } //对TextView的封装 public TextView getTextView(int id){ return findView(id); } //对ImageView的封装 public ImageView getImageView(int id){ return findView(id); } //对Button的封装 public Button getButton(int id){ return findView(id); } //对View的封装 public View getView(int id){ return findView(id); } private <T extends View> T findView(int id){ View view = views.get(id); if (view == null){ view = itemView.findViewById(id); views.put(id,view); } return (T) view; } //对ItemClick的设置的点击事件 @Override public void onClick(View v) { if (mListener != null){ mListener.OnItemClick(v, getLayoutPosition()); } } }
23.106061
92
0.651803
7adf14c9a7a095c7e4e935c844acaca677de3df4
397
package io.github.ealenxie.gitlab.webhook.dto; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Getter; import lombok.Setter; /** * Created by EalenXie on 2021/12/1 9:31 */ @Getter @Setter public class User { private Long id; private String name; private String username; @JsonProperty("avatar_url") private String avatarUrl; private String email; }
19.85
53
0.732997
02085ed9f5cdaeff31c2aabd1406500f164eb1ad
1,609
package org.kokzoz.dluid.content.test; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.control.Accordion; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.VBox; import lombok.Data; import org.kokzoz.dluid.content.TabModelTestController; @Data public class ModelTestTestingController extends AbstractModelTestController { @FXML private Accordion accordion; @FXML private VBox container; private ModelTestTestingTaskController modelTestTestingTaskController; private ModelTestTestingResultTableController modelTestTestingResultTableController; public ModelTestTestingController(TabModelTestController tabModelTestController) { super(tabModelTestController); } public AnchorPane createView() throws Exception { FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/frame/content/test/testing.fxml")); fxmlLoader.setController(this); AnchorPane content = fxmlLoader.load(); return content; } @Override protected void initialize() throws Exception { modelTestTestingTaskController = new ModelTestTestingTaskController(getTabModelTestController()); modelTestTestingResultTableController = new ModelTestTestingResultTableController(getTabModelTestController()); modelTestTestingTaskController.createView(); modelTestTestingResultTableController.createView(); accordion.getPanes().add(modelTestTestingTaskController.getTitledPane()); container.getChildren().add(modelTestTestingResultTableController.getTitledPane()); } }
38.309524
119
0.786203
63b0b6d0a8e4f354f7cf8ab38adb9bca48bcc643
932
package com.linuxtek.kona.app.comm.service; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.linuxtek.kona.app.comm.entity.KSms; import com.linuxtek.kona.app.core.entity.KUser; public abstract class KAbstractSmsService<SMS extends KSms,SMS_EXAMPLE,USER extends KUser> extends KAbstractTwilioService<SMS,SMS_EXAMPLE,USER> implements KSmsService<SMS> { private static Logger logger = LoggerFactory.getLogger(KAbstractSmsService.class); // ---------------------------------------------------------------------------- @Override public boolean isTestPhoneNumber(String phoneNumber) { List<String> prefixList = getTestPhoneNumberPrefixList(); if (prefixList == null) return false; for (String prefix : prefixList) { if (phoneNumber.startsWith(prefix)) { return true; } } return false; } }
25.189189
91
0.648069
8b62836ea8b41975d598f1694f599ed99ffa5eae
1,254
package calculator.model; // Represents a node of the expression binary tree. Holds a value and a right and left branch. // INVARIANT: Nodes with children are always operators, leaves are always operands public class ExpressionNode { private ExpressionNode leftBranch; private ExpressionNode rightBranch; private String expressionValue; //EFFECTS: creates a node with a value and no children; public ExpressionNode(String value) { expressionValue = value; leftBranch = null; rightBranch = null; } //MODIFIES: this //EFFECTS: add a children to the left branch public void addChildrenLeft(ExpressionNode node) { leftBranch = node; } //MODIFIES: this //EFFECTS: add a children to the right branch public void addChildrenRight(ExpressionNode node) { rightBranch = node; } //EFFECTS: returns the leftBranch of the node public ExpressionNode getLeftBranch() { return leftBranch; } //EFFECTS: returns the rightBranch of the node public ExpressionNode getRightBranch() { return rightBranch; } //EFFECTS: returns the value of the node public String getExpressionValue() { return expressionValue; } }
28.5
94
0.688995
6462c8213f3bbc367c7f7a0ccaa862f854774a1e
323
package com.openthinks.svm.core.service; import com.openthinks.svm.core.model.BizUserConfig; /** * ClassName: UserConfigService <br> * date: May 20, 2019 9:11:34 AM <br> * * @author [email protected] * @since JDK 1.8 */ public interface UserConfigService { BizUserConfig findUserConfig(long userId); }
19
51
0.727554
440de49c13fadddab78df995a7930bf2843d5b05
869
package org.gollum.core.messaging; import java.util.Map; /** * @author wurenhai * @date 2017/12/31 */ public abstract class BaseMessage<T> implements Message<T> { private final String id; private final long timestamp; public BaseMessage(String id) { this(id, System.currentTimeMillis()); } public BaseMessage(String id, long timestamp) { this.id = id; this.timestamp = timestamp; } @Override public String getId() { return this.id; } @Override public long getTimestamp() { return timestamp; } @Override public Message<T> withMetaData(Map<String, ?> metaData) { return null; } @Override public Message<T> andMetaData(Map<String, ?> metaData) { return null; } protected abstract Message<T> withMetaData(MetaData metaData); }
18.891304
66
0.626007
ba0990c95ff737b5eaf0deef77717d561917c918
914
package jarvis.utils; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.atomic.AtomicInteger; public class SequenceUtils { private String day; private AtomicInteger atomicInteger; private int incrementAndGet() { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String dateString = sdf.format(new Date()); if (atomicInteger == null || !dateString.equals(day)) { day = dateString; atomicInteger = new AtomicInteger(); } return atomicInteger.incrementAndGet(); } /** * 获取日期序列号 * 可以配置前缀{prefix} * * @param prefix 前缀 * @return String * @author yehao * @since 2018/4/12 */ public String getDailyOrderNo(String prefix) { int seq = incrementAndGet(); return prefix + day + String.format("%05d", seq); } }
23.435897
71
0.611597
a0ab3d382f48cd067f005a8ec658d6e131f4cf3f
2,812
package com.bs.flower.action; import com.bs.flower.entity.Users; import com.bs.flower.service.UserService; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import org.apache.struts2.ServletActionContext; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Map; /** * Created by ben on 2017/4/7. */ public class UserAction extends ActionSupport { //spring管理 private UserService userService; //struts2管理 private Users users; private String err; /** * 用户注册 * @return */ public String userRegister(){ Users u = new Users(); u.setUserName(users.getUserName()); u.setPassword(users.getPassword()); u.setRealName(users.getRealName()); u.setPwdQuestion(users.getPwdQuestion()); u.setPwdQuestionAnswer(users.getPwdQuestionAnswer()); u.setPhoneNo(users.getPhoneNo()); u.setEmail(users.getEmail()); u.setAddress(users.getAddress()); //保存用户 userService.save(u); return "login"; } /** * 验证用户名是否存在 * @return */ public String findByName() throws IOException { if(!users.getUserName().equals("") && users.getUserName()!=null){ Users exisUser = userService.findByUserName(users.getUserName()); HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html;charset=UTF-8"); if (exisUser != null){ response.getWriter().println("<font style=\"color: red\">用户名已存在</font>"); } else { response.getWriter().println("<font style=\"color: green\">用户名可用</font>"); } } return null; } /** * 用户登陆 * @return */ public String userLogin(){ Map session = (Map) ActionContext.getContext().getSession(); Users u = userService.checkUser(users); if (u != null){ session.put("user",u); return "login success"; }else { err = "用户名或密码错误"; return "login"; } } /** * 用户注销 * @return */ public String userLogout(){ Map session = (Map) ActionContext.getContext().getSession(); session.remove("user"); return "logout"; } public UserService getUserService() { return userService; } public void setUserService(UserService userService) { this.userService = userService; } public Users getUsers() { return users; } public void setUsers(Users users) { this.users = users; } public String getErr() { return err; } public void setErr(String err) { this.err = err; } }
25.333333
90
0.59175
72e1a53425151b5473589853362066f3862fa0b1
526
package com.soecode.lyf.book.service; import com.soecode.lyf.book.pojo.Book; import com.soecode.lyf.exception.ParamInvalidException; import java.util.List; /** * 业务接口:站在"使用者"角度设计接口 三个方面:方法定义粒度,参数,返回类型(return 类型/异常) */ public interface BookService { /** * 查询一本图书 * * @param bookId * @return */ Book getById(long bookId,String userName); /** * 查询所有图书 * * @return */ List<Book> getList(); void testException() throws ParamInvalidException; /** * 插入100万本图书 */ void batchSaveBook(); }
13.487179
55
0.6673
96239b70171e5cdd6013b7dddfef45c92a77907b
5,537
/* * Copyright 2000,2004 The Apache Software Foundation. * * 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 net.sf.j2ep; import java.io.File; import java.util.Iterator; import java.util.LinkedList; import net.sf.j2ep.model.ServerContainer; import org.apache.commons.digester.Digester; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * The config parser uses Digester to parse the config file. A rule chain with * links to the servers will be constructed. * * Based on the work by Yoav Shapira for the balancer webapp distributed with * Tomcat. * * @author Anders Nyman, Yoav Shapira */ public class ConfigParser { /** * The resulting server chain. */ private ServerChain serverChain; /** * A logging instance supplied by commons-logging. */ private static Log log; /** * Standard constructor only specifying the input file. The constructor will * parse the config and build a corresponding rule chain with the server * mappings included. * * @param data * The config file containing the XML data structure. */ public ConfigParser(File data) { log = LogFactory.getLog(ConfigParser.class); try { LinkedList serverContainer = createServerList(data); if (log.isDebugEnabled()) { debugServers(serverContainer); } serverChain = new ServerChain(serverContainer); } catch (Exception e) { throw new RuntimeException(e); } } /** * Returns the parsed server chain. * * @return The resulting ServerChain */ public ServerChain getServerChain() { return serverChain; } /** * Creates the rules. * * @return The rules all put into a rule chain */ private LinkedList createServerList(File data) throws Exception { Digester digester = new Digester(); digester.setUseContextClassLoader(true); // Construct server list digester.addObjectCreate("config", LinkedList.class); // Create servers digester.addObjectCreate("config/server", null, "className"); digester.addSetProperties("config/server"); // Create rule digester.addObjectCreate("config/server/rule", null, "className"); digester.addSetProperties("config/server/rule"); digester.addSetNext("config/server/rule", "setRule"); // Create composite rule digester.addObjectCreate("config/server/composite-rule", null, "className"); digester.addSetProperties("config/server/composite-rule"); digester.addObjectCreate("config/server/composite-rule/rule", null, "className"); digester.addSetProperties("config/server/composite-rule/rule"); digester.addSetNext("config/server/composite-rule/rule", "addRule"); digester.addSetNext("config/server/composite-rule", "setRule"); // Add server to list digester.addSetNext("config/server", "add"); // Create cluster servers digester.addObjectCreate("config/cluster-server", null, "className"); digester.addSetProperties("config/cluster-server"); // Create the servers in this cluster digester.addCallMethod("config/cluster-server/server", "addServer", 2); digester.addCallParam("config/cluster-server/server", 0, "domainName"); digester.addCallParam("config/cluster-server/server", 1, "path"); // Create rule digester.addObjectCreate("config/cluster-server/rule", null, "className"); digester.addSetProperties("config/cluster-server/rule"); digester.addSetNext("config/cluster-server/rule", "setRule"); // Create composite rule digester.addObjectCreate("config/cluster-server/composite-rule", null, "className"); digester.addSetProperties("config/cluster-server/composite-rule"); digester.addObjectCreate("config/cluster-server/composite-rule/rule", null, "className"); digester.addSetProperties("config/cluster-server/composite-rule/rule"); digester.addSetNext("config/cluster-server/composite-rule/rule", "addRule"); digester.addSetNext("config/cluster-server/composite-rule", "setRule"); // Add server to list digester.addSetNext("config/cluster-server", "add"); return (LinkedList) digester.parse(data); } /** * Will iterate over the server and print out the mappings between servers * and rules. * * @param servers The server to debug */ private void debugServers(LinkedList servers) { Iterator itr = servers.iterator(); while (itr.hasNext()) { ServerContainer container = (ServerContainer) itr.next(); log.debug(container + " mapped to --> " + container.getRule()); } } }
35.722581
80
0.654325
4a1b6b85a1cb41da939d7eb2f0c8e07f22a17110
9,688
/* * Copyright (c) 2011-2019, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * 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 boofcv.alg.distort; import boofcv.alg.geo.PerspectiveOps; import boofcv.factory.distort.LensDistortionFactory; import boofcv.struct.calib.CameraPinhole; import boofcv.struct.distort.PixelTransform; import boofcv.struct.distort.Point2Transform2_F32; import boofcv.struct.distort.Point2Transform2_F32; import boofcv.struct.distort.SequencePoint2Transform2_F32; import georegression.geometry.UtilPoint2D_F32; import georegression.struct.point.Point2D_F32; import georegression.struct.shapes.RectangleLength2D_F32; import org.ejml.data.FMatrixRMaj; import org.ejml.dense.row.CommonOps_FDRM; import java.util.ArrayList; import java.util.List; /** * Operations related to manipulating lens distortion in images * * @author Peter Abeles */ public class LensDistortionOps_F32 { /** * Creates a {@link Point2Transform2_F32} for converting pixels from original camera model into a new synthetic * model. The scaling of the image can be adjusted to ensure certain visibility requirements. * * @param type The type of adjustment it will apply to the transform * @param paramOriginal Camera model for the current image * @param paramDesired Desired camera model for the distorted image * @param desiredToOriginal If true then the transform's input is assumed to be pixels in the desired * image and the output will be in original image, if false then the reverse transform * is returned. * @param paramMod The modified camera model to meet the requested visibility requirements. Null if you don't want it. * @return The requested transform */ public static <O extends CameraPinhole, D extends CameraPinhole> Point2Transform2_F32 transformChangeModel(AdjustmentType type, O paramOriginal, D paramDesired, boolean desiredToOriginal, D paramMod) { LensDistortionNarrowFOV original = LensDistortionFactory.narrow(paramOriginal); LensDistortionNarrowFOV desired = LensDistortionFactory.narrow(paramDesired); Point2Transform2_F32 ori_p_to_n = original.undistort_F32(true, false); Point2Transform2_F32 des_n_to_p = desired.distort_F32(false, true); Point2Transform2_F32 ori_to_des = new SequencePoint2Transform2_F32(ori_p_to_n,des_n_to_p); Point2D_F32 work = new Point2D_F32(); RectangleLength2D_F32 bound; if( type == AdjustmentType.FULL_VIEW ) { bound = DistortImageOps.boundBox_F32(paramOriginal.width, paramOriginal.height, new PointToPixelTransform_F32(ori_to_des),work); } else if( type == AdjustmentType.EXPAND) { bound = LensDistortionOps_F32.boundBoxInside(paramOriginal.width, paramOriginal.height, new PointToPixelTransform_F32(ori_to_des),work); // ensure there are no strips of black LensDistortionOps_F32.roundInside(bound); } else if( type == AdjustmentType.CENTER) { bound = LensDistortionOps_F32.centerBoxInside(paramOriginal.width, paramOriginal.height, new PointToPixelTransform_F32(ori_to_des),work); } else if( type == AdjustmentType.NONE ) { bound = new RectangleLength2D_F32(0,0,paramDesired.width, paramDesired.height); } else { throw new IllegalArgumentException("Unsupported type "+type); } float scaleX = bound.width/paramDesired.width; float scaleY = bound.height/paramDesired.height; float scale; if( type == AdjustmentType.FULL_VIEW ) { scale = (float)Math.max(scaleX, scaleY); } else if( type == AdjustmentType.EXPAND) { scale = (float)Math.min(scaleX, scaleY); } else if( type == AdjustmentType.CENTER) { scale = (float)Math.max(scaleX, scaleY); } else { scale = 1.0f; } float deltaX = (bound.x0 + (scaleX-scale)*paramDesired.width/ 2.0f ); float deltaY = (bound.y0 + (scaleY-scale)*paramDesired.height/ 2.0f ); // adjustment matrix FMatrixRMaj A = new FMatrixRMaj(3,3,true,scale,0,deltaX,0,scale,deltaY,0,0,1); FMatrixRMaj A_inv = new FMatrixRMaj(3, 3); if (!CommonOps_FDRM.invert(A, A_inv)) { throw new RuntimeException("Failed to invert adjustment matrix. Probably bad."); } if( paramMod != null ) { PerspectiveOps.adjustIntrinsic(paramDesired, A_inv, paramMod); } if( desiredToOriginal ) { Point2Transform2_F32 des_p_to_n = desired.undistort_F32(true, false); Point2Transform2_F32 ori_n_to_p = original.distort_F32(false, true); PointTransformHomography_F32 adjust = new PointTransformHomography_F32(A); return new SequencePoint2Transform2_F32(adjust,des_p_to_n,ori_n_to_p); } else { PointTransformHomography_F32 adjust = new PointTransformHomography_F32(A_inv); return new SequencePoint2Transform2_F32(ori_to_des, adjust); } } /** * Ensures that the entire box will be inside * * @param srcWidth Width of the source image * @param srcHeight Height of the source image * @param transform Transform being applied to the image * @return Bounding box */ public static RectangleLength2D_F32 boundBoxInside(int srcWidth, int srcHeight, PixelTransform<Point2D_F32> transform, Point2D_F32 work ) { List<Point2D_F32> points = computeBoundingPoints(srcWidth, srcHeight, transform, work); Point2D_F32 center = new Point2D_F32(); UtilPoint2D_F32.mean(points,center); float x0,x1,y0,y1; x0 = y0 = Float.MAX_VALUE; x1 = y1 = -Float.MAX_VALUE; for (int i = 0; i < points.size(); i++) { Point2D_F32 p = points.get(i); if( p.x < x0 ) x0 = p.x; if( p.x > x1 ) x1 = p.x; if( p.y < y0 ) y0 = p.y; if( p.y > y1 ) y1 = p.y; } x0 -= center.x; x1 -= center.x; y0 -= center.y; y1 -= center.y; float ox0 = x0; float oy0 = y0; float ox1 = x1; float oy1 = y1; for (int i = 0; i < points.size(); i++) { Point2D_F32 p = points.get(i); float dx = p.x-center.x; float dy = p.y-center.y; // see if the point is inside the box if( dx > x0 && dy > y0 && dx < x1 && dy < y1 ) { // find smallest reduction in side length and closest to original rectangle float d0 = (float) (float)Math.abs(dx - x0) + x0 - ox0; float d1 = (float) (float)Math.abs(dx - x1) + ox1 - x1; float d2 = (float) (float)Math.abs(dy - y0) + y0 - oy0; float d3 = (float) (float)Math.abs(dy - y1) + oy1 - y1; if ( d0 <= d1 && d0 <= d2 && d0 <= d3) { x0 = dx; } else if (d1 <= d2 && d1 <= d3) { x1 = dx; } else if (d2 <= d3) { y0 = dy; } else { y1 = dy; } } } return new RectangleLength2D_F32(x0+center.x,y0+center.y,x1-x0,y1-y0); } /** * Attempts to center the box inside. It will be approximately fitted too. * * @param srcWidth Width of the source image * @param srcHeight Height of the source image * @param transform Transform being applied to the image * @return Bounding box */ public static RectangleLength2D_F32 centerBoxInside(int srcWidth, int srcHeight, PixelTransform<Point2D_F32> transform , Point2D_F32 work ) { List<Point2D_F32> points = computeBoundingPoints(srcWidth, srcHeight, transform, work); Point2D_F32 center = new Point2D_F32(); UtilPoint2D_F32.mean(points,center); float x0,x1,y0,y1; float bx0,bx1,by0,by1; x0=x1=y0=y1=0; bx0=bx1=by0=by1=Float.MAX_VALUE; for (int i = 0; i < points.size(); i++) { Point2D_F32 p = points.get(i); float dx = p.x-center.x; float dy = p.y-center.y; float adx = (float)Math.abs(dx); float ady = (float)Math.abs(dy); if( adx < ady ) { if( dy < 0 ) { if( adx < by0 ) { by0 = adx; y0 = dy; } } else { if( adx < by1 ) { by1 = adx; y1 = dy; } } } else { if( dx < 0 ) { if( ady < bx0 ) { bx0 = ady; x0 = dx; } } else { if( ady < bx1 ) { bx1 = ady; x1 = dx; } } } } return new RectangleLength2D_F32(x0+center.x,y0+center.y,x1-x0,y1-y0); } private static List<Point2D_F32> computeBoundingPoints(int srcWidth, int srcHeight, PixelTransform<Point2D_F32> transform, Point2D_F32 work ) { List<Point2D_F32> points = new ArrayList<>(); for (int x = 0; x < srcWidth; x++) { transform.compute(x, 0, work); points.add(new Point2D_F32(work.x, work.y)); transform.compute(x, srcHeight, work); points.add(new Point2D_F32(work.x, work.y)); } for (int y = 0; y < srcHeight; y++) { transform.compute(0, y, work); points.add(new Point2D_F32(work.x, work.y)); transform.compute(srcWidth, y, work); points.add(new Point2D_F32(work.x, work.y)); } return points; } /** * Adjust bound to ensure the entire image is contained inside, otherwise there might be * single pixel wide black regions */ public static void roundInside( RectangleLength2D_F32 bound ) { float x0 = (float)Math.ceil(bound.x0); float y0 = (float)Math.ceil(bound.y0); float x1 = (float)Math.floor(bound.x0+bound.width); float y1 = (float)Math.floor(bound.y0+bound.height); bound.x0 = x0; bound.y0 = y0; bound.width = x1-x0; bound.height = y1-y0; } }
32.293333
120
0.683216
dfca47d71298072dc3381533c58cf38eaf240754
1,352
/* * Copyright (C) 2020 Baidu, Inc. All Rights Reserved. */ package com.baidubce.common; import java.util.Map; import com.baidubce.http.HttpMethodName; /** * Api info for v2 client to create request * * @author zhangquan07 */ public class ApiInfo { /** * Api method name */ private HttpMethodName method; /** * Api path, use [] to represents path variable. */ private ApiPath path; /** * Api query variables. */ private Map<String, String> queries; /** * Api header variables. */ private Map<String, String> headers; public HttpMethodName getMethod() { return method; } public ApiPath getPath() { return path; } public Map<String, String> getQueries() { return queries; } public Map<String, String> getHeaders() { return headers; } public ApiInfo(HttpMethodName method, ApiPath path, Map<String, String> queries, Map<String, String> headers) { this.method = method; this.path = path; this.queries = queries; this.headers = headers; } public ApiInfo(ApiInfo other) { this.method = other.getMethod(); this.path = other.getPath(); this.queries = other.getQueries(); this.headers = other.getHeaders(); } }
21.125
84
0.591716
dc278209eae7e398cedb7988c35687f8ee033bd8
3,753
package org.lnu.is.domain.asset.address; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.lnu.is.annotation.dbtable.OD; import org.lnu.is.domain.InformationModel; import org.lnu.is.domain.address.type.AddressType; import org.lnu.is.domain.admin.unit.AdminUnit; import org.lnu.is.domain.asset.Asset; import org.lnu.is.domain.street.type.StreetType; /** * Asset Address entity. * * @author kushnir * */ @OD @Entity @Table(name = "q_od_assetaddress") public class AssetAddress extends InformationModel { private static final long serialVersionUID = 1L; @ManyToOne @JoinColumn(name = "adminunit_id") private AdminUnit adminUnit; @ManyToOne @JoinColumn(name = "asset_id") private Asset asset; @ManyToOne @JoinColumn(name = "addresstype_id") private AddressType addressType; @ManyToOne @JoinColumn(name = "streettype_id") private StreetType streetType; @Column(name = "zipcode") private String zipCode; @Column(name = "street") private String street; @Column(name = "house") private String house; @Column(name = "apartment") private String apartment; public AdminUnit getAdminUnit() { return adminUnit; } public void setAdminUnit(final AdminUnit adminUnit) { this.adminUnit = adminUnit; } public Asset getAsset() { return asset; } public void setAsset(final Asset asset) { this.asset = asset; } public AddressType getAddressType() { return addressType; } public void setAddressType(final AddressType addressType) { this.addressType = addressType; } public StreetType getStreetType() { return streetType; } public void setStreetType(final StreetType streetType) { this.streetType = streetType; } public String getZipCode() { return zipCode; } public void setZipCode(final String zipCode) { this.zipCode = zipCode; } public String getStreet() { return street; } public void setStreet(final String street) { this.street = street; } public String getHouse() { return house; } public void setHouse(final String house) { this.house = house; } public String getApartment() { return apartment; } public void setApartment(final String apartment) { this.apartment = apartment; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((apartment == null) ? 0 : apartment.hashCode()); result = prime * result + ((house == null) ? 0 : house.hashCode()); result = prime * result + ((street == null) ? 0 : street.hashCode()); result = prime * result + ((zipCode == null) ? 0 : zipCode.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } AssetAddress other = (AssetAddress) obj; if (apartment == null) { if (other.apartment != null) { return false; } } else if (!apartment.equals(other.apartment)) { return false; } if (house == null) { if (other.house != null) { return false; } } else if (!house.equals(other.house)) { return false; } if (street == null) { if (other.street != null) { return false; } } else if (!street.equals(other.street)) { return false; } if (zipCode == null) { if (other.zipCode != null) { return false; } } else if (!zipCode.equals(other.zipCode)) { return false; } return true; } @Override public String toString() { return "AssetAddress [zipCode=" + zipCode + ", street=" + street + ", house=" + house + ", apartment=" + apartment + "]"; } }
20.620879
73
0.681855
632e88bd27f2d79035711dbfad9e01cd278abde4
3,345
package tech.avente; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.Date; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.tika.detect.AutoDetectReader; import org.apache.tika.exception.TikaException; /** * CSV cleaning main class. * * @author Jeremy Moore */ public class CsvClean { private static final String EOL = "\r\n"; private static final String ENCODING = "windows-1252"; private static final String REPLACEMENT = ">"; private static final Logger logger = Logger.getLogger(CsvClean.class.getName()); /** * Clean a CSV file with windows-1252 encoding. * * @param args The CSV file path must be the first command line argument. */ public static void main(String[] args) { if (args == null || args.length == 0) { logger.log(Level.SEVERE, "File argument required."); System.exit(1); } final File csvFile = new File(args[0]); if (!csvFile.isFile()) { logger.log(Level.SEVERE, "File not found: " + csvFile.getPath()); System.exit(1); } if (!csvFile.getName().endsWith(".csv")) { logger.log(Level.SEVERE, "File does not have \".csv\" extension: " + csvFile.getPath()); System.exit(1); } final Charset charset = detectCharset(csvFile); if (charset == null) { logger.log(Level.SEVERE, "File encoding could not be detected."); System.exit(1); } if (!ENCODING.equals(charset.toString())) { logger.log(Level.SEVERE, "File encoding: " + charset.toString() + ". Must be: " + ENCODING); System.exit(1); } File tmpFile = cleanFile(csvFile, charset); if (tmpFile == null) { logger.log(Level.SEVERE, "Failed to clean file."); System.exit(1); } if (!moveTo(tmpFile, csvFile)) { logger.log(Level.SEVERE, "Failed to replace file."); System.exit(1); } } private static Charset detectCharset(File file) { try (FileInputStream fis = new FileInputStream(file); AutoDetectReader detector = new AutoDetectReader(fis)) { return detector.getCharset(); } catch (IOException | TikaException e) { logger.log(Level.SEVERE, null, e); return null; } } private static String timestamp() { return Long.toString(new Date().getTime()); } private static File tmpFile(File file) { return new File(file.getPath() + "." + timestamp() + ".tmp"); } private static boolean moveTo(File srcFile, File dstFile) { return srcFile.renameTo(dstFile); } private static File cleanFile(File csvFile, Charset charset) { File tmpFile = tmpFile(csvFile); try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(tmpFile), charset)) { List<String> lines = Files.readAllLines(csvFile.toPath(), charset); for (String line : lines) { String clean = replaceNonPrintable(line); writer.write(clean + EOL); if (!clean.equals(line)) { System.out.println("---"); System.out.println("< " + line); System.out.println("> " + clean); } } return tmpFile; } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); return null; } } private static String replaceNonPrintable(String s) { return s.replaceAll("\\P{Print}", REPLACEMENT); } }
26.547619
112
0.684006
97215d519344789c0e36fdb1f2062cb1926af303
3,542
package org.djr.retrofit2ee.jaxb; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import org.djr.retrofit2ee.BeanLookupUtil; import org.djr.retrofit2ee.RetrofitProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import retrofit2.Retrofit; import retrofit2.converter.jaxb.JaxbConverterFactory; import javax.enterprise.inject.Produces; import javax.enterprise.inject.spi.InjectionPoint; import javax.inject.Inject; import java.util.Properties; public class JaxBRetrofitProducer { private static Logger log = LoggerFactory.getLogger(JaxBRetrofitProducer.class); @Inject @RetrofitProperties private Properties properties; @Produces @RetrofitJaxB public Retrofit getClient(InjectionPoint injectionPoint) { RetrofitJaxB jaxbClientConfig = injectionPoint.getAnnotated().getAnnotation(RetrofitJaxB.class); log.debug("getClient() injecting retrofit JAXB client with annotation:{}", jaxbClientConfig); String baseUrlPropertyName = jaxbClientConfig.baseUrlPropertyName(); String captureTrafficLogsPropertyName = jaxbClientConfig.captureTrafficLogsPropertyName(); String baseUrl = properties.getProperty(baseUrlPropertyName); Boolean enableTrafficLogging = Boolean.parseBoolean(properties.getProperty(captureTrafficLogsPropertyName, "FALSE")); return getTransport(baseUrl, enableTrafficLogging, jaxbClientConfig.customJAXBContextName()); } private Retrofit getTransport(String baseUrl, boolean enableTrafficLogging, String customContextName) { log.debug("getTransport() baseUrl:{}, enableTrafficLogging:{}", baseUrl, enableTrafficLogging); OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); setLoggingInterceptor(enableTrafficLogging, httpClient); Retrofit.Builder retrofitBuilder = new Retrofit.Builder(); if ("".equalsIgnoreCase(customContextName.trim())) { retrofitBuilder.addConverterFactory(JaxbConverterFactory.create()); } else { try { retrofitBuilder.addConverterFactory( JaxbConverterFactory.create(getBeanByNameOfClass(customContextName, CustomJAXBContext.class).getJAXBContext())); } catch (Exception ex) { throw new JAXBRetrofitException("Failed to find CustomJAXBContext for name:" + customContextName); } } retrofitBuilder.baseUrl(baseUrl); retrofitBuilder.client(httpClient.build()); return retrofitBuilder.build(); } private void setLoggingInterceptor(boolean enableTrafficLogging, OkHttpClient.Builder builder) { if (enableTrafficLogging) { HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); builder.addInterceptor(loggingInterceptor); } } /** * Method to help classes not managed by CDI to get CDI managed beans * @param name name of the bean you are looking for; should be annotated with @Named("beanName") * @param clazz the class type you are looking for BeanName.class * @param <T> generics * @return instance of BeanName.class * @throws Exception if something goes horribly wrong I suppose it could get thrown */ private <T> T getBeanByNameOfClass(String name, Class<T> clazz) throws Exception { return BeanLookupUtil.getBeanByNameOfClass(name, clazz); } }
45.410256
136
0.730378
0eadfc04a34b26082eaf4a56216d2a94481454f8
7,065
/** */ package CIM.IEC61970.Generation.Production.impl; import CIM.IEC61970.Core.impl.PowerSystemResourceImpl; import CIM.IEC61970.Generation.Production.CombinedCyclePlant; import CIM.IEC61970.Generation.Production.ProductionPackage; import CIM.IEC61970.Generation.Production.ThermalGeneratingUnit; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.util.EObjectWithInverseResolvingEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Combined Cycle Plant</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link CIM.IEC61970.Generation.Production.impl.CombinedCyclePlantImpl#getCombCyclePlantRating <em>Comb Cycle Plant Rating</em>}</li> * <li>{@link CIM.IEC61970.Generation.Production.impl.CombinedCyclePlantImpl#getThermalGeneratingUnits <em>Thermal Generating Units</em>}</li> * </ul> * * @generated */ public class CombinedCyclePlantImpl extends PowerSystemResourceImpl implements CombinedCyclePlant { /** * The default value of the '{@link #getCombCyclePlantRating() <em>Comb Cycle Plant Rating</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCombCyclePlantRating() * @generated * @ordered */ protected static final float COMB_CYCLE_PLANT_RATING_EDEFAULT = 0.0F; /** * The cached value of the '{@link #getCombCyclePlantRating() <em>Comb Cycle Plant Rating</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCombCyclePlantRating() * @generated * @ordered */ protected float combCyclePlantRating = COMB_CYCLE_PLANT_RATING_EDEFAULT; /** * The cached value of the '{@link #getThermalGeneratingUnits() <em>Thermal Generating Units</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getThermalGeneratingUnits() * @generated * @ordered */ protected EList<ThermalGeneratingUnit> thermalGeneratingUnits; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected CombinedCyclePlantImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return ProductionPackage.Literals.COMBINED_CYCLE_PLANT; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public float getCombCyclePlantRating() { return combCyclePlantRating; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setCombCyclePlantRating(float newCombCyclePlantRating) { float oldCombCyclePlantRating = combCyclePlantRating; combCyclePlantRating = newCombCyclePlantRating; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, ProductionPackage.COMBINED_CYCLE_PLANT__COMB_CYCLE_PLANT_RATING, oldCombCyclePlantRating, combCyclePlantRating)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<ThermalGeneratingUnit> getThermalGeneratingUnits() { if (thermalGeneratingUnits == null) { thermalGeneratingUnits = new EObjectWithInverseResolvingEList<ThermalGeneratingUnit>(ThermalGeneratingUnit.class, this, ProductionPackage.COMBINED_CYCLE_PLANT__THERMAL_GENERATING_UNITS, ProductionPackage.THERMAL_GENERATING_UNIT__COMBINED_CYCLE_PLANT); } return thermalGeneratingUnits; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case ProductionPackage.COMBINED_CYCLE_PLANT__THERMAL_GENERATING_UNITS: return ((InternalEList<InternalEObject>)(InternalEList<?>)getThermalGeneratingUnits()).basicAdd(otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case ProductionPackage.COMBINED_CYCLE_PLANT__THERMAL_GENERATING_UNITS: return ((InternalEList<?>)getThermalGeneratingUnits()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case ProductionPackage.COMBINED_CYCLE_PLANT__COMB_CYCLE_PLANT_RATING: return getCombCyclePlantRating(); case ProductionPackage.COMBINED_CYCLE_PLANT__THERMAL_GENERATING_UNITS: return getThermalGeneratingUnits(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case ProductionPackage.COMBINED_CYCLE_PLANT__COMB_CYCLE_PLANT_RATING: setCombCyclePlantRating((Float)newValue); return; case ProductionPackage.COMBINED_CYCLE_PLANT__THERMAL_GENERATING_UNITS: getThermalGeneratingUnits().clear(); getThermalGeneratingUnits().addAll((Collection<? extends ThermalGeneratingUnit>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case ProductionPackage.COMBINED_CYCLE_PLANT__COMB_CYCLE_PLANT_RATING: setCombCyclePlantRating(COMB_CYCLE_PLANT_RATING_EDEFAULT); return; case ProductionPackage.COMBINED_CYCLE_PLANT__THERMAL_GENERATING_UNITS: getThermalGeneratingUnits().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case ProductionPackage.COMBINED_CYCLE_PLANT__COMB_CYCLE_PLANT_RATING: return combCyclePlantRating != COMB_CYCLE_PLANT_RATING_EDEFAULT; case ProductionPackage.COMBINED_CYCLE_PLANT__THERMAL_GENERATING_UNITS: return thermalGeneratingUnits != null && !thermalGeneratingUnits.isEmpty(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (combCyclePlantRating: "); result.append(combCyclePlantRating); result.append(')'); return result.toString(); } } //CombinedCyclePlantImpl
29.560669
254
0.724699
f1dbb06cd312b57a547a9e97cc464aca3dc5b956
3,972
/* * Copyright © 2019 admin ([email protected]) * * 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 org.infrastructurebuilder.imaging.container; import static org.infrastructurebuilder.imaging.container.DockerV1Constants.CONTAINER; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.Arrays; import java.util.List; import org.infrastructurebuilder.automation.PackerException; import org.infrastructurebuilder.imaging.ImageDataDisk; import org.infrastructurebuilder.util.core.DefaultGAV; import org.json.JSONObject; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.skyscreamer.jsonassert.JSONAssert; public class PackerDockerBuilderTest { private DefaultGAV artifact; private JSONObject empty; private PackerContainerBuilder p; @Before public void setUp() throws Exception { p = new PackerContainerBuilder(); artifact = new DefaultGAV("X:Y:1.0.0:jar"); empty = new JSONObject("{\n" + " \"commit\": true,\n" + " \"privileged\": false,\n" + " \"type\": \"docker\",\n" + " \"pull\": true\n" + "}"); } @Ignore @Test public void testAddRequiredItemsToFactory() { fail("Not yet implemented"); } @Test public void testAsJSON() { JSONAssert.assertEquals(empty, p.asJSON(), true); p.setArtifact(artifact); JSONAssert.assertEquals(empty, p.asJSON(), true); } @Test public void testGetAuthor() { assertFalse(p.getAuthor().isPresent()); p.setAuthor("X"); assertEquals("X", p.getAuthor().get()); } @Test public void testGetAuthType() { assertEquals(CONTAINER, p.getAuthType().get()); } @Test public void testGetChanges() { assertFalse(p.getChanges().isPresent()); p.setChanges(Arrays.asList("CMD Y")); assertTrue(p.getChanges().isPresent()); assertEquals("CMD Y", p.getChanges().get().iterator().next()); } @Test public void testGetLookupHint() { assertEquals(CONTAINER, p.getLookupHint().get()); } @Test public void testGetNamedTypes() { assertEquals(1, p.getNamedTypes().size()); assertEquals(CONTAINER, p.getNamedTypes().iterator().next()); } @Test public void testGetPackerType() { assertEquals(CONTAINER, p.getPackerType()); } @Test public void testGetRunCommands() { assertFalse(p.getRunCommands().isPresent()); p.setRunCommands(Arrays.asList("X")); assertEquals(1, p.getRunCommands().get().size()); assertEquals("X", p.getRunCommands().get().iterator().next()); } @Test public void testGetSizes() { assertEquals(1, p.getSizes().size()); } @Test public void testGetVolumes() { assertFalse(p.getVolumes().isPresent()); final PackerDockerBuilderDisk disk = new PackerDockerBuilderDisk(); disk.setHostPath("/"); disk.setContainerPath("/"); final List<ImageDataDisk> d = Arrays.asList(disk); p.setDisk(d); assertEquals(1, p.getVolumes().get().size()); } @Test public void testIsPrivileged() { assertFalse(p.isPrivileged()); p.setPrivileged(true); assertTrue(p.isPrivileged()); } @Ignore @Test public void testMapBuildResult() { fail("Not yet implemented"); } @Test public void testValidate() { try { p.validate(); } catch (final PackerException e) { fail("Need more testing"); } } }
26.837838
119
0.693102
3588496c332e241924ca02f1ca19516b7bbec7ee
7,282
/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.collection; import org.cactoos.list.ListOf; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.HasValues; import org.llorllale.cactoos.matchers.Throws; /** * Test case for {@link Immutable}. * * @since 1.16 * @checkstyle MagicNumber (500 lines) * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @SuppressWarnings("PMD.TooManyMethods") public class ImmutableTest { @Test void size() { new Assertion<>( "size() must be equals to original", new Immutable<>( new ListOf<>(1, 2) ).size(), new IsEqual<>(2) ).affirm(); } @Test void isEmpty() { new Assertion<>( "isEmpty() must be equals to original", new Immutable<>( new ListOf<>(1, 2) ).isEmpty(), new IsEqual<>( new ListOf<>(1, 2).isEmpty() ) ).affirm(); } @Test void iterator() { new Assertion<>( "iterator() is equal to original", () -> new Immutable<>( new ListOf<>(1, 2) ).iterator(), new HasValues<>(1, 2) ).affirm(); } @Test void contains() { new Assertion<>( "contains() must be equals to original", new Immutable<>( new ListOf<>(1, 2) ).contains(1), new IsEqual<>( new ListOf<>(1, 2).contains(1) ) ).affirm(); } @Test void toArray() { new Assertion<>( "toArray() must be equals to original", new Immutable<>( new ListOf<>(1, 2) ).toArray(), new IsEqual<>( new ListOf<>(1, 2).toArray() ) ).affirm(); } @Test void testToArray() { new Assertion<>( "toArray(T[]) must be equals to original", new Immutable<>( new ListOf<>(1, 2, 3) ).toArray(new Integer[3]), new IsEqual<>( new ListOf<>(1, 2, 3).toArray(new Integer[3]) ) ).affirm(); } @Test void add() { new Assertion<>( "add() must throw exception", () -> new Immutable<>( new ListOf<>(1, 2) ).add(3), new Throws<>( "#add(): the collection is read-only", UnsupportedOperationException.class ) ).affirm(); } @Test void remove() { new Assertion<>( "remove() must throw exception", () -> new Immutable<>( new ListOf<>(1, 2) ).remove(1), new Throws<>( "#remove(): the collection is read-only", UnsupportedOperationException.class ) ).affirm(); } @Test void containsAll() { final ListOf<Integer> another = new ListOf<>(3, 4, 5); new Assertion<>( "containsAll() must be equals to original", new Immutable<>( new ListOf<>(1, 2, 3) ).containsAll(another), new IsEqual<>( new ListOf<>(1, 2, 3).containsAll(another) ) ).affirm(); } @Test void addAll() { new Assertion<>( "addAll() must throw exception", () -> new Immutable<>( new ListOf<>(1, 2) ).addAll(new ListOf<>(3, 4)), new Throws<>( "#addAll(): the collection is read-only", UnsupportedOperationException.class ) ).affirm(); } @Test void removeAll() { new Assertion<>( "removeAll() must throw exception", () -> new Immutable<>( new ListOf<>(1, 2, 3) ).removeAll(new ListOf<>(2, 3)), new Throws<>( "#removeAll(): the collection is read-only", UnsupportedOperationException.class ) ).affirm(); } @Test void retainAll() { new Assertion<>( "retainAll() must throw exception", () -> new Immutable<>( new ListOf<>(1, 2, 3) ).retainAll(new ListOf<>(1)), new Throws<>( "#retainAll(): the collection is read-only", UnsupportedOperationException.class ) ).affirm(); } @Test void clear() { new Assertion<>( "clear() must throw exception", () -> { new Immutable<>( new ListOf<>(1, 2, 3) ).clear(); return new Object(); }, new Throws<>( "#clear(): the collection is read-only", UnsupportedOperationException.class ) ).affirm(); } @Test void testToString() { new Assertion<>( "toString() must be equals to original", new Immutable<>( new ListOf<>(1, 2, 3) ).toString(), new IsEqual<>( new ListOf<>(1, 2, 3).toString() ) ).affirm(); } @Test void testHashCode() { new Assertion<>( "hashCode() must be equals to original", new Immutable<>( new ListOf<>(1, 2, 3) ).hashCode(), new IsEqual<>( new ListOf<>(1, 2, 3).hashCode() ) ).affirm(); } @Test void testEquals() { final ListOf<Integer> another = new ListOf<>(4, 5, 6); new Assertion<>( "equals() must be equals to original", new Immutable<>( new ListOf<>(1, 2, 3) ).equals(another), new IsEqual<>( new ListOf<>(1, 2, 3).equals(another) ) ).affirm(); } }
28.224806
80
0.496018
c363f8e052f599ebf43ab86bc6e1ed4431809537
934
package ru.job4j.menu; import java.util.ArrayList; import java.util.List; /** * Class Menu | Create menu [#4748] * @author Aleksey Sidorenko (mailto:[email protected]) * @since 14.01.2020 */ public class Menu { List<MenuContainable> elements; /** * Constructor. */ public Menu() { this.elements = new ArrayList<>(); } /** * Add element to menu. * @param element element. */ public void addElement(Element element) { elements.add(element); } /** * Add subelement to element. * @param rootElement rootElement. * @param element appendable element. */ public void addSubElement(Element rootElement, Element element) { rootElement.append(element); } /** * Show menu. */ public void showMenu() { for (MenuContainable element : elements) { element.show(); } } }
19.87234
69
0.586724
ca8c6cd9ba5d5bfe0bcdccc80a2bdd70e83fe33e
1,826
package se.kth.tracedata.jvm; import se.kth.tracedata.MethodInfo; public class FieldInstruction extends se.kth.tracedata.FieldInstruction{ protected MethodInfo mi; protected String fname; protected String className; protected String varId; protected String sourceLocation; public FieldInstruction(String fname,String fcname, String sourceLocation) { this.fname = fname; this.className = fcname; this.sourceLocation =sourceLocation; } @Override public String getVariableId() { if (varId == null) { varId = className + '.' + fname; } return varId; } @Override public MethodInfo getMethodInfo() { // TODO Auto-generated method stub return mi; } @Override public String getFileLocation() { return sourceLocation; } @Override public String getInvokedMethodName() { // TODO Auto-generated method stub return null; } @Override public String getInvokedMethodClassName() { // TODO Auto-generated method stub return null; } @Override public boolean isInstanceofJVMInvok() { // TODO Auto-generated method stub return false; } @Override public boolean isInstanceofJVMReturnIns() { // TODO Auto-generated method stub return false; } @Override public boolean isInstanceofLockIns() { // TODO Auto-generated method stub return false; } @Override public int getLastLockRef() { // TODO Auto-generated method stub return 0; } @Override public boolean isInstanceofVirtualInv() { // TODO Auto-generated method stub return false; } @Override public boolean isInstanceofFieldIns() { // TODO Auto-generated method stub return false; } @Override public void setMethodInfo(MethodInfo miInfo) { mi = miInfo; } @Override public String getLastlockName() { // TODO Auto-generated method stub return null; } }
18.444444
79
0.719606
de704997d61f73dee384e2ffb0e7c8decb22b244
49
package cn.iocoder.dashboard.modules.system.job;
24.5
48
0.836735
248f510871570772ba95d56a13919889974d2d2e
171
package com.xurent.live.exception; public class UnAuthException extends RuntimeException { public UnAuthException(String message) { super(message); } }
17.1
55
0.725146
62d19e2b57794aefc1c96d9d80c66b990fc4c92a
3,108
package org.netlib.lapack; import org.netlib.err.Xerbla; import org.netlib.util.intW; public final class Sormr2 { public static void sormr2(String paramString1, String paramString2, int paramInt1, int paramInt2, int paramInt3, float[] paramArrayOfFloat1, int paramInt4, int paramInt5, float[] paramArrayOfFloat2, int paramInt6, float[] paramArrayOfFloat3, int paramInt7, int paramInt8, float[] paramArrayOfFloat4, int paramInt9, intW paramintW) { boolean bool1 = false; boolean bool2 = false; int i = 0; int j = 0; int k = 0; int m = 0; int n = 0; int i1 = 0; int i2 = 0; float f = 0.0F; paramintW.val = 0; bool1 = Lsame.lsame(paramString1, "L"); bool2 = Lsame.lsame(paramString2, "N"); if (bool1) { i2 = paramInt1; } else { i2 = paramInt2; } if ((((bool1 ^ true)) && ((Lsame.lsame(paramString1, "R") ^ true)) ? 1 : 0) != 0) { paramintW.val = -1; } else if ((((bool2 ^ true)) && ((Lsame.lsame(paramString2, "T") ^ true)) ? 1 : 0) != 0) { paramintW.val = -2; } else if ((paramInt1 >= 0 ? 0 : 1) != 0) { paramintW.val = -3; } else if ((paramInt2 >= 0 ? 0 : 1) != 0) { paramintW.val = -4; } else { if ((paramInt3 >= 0 ? 0 : 1) == 0) {} if (((paramInt3 <= i2 ? 0 : 1) == 0 ? 0 : 1) != 0) { paramintW.val = -5; } else if ((paramInt5 >= Math.max(1, paramInt3) ? 0 : 1) != 0) { paramintW.val = -7; } else if ((paramInt8 >= Math.max(1, paramInt1) ? 0 : 1) != 0) { paramintW.val = -10; } } if ((paramintW.val == 0 ? 0 : 1) != 0) { Xerbla.xerbla("SORMR2", -paramintW.val); return; } if ((paramInt1 != 0 ? 0 : 1) == 0) {} if (((paramInt2 != 0 ? 0 : 1) == 0 ? 0 : 1) == 0) {} if (((paramInt3 != 0 ? 0 : 1) == 0 ? 0 : 1) != 0) { return; } if (((bool1) && ((bool2 ^ true)) ? 1 : 0) == 0) {} if (((((bool1 ^ true)) && (bool2) ? 1 : 0) == 0 ? 0 : 1) != 0) { j = 1; k = paramInt3; m = 1; } else { j = paramInt3; k = 1; m = -1; } if (bool1) { i1 = paramInt2; } else { n = paramInt1; } i = j; for (int i3 = (k - j + m) / m; i3 > 0; i3--) { if (bool1) { n = paramInt1 - paramInt3 + i; } else { i1 = paramInt2 - paramInt3 + i; } f = paramArrayOfFloat1[(i - 1 + (i2 - paramInt3 + i - 1) * paramInt5 + paramInt4)]; paramArrayOfFloat1[(i - 1 + (i2 - paramInt3 + i - 1) * paramInt5 + paramInt4)] = 1.0F; Slarf.slarf(paramString1, n, i1, paramArrayOfFloat1, i - 1 + (1 - 1) * paramInt5 + paramInt4, paramInt5, paramArrayOfFloat2[(i - 1 + paramInt6)], paramArrayOfFloat3, paramInt7, paramInt8, paramArrayOfFloat4, paramInt9); paramArrayOfFloat1[(i - 1 + (i2 - paramInt3 + i - 1) * paramInt5 + paramInt4)] = f; i += m; } } } /* Location: /Users/assaad/Downloads/arpack_combined_all/!/org/netlib/lapack/Sormr2.class * Java compiler version: 1 (45.3) * JD-Core Version: 0.7.1 */
29.884615
332
0.512548
ff729a48efd78a01927b1eccc21ce67ee535943a
852
package analyzer.tests; import analyzer.ast.ParserVisitor; import analyzer.visitors.IntermediateCodeGenFallVisitor; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.File; import java.util.Collection; @RunWith(Parameterized.class) public class IntermediateCodeGenFallTest extends BaseTest { private static String m_test_suite_path = "./test-suite/IntermediateCodeGenFallTest/data"; public IntermediateCodeGenFallTest(File file) { super(file); } @Test public void run() throws Exception { ParserVisitor algorithm = new IntermediateCodeGenFallVisitor(m_output); runAndAssert(algorithm); } @Parameterized.Parameters(name = "{0}") public static Collection<Object[]> getFiles() { return getFiles(m_test_suite_path); } }
25.818182
94
0.746479
fd3a2565a24cdfd5dc06de50baae4e30aec01d32
7,257
package uk.ac.ebi.spot.goci.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import uk.ac.ebi.spot.goci.model.Association; import uk.ac.ebi.spot.goci.model.Gene; import uk.ac.ebi.spot.goci.model.Locus; import uk.ac.ebi.spot.goci.model.RiskAllele; import uk.ac.ebi.spot.goci.model.SingleNucleotidePolymorphism; import uk.ac.ebi.spot.goci.repository.GeneRepository; import uk.ac.ebi.spot.goci.repository.LocusRepository; import uk.ac.ebi.spot.goci.repository.RiskAlleleRepository; import uk.ac.ebi.spot.goci.repository.SingleNucleotidePolymorphismRepository; import java.util.ArrayList; import java.util.Collection; /** * Created by emma on 13/04/2015. * * @author emma * <p> * Service class that creates and saves the attributes of a locus */ @Service public class LociAttributesService { private SingleNucleotidePolymorphismRepository singleNucleotidePolymorphismRepository; private GeneRepository geneRepository; private RiskAlleleRepository riskAlleleRepository; private LocusRepository locusRepository; private Logger log = LoggerFactory.getLogger(getClass()); protected Logger getLog() { return log; } // Constructor @Autowired public LociAttributesService(SingleNucleotidePolymorphismRepository singleNucleotidePolymorphismRepository, GeneRepository geneRepository, RiskAlleleRepository riskAlleleRepository, LocusRepository locusRepository) { this.singleNucleotidePolymorphismRepository = singleNucleotidePolymorphismRepository; this.geneRepository = geneRepository; this.riskAlleleRepository = riskAlleleRepository; this.locusRepository = locusRepository; } public Collection<Gene> saveGene(Collection<Gene> genes) { Collection<Gene> locusGenes = new ArrayList<Gene>(); genes.forEach(gene -> { // Check if gene already exists Gene geneInDatabase = geneRepository.findByGeneName(gene.getGeneName()); // Exists in database already if (geneInDatabase != null) { getLog().debug("Gene " + geneInDatabase.getGeneName() + " already exists in database"); locusGenes.add(geneInDatabase); } // If gene doesn't exist then create and save else { // Create new gene getLog().debug("Gene " + gene.getGeneName() + " not found in database. Creating and saving new gene."); geneRepository.save(gene); locusGenes.add(gene); } } ); return locusGenes; } public Collection<Gene> createGene(Collection<String> authorReportedGenes) { Collection<Gene> locusGenes = new ArrayList<Gene>(); authorReportedGenes.forEach(authorReportedGene -> { authorReportedGene = tidy_curator_entered_string(authorReportedGene); // Check for intergenic if (authorReportedGene.equals("Intergenic")) { authorReportedGene = authorReportedGene.toLowerCase(); } Gene newGene = new Gene(); newGene.setGeneName(authorReportedGene); // Add genes to collection locusGenes.add(newGene); }); return locusGenes; } public Collection<RiskAllele> saveRiskAlleles(Collection<RiskAllele> strongestRiskAlleles) { //Create new risk allele, at present we always create a new risk allele for each locus within an association Collection<RiskAllele> riskAlleles = new ArrayList<RiskAllele>(); strongestRiskAlleles.forEach(riskAllele -> { getLog().info("Saving " + riskAllele.getRiskAlleleName()); // Save SNP SingleNucleotidePolymorphism savedSnp = saveSnp(riskAllele.getSnp()); riskAllele.setSnp(savedSnp); // Save proxy SNPs Collection<SingleNucleotidePolymorphism> savedProxySnps = new ArrayList<SingleNucleotidePolymorphism>(); if (riskAllele.getProxySnps() != null && !riskAllele.getProxySnps().isEmpty()) { riskAllele.getProxySnps().forEach(singleNucleotidePolymorphism -> { savedProxySnps.add(saveSnp(singleNucleotidePolymorphism)); }); } riskAllele.setProxySnps(savedProxySnps); riskAlleleRepository.save(riskAllele); riskAlleles.add(riskAllele); }); return riskAlleles; } public RiskAllele createRiskAllele(String curatorEnteredRiskAllele, SingleNucleotidePolymorphism snp) { //Create new risk allele, at present we always create a new risk allele for each locus within an association RiskAllele riskAllele = new RiskAllele(); riskAllele.setRiskAlleleName(tidy_curator_entered_string(curatorEnteredRiskAllele)); riskAllele.setSnp(snp); return riskAllele; } public void deleteRiskAllele(RiskAllele riskAllele) { riskAlleleRepository.delete(riskAllele); } public void deleteLocus(Locus locus) { locusRepository.delete(locus); } private SingleNucleotidePolymorphism saveSnp(SingleNucleotidePolymorphism snp) { // Check if SNP already exists SingleNucleotidePolymorphism snpInDatabase = singleNucleotidePolymorphismRepository.findByRsIdIgnoreCase(snp.getRsId()); if (snpInDatabase != null) { return snpInDatabase; } else { // save new SNP return singleNucleotidePolymorphismRepository.save(snp); } } public SingleNucleotidePolymorphism createSnp(String curatorEnteredSNP) { // Create new SNP SingleNucleotidePolymorphism newSNP = new SingleNucleotidePolymorphism(); newSNP.setRsId(tidy_curator_entered_string(curatorEnteredSNP)); return newSNP; } private String tidy_curator_entered_string(String string) { String newString = string.trim(); String newline = System.getProperty("line.separator"); if (newString.contains(newline)) { newString = newString.replace(newline, ""); } // catch common typo in standard RS_IDs if (newString.startsWith("Rs")) { newString = newString.toLowerCase(); } return newString; } public void deleteLocusAndRiskAlleles(Association association) { if (association.getLoci() != null) { Collection<RiskAllele> riskAlleles = new ArrayList<>(); for (Locus locus : association.getLoci()) { locus.getStrongestRiskAlleles().forEach(riskAlleles::add); deleteLocus(locus); } riskAlleles.forEach(riskAllele -> riskAlleleRepository.delete(riskAllele)); } } }
36.651515
133
0.643792
5260ba5787bfa19f2eff1f7297395576988371ca
606
/** * * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.jfinal.weixin.sdk.msg.in.event; import com.jfinal.weixin.sdk.msg.in.InMsg; public abstract class EventInMsg extends InMsg { protected String event; public EventInMsg(String toUserName, String fromUserName, Integer createTime, String msgType, String event) { super(toUserName, fromUserName, createTime, msgType); this.event = event; } public String getEvent() { return event; } public void setEvent(String event) { this.event = event; } }
20.2
111
0.661716
b9ba34cf96d055be017d4bacb8ae52f2c70f8e75
135
package com.matejdro.wearutils.lifecycle; public interface LiveDataLifecycleListener { void onActive(); void onInactive(); }
16.875
44
0.755556
ef2c81e74d4a251f8cf8b6650a0ae0e1e72befd9
820
package com.a9ski.entities; import java.util.Date; import javax.annotation.Generated; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="Dali", date="2018-03-11T16:17:21.093+0200") @StaticMetamodel(AuditableEntity.class) public class AuditableEntity_ extends IdentifiableEntity_ { public static volatile SingularAttribute<AuditableEntity, Date> created; public static volatile SingularAttribute<AuditableEntity, Date> edited; public static volatile SingularAttribute<AuditableEntity, Long> creator; public static volatile SingularAttribute<AuditableEntity, Long> editor; public static volatile SingularAttribute<AuditableEntity, Long> version; public static volatile SingularAttribute<AuditableEntity, Boolean> deleted; }
45.555556
77
0.82439
b238fd4451058bf761ea21944c7080cd74336fcc
1,635
package br.com.caelum.stella.validation.ie; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Test; import org.mockito.Mockito; import br.com.caelum.stella.MessageProducer; import br.com.caelum.stella.validation.InvalidStateException; import br.com.caelum.stella.validation.Validator; import br.com.caelum.stella.validation.error.IEError; public class IEMinasGeraisValidatorTest extends IEValidatorTest { public IEMinasGeraisValidatorTest() { super(wrongFirstCheckDigitUnformattedString, validUnformattedString, validFormattedString, validValues); } private static final String wrongFirstCheckDigitUnformattedString = "0623079040045"; private static final String wrongSecondCheckDigitUnformattedString = "0623079040085"; private static final String validUnformattedString = "0623079040081"; private static final String validFormattedString = "062.307.904/0081"; //TODO adicionar mais exemplo de IE validos private static final String[] validValues = { "062.307.904/0081"}; @Override protected Validator<String> getValidator(MessageProducer messageProducer, boolean isFormatted) { return new IEMinasGeraisValidator(messageProducer, isFormatted); } @Test public void shouldNotValidateIEWithSecondCheckDigitWrong() { Validator<String> validator = getValidator(messageProducer, false); try { validator.assertValid(wrongSecondCheckDigitUnformattedString); fail(); } catch (InvalidStateException e) { assertTrue(e.getInvalidMessages().size() == 1); } Mockito.verify(messageProducer, Mockito.times(1)).getMessage(IEError.INVALID_CHECK_DIGITS); } }
35.543478
106
0.809174
0142bf28cf5c0ccd1e500911e4945f609fa617e0
1,022
package com.abe.order.model; import java.math.BigDecimal; import java.time.LocalDate; import io.swagger.annotations.ApiModelProperty; public class SupplierAnswer { @ApiModelProperty private Long client; @ApiModelProperty private String budgetNumber; @ApiModelProperty private BigDecimal discount; @ApiModelProperty private LocalDate estimatedDeliveryDate; public BigDecimal getDiscount() { return discount; } public void setDiscount(BigDecimal discount) { this.discount = discount; } public LocalDate getEstimatedDeliveryDate() { return estimatedDeliveryDate; } public void setEstimatedDeliveryDate(LocalDate estimatedDeliveryDate) { this.estimatedDeliveryDate = estimatedDeliveryDate; } public String getBudgetNumber() { return budgetNumber; } public void setBudgetNumber(String budgetNumber) { this.budgetNumber = budgetNumber; } public Long getClient() { return client; } public void setClient(Long client) { this.client = client; } }
24.333333
73
0.75636
05b39c05b84216096dfb9cae9fcd4b973c43c0c2
1,449
package com.hwangfantasy.config; import com.hwangfantasy.service.MainService; import com.hwangfantasy.service.QqService; import com.hwangfantasy.service.impl.MainServiceImpl; import com.hwangfantasy.service.impl.QqServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author hwangfantasy * @since 2018/2/28 */ @Configuration public class OauthConfigFactory { @Autowired private OauthQqProperties qqProperties; @Bean public OauthQqConfig qqConfig() { return OauthQqConfig.OauthQqConfigBuilder.anOauthQqConfig() .withOpenId(this.qqProperties.getOpenId()) .withOpenKey(this.qqProperties.getOpenKey()) .withRedirect(this.qqProperties.getRedirect()) .withAuthorizeUrl("https://graph.qq.com/oauth2.0/authorize") .withTokenUrl("https://graph.qq.com/oauth2.0/token") .withMeUrl("https://graph.qq.com/oauth2.0/me") .withUserInfoUrl("https://graph.qq.com/user/get_user_info") .build(); } @Bean public QqService qqService() { QqService qqService = new QqServiceImpl(); qqService.setConfig(qqConfig()); return qqService; } @Bean public MainService mainService() { return new MainServiceImpl(); } }
31.5
76
0.6853
00b4007a57887cc41e1964c0683a0583d38fd04f
335
package org.folio.processing.exceptions; public class ReaderException extends RuntimeException { public ReaderException(Throwable throwable) { super(throwable); } public ReaderException(String message) { super(message); } public ReaderException(String message, Throwable cause) { super(message, cause); } }
19.705882
59
0.740299
4c38a7f36b49a0f9b46bec14d721cfffe93a40ab
2,249
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets 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 io.druid.segment; import io.druid.guice.annotations.PublicApi; import org.joda.time.Interval; import java.io.Closeable; /** */ @PublicApi public interface Segment extends Closeable { public String getIdentifier(); public Interval getDataInterval(); public QueryableIndex asQueryableIndex(); public StorageAdapter asStorageAdapter(); /** * Request an implementation of a particular interface. * * If the passed-in interface is {@link QueryableIndex} or {@link StorageAdapter}, then this method behaves * identically to {@link #asQueryableIndex()} or {@link #asStorageAdapter()}. Other interfaces are only * expected to be requested by callers that have specific knowledge of extra features provided by specific * segment types. For example, an extension might provide a custom Segment type that can offer both * StorageAdapter and some new interface. That extension can also offer a Query that uses that new interface. * * Implementations which accept classes other than {@link QueryableIndex} or {@link StorageAdapter} are limited * to using those classes within the extension. This means that one extension cannot rely on the `Segment.as` * behavior of another extension. * * @param clazz desired interface * @param <T> desired interface * @return instance of clazz, or null if the interface is not supported by this segment */ public <T> T as(Class<T> clazz); }
40.160714
114
0.751