repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
braintree/braintree_android
Card/src/main/java/com/braintreepayments/api/Card.java
7536
package com.braintreepayments.api; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; import androidx.annotation.Nullable; import com.braintreepayments.api.GraphQLConstants.Keys; import org.json.JSONException; import org.json.JSONObject; /** * Use to construct a card tokenization request. */ public class Card extends BaseCard implements Parcelable { private static final String GRAPHQL_CLIENT_SDK_METADATA_KEY = "clientSdkMetadata"; private static final String MERCHANT_ACCOUNT_ID_KEY = "merchantAccountId"; private static final String AUTHENTICATION_INSIGHT_REQUESTED_KEY = "authenticationInsight"; private static final String AUTHENTICATION_INSIGHT_INPUT_KEY = "authenticationInsightInput"; private String merchantAccountId; private boolean authenticationInsightRequested; private boolean shouldValidate; JSONObject buildJSONForGraphQL() throws BraintreeException, JSONException { JSONObject base = new JSONObject(); JSONObject input = new JSONObject(); JSONObject variables = new JSONObject(); base.put(GRAPHQL_CLIENT_SDK_METADATA_KEY, buildMetadataJSON()); JSONObject optionsJson = new JSONObject(); optionsJson.put(VALIDATE_KEY, shouldValidate); input.put(OPTIONS_KEY, optionsJson); variables.put(Keys.INPUT, input); if (TextUtils.isEmpty(merchantAccountId) && authenticationInsightRequested) { throw new BraintreeException("A merchant account ID is required when authenticationInsightRequested is true."); } if (authenticationInsightRequested) { variables.put(AUTHENTICATION_INSIGHT_INPUT_KEY, new JSONObject().put(MERCHANT_ACCOUNT_ID_KEY, merchantAccountId)); } base.put(Keys.QUERY, getCardTokenizationGraphQLMutation()); base.put(OPERATION_NAME_KEY, "TokenizeCreditCard"); JSONObject creditCard = new JSONObject() .put(NUMBER_KEY, getNumber()) .put(EXPIRATION_MONTH_KEY, getExpirationMonth()) .put(EXPIRATION_YEAR_KEY, getExpirationYear()) .put(CVV_KEY, getCvv()) .put(CARDHOLDER_NAME_KEY, getCardholderName()); JSONObject billingAddress = new JSONObject() .put(FIRST_NAME_KEY, getFirstName()) .put(LAST_NAME_KEY, getLastName()) .put(COMPANY_KEY, getCompany()) .put(COUNTRY_CODE_KEY, getCountryCode()) .put(LOCALITY_KEY, getLocality()) .put(POSTAL_CODE_KEY, getPostalCode()) .put(REGION_KEY, getRegion()) .put(STREET_ADDRESS_KEY, getStreetAddress()) .put(EXTENDED_ADDRESS_KEY, getExtendedAddress()); if (billingAddress.length() > 0) { creditCard.put(BILLING_ADDRESS_KEY, billingAddress); } input.put(CREDIT_CARD_KEY, creditCard); base.put(Keys.VARIABLES, variables); return base; } public Card() { } /** * @param id The merchant account id used to generate the authentication insight. */ public void setMerchantAccountId(@Nullable String id) { merchantAccountId = TextUtils.isEmpty(id) ? null : id; } /** * @param shouldValidate Flag to denote if the associated {@link Card} will be validated. Defaults to false. * <p> * Use this flag with caution. Enabling validation may result in adding a card to the Braintree vault. * The circumstances that determine if a Card will be vaulted are not documented. */ public void setShouldValidate(boolean shouldValidate) { this.shouldValidate = shouldValidate; } /** * @param requested If authentication insight will be requested. */ public void setAuthenticationInsightRequested(boolean requested) { authenticationInsightRequested = requested; } /** * @return The merchant account id used to generate the authentication insight. */ @Nullable public String getMerchantAccountId() { return merchantAccountId; } /** * @return If authentication insight will be requested. */ public boolean isAuthenticationInsightRequested() { return authenticationInsightRequested; } /** * @return If the associated card will be validated. */ public boolean getShouldValidate() { return shouldValidate; } @Override JSONObject buildJSON() throws JSONException { JSONObject json = super.buildJSON(); JSONObject paymentMethodNonceJson = json.getJSONObject(CREDIT_CARD_KEY); JSONObject optionsJson = new JSONObject(); optionsJson.put(VALIDATE_KEY, shouldValidate); paymentMethodNonceJson.put(OPTIONS_KEY, optionsJson); if (authenticationInsightRequested) { json.put(MERCHANT_ACCOUNT_ID_KEY, merchantAccountId); json.put(AUTHENTICATION_INSIGHT_REQUESTED_KEY, authenticationInsightRequested); } return json; } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeString(merchantAccountId); dest.writeByte(shouldValidate ? (byte) 1 : 0); dest.writeByte(authenticationInsightRequested ? (byte) 1 : 0); } protected Card(Parcel in) { super(in); merchantAccountId = in.readString(); shouldValidate = in.readByte() > 0; authenticationInsightRequested = in.readByte() > 0; } public static final Creator<Card> CREATOR = new Creator<Card>() { @Override public Card createFromParcel(Parcel in) { return new Card(in); } @Override public Card[] newArray(int size) { return new Card[size]; } }; private String getCardTokenizationGraphQLMutation() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("mutation TokenizeCreditCard($input: TokenizeCreditCardInput!"); if (authenticationInsightRequested) { stringBuilder.append(", $authenticationInsightInput: AuthenticationInsightInput!"); } stringBuilder.append(") {" + " tokenizeCreditCard(input: $input) {" + " token" + " creditCard {" + " bin" + " brand" + " expirationMonth" + " expirationYear" + " cardholderName" + " last4" + " binData {" + " prepaid" + " healthcare" + " debit" + " durbinRegulated" + " commercial" + " payroll" + " issuingBank" + " countryOfIssuance" + " productId" + " }" + " }"); if (authenticationInsightRequested) { stringBuilder.append("" + " authenticationInsight(input: $authenticationInsightInput) {" + " customerAuthenticationRegulationEnvironment" + " }"); } stringBuilder.append("" + " }" + "}"); return stringBuilder.toString(); } }
mit
taowenyin/RLXAPF
app/src/main/java/cn/edu/siso/rlxapf/DeviceActivity.java
995
package cn.edu.siso.rlxapf; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class DeviceActivity extends AppCompatActivity { private Button devicePrefOk = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_device); devicePrefOk = (Button) findViewById(R.id.device_pref_ok); devicePrefOk.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(DeviceActivity.this, MainActivity.class); startActivity(intent); DeviceActivity.this.finish(); } }); getSupportFragmentManager().beginTransaction().replace( R.id.device_pref, new DevicePrefFragment()).commit(); } }
mit
dvt32/cpp-journey
Java/Unsorted/21.05.2015.14.36.java
793
// dvt /* 1. Да се напише if-конструкция, * която изчислява стойността на две целочислени променливи и * разменя техните стойности, * ако стойността на първата променлива е по-голяма от втората. */ package myJava; import java.util.Scanner; public class dvt { public static void main(String[] args) { Scanner read = new Scanner(System.in); int a, b, temp; System.out.print("a = "); a = read.nextInt(); System.out.print("b = "); b = read.nextInt(); if (a > b){ temp = a; a = b; b = temp; System.out.println( "a > b! The values have been switched!\n" + "a = " + a + " b = " + b); } } }
mit
rootulp/school
mobile_apps/assignment6_rootulp/RootulpJsonA/app/src/main/java/com/rootulp/rootulpjsona/picPage.java
2172
package com.rootulp.rootulpjsona; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.ImageView; import java.io.InputStream; public class picPage extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pic_page); Intent local = getIntent(); Bundle localBundle = local.getExtras(); artist selected = (artist) localBundle.getSerializable("selected"); String imageURL = selected.getImageURL(); new DownloadImageTask((ImageView) findViewById(R.id.painting)).execute(imageURL); } private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { ImageView bmImage; public DownloadImageTask(ImageView bmImage) { this.bmImage = bmImage; } protected Bitmap doInBackground(String... urls) { String urldisplay = urls[0]; Bitmap mIcon11 = null; try { InputStream in = new java.net.URL(urldisplay).openStream(); mIcon11 = BitmapFactory.decodeStream(in); } catch (Exception e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } return mIcon11; } protected void onPostExecute(Bitmap result) { bmImage.setImageBitmap(result); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_pic_page, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
mit
adnanaziz/epicode
java/src/main/java/com/epi/RabinKarp.java
3435
// Copyright (c) 2015 Elements of Programming Interviews. All rights reserved. package com.epi; import java.util.Random; public class RabinKarp { // @include // Returns the index of the first character of the substring if found, -1 // otherwise. public static int rabinKarp(String t, String s) { if (s.length() > t.length()) { return -1; // s is not a substring of t. } final int BASE = 26; int tHash = 0, sHash = 0; // Hash codes for the substring of t and s. int powerS = 1; // BASE^|s|. for (int i = 0; i < s.length(); i++) { powerS = i > 0 ? powerS * BASE : 1; tHash = tHash * BASE + t.charAt(i); sHash = sHash * BASE + s.charAt(i); } for (int i = s.length(); i < t.length(); i++) { // Checks the two substrings are actually equal or not, to protect // against hash collision. if (tHash == sHash && t.substring(i - s.length(), i).equals(s)) { return i - s.length(); // Found a match. } // Uses rolling hash to compute the new hash code. tHash -= t.charAt(i - s.length()) * powerS; tHash = tHash * BASE + t.charAt(i); } // Tries to match s and t.substring(t.length() - s.length()). if (tHash == sHash && t.substring(t.length() - s.length()).equals(s)) { return t.length() - s.length(); } return -1; // s is not a substring of t. } // @exclude private static int checkAnswer(String t, String s) { for (int i = 0; i + s.length() - 1 < t.length(); ++i) { boolean find = true; for (int j = 0; j < s.length(); ++j) { if (t.charAt(i + j) != s.charAt(j)) { find = false; break; } } if (find) { return i; } } return -1; // No matching. } private static String randString(int len) { Random r = new Random(); StringBuilder ret = new StringBuilder(len); while (len-- > 0) { ret.append((char)(r.nextInt(26) + 'a')); } return ret.toString(); } private static void smallTest() { assert(rabinKarp("GACGCCA", "CGC") == 2); assert(rabinKarp("GATACCCATCGAGTCGGATCGAGT", "GAG") == 10); assert(rabinKarp("FOOBARWIDGET", "WIDGETS") == -1); assert(rabinKarp("A", "A") == 0); assert(rabinKarp("A", "B") == -1); assert(rabinKarp("A", "") == 0); assert(rabinKarp("ADSADA", "") == 0); assert(rabinKarp("", "A") == -1); assert(rabinKarp("", "AAA") == -1); assert(rabinKarp("A", "AAA") == -1); assert(rabinKarp("AA", "AAA") == -1); assert(rabinKarp("AAA", "AAA") == 0); assert(rabinKarp("BAAAA", "AAA") == 1); assert(rabinKarp("BAAABAAAA", "AAA") == 1); assert(rabinKarp("BAABBAABAAABS", "AAA") == 8); assert(rabinKarp("BAABBAABAAABS", "AAAA") == -1); assert(rabinKarp("FOOBAR", "BAR") > 0); } public static void main(String args[]) { smallTest(); if (args.length == 2) { String t = args[0]; String s = args[1]; System.out.println("t = " + t); System.out.println("s = " + s); assert(checkAnswer(t, s) == rabinKarp(t, s)); } else { Random r = new Random(); for (int times = 0; times < 10000; ++times) { String t = randString(r.nextInt(1000) + 1); String s = randString(r.nextInt(20) + 1); System.out.println("t = " + t); System.out.println("s = " + s); assert(checkAnswer(t, s) == rabinKarp(t, s)); } } } }
mit
AndreiBiruk/DPM
src/main/java/by/itransition/dpm/service/BookService.java
1653
package by.itransition.dpm.service; import by.itransition.dpm.dao.BookDao; import by.itransition.dpm.dao.UserDao; import by.itransition.dpm.entity.Book; import by.itransition.dpm.entity.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service public class BookService { @Autowired private BookDao bookDao; @Autowired private UserDao userDao; @Autowired private UserService userService; public void setBookDao(BookDao bookDao) { this.bookDao = bookDao; } public void setUserDao(UserDao userDao) { this.userDao = userDao; } @Transactional public void addBook(Book book){ Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); String name = authentication.getName(); User user = userDao.getUserByLogin(name); book.setUser(user); bookDao.saveBook(book); userService.addBook(user, book); } @Transactional public List<Book> getAllBooks() { return bookDao.getAllBooks(); } @Transactional public List<Book> getUserBooks(User user) { return user.getBooks(); } @Transactional public void deleteBookById(Integer id) { bookDao.deleteBookById(id); } @Transactional public Book getBookById (Integer id){ return bookDao.getBookById(id); } }
mit
sethbusque/pizzaccio
src_custom/com/aws/global/dao/PizzaDAO.java
1598
package com.aws.global.dao; import java.util.ArrayList; import com.aws.global.classes.Pizza; import com.aws.global.common.base.BaseDAO; import com.aws.global.mapper.PizzaRowMapper; public class PizzaDAO extends BaseDAO{ //SQL Statement when user adds a pizza to his inventory public void addPizza(String pizzaName, int pizzaPrice) { String sql = "INSERT INTO PIZZA (pizza_id, pizza_name, pizza_price) VALUES (NULL, ?, ?);"; getJdbcTemplate().update(sql, new Object[] { pizzaName, pizzaPrice}); } //SQL Statement when user wants to get a list of pizzas public ArrayList<Pizza> getAllPizza() { String sql = "SELECT * FROM Pizza"; ArrayList<Pizza> pizzas = (ArrayList<Pizza>) getJdbcTemplate().query(sql, new PizzaRowMapper()); return pizzas; } //SQL Statement when user wants to get a pizza record using a pizza id public Pizza getPizzaById(int id) { String sql = "SELECT * FROM PIZZA WHERE pizza_id = ?"; Pizza pizza = (Pizza)getJdbcTemplate().queryForObject( sql, new Object[] { id }, new PizzaRowMapper()); return pizza; } //SQL Statement when user wants to update a certain pizza's information public void editPizza(String pizza_name, int pizza_price, int id) { String sql = "UPDATE PIZZA SET pizza_name = ?, pizza_price = ? WHERE pizza_id = ?;"; getJdbcTemplate().update(sql, new Object[] { pizza_name, pizza_price, id }); } //SQL Statement when user wants to delete a pizza information public void deletePizza(int id) { String sql = "DELETE FROM PIZZA WHERE pizza_id = ?"; getJdbcTemplate().update(sql, new Object[] { id }); } }
mit
instaclick/PDI-Plugin-Step-BloomFilter
ic-filter/src/main/java/com/instaclick/filter/DataFilter.java
780
package com.instaclick.filter; /** * Defines a behavior that should be implement by all filter * * @author Fabio B. Silva <fabio.bat.silva@gmail.com> */ public interface DataFilter { /** * Adds the given {@link Data} if it does not exists * * @param data * * @return <b>TRUE</b> if the the {@link Data} does not exists; <b>FALSE</b> otherwise */ public boolean add(Data data); /** * Check if the given {@link Data} exists * * @param data * * @return <b>TRUE</b> if the the {@link Data} does not exists; <b>FALSE</b> otherwise */ public boolean contains(Data data); /** * Flushes the filter data, this operation should be invoked at the end of the filter */ public void flush(); }
mit
PtitNoony/FxTreeMap
src/main/java/com/github/ptitnoony/components/fxtreemap/MapData.java
3281
/* * The MIT License * * Copyright 2017 Arnaud Hamon * * 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 NONINFRINGEMENT. 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 com.github.ptitnoony.components.fxtreemap; import java.beans.PropertyChangeListener; import java.util.List; /** * * @author ahamon */ public interface MapData { /** * Data type that represents whether a data is represents a single object * (ie LEAF) or an aggregation of objects (ie NODE) */ enum DataType { LEAF, NODE }; DataType getType(); /** * Get the data value. * * @return the data value */ double getValue(); /** * Set the data value. If the data has children data, their value will be * set with the same percentage of the value they use to have before the * setValue is applied. The value must be equal or greater to 0. * * @param newValue the new data value */ void setValue(double newValue); /** * Get the data name. * * @return the data name */ String getName(); /** * Set the data name. * * @param newName the new data name */ void setName(String newName); /** * If the data is an aggregation of children data. * * @return if the data is an aggregation of children data */ boolean hasChildrenData(); /** * Get the children aggregated data if any. * * @return the list of aggregated data */ List<MapData> getChildrenData(); /** * Add a child data. If the data had no child before, adding a child data * will override the previously set data value. * * @param data the data to be added as a child data to aggregate */ void addChildrenData(MapData data); /** * Remove a child data. * * @param data the data to be removed */ void removeChildrenData(MapData data); /** * Add a property change listener. * * @param listener the listener to be added */ void addPropertyChangeListener(PropertyChangeListener listener); /** * Remove a property change listener. * * @param listener the listener to be removed */ void removePropertyChangeListener(PropertyChangeListener listener); }
mit
ngageoint/geopackage-android
geopackage-sdk/src/androidTest/java/mil/nga/geopackage/extension/rtree/RTreeIndexExtensionCreateTest.java
690
package mil.nga.geopackage.extension.rtree; import org.junit.Test; import java.sql.SQLException; import mil.nga.geopackage.CreateGeoPackageTestCase; /** * Test RTree Extension from a created database * * @author osbornb */ public class RTreeIndexExtensionCreateTest extends CreateGeoPackageTestCase { /** * Constructor */ public RTreeIndexExtensionCreateTest() { } /** * Test RTree * * @throws SQLException upon error */ @Test public void testRTree() throws SQLException { RTreeIndexExtensionUtils.testRTree(geoPackage); } @Override public boolean allowEmptyFeatures() { return false; } }
mit
fyskam/FysKams-sangbok
FysKamsSangbok/app/src/main/java/fyskam/fyskamssngbok/NavigationDrawerFragment.java
10600
package fyskam.fyskamssngbok; import android.app.Activity; import android.app.ActionBar; import android.app.Fragment; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; /** * Fragment used for managing interactions for and presentation of a navigation drawer. * See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction"> * design guidelines</a> for a complete explanation of the behaviors implemented here. */ public class NavigationDrawerFragment extends Fragment { /** * Remember the position of the selected item. */ private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position"; /** * Per the design guidelines, you should show the drawer on launch until the user manually * expands it. This shared preference tracks this. */ private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned"; /** * A pointer to the current callbacks instance (the Activity). */ private NavigationDrawerCallbacks mCallbacks; /** * Helper component that ties the action bar to the navigation drawer. */ private ActionBarDrawerToggle mDrawerToggle; private DrawerLayout mDrawerLayout; private ListView mDrawerListView; private View mFragmentContainerView; private int mCurrentSelectedPosition = 0; private boolean mFromSavedInstanceState; private boolean mUserLearnedDrawer; public NavigationDrawerFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Read in the flag indicating whether or not the user has demonstrated awareness of the // drawer. See PREF_USER_LEARNED_DRAWER for details. SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity()); mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false); if (savedInstanceState != null) { mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION); mFromSavedInstanceState = true; } // Select either the default item (0) or the last selected item. selectItem(mCurrentSelectedPosition); } @Override public void onActivityCreated (Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Indicate that this fragment would like to influence the set of actions in the action bar. setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mDrawerListView = (ListView) inflater.inflate( R.layout.fragment_navigation_drawer, container, false); mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectItem(position); } }); mDrawerListView.setAdapter(new ArrayAdapter<String>( getActionBar().getThemedContext(), android.R.layout.simple_list_item_activated_1, android.R.id.text1, new String[]{ getString(R.string.title_section1), getString(R.string.title_section2), getString(R.string.title_section3), })); mDrawerListView.setItemChecked(mCurrentSelectedPosition, true); return mDrawerListView; } public boolean isDrawerOpen() { return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView); } /** * Users of this fragment must call this method to set up the navigation drawer interactions. * * @param fragmentId The android:id of this fragment in its activity's layout. * @param drawerLayout The DrawerLayout containing this fragment's UI. */ public void setUp(int fragmentId, DrawerLayout drawerLayout) { mFragmentContainerView = getActivity().findViewById(fragmentId); mDrawerLayout = drawerLayout; // set a custom shadow that overlays the main content when the drawer opens mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); // set up the drawer's list view with items and click listener ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeButtonEnabled(true); // ActionBarDrawerToggle ties together the the proper interactions // between the navigation drawer and the action bar app icon. mDrawerToggle = new ActionBarDrawerToggle( getActivity(), /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */ R.string.navigation_drawer_open, /* "open drawer" description for accessibility */ R.string.navigation_drawer_close /* "close drawer" description for accessibility */ ) { @Override public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); if (!isAdded()) { return; } getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu() } @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); if (!isAdded()) { return; } if (!mUserLearnedDrawer) { // The user manually opened the drawer; store this flag to prevent auto-showing // the navigation drawer automatically in the future. mUserLearnedDrawer = true; SharedPreferences sp = PreferenceManager .getDefaultSharedPreferences(getActivity()); sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply(); } getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu() } }; // If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer, // per the navigation drawer design guidelines. if (!mUserLearnedDrawer && !mFromSavedInstanceState) { mDrawerLayout.openDrawer(mFragmentContainerView); } // Defer code dependent on restoration of previous instance state. mDrawerLayout.post(new Runnable() { @Override public void run() { mDrawerToggle.syncState(); } }); mDrawerLayout.setDrawerListener(mDrawerToggle); } private void selectItem(int position) { mCurrentSelectedPosition = position; if (mDrawerListView != null) { mDrawerListView.setItemChecked(position, true); } if (mDrawerLayout != null) { mDrawerLayout.closeDrawer(mFragmentContainerView); } if (mCallbacks != null) { mCallbacks.onNavigationDrawerItemSelected(position); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mCallbacks = (NavigationDrawerCallbacks) activity; } catch (ClassCastException e) { throw new ClassCastException("Activity must implement NavigationDrawerCallbacks."); } } @Override public void onDetach() { super.onDetach(); mCallbacks = null; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Forward the new configuration the drawer toggle component. mDrawerToggle.onConfigurationChanged(newConfig); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // If the drawer is open, show the global app actions in the action bar. See also // showGlobalContextActionBar, which controls the top-left area of the action bar. if (mDrawerLayout != null && isDrawerOpen()) { inflater.inflate(R.menu.global, menu); showGlobalContextActionBar(); } super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } if (item.getItemId() == R.id.action_example) { Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show(); return true; } return super.onOptionsItemSelected(item); } /** * Per the navigation drawer design guidelines, updates the action bar to show the global app * 'context', rather than just what's in the current screen. */ private void showGlobalContextActionBar() { ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(true); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setTitle(R.string.app_name); } private ActionBar getActionBar() { return getActivity().getActionBar(); } /** * Callbacks interface that all activities using this fragment must implement. */ public static interface NavigationDrawerCallbacks { /** * Called when an item in the navigation drawer is selected. */ void onNavigationDrawerItemSelected(int position); } }
mit
chriske/nytimes_api_demo
app/src/main/java/hu/autsoft/nytimes/exception/OkHttpException.java
172
package hu.autsoft.nytimes.exception; public class OkHttpException extends RuntimeException { public OkHttpException(Throwable cause) { super(cause); } }
mit
Wadpam/lets-the-right-one-in
lroi-lib/src/main/java/se/leiflandia/lroi/utils/AuthUtils.java
3349
package se.leiflandia.lroi.utils; import android.accounts.Account; import android.accounts.AccountManager; import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import se.leiflandia.lroi.auth.model.AccessToken; import se.leiflandia.lroi.auth.model.UserCredentials; public class AuthUtils { private static final String PREF_ACTIVE_ACCOUNT = "active_account"; private static final String PREFS_NAME = "se.leiflandia.lroi.prefs"; public static void removeActiveAccount(Context context, String accountType) { Account account = getActiveAccount(context, accountType); if (account != null) { AccountManager.get(context).removeAccount(account, null, null); } setActiveAccountName(context, null); } public static Account getActiveAccount(final Context context, final String accountType) { Account[] accounts = AccountManager.get(context).getAccountsByType(accountType); return getActiveAccount(accounts, getActiveAccountName(context)); } public static boolean hasActiveAccount(final Context context, final String accountType) { return getActiveAccount(context, accountType) != null; } private static String getActiveAccountName(final Context context) { return getSharedPreferences(context) .getString(PREF_ACTIVE_ACCOUNT, null); } public static void setActiveAccountName(final Context context, final String name) { getSharedPreferences(context).edit() .putString(PREF_ACTIVE_ACCOUNT, name) .commit(); } private static Account getActiveAccount(final Account[] accounts, final String activeAccountName) { for (Account account : accounts) { if (TextUtils.equals(account.name, activeAccountName)) { return account; } } return null; } private static SharedPreferences getSharedPreferences(final Context context) { return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); } /** * Saves an authorized account in account manager and set as active account. */ public static void setAuthorizedAccount(Context context, UserCredentials credentials, AccessToken token, String authtokenType, String accountType) { final AccountManager accountManager = AccountManager.get(context); Account account = findOrCreateAccount(accountManager, credentials.getUsername(), token.getRefreshToken(), accountType); accountManager.setAuthToken(account, authtokenType, token.getAccessToken()); setActiveAccountName(context, account.name); } /** * Sets password of account, creates a new account if necessary. */ private static Account findOrCreateAccount(AccountManager accountManager, String username, String refreshToken, String accountType) { for (Account account : accountManager.getAccountsByType(accountType)) { if (account.name.equals(username)) { accountManager.setPassword(account, refreshToken); return account; } } Account account = new Account(username, accountType); accountManager.addAccountExplicitly(account, refreshToken, null); return account; } }
mit
selvasingh/azure-sdk-for-java
sdk/network/mgmt-v2020_04_01/src/main/java/com/microsoft/azure/management/network/v2020_04_01/ExpressRouteCircuitSku.java
2518
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2020_04_01; import com.fasterxml.jackson.annotation.JsonProperty; /** * Contains SKU in an ExpressRouteCircuit. */ public class ExpressRouteCircuitSku { /** * The name of the SKU. */ @JsonProperty(value = "name") private String name; /** * The tier of the SKU. Possible values include: 'Standard', 'Premium', * 'Basic', 'Local'. */ @JsonProperty(value = "tier") private ExpressRouteCircuitSkuTier tier; /** * The family of the SKU. Possible values include: 'UnlimitedData', * 'MeteredData'. */ @JsonProperty(value = "family") private ExpressRouteCircuitSkuFamily family; /** * Get the name of the SKU. * * @return the name value */ public String name() { return this.name; } /** * Set the name of the SKU. * * @param name the name value to set * @return the ExpressRouteCircuitSku object itself. */ public ExpressRouteCircuitSku withName(String name) { this.name = name; return this; } /** * Get the tier of the SKU. Possible values include: 'Standard', 'Premium', 'Basic', 'Local'. * * @return the tier value */ public ExpressRouteCircuitSkuTier tier() { return this.tier; } /** * Set the tier of the SKU. Possible values include: 'Standard', 'Premium', 'Basic', 'Local'. * * @param tier the tier value to set * @return the ExpressRouteCircuitSku object itself. */ public ExpressRouteCircuitSku withTier(ExpressRouteCircuitSkuTier tier) { this.tier = tier; return this; } /** * Get the family of the SKU. Possible values include: 'UnlimitedData', 'MeteredData'. * * @return the family value */ public ExpressRouteCircuitSkuFamily family() { return this.family; } /** * Set the family of the SKU. Possible values include: 'UnlimitedData', 'MeteredData'. * * @param family the family value to set * @return the ExpressRouteCircuitSku object itself. */ public ExpressRouteCircuitSku withFamily(ExpressRouteCircuitSkuFamily family) { this.family = family; return this; } }
mit
mjsmith707/KSPCompiler
src/ASMCode.java
4329
import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.LinkedList; //this code contains the output assembly code that the program outputs. //will have at least three functions: //add(string, string, string, string) <- adds an assembly code line //optimise(int) <- optimises the output code, wherever possible //write(string) <- writes the code to the desired filename public class ASMCode { LinkedList<String> lines = new LinkedList<String>(); LinkedList<String> data = new LinkedList<String>(); HashMap<String, String> stringMap = new HashMap<String, String>(); LinkedList<lineWrapper> functionLines = new LinkedList<lineWrapper>(); boolean hasFCall; private interface lineWrapper { String compile(int stacksize, boolean funcCall); } private class stdLineWrapper implements lineWrapper { private String line; @Override public String compile(int stacksize, boolean funcCall) { return line; } public stdLineWrapper(String s) { line = s; } } private class functionReturnWrapper implements lineWrapper { @Override public String compile(int stacksize, boolean funcCall) { StringBuilder s = new StringBuilder(); if(stacksize != 0) { s.append("\tmov\tsp, fp"); s.append(System.getProperty("line.separator"));//system independent newline s.append("\tpop\tfp"); s.append(System.getProperty("line.separator")); } if(hasFCall) { s.append("\tpop\tra"); s.append(System.getProperty("line.separator")); } s.append("\tjmpr\tra"); return s.toString(); } } public void add(String inst, String reg1, String reg2, String reg3) { if(deadCode) return; String newInst = "\t"+inst; if(reg1 != null) { newInst = newInst + "\t" + reg1; if(reg2 != null) { newInst = newInst + ", " + reg2; if(reg3 != null) { newInst = newInst + ", " + reg3; } } } functionLines.addLast(new stdLineWrapper(newInst)); } public void add(String inst, String reg1, String reg2) { add(inst, reg1, reg2, null); } public void add(String inst, String reg1) { add(inst, reg1, null, null); } public void add(String inst) { add(inst, null, null, null); } int labIndex = 0; public String addString(String s) { //makes sure we don't have duplicate strings in memory if(stringMap.containsKey(s)) return stringMap.get(s); //generate a label String label = "string" + labIndex++; data.addLast(label+":"); data.addLast("#string " +s); stringMap.put(s, label); return label; } public void addGlobal(String data, String label) { //generate a label this.data.addLast(label+":"); this.data.addLast(data); } public void put(String s) { if(!deadCode) functionLines.addLast(new stdLineWrapper(s)); } private String fname; public void beginFunction(String name) { functionLines = new LinkedList<lineWrapper>(); fname = name; hasFCall = false; } public void endFunction(int varCount) { lines.addLast("#global " + fname); lines.addLast(fname+":"); if(hasFCall) { lines.addLast("\tpush\tra"); } if(varCount != 0) { lines.addLast("\tpush\tfp"); lines.addLast("\tmov\tfp, sp"); lines.addLast("\taddi\tsp, sp, " + varCount); } for(lineWrapper w : functionLines) { lines.addLast(w.compile(varCount, hasFCall)); } } public void setHasFCall() { if(deadCode) return; hasFCall = true; } public void functionReturn() { if(deadCode) return; functionLines.addLast(new functionReturnWrapper()); } public void write(String filename) { //System.out.println(".text"); //for(String s : lines) { // System.out.println(s); //} //System.out.println(".data"); //for(String s : data) { // System.out.println(s); //} System.out.println("Compilation successful!"); System.out.println("Writing..."); try { PrintWriter out = new PrintWriter(new FileWriter(filename+".asm")); out.println(".text"); for(String s : lines) { out.println(s); } out.println(".data"); for(String s : data) { out.println(s); } out.close(); } catch(IOException e) { System.out.println("Writing failed"); return; } System.out.println("Program created!"); } boolean deadCode; public void deadCode(boolean codeIsDead) { deadCode = codeIsDead; } }
mit
weeniearms/graffiti
src/main/java/com/github/weeniearms/graffiti/GraphService.java
1097
package com.github.weeniearms.graffiti; import com.github.weeniearms.graffiti.config.CacheConfiguration; import com.github.weeniearms.graffiti.generator.GraphGenerator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import java.io.IOException; import java.util.Arrays; @Service public class GraphService { private final GraphGenerator[] generators; @Autowired public GraphService(GraphGenerator[] generators) { this.generators = generators; } @Cacheable(CacheConfiguration.GRAPH) public byte[] generateGraph(String source, GraphGenerator.OutputFormat format) throws IOException { GraphGenerator generator = Arrays.stream(generators) .filter(g -> g.isSourceSupported(source)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("No matching generator found for source")); return generator.generateGraph(source, format); } }
mit
caat91/NagiosAlert
NagiosAlert-App/src/redes3/proyecto/nagiosalert/InfoServiceActivity.java
2141
package redes3.proyecto.nagiosalert; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.TextView; public class InfoServiceActivity extends Activity { String nombre; int status; String duracion; String revision; String info; ImageView image ; TextView tvNombre ; TextView tvStatus ; TextView tvDuracion ; TextView tvRevision ; TextView tvInfo ; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_info_service); nombre = new String(); status = 0 ; duracion = new String(); revision = new String(); info = new String(); image = (ImageView) findViewById(R.id.image); tvNombre = (TextView)this.findViewById(R.id.tvNombreServicio); tvStatus = (TextView)this.findViewById(R.id.status); tvDuracion = (TextView)this.findViewById(R.id.duracion); tvRevision = (TextView)this.findViewById(R.id.revision); tvInfo = (TextView)this.findViewById(R.id.info); Bundle extras = getIntent().getExtras(); nombre = extras.getString("nombre"); status = extras.getInt("status"); duracion = extras.getString("duracion"); revision = extras.getString("revision"); info = extras.getString("info"); tvNombre.setText(nombre); tvDuracion.setText("Duracion : \n"+duracion); tvRevision.setText("Revision : \n"+revision); tvInfo.setText("Descripción : \n"+info); if(status== 0){ tvStatus.setText("Estado : \nOk"); image.setImageResource(R.drawable.fine); }else if(status== 1){ tvStatus.setText("Estado : \nFail"); image.setImageResource(R.drawable.fail); }if(status== 2){ tvStatus.setText("Estado : \nWarning"); image.setImageResource(R.drawable.warning); }if(status== 3){ tvStatus.setText("Estado : \nUnknown"); image.setImageResource(R.drawable.unknown); } } }
mit
jonestimd/finances
src/main/java/io/github/jonestimd/finance/file/Reconciler.java
3250
// The MIT License (MIT) // // Copyright (c) 2016 Tim Jones // // 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 NONINFRINGEMENT. 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 io.github.jonestimd.finance.file; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.function.Predicate; import java.util.stream.Collectors; import io.github.jonestimd.finance.domain.transaction.Transaction; import io.github.jonestimd.finance.swing.transaction.TransactionTableModel; import static io.github.jonestimd.util.JavaPredicates.*; public class Reconciler { private final TransactionTableModel tableModel; private final List<Transaction> uncleared; public Reconciler(TransactionTableModel tableModel) { this.tableModel = tableModel; this.uncleared = tableModel.getBeans().stream() .filter(not(Transaction::isCleared)).filter(not(Transaction::isNew)) .collect(Collectors.toList()); } public void reconcile(Collection<Transaction> transactions) { transactions.forEach(this::reconcile); } private void reconcile(Transaction transaction) { Transaction toClear = select(transaction); if (toClear.isNew()) { toClear.setCleared(true); tableModel.queueAdd(tableModel.getBeanCount()-1, toClear); } else { tableModel.setValueAt(true, tableModel.rowIndexOf(toClear), tableModel.getClearedColumn()); } } private Transaction select(Transaction transaction) { return uncleared.stream().filter(sameProperties(transaction)).min(nearestDate(transaction)).orElse(transaction); } private Predicate<Transaction> sameProperties(Transaction transaction) { return t2 -> transaction.getAmount().compareTo(t2.getAmount()) == 0 && transaction.getAssetQuantity().compareTo(t2.getAssetQuantity()) == 0 && Objects.equals(transaction.getPayee(), t2.getPayee()) && Objects.equals(transaction.getSecurity(), t2.getSecurity()); } private Comparator<Transaction> nearestDate(Transaction transaction) { return Comparator.comparingInt(t -> transaction.getDate().compareTo(t.getDate())); } }
mit
tsmith328/Homework
Java/CS 1332/Homework 01/CircularLinkedList.java
4722
/** * CircularLinkedList implementation * @author Tyler Smith * @version 1.0 */ public class CircularLinkedList<T> implements LinkedListInterface<T> { private Node<T> head = null, tail = head; private int size = 0; @Override public void addAtIndex(int index, T data) { if (index < 0 || index > this.size()) { throw new IndexOutOfBoundsException(); } if (index == 0) { this.addToFront(data); } else if (index == this.size()) { this.addToBack(data); } else { Node<T> current = head; if (index == 1) { current.setNext(new Node<T>(data, current.getNext())); } else { for (int i = 0; i < index - 1; i++) { current = current.getNext(); } Node<T> temp = current; current = new Node<T>(data, temp); } size++; } } @Override public T get(int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(); } Node<T> current = head; for (int i = 0; i < index; i++) { current = current.getNext(); } return current.getData(); } @Override public T removeAtIndex(int index) { if (index < 0 || index >= this.size()) { throw new IndexOutOfBoundsException(); } if (index == 0) { T data = head.getData(); head = head.getNext(); tail.setNext(head); size--; return data; } else { Node<T> before = tail; Node<T> current = head; for (int i = 0; i < index; i++) { before = current; current = current.getNext(); } T data = current.getData(); before.setNext(current.getNext()); size--; return data; } } @Override public void addToFront(T t) { if (this.isEmpty()) { head = new Node<T>(t, tail); tail = head; tail.setNext(head); size++; return; } Node<T> node = new Node<T>(t, head); head = node; tail.setNext(head); size++; } @Override public void addToBack(T t) { if (this.isEmpty()) { tail = new Node<T>(t); head = tail; tail.setNext(head); head.setNext(tail); size++; } else { Node<T> temp = tail; tail = new Node<T>(t, head); temp.setNext(tail); size++; } } @Override public T removeFromFront() { if (this.isEmpty()) { return null; } Node<T> ret = head; head = head.getNext(); tail.setNext(head); size--; return ret.getData(); } @Override public T removeFromBack() { if (this.isEmpty()) { return null; } Node<T> iterate = head; while (iterate.getNext() != tail) { iterate = iterate.getNext(); } iterate.setNext(head); Node<T> ret = tail; tail = iterate; size--; return ret.getData(); } @SuppressWarnings("unchecked") @Override public T[] toList() { Object[] list = new Object[this.size()]; int i = 0; Node<T> current = head; while (i < this.size()) { list[i] = current.getData(); current = current.getNext(); i++; } return ((T[]) list); } @Override public boolean isEmpty() { return (this.size() == 0); } @Override public int size() { return size; } @Override public void clear() { head = null; tail = null; size = 0; } /** * Reference to the head node of the linked list. * Normally, you would not do this, but we need it * for grading your work. * * @return Node representing the head of the linked list */ public Node<T> getHead() { return head; } /** * Reference to the tail node of the linked list. * Normally, you would not do this, but we need it * for grading your work. * * @return Node representing the tail of the linked list */ public Node<T> getTail() { return tail; } /** * This method is for your testing purposes. * You may choose to implement it if you wish. */ @Override public String toString() { return ""; } }
mit
selvasingh/azure-sdk-for-java
sdk/synapse/mgmt-v2019_06_01_preview/src/main/java/com/microsoft/azure/management/synapse/v2019_06_01_preview/IntegrationRuntimeState.java
2607
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.synapse.v2019_06_01_preview; import java.util.Collection; import com.fasterxml.jackson.annotation.JsonCreator; import com.microsoft.rest.ExpandableStringEnum; /** * Defines values for IntegrationRuntimeState. */ public final class IntegrationRuntimeState extends ExpandableStringEnum<IntegrationRuntimeState> { /** Static value Initial for IntegrationRuntimeState. */ public static final IntegrationRuntimeState INITIAL = fromString("Initial"); /** Static value Stopped for IntegrationRuntimeState. */ public static final IntegrationRuntimeState STOPPED = fromString("Stopped"); /** Static value Started for IntegrationRuntimeState. */ public static final IntegrationRuntimeState STARTED = fromString("Started"); /** Static value Starting for IntegrationRuntimeState. */ public static final IntegrationRuntimeState STARTING = fromString("Starting"); /** Static value Stopping for IntegrationRuntimeState. */ public static final IntegrationRuntimeState STOPPING = fromString("Stopping"); /** Static value NeedRegistration for IntegrationRuntimeState. */ public static final IntegrationRuntimeState NEED_REGISTRATION = fromString("NeedRegistration"); /** Static value Online for IntegrationRuntimeState. */ public static final IntegrationRuntimeState ONLINE = fromString("Online"); /** Static value Limited for IntegrationRuntimeState. */ public static final IntegrationRuntimeState LIMITED = fromString("Limited"); /** Static value Offline for IntegrationRuntimeState. */ public static final IntegrationRuntimeState OFFLINE = fromString("Offline"); /** Static value AccessDenied for IntegrationRuntimeState. */ public static final IntegrationRuntimeState ACCESS_DENIED = fromString("AccessDenied"); /** * Creates or finds a IntegrationRuntimeState from its string representation. * @param name a name to look for * @return the corresponding IntegrationRuntimeState */ @JsonCreator public static IntegrationRuntimeState fromString(String name) { return fromString(name, IntegrationRuntimeState.class); } /** * @return known IntegrationRuntimeState values */ public static Collection<IntegrationRuntimeState> values() { return values(IntegrationRuntimeState.class); } }
mit
kristofersokk/RainControl
src/main/java/com/timotheteus/raincontrol/handlers/GuiHandler.java
2028
package com.timotheteus.raincontrol.handlers; import com.timotheteus.raincontrol.tileentities.IGUITile; import com.timotheteus.raincontrol.tileentities.TileEntityInventoryBase; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.fml.common.network.IGuiHandler; import net.minecraftforge.fml.network.FMLPlayMessages; import net.minecraftforge.fml.network.NetworkHooks; import javax.annotation.Nullable; public class GuiHandler implements IGuiHandler { public static GuiScreen openGui(FMLPlayMessages.OpenContainer openContainer) { BlockPos pos = openContainer.getAdditionalData().readBlockPos(); // new GUIChest(type, (IInventory) Minecraft.getInstance().player.inventory, (IInventory) Minecraft.getInstance().world.getTileEntity(pos)); TileEntityInventoryBase te = (TileEntityInventoryBase) Minecraft.getInstance().world.getTileEntity(pos); if (te != null) { return te.createGui(Minecraft.getInstance().player); } return null; } //TODO can remove these, I think @Nullable @Override public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { BlockPos pos = new BlockPos(x, y, z); TileEntity te = world.getTileEntity(pos); if (te instanceof IGUITile) { return ((IGUITile) te).createContainer(player); } return null; } @Nullable @Override public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { BlockPos pos = new BlockPos(x, y, z); TileEntity te = world.getTileEntity(pos); if (te instanceof IGUITile) { return ((IGUITile) te).createGui(player); } return null; } }
mit
fvasquezjatar/fermat-unused
DMP/plugin/basic_wallet/fermat-dmp-plugin-basic-wallet-bitcoin-wallet-bitdubai/src/test/java/unit/com/bitdubai/fermat_dmp_plugin/layer/basic_wallet/bitcoin_wallet/developer/bitdubai/version_1/structure/BitcoinWalletBasicWalletAvailableBalance/CreditTest.java
5641
package unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.BitcoinWalletBasicWalletAvailableBalance; import com.bitdubai.fermat_api.layer.dmp_basic_wallet.common.exceptions.CantRegisterCreditException; import com.bitdubai.fermat_api.layer.dmp_basic_wallet.bitcoin_wallet.interfaces.BitcoinWalletTransactionRecord; import com.bitdubai.fermat_api.layer.osa_android.database_system.Database; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTable; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableRecord; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTransaction; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantLoadTableToMemoryException; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantOpenDatabaseException; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.DatabaseNotFoundException; import com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.BitcoinWalletBasicWalletAvailableBalance; import com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.BitcoinWalletDatabaseConstants; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.ArrayList; import java.util.List; import unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.mocks.MockBitcoinWalletTransactionRecord; import unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.mocks.MockDatabaseTableRecord; import static com.googlecode.catchexception.CatchException.catchException; import static com.googlecode.catchexception.CatchException.caughtException; import static org.fest.assertions.api.Assertions.*; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.when; /** * Created by jorgegonzalez on 2015.07.14.. */ @RunWith(MockitoJUnitRunner.class) public class CreditTest { @Mock private Database mockDatabase; @Mock private DatabaseTable mockWalletTable; @Mock private DatabaseTable mockBalanceTable; @Mock private DatabaseTransaction mockTransaction; private List<DatabaseTableRecord> mockRecords; private DatabaseTableRecord mockBalanceRecord; private DatabaseTableRecord mockWalletRecord; private BitcoinWalletTransactionRecord mockTransactionRecord; private BitcoinWalletBasicWalletAvailableBalance testBalance; @Before public void setUpMocks(){ mockTransactionRecord = new MockBitcoinWalletTransactionRecord(); mockBalanceRecord = new MockDatabaseTableRecord(); mockWalletRecord = new MockDatabaseTableRecord(); mockRecords = new ArrayList<>(); mockRecords.add(mockBalanceRecord); setUpMockitoRules(); } public void setUpMockitoRules(){ when(mockDatabase.getTable(BitcoinWalletDatabaseConstants.BITCOIN_WALLET_TABLE_NAME)).thenReturn(mockWalletTable); when(mockDatabase.getTable(BitcoinWalletDatabaseConstants.BITCOIN_WALLET_BALANCE_TABLE_NAME)).thenReturn(mockBalanceTable); when(mockBalanceTable.getRecords()).thenReturn(mockRecords); when(mockWalletTable.getEmptyRecord()).thenReturn(mockWalletRecord); when(mockDatabase.newTransaction()).thenReturn(mockTransaction); } @Before public void setUpAvailableBalance(){ testBalance = new BitcoinWalletBasicWalletAvailableBalance(mockDatabase); } @Test public void Credit_SuccesfullyInvoked_ReturnsAvailableBalance() throws Exception{ catchException(testBalance).credit(mockTransactionRecord); assertThat(caughtException()).isNull(); } @Test public void Credit_OpenDatabaseCantOpenDatabase_ThrowsCantRegisterCreditException() throws Exception{ doThrow(new CantOpenDatabaseException("MOCK", null, null, null)).when(mockDatabase).openDatabase(); catchException(testBalance).credit(mockTransactionRecord); assertThat(caughtException()) .isNotNull() .isInstanceOf(CantRegisterCreditException.class); } @Test public void Credit_OpenDatabaseDatabaseNotFound_ThrowsCantRegisterCreditException() throws Exception{ doThrow(new DatabaseNotFoundException("MOCK", null, null, null)).when(mockDatabase).openDatabase(); catchException(testBalance).credit(mockTransactionRecord); assertThat(caughtException()) .isNotNull() .isInstanceOf(CantRegisterCreditException.class); } @Test public void Credit_DaoCantCalculateBalanceException_ThrowsCantRegisterCreditException() throws Exception{ doThrow(new CantLoadTableToMemoryException("MOCK", null, null, null)).when(mockWalletTable).loadToMemory(); catchException(testBalance).credit(mockTransactionRecord); assertThat(caughtException()) .isNotNull() .isInstanceOf(CantRegisterCreditException.class); } @Test public void Credit_GeneralException_ThrowsCantRegisterCreditException() throws Exception{ when(mockBalanceTable.getRecords()).thenReturn(null); catchException(testBalance).credit(mockTransactionRecord); assertThat(caughtException()) .isNotNull() .isInstanceOf(CantRegisterCreditException.class); } }
mit
sdl/Testy
src/main/java/com/sdl/selenium/extjs3/button/DownloadLink.java
1642
package com.sdl.selenium.extjs3.button; import com.sdl.selenium.bootstrap.button.Download; import com.sdl.selenium.extjs3.ExtJsComponent; import com.sdl.selenium.web.SearchType; import com.sdl.selenium.web.WebLocator; public class DownloadLink extends ExtJsComponent implements Download { public DownloadLink() { setClassName("DownloadLink"); setTag("a"); } public DownloadLink(WebLocator container) { this(); setContainer(container); } public DownloadLink(WebLocator container, String text) { this(container); setText(text, SearchType.EQUALS); } /** * Wait for the element to be activated when there is deactivation mask on top of it * * @param seconds time */ @Override public boolean waitToActivate(int seconds) { return getXPath().contains("ext-ux-livegrid") || super.waitToActivate(seconds); } /** * if WebDriverConfig.isSilentDownload() is true, se face silentDownload, is is false se face download with AutoIT. * Download file with AutoIT, works only on FireFox. SilentDownload works FireFox and Chrome * Use only this: button.download("C:\\TestSet.tmx"); * return true if the downloaded file is the same one that is meant to be downloaded, otherwise returns false. * * @param fileName e.g. "TestSet.tmx" */ @Override public boolean download(String fileName) { openBrowse(); return executor.download(fileName, 10000L); } private void openBrowse() { executor.browse(this); } }
mit
njacinto/Utils
src/main/java/org/nfpj/utils/arrays/ArrayFilterIterator.java
3840
/* * The MIT License * * Copyright 2016 njacinto. * * 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 NONINFRINGEMENT. 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.nfpj.utils.arrays; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.function.Predicate; import org.nfpj.utils.predicates.TruePredicate; /** * * @author njacinto * @param <T> the type of object being returned by this iterator */ public class ArrayFilterIterator<T> implements Iterator<T> { protected static final int END_OF_ITERATION = -2; // private int nextIndex; // protected final T[] array; protected final Predicate<T> predicate; // <editor-fold defaultstate="expanded" desc="Constructors"> /** * Creates an instance of this class * * @param array the array from where this instance will extract the elements * @param predicate the filter to be applied to the elements */ public ArrayFilterIterator(T[] array, Predicate<T> predicate) { this(array, predicate, -1); } /** * * @param array * @param predicate * @param prevIndex */ protected ArrayFilterIterator(T[] array, Predicate<T> predicate, int prevIndex) { this.array = array!=null ? array : ArrayUtil.empty(); this.predicate = predicate!=null ? predicate : TruePredicate.getInstance(); this.nextIndex = getNextIndex(prevIndex); } // </editor-fold> // <editor-fold defaultstate="expanded" desc="Public methods"> /** * {@inheritDoc} */ @Override public boolean hasNext() { return nextIndex != END_OF_ITERATION; } /** * {@inheritDoc} */ @Override public T next() { if(nextIndex==END_OF_ITERATION){ throw new NoSuchElementException("The underline collection has no elements."); } int index = nextIndex; nextIndex = getNextIndex(nextIndex); return array[index]; } /** * {@inheritDoc} */ @Override public void remove() { throw new UnsupportedOperationException("The iterator doesn't allow changes."); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Protected methods"> /** * Searches for the next element that matches the filtering conditions and * returns it. * * @param currIndex * @return the next element that matches the filtering conditions or null * if no more elements are available */ protected int getNextIndex(int currIndex){ if(currIndex!=END_OF_ITERATION){ for(int i=currIndex+1; i<array.length; i++){ if(predicate.test(array[i])){ return i; } } } return END_OF_ITERATION; } // </editor-fold> }
mit
ze-pequeno/mockito
src/test/java/org/mockitousage/verification/AtMostXVerificationTest.java
3400
/* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockitousage.verification; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.atMost; import static org.mockito.Mockito.atMostOnce; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import java.util.List; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.exceptions.base.MockitoException; import org.mockito.exceptions.verification.MoreThanAllowedActualInvocations; import org.mockito.exceptions.verification.NoInteractionsWanted; import org.mockitoutil.TestBase; public class AtMostXVerificationTest extends TestBase { @Mock private List<String> mock; @Test public void shouldVerifyAtMostXTimes() throws Exception { mock.clear(); mock.clear(); verify(mock, atMost(2)).clear(); verify(mock, atMost(3)).clear(); try { verify(mock, atMostOnce()).clear(); fail(); } catch (MoreThanAllowedActualInvocations e) { } } @Test public void shouldWorkWithArgumentMatchers() throws Exception { mock.add("one"); verify(mock, atMost(5)).add(anyString()); try { verify(mock, atMost(0)).add(anyString()); fail(); } catch (MoreThanAllowedActualInvocations e) { } } @Test public void shouldNotAllowNegativeNumber() throws Exception { try { verify(mock, atMost(-1)).clear(); fail(); } catch (MockitoException e) { assertEquals("Negative value is not allowed here", e.getMessage()); } } @Test public void shouldPrintDecentMessage() throws Exception { mock.clear(); mock.clear(); try { verify(mock, atMostOnce()).clear(); fail(); } catch (MoreThanAllowedActualInvocations e) { assertEquals("\nWanted at most 1 time but was 2", e.getMessage()); } } @Test public void shouldNotAllowInOrderMode() throws Exception { mock.clear(); InOrder inOrder = inOrder(mock); try { inOrder.verify(mock, atMostOnce()).clear(); fail(); } catch (MockitoException e) { assertEquals("AtMost is not implemented to work with InOrder", e.getMessage()); } } @Test public void shouldMarkInteractionsAsVerified() throws Exception { mock.clear(); mock.clear(); verify(mock, atMost(3)).clear(); verifyNoMoreInteractions(mock); } @Test public void shouldDetectUnverifiedInMarkInteractionsAsVerified() throws Exception { mock.clear(); mock.clear(); undesiredInteraction(); verify(mock, atMost(3)).clear(); try { verifyNoMoreInteractions(mock); fail(); } catch (NoInteractionsWanted e) { assertThat(e).hasMessageContaining("undesiredInteraction("); } } private void undesiredInteraction() { mock.add(""); } }
mit
niralittle/LibraryApp
src/controller/server/RMIServer.java
533
package controller.server; import controller.LibraryService; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import java.rmi.RemoteException; public class RMIServer { public static void main(String[] args) throws RemoteException, NamingException { LibraryService service = new DBController(); Context namingContext = new InitialContext(); namingContext.rebind("rmi:books", service); System.out.println("RMI-server is working..."); } }
mit
Azure/azure-sdk-for-java
sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/UserAssignedIdentity.java
1557
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.applicationinsights.models; import com.azure.core.annotation.Immutable; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.UUID; /** User assigned identity properties. */ @Immutable public class UserAssignedIdentity { @JsonIgnore private final ClientLogger logger = new ClientLogger(UserAssignedIdentity.class); /* * The principal ID of the assigned identity. */ @JsonProperty(value = "principalId", access = JsonProperty.Access.WRITE_ONLY) private UUID principalId; /* * The client ID of the assigned identity. */ @JsonProperty(value = "clientId", access = JsonProperty.Access.WRITE_ONLY) private UUID clientId; /** * Get the principalId property: The principal ID of the assigned identity. * * @return the principalId value. */ public UUID principalId() { return this.principalId; } /** * Get the clientId property: The client ID of the assigned identity. * * @return the clientId value. */ public UUID clientId() { return this.clientId; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { } }
mit
rasmusgreve/questionaire
dk.itu.smdp.group2.questionaire.ui/xtend-gen/dk/itu/smdp/group2/ui/outline/QuestionaireOutlineTreeProvider.java
382
/** * generated by Xtext */ package dk.itu.smdp.group2.ui.outline; import org.eclipse.xtext.ui.editor.outline.impl.DefaultOutlineTreeProvider; /** * Customization of the default outline structure. * * see http://www.eclipse.org/Xtext/documentation.html#outline */ @SuppressWarnings("all") public class QuestionaireOutlineTreeProvider extends DefaultOutlineTreeProvider { }
mit
Falkplan/lightspeedecom-api
lightspeedecom-api/src/main/java/com/lightspeedhq/ecom/LightspeedEComErrorException.java
528
package com.lightspeedhq.ecom; import com.lightspeedhq.ecom.domain.LightspeedEComError; import feign.FeignException; import lombok.Getter; /** * * @author stevensnoeijen */ public class LightspeedEComErrorException extends FeignException { @Getter private LightspeedEComError error; public LightspeedEComErrorException(String message, LightspeedEComError error) { super(message); this.error = error; } @Override public String toString() { return error.toString(); } }
mit
bladestery/Sapphire
example_apps/AndroidStudioMinnie/sapphire/src/main/java/boofcv/alg/filter/binary/ContourTracer.java
6808
/* * Copyright (c) 2011-2016, 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.filter.binary; import boofcv.struct.ConnectRule; import boofcv.struct.image.GrayS32; import boofcv.struct.image.GrayU8; import georegression.struct.point.Point2D_I32; import sapphire.app.SapphireObject; import org.ddogleg.struct.FastQueue; import java.util.List; /** * Used to trace the external and internal contours around objects for {@link LinearContourLabelChang2004}. As it * is tracing an object it will modify the binary image by labeling. The input binary image is assumed to have * a 1-pixel border that needs to be compensated for. * * @author Peter Abeles */ public class ContourTracer implements SapphireObject { // which connectivity rule is being used. 4 and 8 supported private ConnectRule rule; private int ruleN; // storage for contour points. private FastQueue<Point2D_I32> storagePoints; // binary image being traced private GrayU8 binary; // label image being marked private GrayS32 labeled; // storage for contour private List<Point2D_I32> contour; // coordinate of pixel being examined (x,y) private int x,y; // label of the object being traced private int label; // direction it moved in private int dir; // index of the pixel in the image's internal array private int indexBinary; private int indexLabel; // the pixel index offset to each neighbor private int offsetsBinary[]; private int offsetsLabeled[]; // lookup table for which direction it should search next given the direction it traveled into the current pixel private int nextDirection[]; /** * Specifies connectivity rule * * @param rule Specifies 4 or 8 as connectivity rule */ public ContourTracer( ConnectRule rule ) { this.rule = rule; if( ConnectRule.EIGHT == rule ) { // start the next search +2 away from the square it came from // the square it came from is the opposite from the previous 'dir' nextDirection = new int[8]; for( int i = 0; i < 8; i++ ) nextDirection[i] = ((i+4)%8 + 2)%8; ruleN = 8; } else if( ConnectRule.FOUR == rule ) { nextDirection = new int[4]; for( int i = 0; i < 4; i++ ) nextDirection[i] = ((i+2)%4 + 1)%4; ruleN = 4; } else { throw new IllegalArgumentException("Connectivity rule must be 4 or 8 not "+rule); } offsetsBinary = new int[ruleN]; offsetsLabeled = new int[ruleN]; } /** * * @param binary Binary image with a border of zeros added to the outside. * @param labeled Labeled image. Size is the same as the original binary image without border. * @param storagePoints */ public void setInputs(GrayU8 binary , GrayS32 labeled , FastQueue<Point2D_I32> storagePoints ) { this.binary = binary; this.labeled = labeled; this.storagePoints = storagePoints; if( rule == ConnectRule.EIGHT ) { setOffsets8(offsetsBinary,binary.stride); setOffsets8(offsetsLabeled,labeled.stride); } else { setOffsets4(offsetsBinary,binary.stride); setOffsets4(offsetsLabeled,labeled.stride); } } private void setOffsets8( int offsets[] , int stride ) { int s = stride; offsets[0] = 1; // x = 1 y = 0 offsets[1] = 1+s; // x = 1 y = 1 offsets[2] = s; // x = 0 y = 1 offsets[3] = -1+s; // x = -1 y = 1 offsets[4] = -1 ; // x = -1 y = 0 offsets[5] = -1-s; // x = -1 y = -1 offsets[6] = -s; // x = 0 y = -1 offsets[7] = 1-s; // x = 1 y = -1 } private void setOffsets4( int offsets[] , int stride ) { int s = stride; offsets[0] = 1; // x = 1 y = 0 offsets[1] = s; // x = 0 y = 1 offsets[2] = -1; // x = -1 y = 0 offsets[3] = -s; // x = 0 y = -1 } /** * * @param label * @param initialX * @param initialY * @param external True for tracing an external contour or false for internal.. * @param contour */ public void trace( int label , int initialX , int initialY , boolean external , List<Point2D_I32> contour ) { int initialDir; if( rule == ConnectRule.EIGHT ) initialDir = external ? 7 : 3; else initialDir = external ? 0 : 2; this.label = label; this.contour = contour; this.dir = initialDir; x = initialX; y = initialY; // index of pixels in the image array // binary has a 1 pixel border which labeled lacks, hence the -1,-1 for labeled indexBinary = binary.getIndex(x,y); indexLabel = labeled.getIndex(x-1,y-1); add(x,y); // find the next black pixel. handle case where its an isolated point if( !searchBlack() ) { return; } else { initialDir = dir; moveToNext(); dir = nextDirection[dir]; } while( true ) { // search in clockwise direction around the current pixel for next black pixel searchBlack(); if( x == initialX && y == initialY && dir == initialDir ) { // returned to the initial state again. search is finished return; }else { add(x, y); moveToNext(); dir = nextDirection[dir]; } } } /** * Searches in a circle around the current point in a clock-wise direction for the first black pixel. */ private boolean searchBlack() { for( int i = 0; i < offsetsBinary.length; i++ ) { if( checkBlack(indexBinary + offsetsBinary[dir])) return true; dir = (dir+1)%ruleN; } return false; } /** * Checks to see if the specified pixel is black (1). If not the pixel is marked so that it * won't be searched again */ private boolean checkBlack( int index ) { if( binary.data[index] == 1 ) { return true; } else { // mark white pixels as negative numbers to avoid retracing this contour in the future binary.data[index] = -1; return false; } } private void moveToNext() { // move to the next pixel using the precomputed pixel index offsets indexBinary += offsetsBinary[dir]; indexLabel += offsetsLabeled[dir]; // compute the new pixel coordinate from the binary pixel index int a = indexBinary - binary.startIndex; x = a%binary.stride; y = a/binary.stride; } /** * Adds a point to the contour list */ private void add( int x , int y ) { Point2D_I32 p = storagePoints.grow(); // compensate for the border added to binary image p.set(x-1, y-1); contour.add(p); labeled.data[indexLabel] = label; } }
mit
godong9/spring-board
board/src/main/java/com/board/gd/domain/stock/StockResult.java
777
package com.board.gd.domain.stock; import lombok.Data; import java.util.List; import java.util.stream.Collectors; /** * Created by gd.godong9 on 2017. 5. 19. */ @Data public class StockResult { private Long id; private String name; private String code; public static StockResult getStockResult(Stock stock) { StockResult stockResult = new StockResult(); stockResult.setId(stock.getId()); stockResult.setName(stock.getName()); stockResult.setCode(stock.getCode()); return stockResult; } public static List<StockResult> getStockResultList(List<Stock> stockList) { return stockList.stream() .map(stock -> getStockResult(stock)) .collect(Collectors.toList()); } }
mit
Enginecrafter77/LMPluger
src/addonloader/util/ObjectSettings.java
1423
package addonloader.util; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.Properties; /** * Simple wrapper around {@link Properites}, * allowing to easily access objects. * @author Enginecrafter77 */ public class ObjectSettings extends Properties{ private static final long serialVersionUID = -8939834947658913650L; private final File path; public ObjectSettings(File path) throws FileNotFoundException, IOException { this.path = path; this.load(new FileReader(path)); } public ObjectSettings(String path) throws FileNotFoundException, IOException { this(new File(path)); } public boolean getBoolean(String key, boolean def) { return Boolean.parseBoolean(this.getProperty(key, String.valueOf(def))); } public int getInteger(String key, int def) { return Integer.parseInt(this.getProperty(key, String.valueOf(def))); } public float getFloat(String key, float def) { return Float.parseFloat(this.getProperty(key, String.valueOf(def))); } public void set(String key, Object val) { this.setProperty(key, val.toString()); } public void store(String comment) { try { this.store(new FileOutputStream(path), comment); } catch(IOException e) { e.printStackTrace(); } } }
mit
bisignam/koukan
src/main/java/ch/bisi/koukan/job/ECBDataLoaderScheduler.java
3982
package ch.bisi.koukan.job; import ch.bisi.koukan.provider.XMLExchangeRatesProvider; import ch.bisi.koukan.repository.DataAccessException; import ch.bisi.koukan.repository.ExchangeRatesRepository; import java.io.IOException; import java.io.InputStream; import java.net.URL; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** * Executes scheduled tasks for updating the in memory exchange rates * by querying the European Central Bank endpoints. */ @Component public class ECBDataLoaderScheduler { private static final Logger logger = LoggerFactory.getLogger(ECBDataLoaderScheduler.class); private final XMLExchangeRatesProvider xmlExchangeRatesProvider; private final ExchangeRatesRepository exchangeRatesRepository; private final URL dailyEndpoint; private final URL pastDaysEndpoint; /** * Instantiates a new {@link ECBDataLoaderScheduler}. * * @param xmlExchangeRatesProvider the provider of exchange rates * @param exchangeRatesRepository the repository * @param dailyEndpoint the ECB daily endpoint {@link URL} * @param pastDaysEndpoint the ECB endpoint {@link URL} for retrieving past days data */ @Autowired public ECBDataLoaderScheduler( @Qualifier("ECBProvider") final XMLExchangeRatesProvider xmlExchangeRatesProvider, final ExchangeRatesRepository exchangeRatesRepository, @Qualifier("dailyEndpoint") final URL dailyEndpoint, @Qualifier("pastDaysEndpoint") final URL pastDaysEndpoint) { this.xmlExchangeRatesProvider = xmlExchangeRatesProvider; this.exchangeRatesRepository = exchangeRatesRepository; this.dailyEndpoint = dailyEndpoint; this.pastDaysEndpoint = pastDaysEndpoint; } /** * Retrieves the whole exchange rates daily data. * * @throws IOException in case of the problems accessing the ECB endpoint * @throws XMLStreamException in case of problems parsing the ECB XML * @throws DataAccessException in case of problems accessing the underlying data */ @Scheduled(initialDelay = 0, fixedRateString = "${daily.rates.update.rate}") public void loadDailyData() throws IOException, XMLStreamException, DataAccessException { try (final InputStream inputStream = dailyEndpoint.openStream()) { logger.info("Updating ECB daily exchange rates data"); loadData(inputStream); } } /** * Retrieves the whole exchange rates data for past days. * * @throws IOException in case of the problems accessing the ECB endpoint * @throws XMLStreamException in case of problems parsing the ECB XML * @throws DataAccessException in case of problems accessing the underlying data */ @Scheduled(initialDelay = 0, fixedRateString = "${past.days.rates.update.rate}") public void loadPastDaysData() throws IOException, XMLStreamException, DataAccessException { try (final InputStream inputStream = pastDaysEndpoint.openStream()) { logger.info("Updating ECB exchange rates data for the past 90 days"); loadData(inputStream); } } /** * Loads exchange rates data from the given {@link InputStream}. * * @param inputStream the {@link InputStream} * @throws XMLStreamException in case of problems parsing the ECB XML * @throws DataAccessException in case of problems accessing the underlying data */ private void loadData(final InputStream inputStream) throws XMLStreamException, DataAccessException { final XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance() .createXMLStreamReader(inputStream); exchangeRatesRepository.save(xmlExchangeRatesProvider.retrieveAll(xmlStreamReader)); } }
mit
VDuda/SyncRunner-Pub
src/API/amazon/mws/xml/JAXB/CdrhClassification.java
3909
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.05.03 at 03:15:27 PM EDT // package API.amazon.mws.xml.JAXB; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlValue; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="value"> * &lt;complexType> * &lt;simpleContent> * &lt;extension base="&lt;>String200Type"> * &lt;/extension> * &lt;/simpleContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;attribute name="delete" type="{}BooleanType" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @XmlRootElement(name = "cdrh_classification") public class CdrhClassification { @XmlElement(required = true) protected CdrhClassification.Value value; @XmlAttribute(name = "delete") protected BooleanType delete; /** * Gets the value of the value property. * * @return * possible object is * {@link CdrhClassification.Value } * */ public CdrhClassification.Value getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link CdrhClassification.Value } * */ public void setValue(CdrhClassification.Value value) { this.value = value; } /** * Gets the value of the delete property. * * @return * possible object is * {@link BooleanType } * */ public BooleanType getDelete() { return delete; } /** * Sets the value of the delete property. * * @param value * allowed object is * {@link BooleanType } * */ public void setDelete(BooleanType value) { this.delete = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;simpleContent> * &lt;extension base="&lt;>String200Type"> * &lt;/extension> * &lt;/simpleContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) public static class Value { @XmlValue protected String value; /** * Gets the value of the value property. * * @return * possible object is * {@link String } * */ public String getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setValue(String value) { this.value = value; } } }
mit
byronka/xenos
utils/pmd-bin-5.2.2/src/pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/ClassNode.java
585
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.dfa.report; public class ClassNode extends AbstractReportNode { private String className; public ClassNode(String className) { this.className = className; } public String getClassName() { return className; } public boolean equalsNode(AbstractReportNode arg0) { if (!(arg0 instanceof ClassNode)) { return false; } return ((ClassNode) arg0).getClassName().equals(className); } }
mit
Pankiev/MMORPG_Prototype
Server/core/src/pl/mmorpg/prototype/server/objects/monsters/properties/builders/SnakePropertiesBuilder.java
384
package pl.mmorpg.prototype.server.objects.monsters.properties.builders; import pl.mmorpg.prototype.clientservercommon.packets.monsters.properties.MonsterProperties; public class SnakePropertiesBuilder extends MonsterProperties.Builder { @Override public MonsterProperties build() { experienceGain(100) .hp(100) .strength(5) .level(1); return super.build(); } }
mit
FlareBot/FlareBot
src/main/java/stream/flarebot/flarebot/mod/modlog/ModAction.java
1090
package stream.flarebot.flarebot.mod.modlog; public enum ModAction { BAN(true, ModlogEvent.USER_BANNED), SOFTBAN(true, ModlogEvent.USER_SOFTBANNED), FORCE_BAN(true, ModlogEvent.USER_BANNED), TEMP_BAN(true, ModlogEvent.USER_TEMP_BANNED), UNBAN(false, ModlogEvent.USER_UNBANNED), KICK(true, ModlogEvent.USER_KICKED), TEMP_MUTE(true, ModlogEvent.USER_TEMP_MUTED), MUTE(true, ModlogEvent.USER_MUTED), UNMUTE(false, ModlogEvent.USER_UNMUTED), WARN(true, ModlogEvent.USER_WARNED); private boolean infraction; private ModlogEvent event; ModAction(boolean infraction, ModlogEvent modlogEvent) { this.infraction = infraction; this.event = modlogEvent; } public boolean isInfraction() { return infraction; } @Override public String toString() { return name().charAt(0) + name().substring(1).toLowerCase().replaceAll("_", " "); } public String getLowercaseName() { return toString().toLowerCase(); } public ModlogEvent getEvent() { return event; } }
mit
ohhopi/six-couleurs
6Colors/src/edu/isep/sixcolors/view/listener/Exit.java
702
package edu.isep.sixcolors.view.listener; import edu.isep.sixcolors.model.Config; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * A popup window asking if the player want's to exit Six Colors */ public class Exit implements ActionListener { @Override public void actionPerformed(ActionEvent e) { int option = JOptionPane.showConfirmDialog( null, Config.EXIT_MESSAGE, Config.EXIT_TITLE, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE ); if (option == JOptionPane.YES_OPTION){ System.exit(0); } } }
mit
nosered/contact-cloud
src/main/java/br/eti/qisolucoes/contactcloud/config/SecurityConfig.java
1557
package br.eti.qisolucoes.contactcloud.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/").authenticated() .antMatchers("/theme/**", "/plugins/**", "/page/**", "/", "/usuario/form", "/usuario/salvar").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginProcessingUrl("/login").loginPage("/login").permitAll().defaultSuccessUrl("/agenda/abrir", true) .and() .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/"); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { super.configure(auth); auth.userDetailsService(userDetailsService); } }
mit
andrehertwig/admintool
admin-tools-security/admin-tools-security-dbuser/src/main/java/de/chandre/admintool/security/dbuser/repo/RoleRepository.java
724
package de.chandre.admintool.security.dbuser.repo; import java.util.List; import java.util.Set; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import de.chandre.admintool.security.dbuser.domain.ATRole; /** * * @author André * @since 1.1.7 */ @Repository public interface RoleRepository extends JpaRepository<ATRole, String> { ATRole findByName(String name); @Query("SELECT r.name FROM ATRole r") List<String> findAllRoleNames(); List<ATRole> findByNameIn(Set<String> ids); List<ATRole> findByIdIn(Set<String> ids); void deleteByName(String name); }
mit
Mr-DLib/jabref
src/main/java/net/sf/jabref/gui/util/TaskExecutor.java
528
package net.sf.jabref.gui.util; import javafx.concurrent.Task; /** * An object that executes submitted {@link Task}s. This * interface provides a way of decoupling task submission from the * mechanics of how each task will be run, including details of thread * use, scheduling, thread pooling, etc. */ public interface TaskExecutor { /** * Runs the given task. * * @param task the task to run * @param <V> type of return value of the task */ <V> void execute(BackgroundTask<V> task); }
mit
mgireesh05/leetcode
first-bad-version/src/com/mgireesh/Solution.java
331
package com.mgireesh; public class Solution extends VersionControl { public int firstBadVersion(int n) { int badVersion = 0; int start = 1; int end = n; while (start < end) { int mid = start + (end - start) / 2; if (isBadVersion(mid)) { end = mid; } else { start = mid + 1; } } return start; } }
mit
lucko/LuckPerms
nukkit/src/main/java/me/lucko/luckperms/nukkit/inject/server/InjectorSubscriptionMap.java
4057
/* * This file is part of LuckPerms, licensed under the MIT License. * * Copyright (c) lucko (Luck) <luck@lucko.me> * Copyright (c) contributors * * 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 NONINFRINGEMENT. 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 me.lucko.luckperms.nukkit.inject.server; import me.lucko.luckperms.nukkit.LPNukkitPlugin; import cn.nukkit.Server; import cn.nukkit.permission.Permissible; import cn.nukkit.plugin.PluginManager; import java.lang.reflect.Field; import java.util.Map; import java.util.Objects; import java.util.Set; /** * Injects a {@link LuckPermsSubscriptionMap} into the {@link PluginManager}. */ public class InjectorSubscriptionMap implements Runnable { private static final Field PERM_SUBS_FIELD; static { Field permSubsField = null; try { permSubsField = PluginManager.class.getDeclaredField("permSubs"); permSubsField.setAccessible(true); } catch (Exception e) { // ignore } PERM_SUBS_FIELD = permSubsField; } private final LPNukkitPlugin plugin; public InjectorSubscriptionMap(LPNukkitPlugin plugin) { this.plugin = plugin; } @Override public void run() { try { LuckPermsSubscriptionMap subscriptionMap = inject(); if (subscriptionMap != null) { this.plugin.setSubscriptionMap(subscriptionMap); } } catch (Exception e) { this.plugin.getLogger().severe("Exception occurred whilst injecting LuckPerms Permission Subscription map.", e); } } private LuckPermsSubscriptionMap inject() throws Exception { Objects.requireNonNull(PERM_SUBS_FIELD, "PERM_SUBS_FIELD"); PluginManager pluginManager = this.plugin.getBootstrap().getServer().getPluginManager(); Object map = PERM_SUBS_FIELD.get(pluginManager); if (map instanceof LuckPermsSubscriptionMap) { if (((LuckPermsSubscriptionMap) map).plugin == this.plugin) { return null; } map = ((LuckPermsSubscriptionMap) map).detach(); } //noinspection unchecked Map<String, Set<Permissible>> castedMap = (Map<String, Set<Permissible>>) map; // make a new subscription map & inject it LuckPermsSubscriptionMap newMap = new LuckPermsSubscriptionMap(this.plugin, castedMap); PERM_SUBS_FIELD.set(pluginManager, newMap); return newMap; } public static void uninject() { try { Objects.requireNonNull(PERM_SUBS_FIELD, "PERM_SUBS_FIELD"); PluginManager pluginManager = Server.getInstance().getPluginManager(); Object map = PERM_SUBS_FIELD.get(pluginManager); if (map instanceof LuckPermsSubscriptionMap) { LuckPermsSubscriptionMap lpMap = (LuckPermsSubscriptionMap) map; PERM_SUBS_FIELD.set(pluginManager, lpMap.detach()); } } catch (Exception e) { e.printStackTrace(); } } }
mit
buckbaskin/RoboCodeGit
old_src/cwr/RobotBite.java
1934
package cwr; import java.util.ArrayList; public class RobotBite { //0 = time [state] //1 = x [state] //2 = y [state] //3 = energy [state] //4 = bearing radians [relative position] //5 = distance [relative position] //6 = heading radians [travel] //7 = velocity [travel] String name; long cTime; double cx; double cy; cwruBase origin; double cEnergy; double cBearing_radians; double cDistance; double cHeading_radians; double cVelocity; ArrayList<Projection> projec; //forward projections for x public RobotBite(String name, long time, cwruBase self, double energy, double bearing_radians, double distance, double heading_radians, double velocity) { this.name = name; cTime = time; origin = self; cEnergy = energy; cBearing_radians = bearing_radians; double myBearing = self.getHeadingRadians(); //System.out.println("I'm going "+self.getHeadingRadians()); double adjust_bearing = (bearing_radians+myBearing)%(2*Math.PI); //System.out.println("input bearing "+(bearing_radians)); //System.out.println("adjust bearing "+(adjust_bearing)); //System.out.println("math bearing"+(-adjust_bearing+Math.PI/2)); cDistance = distance; cHeading_radians = heading_radians; //System.out.println("location heading "+heading_radians); cVelocity = velocity; double myX = self.getX(); double myY = self.getY(); double math_bearing = (-adjust_bearing+Math.PI/2)%(2*Math.PI); //double math_heading = (-heading_radians+Math.PI/2)%(2*Math.PI); /* * 0 * 90 * -90 180 0 90 * -90 * 180 */ double dX = distance*Math.cos(math_bearing); //System.out.println("location dx:" + dX); double dY = distance*Math.sin(math_bearing); //System.out.println("location dy:" + dY); cx = myX+dX; cy = myY+dY; } public void attachProjection(ArrayList<Projection> projList) { projec = projList; } }
mit
fvasquezjatar/fermat-unused
DMP/plugin/basic_wallet/fermat-dmp-plugin-basic-wallet-bitcoin-wallet-bitdubai/src/test/java/unit/com/bitdubai/fermat_dmp_plugin/layer/basic_wallet/bitcoin_wallet/developer/bitdubai/version_1/structure/BitcoinWalletBasicWalletAvailableBalance/DebitTest.java
5573
package unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.BitcoinWalletBasicWalletAvailableBalance; import com.bitdubai.fermat_api.layer.dmp_basic_wallet.common.exceptions.CantRegisterDebitException; import com.bitdubai.fermat_api.layer.dmp_basic_wallet.bitcoin_wallet.interfaces.BitcoinWalletTransactionRecord; import com.bitdubai.fermat_api.layer.osa_android.database_system.Database; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTable; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableRecord; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTransaction; import com.bitdubai.fermat_api.layer.osa_android.database_system.PluginDatabaseSystem; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantLoadTableToMemoryException; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantOpenDatabaseException; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.DatabaseNotFoundException; import com.bitdubai.fermat_pip_api.layer.pip_platform_service.error_manager.ErrorManager; import com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.BitcoinWalletBasicWalletAvailableBalance; import com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.BitcoinWalletDatabaseConstants; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.ArrayList; import java.util.List; import unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.mocks.MockBitcoinWalletTransactionRecord; import unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.mocks.MockDatabaseTableRecord; import static com.googlecode.catchexception.CatchException.catchException; import static com.googlecode.catchexception.CatchException.caughtException; import static org.fest.assertions.api.Assertions.assertThat; import static org.fest.assertions.api.Assertions.fail; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.when; /** * Created by jorgegonzalez on 2015.07.14.. */ @RunWith(MockitoJUnitRunner.class) public class DebitTest { @Mock private ErrorManager mockErrorManager; @Mock private PluginDatabaseSystem mockPluginDatabaseSystem; @Mock private Database mockDatabase; @Mock private DatabaseTable mockWalletTable; @Mock private DatabaseTable mockBalanceTable; @Mock private DatabaseTransaction mockTransaction; private List<DatabaseTableRecord> mockRecords; private DatabaseTableRecord mockBalanceRecord; private DatabaseTableRecord mockWalletRecord; private BitcoinWalletTransactionRecord mockTransactionRecord; private BitcoinWalletBasicWalletAvailableBalance testBalance; @Before public void setUpMocks(){ mockTransactionRecord = new MockBitcoinWalletTransactionRecord(); mockBalanceRecord = new MockDatabaseTableRecord(); mockWalletRecord = new MockDatabaseTableRecord(); mockRecords = new ArrayList<>(); mockRecords.add(mockBalanceRecord); setUpMockitoRules(); } public void setUpMockitoRules(){ when(mockDatabase.getTable(BitcoinWalletDatabaseConstants.BITCOIN_WALLET_TABLE_NAME)).thenReturn(mockWalletTable); when(mockDatabase.getTable(BitcoinWalletDatabaseConstants.BITCOIN_WALLET_BALANCE_TABLE_NAME)).thenReturn(mockBalanceTable); when(mockBalanceTable.getRecords()).thenReturn(mockRecords); when(mockWalletTable.getEmptyRecord()).thenReturn(mockWalletRecord); when(mockDatabase.newTransaction()).thenReturn(mockTransaction); } @Before public void setUpAvailableBalance(){ testBalance = new BitcoinWalletBasicWalletAvailableBalance(mockDatabase); } @Test public void Debit_SuccesfullyInvoked_ReturnsAvailableBalance() throws Exception{ catchException(testBalance).debit(mockTransactionRecord); assertThat(caughtException()).isNull(); } @Test public void Debit_OpenDatabaseCantOpenDatabase_ReturnsAvailableBalance() throws Exception{ doThrow(new CantOpenDatabaseException("MOCK", null, null, null)).when(mockDatabase).openDatabase(); catchException(testBalance).debit(mockTransactionRecord); assertThat(caughtException()) .isNotNull() .isInstanceOf(CantRegisterDebitException.class); } @Test public void Debit_OpenDatabaseDatabaseNotFound_Throws() throws Exception{ doThrow(new DatabaseNotFoundException("MOCK", null, null, null)).when(mockDatabase).openDatabase(); catchException(testBalance).debit(mockTransactionRecord); assertThat(caughtException()) .isNotNull() .isInstanceOf(CantRegisterDebitException.class); } @Test public void Debit_DaoCantCalculateBalanceException_ReturnsAvailableBalance() throws Exception{ doThrow(new CantLoadTableToMemoryException("MOCK", null, null, null)).when(mockWalletTable).loadToMemory(); catchException(testBalance).debit(mockTransactionRecord); assertThat(caughtException()) .isNotNull() .isInstanceOf(CantRegisterDebitException.class); } }
mit
Arctos6135/frc-2017
src/org/usfirst/frc/team6135/robot/subsystems/Drive.java
4676
package org.usfirst.frc.team6135.robot.subsystems; import java.awt.geom.Arc2D.Double; import org.usfirst.frc.team6135.robot.RobotMap; import org.usfirst.frc.team6135.robot.commands.teleopDrive; import com.kauailabs.navx.frc.AHRS; import edu.wpi.first.wpilibj.ADXRS450_Gyro; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.SerialPort; import edu.wpi.first.wpilibj.VictorSP; import edu.wpi.first.wpilibj.command.Subsystem; public class Drive extends Subsystem { //Constants private static final boolean rReverse = true; private static final boolean lReverse = false; private static final double kA=0.03; //Objects private VictorSP leftDrive = null; private VictorSP rightDrive = null; public ADXRS450_Gyro gyro=null; public AHRS ahrs=null; public RobotDrive robotDrive=null; //Constructors public Drive() { gyro=RobotMap.gyro; ahrs=new AHRS(SerialPort.Port.kUSB1); robotDrive=new RobotDrive(RobotMap.leftDriveVictor,RobotMap.rightDriveVictor); leftDrive = RobotMap.leftDriveVictor; rightDrive = RobotMap.rightDriveVictor; leftDrive.set(0); rightDrive.set(0); leftDrive.setInverted(lReverse); rightDrive.setInverted(rReverse); ahrs.reset(); } //Direct object access methods public void setMotors(double l, double r) {//sets motor speeds accounting for directions of motors leftDrive.set(l); rightDrive.set(r); } public void setLeft(double d) { leftDrive.set(d); } public void setRight(double d) { rightDrive.set(d); } //Teleop Driving methods private static final double accBoundX = 0.7; //The speed after which the drive starts to accelerate over time private static final int accLoopX = 15; //The number of loops for the bot to accelerate to max speed private int accLoopCountX = 0; public double accCalcX(double input) {//applies a delay for motors to reach full speed for larger joystick inputs if(input > accBoundX && accLoopCountX < accLoopX) {//positive inputs return accBoundX + (input - accBoundX) * (accLoopCountX++ / (double) accLoopX); } else if(input < -accBoundX && accLoopCountX < accLoopX) {//negative inputs return -accBoundX + (input + accBoundX) * (accLoopCountX++ / (double) accLoopX); } else if(Math.abs(input) <= accBoundX) { accLoopCountX = 0; } return input; } private static final double accBoundY = 0.7; //The speed after which the drive starts to accelerate over time private static final int accLoopY = 15; //The number of loops for the bot to accelerate to max speed private int accLoopCountY = 0; public double accCalcY(double input) {//applies a delay for motors to reach full speed for larger joystick inputs if(input > accBoundY && accLoopCountY < accLoopY) {//positive inputs return accBoundY + (input - accBoundY) * (accLoopCountY++ / (double) accLoopY); } else if(input < -accBoundY && accLoopCountY < accLoopY) {//negative inputs return -accBoundY + (input + accBoundY) * (accLoopCountY++ / (double) accLoopY); } else if(Math.abs(input) <= accBoundY) { accLoopCountY = 0; } return input; } private static final double accBoundZ = 0.7; //The speed after which the drive starts to accelerate over time private static final int accLoopZ = 15; //The number of loops for the bot to accelerate to max speed private int accLoopCountZ = 0; public double accCalcZ(double input) {//applies a delay for motors to reach full speed for larger joystick inputs if(input > accBoundZ && accLoopCountZ < accLoopZ) {//positive inputs return accBoundZ + (input - accBoundZ) * (accLoopCountZ++ / (double) accLoopZ); } else if(input < -accBoundZ && accLoopCountZ < accLoopZ) {//negative inputs return -accBoundZ + (input + accBoundZ) * (accLoopCountZ++ / (double) accLoopZ); } else if(Math.abs(input) <= accBoundZ) { accLoopCountZ = 0; } return input; } public double sensitivityCalc(double input) {//Squares magnitude of input to reduce magnitude of smaller joystick inputs if (input >= 0.0) { return (input * input); } else { return -(input * input); } } public void reverse() { leftDrive.setInverted(!leftDrive.getInverted()); rightDrive.setInverted(!rightDrive.getInverted()); VictorSP temp1 = leftDrive; VictorSP temp2 = rightDrive; rightDrive = temp1; leftDrive = temp2; } public double getGyroAngle() { return gyro.getAngle(); } public double getNAVXAngle() { return ahrs.getAngle(); } public void driveStraight() { robotDrive.drive(0.6, -gyro.getAngle()*kA); } @Override protected void initDefaultCommand() { setDefaultCommand(new teleopDrive()); } }
mit
Azure/azure-sdk-for-java
sdk/vmwarecloudsimple/azure-resourcemanager-vmwarecloudsimple/src/main/java/com/azure/resourcemanager/vmwarecloudsimple/models/CustomizationPolicy.java
2001
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.vmwarecloudsimple.models; import com.azure.resourcemanager.vmwarecloudsimple.fluent.models.CustomizationPolicyInner; /** An immutable client-side representation of CustomizationPolicy. */ public interface CustomizationPolicy { /** * Gets the id property: Customization policy azure id. * * @return the id value. */ String id(); /** * Gets the location property: Azure region. * * @return the location value. */ String location(); /** * Gets the name property: Customization policy name. * * @return the name value. */ String name(); /** * Gets the type property: The type property. * * @return the type value. */ String type(); /** * Gets the description property: Policy description. * * @return the description value. */ String description(); /** * Gets the privateCloudId property: The Private cloud id. * * @return the privateCloudId value. */ String privateCloudId(); /** * Gets the specification property: Detailed customization policy specification. * * @return the specification value. */ CustomizationSpecification specification(); /** * Gets the typePropertiesType property: The type of customization (Linux or Windows). * * @return the typePropertiesType value. */ CustomizationPolicyPropertiesType typePropertiesType(); /** * Gets the version property: Policy version. * * @return the version value. */ String version(); /** * Gets the inner com.azure.resourcemanager.vmwarecloudsimple.fluent.models.CustomizationPolicyInner object. * * @return the inner object. */ CustomizationPolicyInner innerModel(); }
mit
reasm/reasm-m68k
src/main/java/org/reasm/m68k/assembly/internal/WhileDirective.java
1747
package org.reasm.m68k.assembly.internal; import javax.annotation.Nonnull; import javax.annotation.concurrent.Immutable; import org.reasm.Value; import org.reasm.ValueToBooleanVisitor; /** * The <code>WHILE</code> directive. * * @author Francis Gagné */ @Immutable class WhileDirective extends Mnemonic { @Nonnull static final WhileDirective WHILE = new WhileDirective(); private WhileDirective() { } @Override void assemble(M68KAssemblyContext context) { context.sizeNotAllowed(); final Object blockState = context.getParentBlock(); if (!(blockState instanceof WhileBlockState)) { throw new AssertionError(); } final WhileBlockState whileBlockState = (WhileBlockState) blockState; // The WHILE directive is assembled on every iteration. // Parse the condition operand on the first iteration only. if (!whileBlockState.parsedCondition) { if (context.requireNumberOfOperands(1)) { whileBlockState.conditionExpression = parseExpressionOperand(context, 0); } whileBlockState.parsedCondition = true; } final Value condition; if (whileBlockState.conditionExpression != null) { condition = whileBlockState.conditionExpression.evaluate(context.getEvaluationContext()); } else { condition = null; } final Boolean result = Value.accept(condition, ValueToBooleanVisitor.INSTANCE); if (!(result != null && result.booleanValue())) { // Skip the block body and stop the iteration. whileBlockState.iterator.next(); whileBlockState.hasNextIteration = false; } } }
mit
games647/FlexibleLogin
src/main/java/com/github/games647/flexiblelogin/listener/prevent/PreventListener.java
8213
/* * This file is part of FlexibleLogin * * The MIT License (MIT) * * Copyright (c) 2015-2018 contributors * * 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 NONINFRINGEMENT. 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 com.github.games647.flexiblelogin.listener.prevent; import com.flowpowered.math.vector.Vector3i; import com.github.games647.flexiblelogin.FlexibleLogin; import com.github.games647.flexiblelogin.PomData; import com.github.games647.flexiblelogin.config.Settings; import com.google.inject.Inject; import java.util.List; import java.util.Optional; import org.spongepowered.api.command.CommandManager; import org.spongepowered.api.command.CommandMapping; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.Order; import org.spongepowered.api.event.block.InteractBlockEvent; import org.spongepowered.api.event.command.SendCommandEvent; import org.spongepowered.api.event.entity.DamageEntityEvent; import org.spongepowered.api.event.entity.InteractEntityEvent; import org.spongepowered.api.event.entity.MoveEntityEvent; import org.spongepowered.api.event.filter.Getter; import org.spongepowered.api.event.filter.cause.First; import org.spongepowered.api.event.filter.cause.Root; import org.spongepowered.api.event.filter.type.Exclude; import org.spongepowered.api.event.item.inventory.ChangeInventoryEvent; import org.spongepowered.api.event.item.inventory.ClickInventoryEvent; import org.spongepowered.api.event.item.inventory.ClickInventoryEvent.NumberPress; import org.spongepowered.api.event.item.inventory.DropItemEvent; import org.spongepowered.api.event.item.inventory.InteractInventoryEvent; import org.spongepowered.api.event.item.inventory.InteractItemEvent; import org.spongepowered.api.event.item.inventory.UseItemStackEvent; import org.spongepowered.api.event.message.MessageChannelEvent; public class PreventListener extends AbstractPreventListener { private final CommandManager commandManager; @Inject PreventListener(FlexibleLogin plugin, Settings settings, CommandManager commandManager) { super(plugin, settings); this.commandManager = commandManager; } @Listener(order = Order.FIRST, beforeModifications = true) public void onPlayerMove(MoveEntityEvent playerMoveEvent, @First Player player) { if (playerMoveEvent instanceof MoveEntityEvent.Teleport) { return; } Vector3i oldLocation = playerMoveEvent.getFromTransform().getPosition().toInt(); Vector3i newLocation = playerMoveEvent.getToTransform().getPosition().toInt(); if (oldLocation.getX() != newLocation.getX() || oldLocation.getZ() != newLocation.getZ()) { checkLoginStatus(playerMoveEvent, player); } } @Listener(order = Order.FIRST, beforeModifications = true) public void onChat(MessageChannelEvent.Chat chatEvent, @First Player player) { checkLoginStatus(chatEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onCommand(SendCommandEvent commandEvent, @First Player player) { String command = commandEvent.getCommand(); Optional<? extends CommandMapping> commandOpt = commandManager.get(command); if (commandOpt.isPresent()) { CommandMapping mapping = commandOpt.get(); command = mapping.getPrimaryAlias(); //do not blacklist our own commands if (commandManager.getOwner(mapping) .map(pc -> pc.getId().equals(PomData.ARTIFACT_ID)) .orElse(false)) { return; } } commandEvent.setResult(CommandResult.empty()); if (settings.getGeneral().isCommandOnlyProtection()) { List<String> protectedCommands = settings.getGeneral().getProtectedCommands(); if (protectedCommands.contains(command) && !plugin.getDatabase().isLoggedIn(player)) { player.sendMessage(settings.getText().getProtectedCommand()); commandEvent.setCancelled(true); } } else { checkLoginStatus(commandEvent, player); } } @Listener(order = Order.FIRST, beforeModifications = true) public void onPlayerItemDrop(DropItemEvent dropItemEvent, @First Player player) { checkLoginStatus(dropItemEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onPlayerItemPickup(ChangeInventoryEvent.Pickup pickupItemEvent, @Root Player player) { checkLoginStatus(pickupItemEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onItemConsume(UseItemStackEvent.Start itemConsumeEvent, @First Player player) { checkLoginStatus(itemConsumeEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onItemInteract(InteractItemEvent interactItemEvent, @First Player player) { checkLoginStatus(interactItemEvent, player); } // Ignore number press events, because Sponge before this commit // https://github.com/SpongePowered/SpongeForge/commit/f0605fb0bd62ca2f958425378776608c41f16cca // has a duplicate bug. Using this exclude we can ignore it, but still cancel the movement of the item // it appears to be fixed using SpongeForge 4005 (fixed) and 4004 with this change @Exclude(NumberPress.class) @Listener(order = Order.FIRST, beforeModifications = true) public void onInventoryChange(ChangeInventoryEvent changeInventoryEvent, @First Player player) { checkLoginStatus(changeInventoryEvent, player); } @Exclude(NumberPress.class) @Listener(order = Order.FIRST, beforeModifications = true) public void onInventoryInteract(InteractInventoryEvent interactInventoryEvent, @First Player player) { checkLoginStatus(interactInventoryEvent, player); } @Exclude(NumberPress.class) @Listener(order = Order.FIRST, beforeModifications = true) public void onInventoryClick(ClickInventoryEvent clickInventoryEvent, @First Player player) { checkLoginStatus(clickInventoryEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onBlockInteract(InteractBlockEvent interactBlockEvent, @First Player player) { checkLoginStatus(interactBlockEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onPlayerInteractEntity(InteractEntityEvent interactEntityEvent, @First Player player) { checkLoginStatus(interactEntityEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onPlayerDamage(DamageEntityEvent damageEntityEvent, @First Player player) { //player is damage source checkLoginStatus(damageEntityEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onDamagePlayer(DamageEntityEvent damageEntityEvent, @Getter("getTargetEntity") Player player) { //player is damage target checkLoginStatus(damageEntityEvent, player); } }
mit
contexthub/storage-android
StorageApp/app/src/main/java/com/contexthub/storageapp/MainActivity.java
4259
package com.contexthub.storageapp; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.SearchView; import android.view.Menu; import android.view.MenuItem; import com.chaione.contexthub.sdk.model.VaultDocument; import com.contexthub.storageapp.fragments.AboutFragment; import com.contexthub.storageapp.fragments.EditVaultItemFragment; import com.contexthub.storageapp.fragments.VaultItemListFragment; import com.contexthub.storageapp.models.Person; public class MainActivity extends ActionBarActivity implements VaultItemListFragment.Listener, FragmentManager.OnBackStackChangedListener { private MenuItem menuSearch; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if(savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .replace(android.R.id.content, new VaultItemListFragment()) .commit(); getSupportFragmentManager().addOnBackStackChangedListener(this); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); setupSearchView(menu.findItem(R.id.action_search)); return true; } private void setupSearchView(final MenuItem menuSearch) { this.menuSearch = menuSearch; SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuSearch); SearchView.SearchAutoComplete searchAutoComplete = (SearchView.SearchAutoComplete) searchView.findViewById(R.id.search_src_text); searchAutoComplete.setHint(R.string.search_hint); searchView.setOnQueryTextListener(new android.support.v7.widget.SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { menuSearch.collapseActionView(); getSupportFragmentManager().beginTransaction() .addToBackStack(null) .replace(android.R.id.content, VaultItemListFragment.newInstance(query)) .commit(); return true; } @Override public boolean onQueryTextChange(String query) { return false; } }); } @Override public boolean onPrepareOptionsMenu(Menu menu) { boolean isMainFragment = getSupportFragmentManager().getBackStackEntryCount() <= 0; menu.findItem(R.id.action_search).setVisible(isMainFragment); menu.findItem(R.id.action_add).setVisible(isMainFragment); menu.findItem(R.id.action_about).setVisible(isMainFragment); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { menuSearch.collapseActionView(); switch(item.getItemId()) { case R.id.action_add: launchEditVaultItemFragment(null); return true; case R.id.action_about: getSupportFragmentManager().beginTransaction() .addToBackStack(null) .replace(android.R.id.content, new AboutFragment()) .commit(); return true; default: return super.onOptionsItemSelected(item); } } private void launchEditVaultItemFragment(VaultDocument<Person> document) { EditVaultItemFragment fragment = document == null ? new EditVaultItemFragment() : EditVaultItemFragment.newInstance(document); getSupportFragmentManager().beginTransaction() .addToBackStack(null) .replace(android.R.id.content, fragment) .commit(); } @Override public void onItemClick(VaultDocument<Person> document) { menuSearch.collapseActionView(); launchEditVaultItemFragment(document); } @Override public void onBackStackChanged() { supportInvalidateOptionsMenu(); } }
mit
jarney/snackbot
src/main/java/org/ensor/robots/roboclawdriver/CommandReadMainBatteryVoltage.java
1602
/* * The MIT License * * Copyright 2014 Jon Arney, Ensor Robotics. * * 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 NONINFRINGEMENT. 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.ensor.robots.roboclawdriver; /** * * @author jona */ class CommandReadMainBatteryVoltage extends CommandReadBatteryVoltage { protected CommandReadMainBatteryVoltage(RoboClaw aRoboClaw) { super(aRoboClaw); } @Override protected byte getCommandByte() { return (byte)24; } @Override protected void onResponse(double voltage) { mRoboClaw.setMainBatteryVoltage(voltage); } }
mit
kalnee/trivor
insights/src/main/java/org/kalnee/trivor/insights/web/rest/InsightsResource.java
4162
package org.kalnee.trivor.insights.web.rest; import com.codahale.metrics.annotation.Timed; import org.kalnee.trivor.insights.domain.insights.Insights; import org.kalnee.trivor.insights.service.InsightService; import org.kalnee.trivor.nlp.domain.ChunkFrequency; import org.kalnee.trivor.nlp.domain.PhrasalVerbUsage; import org.kalnee.trivor.nlp.domain.SentenceFrequency; import org.kalnee.trivor.nlp.domain.WordUsage; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map; import java.util.Set; @RestController @RequestMapping(value = "/api/insights") public class InsightsResource { private final InsightService insightService; public InsightsResource(InsightService insightService) { this.insightService = insightService; } @GetMapping public ResponseEntity<Page<Insights>> findByInsightAndImdb(@RequestParam("imdbId") String imdbId, Pageable pageable) { return ResponseEntity.ok().body(insightService.findByImdbId(imdbId, pageable)); } @GetMapping("/summary") @Timed public ResponseEntity<Map<String, Object>> getInsightsSummary(@RequestParam("imdbId") String imdbId) { return ResponseEntity.ok().body(insightService.getInsightsSummary(imdbId)); } @GetMapping("/sentences/frequency") @Timed public ResponseEntity<List<SentenceFrequency>> findSentencesFrequency(@RequestParam("imdbId") String imdbId, @RequestParam(value = "limit", required = false) Integer limit) { return ResponseEntity.ok().body( insightService.findSentencesFrequencyByImdbId(imdbId, limit) ); } @GetMapping("/chunks/frequency") @Timed public ResponseEntity<List<ChunkFrequency>> findChunksFrequency(@RequestParam("imdbId") String imdbId, @RequestParam(value = "limit", required = false) Integer limit) { return ResponseEntity.ok().body( insightService.findChunksFrequencyByImdbId(imdbId, limit) ); } @GetMapping("/phrasal-verbs/usage") @Timed public ResponseEntity<List<PhrasalVerbUsage>> findPhrasalVerbsUsageByImdbId(@RequestParam("imdbId") String imdbId) { return ResponseEntity.ok().body(insightService.findPhrasalVerbsUsageByImdbId(imdbId)); } @GetMapping("/vocabulary/{vocabulary}/frequency") @Timed public ResponseEntity<Map<String, Integer>> findVocabularyFrequencyByImdbId( @PathVariable("vocabulary") String vocabulary, @RequestParam("imdbId") String imdbId, @RequestParam(value = "limit", required = false) Integer limit) { return ResponseEntity.ok().body(insightService.findVocabularyFrequencyByImdbId(vocabulary, imdbId, limit)); } @GetMapping("/vocabulary/{vocabulary}/usage") @Timed public ResponseEntity<List<WordUsage>> findVocabularyUsageByImdbAndSeasonAndEpisode( @PathVariable("vocabulary") String vocabulary, @RequestParam("imdbId") String imdbId, @RequestParam(value = "season", required = false) Integer season, @RequestParam(value = "episode", required = false) Integer episode) { return ResponseEntity.ok().body( insightService.findVocabularyUsageByImdbAndSeasonAndEpisode(vocabulary, imdbId, season, episode) ); } @GetMapping("/{insight}/genres/{genre}") @Timed public ResponseEntity<List<Insights>> findInsightsByGenre( @PathVariable("genre") String genre) { return ResponseEntity.ok().body(insightService.findInsightsByInsightAndGenre(genre)); } @GetMapping("/{insight}/keywords/{keyword}") @Timed public ResponseEntity<List<Insights>> findInsightsByKeyword( @PathVariable("keyword") String keyword) { return ResponseEntity.ok().body(insightService.findInsightsByInsightAndKeyword(keyword)); } }
mit
manniwood/cl4pg
src/main/java/com/manniwood/cl4pg/v1/exceptions/Cl4pgConfFileException.java
1781
/* The MIT License (MIT) Copyright (c) 2014 Manni Wood 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 NONINFRINGEMENT. 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 com.manniwood.cl4pg.v1.exceptions; public class Cl4pgConfFileException extends Cl4pgException { private static final long serialVersionUID = 1L; public Cl4pgConfFileException() { super(); } public Cl4pgConfFileException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public Cl4pgConfFileException(String message, Throwable cause) { super(message, cause); } public Cl4pgConfFileException(String message) { super(message); } public Cl4pgConfFileException(Throwable cause) { super(cause); } }
mit
Cosium/spring-data-jpa-entity-graph
core/src/main/java/com/cosium/spring/data/jpa/entity/graph/repository/support/EntityGraphBean.java
2555
package com.cosium.spring.data.jpa.entity.graph.repository.support; import com.google.common.base.MoreObjects; import org.springframework.core.ResolvableType; import org.springframework.data.jpa.repository.query.JpaEntityGraph; import static java.util.Objects.requireNonNull; /** * Wrapper class allowing to hold a {@link JpaEntityGraph} with its associated domain class. Created * on 23/11/16. * * @author Reda.Housni-Alaoui */ class EntityGraphBean { private final JpaEntityGraph jpaEntityGraph; private final Class<?> domainClass; private final ResolvableType repositoryMethodReturnType; private final boolean optional; private final boolean primary; private final boolean valid; public EntityGraphBean( JpaEntityGraph jpaEntityGraph, Class<?> domainClass, ResolvableType repositoryMethodReturnType, boolean optional, boolean primary) { this.jpaEntityGraph = requireNonNull(jpaEntityGraph); this.domainClass = requireNonNull(domainClass); this.repositoryMethodReturnType = requireNonNull(repositoryMethodReturnType); this.optional = optional; this.primary = primary; this.valid = computeValidity(); } private boolean computeValidity() { Class<?> resolvedReturnType = repositoryMethodReturnType.resolve(); if (Void.TYPE.equals(resolvedReturnType) || domainClass.isAssignableFrom(resolvedReturnType)) { return true; } for (Class genericType : repositoryMethodReturnType.resolveGenerics()) { if (domainClass.isAssignableFrom(genericType)) { return true; } } return false; } /** @return The jpa entity graph */ public JpaEntityGraph getJpaEntityGraph() { return jpaEntityGraph; } /** @return The jpa entity class */ public Class<?> getDomainClass() { return domainClass; } /** @return True if this entity graph is not mandatory */ public boolean isOptional() { return optional; } /** @return True if this EntityGraph seems valid */ public boolean isValid() { return valid; } /** * @return True if this EntityGraph is a primary one. Default EntityGraph is an example of non * primary EntityGraph. */ public boolean isPrimary() { return primary; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("jpaEntityGraph", jpaEntityGraph) .add("domainClass", domainClass) .add("repositoryMethodReturnType", repositoryMethodReturnType) .add("optional", optional) .toString(); } }
mit
bigfatnoob/Decaf
src/stage2/DecafError.java
471
package stage2; public class DecafError { int numErrors; DecafError(){ } public static String errorPos(Position p){ return "(L: " + p.startLine + ", Col: " + p.startCol + ") -- (L: " + p.endLine + ", Col: " + p.endCol + ")"; } public void error(String s, Position p) { System.out.println("Error found at location "+ errorPos(p) + ":\n"+s); } public boolean haveErrors() { return (numErrors>0); } }
mit
dayse/gesplan
test/cargaDoSistema/CargaUsuario.java
4187
/* * * Copyright (c) 2013 - 2014 INT - National Institute of Technology & COPPE - Alberto Luiz Coimbra Institute - Graduate School and Research in Engineering. * See the file license.txt for copyright permission. * */ package cargaDoSistema; import modelo.TipoUsuario; import modelo.Usuario; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import service.TipoUsuarioAppService; import service.UsuarioAppService; import service.controleTransacao.FabricaDeAppService; import service.exception.AplicacaoException; import util.JPAUtil; /** * Classe responsável pela inclusão de Tipos de Usuário e de Usuário. * É usada na carga do sistema e deve ser a primeira a ser executada. * Está criando um usuário para cada tipo. (dma) * * @author marques * */ public class CargaUsuario { // Services public TipoUsuarioAppService tipoUsuarioService; public UsuarioAppService usuarioService; @BeforeClass public void setupClass(){ try { tipoUsuarioService = FabricaDeAppService.getAppService(TipoUsuarioAppService.class); usuarioService = FabricaDeAppService.getAppService(UsuarioAppService.class); } catch (Exception e) { e.printStackTrace(); } } @Test public void incluirTiposDeUsuario() { TipoUsuario tipoUsuarioAdmin = new TipoUsuario(); TipoUsuario tipoUsuarioAluno = new TipoUsuario(); TipoUsuario tipoUsuarioGestor = new TipoUsuario(); TipoUsuario tipoUsuarioEngenheiro = new TipoUsuario(); tipoUsuarioAdmin.setTipoUsuario(TipoUsuario.ADMINISTRADOR); tipoUsuarioAdmin.setDescricao("O usuário ADMINISTRADOR pode realizar qualquer operação no Sistema."); tipoUsuarioAluno.setTipoUsuario(TipoUsuario.ALUNO); tipoUsuarioAluno.setDescricao("O usuário ALUNO pode realizar apenas consultas e impressão de relatórios nas telas " + "relativas ao Horizonte de Planejamento (HP,Periodo PMP, Periodo PAP) e não acessa " + "Administração e Eng. Conhecimento"); tipoUsuarioGestor.setTipoUsuario(TipoUsuario.GESTOR); tipoUsuarioGestor.setDescricao("O usuário GESTOR pode realizar qualquer operação no Sistema, porém não possui acesso" + "as áreas de Administração e Engenharia de Conhecimento."); tipoUsuarioEngenheiro.setTipoUsuario(TipoUsuario.ENGENHEIRO_DE_CONHECIMENTO); tipoUsuarioEngenheiro.setDescricao("O usuário ENGENHEIRO pode realizar a parte de Logica Fuzzy (Engenharia de Conhecimento)" + "no Sistema. Porém, não possui acesso a área Administrativa."); tipoUsuarioService.inclui(tipoUsuarioAdmin); tipoUsuarioService.inclui(tipoUsuarioAluno); tipoUsuarioService.inclui(tipoUsuarioGestor); tipoUsuarioService.inclui(tipoUsuarioEngenheiro); Usuario usuarioAdmin = new Usuario(); Usuario usuarioAluno = new Usuario(); Usuario usuarioGestor = new Usuario(); Usuario usuarioEngenheiro = new Usuario(); usuarioAdmin.setNome("Administrador"); usuarioAdmin.setLogin("dgep"); usuarioAdmin.setSenha("admgesplan2@@8"); usuarioAdmin.setTipoUsuario(tipoUsuarioAdmin); usuarioAluno.setNome("Alberto da Silva"); usuarioAluno.setLogin("alberto"); usuarioAluno.setSenha("alberto"); usuarioAluno.setTipoUsuario(tipoUsuarioAluno); usuarioEngenheiro.setNome("Bernadete da Silva"); usuarioEngenheiro.setLogin("bernadete"); usuarioEngenheiro.setSenha("bernadete"); usuarioEngenheiro.setTipoUsuario(tipoUsuarioEngenheiro); usuarioGestor.setNome("Carlos da Silva"); usuarioGestor.setLogin("carlos"); usuarioGestor.setSenha("carlos"); usuarioGestor.setTipoUsuario(tipoUsuarioGestor); try { usuarioService.inclui(usuarioAdmin, usuarioAdmin.getSenha()); usuarioService.inclui(usuarioEngenheiro, usuarioEngenheiro.getSenha()); usuarioService.inclui(usuarioGestor, usuarioGestor.getSenha()); usuarioService.inclui(usuarioAluno, usuarioAluno.getSenha()); } catch (AplicacaoException e) { //e.printStackTrace(); System.out.println("Erro na inclusao do usuario: "+ e.getMessage()); } } }
mit
ov3rk1ll/KinoCast
app/src/main/java/com/ov3rk1ll/kinocast/ui/util/glide/ViewModelGlideRequest.java
609
package com.ov3rk1ll.kinocast.ui.util.glide; import com.ov3rk1ll.kinocast.data.ViewModel; public class ViewModelGlideRequest { private ViewModel viewModel; private int screenWidthPx; private String type; public ViewModelGlideRequest(ViewModel viewModel, int screenWidthPx, String type) { this.viewModel = viewModel; this.screenWidthPx = screenWidthPx; this.type = type; } ViewModel getViewModel() { return viewModel; } int getScreenWidthPx() { return screenWidthPx; } public String getType() { return type; } }
mit
kanonirov/lanb-client
src/main/java/ru/lanbilling/webservice/wsdl/GetClientDocumentsResponse.java
2281
package ru.lanbilling.webservice.wsdl; import java.util.ArrayList; import java.util.List; import javax.annotation.Generated; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="ret" type="{urn:api3}soapDocument" maxOccurs="unbounded"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "ret" }) @XmlRootElement(name = "getClientDocumentsResponse") @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") public class GetClientDocumentsResponse { @XmlElement(required = true) @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") protected List<SoapDocument> ret; /** * Gets the value of the ret property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the ret property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRet().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link SoapDocument } * * */ @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") public List<SoapDocument> getRet() { if (ret == null) { ret = new ArrayList<SoapDocument>(); } return this.ret; } }
mit
mvasilchuk/webproxy
src/main/java/com/mvas/webproxy/portals/StalkerRequestHandler.java
9322
package com.mvas.webproxy.portals; import com.mvas.webproxy.DeviceConnectionInfo; import com.mvas.webproxy.RequestData; import com.mvas.webproxy.WebServer; import com.mvas.webproxy.config.PortalConfiguration; import org.apache.commons.io.IOUtils; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StalkerRequestHandler implements AbstractRequestHandler { private static final Logger logger = LoggerFactory.getLogger(StalkerRequestHandler.class); public static final String GET_PARAM_DEVICE_ID = "device_id"; public static final String GET_PARAM_DEVICE_ID2 = "device_id2"; public static final String GET_PARAM_SIGNATURE = "signature"; public static final String GET_PARAM_SESSION = "session"; public static final String CONFIG_PORTAL_URL = "portal"; public static final String GET_PARAM_MAC_ADDRESS = "mac"; public static final String ACTION_HANDSHAKE = "action=handshake"; Pattern cookiePattern = Pattern.compile(".*mac=(([0-9A-F]{2}[:-]){5}([0-9A-F]{2})).*"); Pattern handshakePattern = Pattern.compile(ACTION_HANDSHAKE); public static final String HEADER_AUTHORIZATION = "Authorization"; public static final class HeadersList { public HashMap<String, String> getList() { return list; } private HashMap<String, String> list = new HashMap<>(); } public static final class ParamsList { public HashMap<String, String> getList() { return list; } private HashMap<String, String> list = new HashMap<>(); } public HashMap<String, HeadersList> staticHeadersForMac = new HashMap<>(); public HashMap<String, ParamsList> staticParamsForMac = new HashMap<>(); DeviceConnectionInfo deviceConnectionInfo; static HashMap<String, Pattern> replacements = new HashMap<>(); static String[] configOptions; static String[] getParamNames; static { getParamNames = new String[] { GET_PARAM_DEVICE_ID, GET_PARAM_DEVICE_ID2, GET_PARAM_SIGNATURE, GET_PARAM_SESSION }; for (String name : getParamNames) { replacements.put(name, Pattern.compile("([\\?&])?(" + name + ")=([a-zA-Z0-9/+]*)")); } configOptions = new String[] { GET_PARAM_DEVICE_ID, GET_PARAM_DEVICE_ID2, GET_PARAM_SIGNATURE, GET_PARAM_SESSION, CONFIG_PORTAL_URL, GET_PARAM_MAC_ADDRESS }; } private HeadersList getHeadersForRequest(final RequestData requestData) { return staticHeadersForMac.get(requestData.getMacAddress()); } private ParamsList getParamsForRequest(final RequestData requestData) { return staticParamsForMac.get(requestData.getMacAddress()); } public StalkerRequestHandler(DeviceConnectionInfo deviceConnectionInfo) { this.deviceConnectionInfo = deviceConnectionInfo; } @Override public String getURL(final RequestData requestData) { logger.debug("StalkerRequestHandler::getURL()"); String result = requestData.getRealUrl().toString(); HashMap<String, String> staticParams = getParamsForRequest(requestData).getList(); for(Map.Entry<String, Pattern> entry: replacements.entrySet()) { Matcher matcher = entry.getValue().matcher(result); if(matcher.find()) { String name = matcher.group(2); if(staticParams.get(name) == null) { String value = matcher.group(3); staticParams.put(name, value); logger.debug("set static param [" + name + "] to [" + value + "]"); if(name.equals(GET_PARAM_DEVICE_ID)) WebServer.getPortalConfiguration().set(requestData.getConnectionName(), name, value); if(name.equals(GET_PARAM_DEVICE_ID2)) WebServer.getPortalConfiguration().set(requestData.getConnectionName(), name, value); } } } for(Map.Entry<String, Pattern> rep: replacements.entrySet()) { Pattern from = rep.getValue(); String to = rep.getKey(); result = result.replaceAll(from.pattern(), "$1$2=" + staticParams.get(to)); } logger.debug("New query string: " + result); return result; } @Override public void onRequest(final RequestData requestData, final URLConnection urlConnection) { logger.debug("StalkerRequestHandler::onRequest()"); HashMap<String, String> staticHeaders = getHeadersForRequest(requestData).getList(); for(Map.Entry<String, String> header: requestData.getHeaders().entrySet()) { String headerName = header.getKey(); String headerValue = header.getValue(); if(headerName.equals(HEADER_AUTHORIZATION)) { if(staticHeaders.get(HEADER_AUTHORIZATION) == null) staticHeaders.put(HEADER_AUTHORIZATION, headerValue); else { String authorizationHeader = staticHeaders.get(HEADER_AUTHORIZATION); if(headerValue.equals(authorizationHeader)) continue; logger.debug("Overwriting [" + HEADER_AUTHORIZATION + "] from {" + headerValue + " } to {" + authorizationHeader + "}"); urlConnection.setRequestProperty(HEADER_AUTHORIZATION, authorizationHeader); } } } } @Override public InputStream onResponse(final RequestData requestData, final InputStream iStream) { logger.debug("StalkerRequestHandler::onResponse()"); String target = requestData.getTarget(); if(!target.contains(".php")) return iStream; try { String data = IOUtils.toString(iStream); Matcher matcher = handshakePattern.matcher(requestData.getRealUrl().toString()); if(matcher.find()) { processHandshake(requestData, data); } return IOUtils.toInputStream(data); } catch (IOException e) { e.printStackTrace(); } return iStream; } @Override public void onBeforeRequest(final RequestData requestData, final PortalConfiguration portalConfiguration) { logger.debug("StalkerRequestHandler::onBeforeRequest()"); String macAddress = requestData.getMacAddress(); if(macAddress == null || macAddress.isEmpty()) { String cookie = requestData.getCookie().replace("%3A", ":"); Matcher matcher = cookiePattern.matcher(cookie); if(matcher.find()) { requestData.setMacAddress(matcher.group(1)); macAddress = matcher.group(1); logger.debug("MAC: " + matcher.group(1)); } else macAddress = "empty"; } if(!staticHeadersForMac.containsKey(macAddress)) staticHeadersForMac.put(macAddress, new HeadersList()); HashMap<String, String> staticHeaders = getHeadersForRequest(requestData).getList(); String token = portalConfiguration.get(requestData.getConnectionName(), "token"); if(token != null) staticHeaders.put(HEADER_AUTHORIZATION, "Bearer " + token); if(!staticParamsForMac.containsKey(macAddress)) { ParamsList params = new ParamsList(); HashMap<String, String> list = params.getList(); for(String name: configOptions) { String value = portalConfiguration.get(requestData.getConnectionName(), name); if(value == null) { logger.debug("Skipping NULL config value [" + name + "]"); continue; } logger.debug("Loading {" + name + "} -> {" + value + "}"); list.put(name, value); } staticParamsForMac.put(macAddress, params); } try { requestData.setRealUrl(new URL(getURL(requestData))); } catch (MalformedURLException e) { e.printStackTrace(); } } public void processHandshake(final RequestData requestData, final String data) { logger.debug("StalkerRequestHandler::processHandshake()"); HashMap<String, String> staticHeaders = getHeadersForRequest(requestData).getList(); JSONObject json; try { json = new JSONObject(data); JSONObject js = json.getJSONObject("js"); String token = js.getString("token"); staticHeaders.put(HEADER_AUTHORIZATION, "Bearer " + token); WebServer.getPortalConfiguration().set(requestData.getConnectionName(), "token", token); } catch (JSONException e) { e.printStackTrace(); } } }
mit
archimatetool/archi
com.archimatetool.editor/src/com/archimatetool/editor/actions/CheckForNewVersionAction.java
4513
/** * This program and the accompanying materials * are made available under the terms of the License * which accompanies this distribution in the file LICENSE.txt */ package com.archimatetool.editor.actions; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.browser.IWebBrowser; import org.eclipse.ui.browser.IWorkbenchBrowserSupport; import com.archimatetool.editor.ArchiPlugin; import com.archimatetool.editor.preferences.IPreferenceConstants; import com.archimatetool.editor.utils.StringUtils; /** * Check for New Action * * @author Phillip Beauvoir */ public class CheckForNewVersionAction extends Action { public CheckForNewVersionAction() { super(Messages.CheckForNewVersionAction_0); } String getOnlineVersion(URL url) throws IOException { URLConnection connection = url.openConnection(); connection.connect(); InputStream is = connection.getInputStream(); char[] buf = new char[32]; Reader r = new InputStreamReader(is, "UTF-8"); //$NON-NLS-1$ StringBuilder s = new StringBuilder(); while(true) { int n = r.read(buf); if(n < 0) { break; } s.append(buf, 0, n); } is.close(); r.close(); return s.toString(); } @Override public void run() { try { String versionFile = ArchiPlugin.PREFERENCES.getString(IPreferenceConstants.UPDATE_URL); if(!StringUtils.isSet(versionFile)) { return; } URL url = new URL(versionFile); String newVersion = getOnlineVersion(url); // Get this app's main version number String thisVersion = ArchiPlugin.INSTANCE.getVersion(); if(StringUtils.compareVersionNumbers(newVersion, thisVersion) > 0) { String downloadURL = ArchiPlugin.PREFERENCES.getString(IPreferenceConstants.DOWNLOAD_URL); // No download URL if(!StringUtils.isSet(downloadURL)) { MessageDialog.openInformation(null, Messages.CheckForNewVersionAction_1, Messages.CheckForNewVersionAction_2 + " (" + newVersion + "). "); //$NON-NLS-1$ //$NON-NLS-2$ return; } // Does have download URL boolean reply = MessageDialog.openQuestion(null, Messages.CheckForNewVersionAction_1, Messages.CheckForNewVersionAction_2 + " (" + newVersion + "). " + //$NON-NLS-1$ //$NON-NLS-2$ Messages.CheckForNewVersionAction_3); if(reply) { IWorkbenchBrowserSupport support = PlatformUI.getWorkbench().getBrowserSupport(); IWebBrowser browser = support.getExternalBrowser(); if(browser != null) { URL url2 = new URL(downloadURL); browser.openURL(url2); } } } else { MessageDialog.openInformation(null, Messages.CheckForNewVersionAction_1, Messages.CheckForNewVersionAction_4); } } catch(MalformedURLException ex) { ex.printStackTrace(); } catch(IOException ex) { ex.printStackTrace(); showErrorMessage(Messages.CheckForNewVersionAction_5 + " " + ex.getMessage()); //$NON-NLS-1$ return; } catch(PartInitException ex) { ex.printStackTrace(); } }; @Override public boolean isEnabled() { String versionFile = ArchiPlugin.PREFERENCES.getString(IPreferenceConstants.UPDATE_URL); return StringUtils.isSet(versionFile); } private void showErrorMessage(String message) { MessageDialog.openError(null, Messages.CheckForNewVersionAction_6, message); } }
mit
haftommit/FPP.github.io
FPPSecondProject/src/week1lesson2/Q2.java
545
package fPPPrograms; import java.util.Scanner; public class LeapYear { public static void main(String[] args) { System.out.println("Enter a year to determine whether it is a leap year or not?"); Scanner yourInput = new Scanner(System.in); int year = yourInput.nextInt(); //String y = year%400 == 0? (year%4 == 0 ) && (year%100 !=0) ? "Yes" : "Not" : "Not" ; String y = ((year%4 == 0) && (year%100 != 0) || (year%400 == 0)) ? "Yes" : "Not"; System.out.println("The Year You Entered is " + y + " a Leap Year"); } }
mit
rlviana/pricegrabber-app
pricegrabber-model/src/test/java/net/rlviana/pricegrabber/model/entity/common/CurrencyTest.java
1712
/* * Created on 24/02/2014 * */ package net.rlviana.pricegrabber.model.entity.common; import net.rlviana.pricegrabber.context.JPAPersistenceContext; import net.rlviana.pricegrabber.model.entity.AbstractReadOnlyEntityTest; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; /** * @author ramon */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {JPAPersistenceContext.class}) @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false) @Transactional public class CurrencyTest extends AbstractReadOnlyEntityTest<Currency, String> { private static final Logger LOGGER = LoggerFactory.getLogger(CurrencyTest.class); @Test public void testFindAll() { } @Test public void testFindByCriteria() { } /** * @return * @see net.rlviana.pricegrabber.model.entity.AbstractReadOnlyEntityTest#getEntityPKFindOK() */ @Override protected String getEntityPKFindOK() { return "EU"; } /** * @return * @see net.rlviana.pricegrabber.model.entity.AbstractReadOnlyEntityTest#getEntityPKFindKO() */ @Override protected String getEntityPKFindKO() { return "NEU"; } /** * @return * @see net.rlviana.pricegrabber.model.entity.AbstractReadOnlyEntityTest#getTestClass() */ @Override protected Class<Currency> getTestClass() { return Currency.class; } }
mit
MoodCat/MoodCat.me-Core
src/main/java/me/moodcat/api/Mood.java
3192
package me.moodcat.api; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.stream.Collectors; import lombok.Getter; import me.moodcat.database.embeddables.VAVector; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; /** * A mood represents a vector in the valence-arousal plane which will be attached to song. */ @JsonFormat(shape = JsonFormat.Shape.OBJECT) public enum Mood { // CHECKSTYLE:OFF ANGRY(new VAVector(-0.6, 0.6), "Angry"), CALM(new VAVector(0.3, -0.9), "Calm"), EXCITING(new VAVector(0.4, 0.8), "Exciting"), HAPPY(new VAVector(0.7, 0.6), "Happy"), NERVOUS(new VAVector(-0.7, 0.4), "Nervous"), PLEASING(new VAVector(0.6, 0.3), "Pleasing"), PEACEFUL(new VAVector(0.5, -0.7), "Peaceful"), RELAXED(new VAVector(0.6, -0.3), "Relaxed"), SAD(new VAVector(-0.7, -0.2), "Sad"), SLEEPY(new VAVector(-0.2, -0.9), "Sleepy"); // CHECKSTYLE:ON /** * List of all names that represent moods. Used in {@link #nameRepresentsMood(String)}. * By storing this once, we save a lot of unnecessary list creations. */ private static final List<String> MOOD_NAMES = Arrays.asList(Mood.values()).stream() .map(moodValue -> moodValue.getName()) .collect(Collectors.toList()); /** * The vector that represents this mood. * * @return The vector of this mood. */ @Getter @JsonIgnore private final VAVector vector; /** * Readable name for the frontend. * * @return The readable name of this mood. */ @Getter private final String name; private Mood(final VAVector vector, final String name) { this.vector = vector; this.name = name; } /** * Get the mood that is closest to the given vector. * * @param vector * The vector to determine the mood for. * @return The Mood that is closest to the vector. */ public static Mood closestTo(final VAVector vector) { double distance = Double.MAX_VALUE; Mood mood = null; for (final Mood m : Mood.values()) { final double moodDistance = m.vector.distance(vector); if (moodDistance < distance) { distance = moodDistance; mood = m; } } return mood; } /** * Get the vector that represents the average of the provided list of moods. * * @param moods * The textual list of moods. * @return The average vector, or the zero-vector if no moods were found. */ public static VAVector createTargetVector(final List<String> moods) { final List<VAVector> actualMoods = moods.stream() .filter(Mood::nameRepresentsMood) .map(mood -> Mood.valueOf(mood.toUpperCase(Locale.ROOT))) .map(mood -> mood.getVector()) .collect(Collectors.toList()); return VAVector.average(actualMoods); } private static boolean nameRepresentsMood(final String mood) { return MOOD_NAMES.contains(mood); } }
mit
Nocket/nocket
examples/java/forscher/nocket/page/gen/ajax/AjaxTargetUpdateTestInner.java
518
package forscher.nocket.page.gen.ajax; import gengui.annotations.Eager; import java.io.Serializable; public class AjaxTargetUpdateTestInner implements Serializable { private String feld1; private String feld2; public String getEagerFeld1() { return feld1; } @Eager public void setEagerFeld1(String feld1) { this.feld1 = feld1; } public String getFeld2() { return feld2; } public void setFeld2(String feld2) { this.feld2 = feld2; } }
mit
jvasileff/aos-xp
src.java/org/anodyneos/xp/tagext/XpTag.java
480
package org.anodyneos.xp.tagext; import javax.servlet.jsp.el.ELException; import org.anodyneos.xp.XpContext; import org.anodyneos.xp.XpException; import org.anodyneos.xp.XpOutput; import org.xml.sax.SAXException; /** * @author jvas */ public interface XpTag { void doTag(XpOutput out) throws XpException, ELException, SAXException; XpTag getParent(); void setXpBody(XpFragment xpBody); void setXpContext(XpContext xpc); void setParent(XpTag parent); }
mit
RealTwo-Space/Neumann
neumann/src/org/real2space/neumann/evaris/core/structure/Field.java
426
package org.real2space.neumann.evaris.core.structure; /** * Project Neumann * * @author RealTwo-Space * @version 0 * * created 2016/11/01 * added "extends Ring<F>" 2016/11/9 */ public interface Field<F> extends Ring<F> { /* * Multiply this member by an inverse of "other". */ public void divide (F other); /* * Returns an inverse of this member. */ public F inverse (); }
mit
chriskearney/creeper
src/test/com/comandante/creeper/command/commands/FriendlyTimeTest.java
472
package com.comandante.creeper.command.commands; import com.comandante.creeper.common.FriendlyTime; import org.junit.Test; public class FriendlyTimeTest { @Test public void testFriendlyParsing() throws Exception { FriendlyTime friendlyTime = new FriendlyTime(400); System.out.println("Friendly Long: " + friendlyTime.getFriendlyFormatted()); System.out.println("Friendly Short: " + friendlyTime.getFriendlyFormattedShort()); } }
mit
leomv09/FileSystem
src/fs/command/CreateFileCommand.java
1247
package fs.command; import fs.App; import fs.Disk; import fs.util.FileUtils; import java.util.Arrays; /** * * @author José Andrés García Sáenz <jags9415@gmail.com> */ public class CreateFileCommand extends Command { public final static String COMMAND = "mkfile"; @Override public void execute(String[] args) { if (args.length != 2 && args.length != 3) { reportSyntaxError(); return; } String path = args[1]; String content = String.join(" ", Arrays.copyOfRange(args, 2, args.length)); App app = App.getInstance(); Disk disk = app.getDisk(); if (disk.exists(path) && !FileUtils.promptForVirtualOverride(path)) { return; } try { disk.createFile(path, content); } catch (Exception ex) { reportError(ex); } } @Override protected String getName() { return CreateFileCommand.COMMAND; } @Override protected String getDescription() { return "Create a file and set its content."; } @Override protected String getSyntax() { return getName() + " FILENAME \"<CONTENT>\""; } }
mit
navalev/azure-sdk-for-java
sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java
11381
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.data.cosmos.internal.query; import com.azure.data.cosmos.BadRequestException; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CommonsBridgeInternal; import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.Strings; import com.azure.data.cosmos.internal.Utils; import com.azure.data.cosmos.internal.caches.RxCollectionCache; import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; import com.azure.data.cosmos.internal.routing.Range; import org.apache.commons.lang3.StringUtils; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.util.Collections; import java.util.List; import java.util.UUID; /** * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. */ public class DocumentQueryExecutionContextFactory { private final static int PageSizeFactorForTop = 5; private static Mono<Utils.ValueHolder<DocumentCollection>> resolveCollection(IDocumentQueryClient client, SqlQuerySpec query, ResourceType resourceTypeEnum, String resourceLink) { RxCollectionCache collectionCache = client.getCollectionCache(); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( OperationType.Query, resourceTypeEnum, resourceLink, null // TODO AuthorizationTokenType.INVALID) ); //this request doesnt actually go to server return collectionCache.resolveCollectionAsync(request); } public static <T extends Resource> Flux<? extends IDocumentQueryExecutionContext<T>> createDocumentQueryExecutionContextAsync( IDocumentQueryClient client, ResourceType resourceTypeEnum, Class<T> resourceType, SqlQuerySpec query, FeedOptions feedOptions, String resourceLink, boolean isContinuationExpected, UUID correlatedActivityId) { // return proxy Flux<Utils.ValueHolder<DocumentCollection>> collectionObs = Flux.just(new Utils.ValueHolder<>(null)); if (resourceTypeEnum.isCollectionChild()) { collectionObs = resolveCollection(client, query, resourceTypeEnum, resourceLink).flux(); } DefaultDocumentQueryExecutionContext<T> queryExecutionContext = new DefaultDocumentQueryExecutionContext<T>( client, resourceTypeEnum, resourceType, query, feedOptions, resourceLink, correlatedActivityId, isContinuationExpected); if (ResourceType.Document != resourceTypeEnum) { return Flux.just(queryExecutionContext); } Mono<PartitionedQueryExecutionInfo> queryExecutionInfoMono = com.azure.data.cosmos.internal.query.QueryPlanRetriever.getQueryPlanThroughGatewayAsync(client, query, resourceLink); return collectionObs.single().flatMap(collectionValueHolder -> queryExecutionInfoMono.flatMap(partitionedQueryExecutionInfo -> { QueryInfo queryInfo = partitionedQueryExecutionInfo.getQueryInfo(); // Non value aggregates must go through // DefaultDocumentQueryExecutionContext // Single partition query can serve queries like SELECT AVG(c // .age) FROM c // SELECT MIN(c.age) + 5 FROM c // SELECT MIN(c.age), MAX(c.age) FROM c // while pipelined queries can only serve // SELECT VALUE <AGGREGATE>. So we send the query down the old // pipeline to avoid a breaking change. // Should be fixed by adding support for nonvalueaggregates if (queryInfo.hasAggregates() && !queryInfo.hasSelectValue()) { if (feedOptions != null && feedOptions.enableCrossPartitionQuery()) { return Mono.error(BridgeInternal.createCosmosClientException(HttpConstants.StatusCodes.BADREQUEST, "Cross partition query only supports 'VALUE " + "<AggreateFunc>' for aggregates")); } return Mono.just(queryExecutionContext); } Mono<List<PartitionKeyRange>> partitionKeyRanges; // The partitionKeyRangeIdInternal is no more a public API on FeedOptions, but have the below condition // for handling ParallelDocumentQueryTest#partitionKeyRangeId if (feedOptions != null && !StringUtils.isEmpty(CommonsBridgeInternal.partitionKeyRangeIdInternal(feedOptions))) { partitionKeyRanges = queryExecutionContext.getTargetPartitionKeyRangesById(collectionValueHolder.v.resourceId(), CommonsBridgeInternal.partitionKeyRangeIdInternal(feedOptions)); } else { List<Range<String>> queryRanges = partitionedQueryExecutionInfo.getQueryRanges(); if (feedOptions != null && feedOptions.partitionKey() != null) { PartitionKeyInternal internalPartitionKey = feedOptions.partitionKey() .getInternalPartitionKey(); Range<String> range = Range.getPointRange(internalPartitionKey .getEffectivePartitionKeyString(internalPartitionKey, collectionValueHolder.v.getPartitionKey())); queryRanges = Collections.singletonList(range); } partitionKeyRanges = queryExecutionContext .getTargetPartitionKeyRanges(collectionValueHolder.v.resourceId(), queryRanges); } return partitionKeyRanges .flatMap(pkranges -> createSpecializedDocumentQueryExecutionContextAsync(client, resourceTypeEnum, resourceType, query, feedOptions, resourceLink, isContinuationExpected, partitionedQueryExecutionInfo, pkranges, collectionValueHolder.v.resourceId(), correlatedActivityId).single()); })).flux(); } public static <T extends Resource> Flux<? extends IDocumentQueryExecutionContext<T>> createSpecializedDocumentQueryExecutionContextAsync( IDocumentQueryClient client, ResourceType resourceTypeEnum, Class<T> resourceType, SqlQuerySpec query, FeedOptions feedOptions, String resourceLink, boolean isContinuationExpected, PartitionedQueryExecutionInfo partitionedQueryExecutionInfo, List<PartitionKeyRange> targetRanges, String collectionRid, UUID correlatedActivityId) { if (feedOptions == null) { feedOptions = new FeedOptions(); } int initialPageSize = Utils.getValueOrDefault(feedOptions.maxItemCount(), ParallelQueryConfig.ClientInternalPageSize); BadRequestException validationError = Utils.checkRequestOrReturnException( initialPageSize > 0 || initialPageSize == -1, "MaxItemCount", "Invalid MaxItemCount %s", initialPageSize); if (validationError != null) { return Flux.error(validationError); } QueryInfo queryInfo = partitionedQueryExecutionInfo.getQueryInfo(); if (!Strings.isNullOrEmpty(queryInfo.getRewrittenQuery())) { query = new SqlQuerySpec(queryInfo.getRewrittenQuery(), query.parameters()); } boolean getLazyFeedResponse = queryInfo.hasTop(); // We need to compute the optimal initial page size for order-by queries if (queryInfo.hasOrderBy()) { int top; if (queryInfo.hasTop() && (top = partitionedQueryExecutionInfo.getQueryInfo().getTop()) > 0) { int pageSizeWithTop = Math.min( (int)Math.ceil(top / (double)targetRanges.size()) * PageSizeFactorForTop, top); if (initialPageSize > 0) { initialPageSize = Math.min(pageSizeWithTop, initialPageSize); } else { initialPageSize = pageSizeWithTop; } } // TODO: do not support continuation in string format right now // else if (isContinuationExpected) // { // if (initialPageSize < 0) // { // initialPageSize = (int)Math.Max(feedOptions.MaxBufferedItemCount, ParallelQueryConfig.GetConfig().DefaultMaximumBufferSize); // } // // initialPageSize = Math.Min( // (int)Math.Ceiling(initialPageSize / (double)targetRanges.Count) * PageSizeFactorForTop, // initialPageSize); // } } return PipelinedDocumentQueryExecutionContext.createAsync( client, resourceTypeEnum, resourceType, query, feedOptions, resourceLink, collectionRid, partitionedQueryExecutionInfo, targetRanges, initialPageSize, isContinuationExpected, getLazyFeedResponse, correlatedActivityId); } }
mit
AVSystem/scex
scex-util/src/main/scala/com/avsystem/scex/util/function/StringUtilImpl.java
5283
package com.avsystem.scex.util.function; import org.apache.commons.codec.digest.HmacAlgorithms; import org.apache.commons.codec.digest.HmacUtils; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import java.util.Collection; public class StringUtilImpl implements StringUtil { public static final StringUtilImpl INSTANCE = new StringUtilImpl(); private StringUtilImpl() { } @Override public String concat(String... parts) { return StringFunctions.concat(parts); } @Override public boolean contains(String list, String item) { return StringFunctions.contains(list, item); } @Override public double extract(String string) { return StringFunctions.extract(string); } @Override public String regexFind(String value, String pattern) { return StringFunctions.regexFind(value, pattern); } @Override public String regexFindGroup(String value, String pattern) { return StringFunctions.regexFindGroup(value, pattern); } @Override public boolean regexMatches(String value, String pattern) { return StringFunctions.regexMatches(value, pattern); } @Override public String regexReplace(String value, String pattern, String replacement) { return StringFunctions.regexReplace(value, pattern, replacement); } @Override public String regexReplaceAll(String value, String pattern, String replacement) { return StringFunctions.regexReplaceAll(value, pattern, replacement); } @Override public String slice(String item, int from) { return StringFunctions.slice(item, from); } @Override public String slice(String item, int from, int to, boolean dot) { return StringFunctions.slice(item, from, to, dot); } @Override public String stripToAlphanumeric(String source, String replacement) { return StringFunctions.stripToAlphanumeric(source, replacement); } /** * Remove end for string if exist * * @param source source string * @param end string to remove from the end of source * @return string with removed end */ @Override public String removeEnd(String source, String end) { if (source != null && end != null) { return source.endsWith(end) ? source.substring(0, source.length() - end.length()) : source; } return null; } /** * Remove start from string if exist * * @param source source string * @param start string to remove from the start of source * @return string with removed end */ @Override public String removeStart(String source, String start) { if (source != null && start != null) { return source.startsWith(start) ? source.substring(start.length(), source.length()) : source; } return null; } @Override public String removeTRRoot(String source) { if (source != null) { if (source.startsWith("InternetGatewayDevice.")) { source = source.replaceFirst("InternetGatewayDevice.", ""); } else if (source.startsWith("Device.")) { source = source.replaceFirst("Device.", ""); } } return source; } @Override public String random(int length) { return RandomStringUtils.randomAlphanumeric(length); } /** * Left pad a String with a specified String. * * @param str the String to pad out, may be null * @param size the size to pad to * @param padStr the String to pad with, null or empty treated as single space * @return right padded String */ @Override public String leftPad(String str, int size, String padStr) { return StringFunctions.leftPad(str, size, padStr); } /** * Right pad a String with a specified String. * * @param str the String to pad out, may be null * @param size the size to pad to * @param padStr the String to pad with, null or empty treated as single space * @return left padded String */ @Override public String rightPad(String str, int size, String padStr) { return StringFunctions.rightPad(str, size, padStr); } @Override public String subString(String str, int from, int to) { return StringUtils.substring(str, from, to); } @Override public String[] split(String str, String separator) { return StringUtils.split(str, separator); } @Override public String trimToEmpty(String str) { return StringUtils.trimToEmpty(str); } @Override public String replace(String str, String find, String replacement) { return StringUtils.replace(str, find, replacement); } @Override public String join(Collection<String> list, String separator) { return StringUtils.join(list, separator); } @Override public boolean stringContains(String source, String item) { return StringUtils.contains(source, item); } @Override public String hmacMD5(String str, String key) { return new HmacUtils(HmacAlgorithms.HMAC_MD5, key).hmacHex(str); } }
mit
wangzhaoming/Poker
code/poker-server/src/main/java/work/notech/poker/room/GameRoom.java
671
package work.notech.poker.room; import work.notech.poker.logic.Cards; import java.util.List; public class GameRoom { private Integer roomIds; private List<Integer> clientIds; private Cards cards; public Integer getRoomIds() { return roomIds; } public void setRoomIds(Integer roomIds) { this.roomIds = roomIds; } public List<Integer> getClientIds() { return clientIds; } public void setClientIds(List<Integer> clientIds) { this.clientIds = clientIds; } public Cards getCards() { return cards; } public void setCards(Cards cards) { this.cards = cards; } }
mit
sunilson/My-Ticker-Android
Android App/app/src/main/java/com/sunilson/pro4/activities/AddLivetickerActivity.java
11353
package com.sunilson.pro4.activities; import android.app.DatePickerDialog; import android.app.TimePickerDialog; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.CompoundButton; import android.widget.DatePicker; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Switch; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.sunilson.pro4.R; import com.sunilson.pro4.baseClasses.Liveticker; import com.sunilson.pro4.exceptions.LivetickerSetException; import com.sunilson.pro4.utilities.Constants; import com.sunilson.pro4.views.SubmitButtonBig; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Locale; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class AddLivetickerActivity extends BaseActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener { private ValueEventListener resultListener; private DatabaseReference mReference, currentResultReference; private boolean finished, startNow; private String privacy = "public"; private String livetickerID; private Calendar calendar; private ArrayList<DatabaseReference> references = new ArrayList<>(); private CompoundButton.OnCheckedChangeListener switchListener; @BindView(R.id.add_liveticker_date) TextView dateTextView; @BindView(R.id.add_liveticker_time) TextView timeTextView; @BindView(R.id.add_liveticker_title_edittext) EditText titleEditText; @BindView(R.id.add_liveticker_description_edittext) EditText descriptionEditText; @BindView(R.id.add_liveticker_status_edittext) EditText statusEditText; @BindView(R.id.add_liveticker_start_switch) Switch dateSwitch; @BindView(R.id.add_liveticker_privacy_switch) Switch privacySwitch; @BindView(R.id.add_liveticker_date_layout) LinearLayout dateLayout; @BindView(R.id.add_liveticker_privacy_title) TextView privacyTitle; @BindView(R.id.submit_button_view) SubmitButtonBig submitButtonBig; @OnClick(R.id.submit_button) public void submit(View view) { final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if (user == null || user.isAnonymous()) { Toast.makeText(this, R.string.add_liveticker_user_failure, Toast.LENGTH_SHORT).show(); return; } final Liveticker liveticker = new Liveticker(); try { liveticker.setTitle(titleEditText.getText().toString()); liveticker.setDescription(descriptionEditText.getText().toString()); liveticker.setAuthorID(user.getUid()); liveticker.setStateTimestamp(calendar.getTimeInMillis()); liveticker.setPrivacy(privacy); liveticker.setStatus(statusEditText.getText().toString()); } catch (LivetickerSetException e) { Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show(); return; } loading(true); final DatabaseReference ref = FirebaseDatabase.getInstance().getReference("/request/" + user.getUid() + "/addLiveticker/").push(); ref.setValue(liveticker).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { //Remove Event Listener from Queue, if it has been started if (currentResultReference != null && resultListener != null) { currentResultReference.removeEventListener(resultListener); } //Listen for results from Queue DatabaseReference taskRef = FirebaseDatabase.getInstance().getReference("/result/" + user.getUid() + "/addLiveticker/" + ref.getKey()); //Add Listener to Reference and store Reference so we can later detach Listener taskRef.addValueEventListener(resultListener); currentResultReference = taskRef; } }); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_liveticker); ButterKnife.bind(this); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mReference = FirebaseDatabase.getInstance().getReference(); initializeQueueListener(); calendar = Calendar.getInstance(); updateDateTime(); dateTextView.setOnClickListener(this); timeTextView.setOnClickListener(this); dateSwitch.setOnCheckedChangeListener(this); privacySwitch.setOnCheckedChangeListener(this); submitButtonBig.setText(getString(R.string.channel_edit_save), getString(R.string.loading)); } @Override protected void onStop() { super.onStop(); //Remove Event Listener from Queue, if it has been started if (currentResultReference != null && resultListener != null) { currentResultReference.removeEventListener(resultListener); } } @Override protected void authChanged(FirebaseUser user) { if (user.isAnonymous()) { Intent i = new Intent(AddLivetickerActivity.this, MainActivity.class); startActivity(i); Toast.makeText(this, R.string.no_access_permission, Toast.LENGTH_SHORT).show(); } } /** * Initialize Listener for "Add Liveticker Queue" */ private void initializeQueueListener() { resultListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (!finished) { //Check what state the Queue event has if (dataSnapshot.child("state").getValue() != null) { //Liveticker was added successfully if (dataSnapshot.child("state").getValue().toString().equals("success")) { finished = true; Intent i = new Intent(); i.putExtra("livetickerID", dataSnapshot.child("successDetails").getValue().toString()); setResult(Constants.ADD_LIVETICKER_RESULT_CODE, i); finish(); } else if (dataSnapshot.child("state").getValue().toString().equals("error")) { loading(false); Toast.makeText(AddLivetickerActivity.this, dataSnapshot.child("errorDetails").getValue().toString(), Toast.LENGTH_LONG).show(); } } } } @Override public void onCancelled(DatabaseError databaseError) { } }; } /** * Change visual loading state * * @param loading */ private void loading(boolean loading) { if (loading) { submitButtonBig.loading(true); } else { submitButtonBig.loading(false); } } @Override public void onClick(View view) { switch (view.getId()) { case R.id.add_liveticker_date: showDateDialog(); break; case R.id.add_liveticker_time: showTimeDialog(); break; } } /** * A dialog to pick a date and set the calendar to that date */ private void showDateDialog() { DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) { calendar.set(Calendar.MONTH, month); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); updateDateTime(); } }; DatePickerDialog datePickerDialog = new DatePickerDialog(this, onDateSetListener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000); datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis() + 432000000); datePickerDialog.show(); } /** * A dialog to pick a time and set the calendar to that time */ private void showTimeDialog() { TimePickerDialog.OnTimeSetListener onTimeSetListener = new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker timePicker, int hour, int minute) { calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, minute); updateDateTime(); } }; TimePickerDialog timePickerDialog = new TimePickerDialog(this, onTimeSetListener, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true); timePickerDialog.show(); } /** * Update the Textviews with the current date from the calendar */ private void updateDateTime() { Date date = calendar.getTime(); SimpleDateFormat formatDate = new SimpleDateFormat("dd.MM.yyyy", Locale.getDefault()); SimpleDateFormat formatTime = new SimpleDateFormat("HH:mm", Locale.getDefault()); dateTextView.setText(formatDate.format(date)); timeTextView.setText(formatTime.format(date)); } /** * When a switch gets toggled * * @param compoundButton Switch that was toggled * @param b Value of switch */ @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { switch (compoundButton.getId()) { case R.id.add_liveticker_start_switch: startNow = !startNow; if (b) { dateLayout.setVisibility(View.GONE); } else { dateLayout.setVisibility(View.VISIBLE); } break; case R.id.add_liveticker_privacy_switch: if (b) { privacy = "public"; privacyTitle.setText(getString(R.string.add_liveticker_public_title)); } else { privacy = "private"; privacyTitle.setText(getString(R.string.add_liveticker_public_title_private)); } break; } } }
mit
SpongePowered/SpongeCommon
src/main/java/org/spongepowered/common/mixin/core/network/NetworkManagerMixin.java
3754
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * 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 NONINFRINGEMENT. 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.spongepowered.common.mixin.core.network; import io.netty.channel.Channel; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.local.LocalAddress; import net.minecraft.network.NetworkManager; import org.spongepowered.api.MinecraftVersion; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.common.SpongeMinecraftVersion; import org.spongepowered.common.bridge.network.NetworkManagerBridge; import org.spongepowered.common.util.Constants; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.UnknownHostException; import javax.annotation.Nullable; @SuppressWarnings("rawtypes") @Mixin(NetworkManager.class) public abstract class NetworkManagerMixin extends SimpleChannelInboundHandler implements NetworkManagerBridge { @Shadow private Channel channel; @Shadow public abstract SocketAddress getRemoteAddress(); @Nullable private InetSocketAddress impl$virtualHost; @Nullable private MinecraftVersion impl$version; @Override public InetSocketAddress bridge$getAddress() { final SocketAddress remoteAddress = getRemoteAddress(); if (remoteAddress instanceof LocalAddress) { // Single player return Constants.Networking.LOCALHOST; } return (InetSocketAddress) remoteAddress; } @Override public InetSocketAddress bridge$getVirtualHost() { if (this.impl$virtualHost != null) { return this.impl$virtualHost; } final SocketAddress local = this.channel.localAddress(); if (local instanceof LocalAddress) { return Constants.Networking.LOCALHOST; } return (InetSocketAddress) local; } @Override public void bridge$setVirtualHost(final String host, final int port) { try { this.impl$virtualHost = new InetSocketAddress(InetAddress.getByAddress(host, ((InetSocketAddress) this.channel.localAddress()).getAddress().getAddress()), port); } catch (UnknownHostException e) { this.impl$virtualHost = InetSocketAddress.createUnresolved(host, port); } } @Override public MinecraftVersion bridge$getVersion() { return this.impl$version; } @Override public void bridge$setVersion(final int version) { this.impl$version = new SpongeMinecraftVersion(String.valueOf(version), version); } }
mit
craigfreilly/masters-project-submission
src/KnotTheory/JavaKh-v2/src/org/katlas/JavaKh/rows/RedBlackIntegerMap.java
518
package org.katlas.JavaKh.rows; import org.katlas.JavaKh.utils.RedBlackIntegerTree; public class RedBlackIntegerMap<F> extends RedBlackIntegerTree<F> implements MatrixRow<F> { /** * */ private static final long serialVersionUID = 5885667469881867107L; public void compact() { } public void putLast(int key, F f) { put(key, f); } @Override public void put(int key, F value) { if(value == null) { remove(key); } else { super.put(key, value); } } }
mit
selvasingh/azure-sdk-for-java
sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/ListEdgePoliciesInput.java
1044
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.mediaservices.v2018_07_01; import com.fasterxml.jackson.annotation.JsonProperty; /** * The ListEdgePoliciesInput model. */ public class ListEdgePoliciesInput { /** * Unique identifier of the edge device. */ @JsonProperty(value = "deviceId") private String deviceId; /** * Get unique identifier of the edge device. * * @return the deviceId value */ public String deviceId() { return this.deviceId; } /** * Set unique identifier of the edge device. * * @param deviceId the deviceId value to set * @return the ListEdgePoliciesInput object itself. */ public ListEdgePoliciesInput withDeviceId(String deviceId) { this.deviceId = deviceId; return this; } }
mit
selvasingh/azure-sdk-for-java
sdk/apimanagement/mgmt-v2019_12_01/src/main/java/com/microsoft/azure/management/apimanagement/v2019_12_01/implementation/LoggersImpl.java
3159
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * jkl */ package com.microsoft.azure.management.apimanagement.v2019_12_01.implementation; import com.microsoft.azure.arm.model.implementation.WrapperImpl; import com.microsoft.azure.management.apimanagement.v2019_12_01.Loggers; import rx.Completable; import rx.functions.Func1; import rx.Observable; import com.microsoft.azure.Page; import com.microsoft.azure.management.apimanagement.v2019_12_01.LoggerContract; class LoggersImpl extends WrapperImpl<LoggersInner> implements Loggers { private final ApiManagementManager manager; LoggersImpl(ApiManagementManager manager) { super(manager.inner().loggers()); this.manager = manager; } public ApiManagementManager manager() { return this.manager; } @Override public LoggerContractImpl define(String name) { return wrapModel(name); } private LoggerContractImpl wrapModel(LoggerContractInner inner) { return new LoggerContractImpl(inner, manager()); } private LoggerContractImpl wrapModel(String name) { return new LoggerContractImpl(name, this.manager()); } @Override public Observable<LoggerContract> listByServiceAsync(final String resourceGroupName, final String serviceName) { LoggersInner client = this.inner(); return client.listByServiceAsync(resourceGroupName, serviceName) .flatMapIterable(new Func1<Page<LoggerContractInner>, Iterable<LoggerContractInner>>() { @Override public Iterable<LoggerContractInner> call(Page<LoggerContractInner> page) { return page.items(); } }) .map(new Func1<LoggerContractInner, LoggerContract>() { @Override public LoggerContract call(LoggerContractInner inner) { return new LoggerContractImpl(inner, manager()); } }); } @Override public Completable getEntityTagAsync(String resourceGroupName, String serviceName, String loggerId) { LoggersInner client = this.inner(); return client.getEntityTagAsync(resourceGroupName, serviceName, loggerId).toCompletable(); } @Override public Observable<LoggerContract> getAsync(String resourceGroupName, String serviceName, String loggerId) { LoggersInner client = this.inner(); return client.getAsync(resourceGroupName, serviceName, loggerId) .map(new Func1<LoggerContractInner, LoggerContract>() { @Override public LoggerContract call(LoggerContractInner inner) { return new LoggerContractImpl(inner, manager()); } }); } @Override public Completable deleteAsync(String resourceGroupName, String serviceName, String loggerId, String ifMatch) { LoggersInner client = this.inner(); return client.deleteAsync(resourceGroupName, serviceName, loggerId, ifMatch).toCompletable(); } }
mit
stummk/psp-eclipse
Source/de.uni.bremen.stummk.psp/src/de/uni/bremen/stummk/psp/calculation/EditorToolbarAction.java
5479
package de.uni.bremen.stummk.psp.calculation; import java.lang.reflect.InvocationTargetException; import java.util.List; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction; import de.uni.bremen.stummk.psp.control.BarChart; import de.uni.bremen.stummk.psp.control.LineChart; import de.uni.bremen.stummk.psp.control.PieChart; import de.uni.bremen.stummk.psp.data.PSPProject; import de.uni.bremen.stummk.psp.data.ScheduleEntry; import de.uni.bremen.stummk.psp.utility.CheckOperation; import de.uni.bremen.stummk.psp.utility.Constants; import de.uni.bremen.stummk.psp.utility.DataIO; import de.uni.bremen.stummk.psp.utility.FileHash; /** * Class represents an action of the toolbar in the editor * * @author Konstantin * */ public class EditorToolbarAction extends Action implements IWorkbenchAction { private EditorToolbarController etc; /** * Constructor * * @param id the Id of the Action * @param editorToolbarController the {@link EditorToolbarController} of the * {@link EditorToolbarAction} */ public EditorToolbarAction(String id, EditorToolbarController editorToolbarController) { setId(id); this.etc = editorToolbarController; } @Override public void run() { handleAction(getId()); } private void handleAction(String id) { // execute action depending on id switch (id) { case Constants.COMMAND_SYNC: exportData(); break; case Constants.COMMAND_PLAN_ACTUAL_DIAGRAM: new BarChart(etc.getProjectPlanSummary(), "Plan vs. Actual Values - " + etc.getProjectPlanSummary().getProject().getProjectName()); break; case Constants.COMMAND_TIME_IN_PHASE_PERCENTAGE: new PieChart(etc.getProjectPlanSummary(), Constants.KEY_TIME_IN_PHASE_IDX, "Distribution of time in phase - " + etc.getProjectPlanSummary().getProject().getProjectName()); break; case Constants.COMMAND_DEFECT_INJECTED_PERCENTAGE: new PieChart(etc.getProjectPlanSummary(), Constants.KEY_DEFECTS_INJECTED_IDX, "Distribution of injected defects - " + etc.getProjectPlanSummary().getProject().getProjectName()); break; case Constants.COMMAND_DEFECT_REMOVED_PERCENTAGE: new PieChart(etc.getProjectPlanSummary(), Constants.KEY_DEFECTS_REMOVED_IDX, "Distribution of removed defects - " + etc.getProjectPlanSummary().getProject().getProjectName()); break; case Constants.COMMAND_TIME_TRACKING: List<ScheduleEntry> entries = Manager.getInstance().getSchedulePlanning(etc.getProjectPlanSummary().getProject().getProjectName()); new LineChart("Time Progress in Project - " + etc.getProjectPlanSummary().getProject().getProjectName(), Constants.CHART_TIME, entries); break; case Constants.COMMAND_EARNED_VALUE_TRACKING: List<ScheduleEntry> e = Manager.getInstance().getSchedulePlanning(etc.getProjectPlanSummary().getProject().getProjectName()); new LineChart("Earned Value Tracking in Project - " + etc.getProjectPlanSummary().getProject().getProjectName(), Constants.CHART_VALUE, e); break; } } private void exportData() { // exports data to psp-file and create hash try { Shell activeShell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); IRunnableWithProgress op = new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { monitor.beginTask("Export data to psp.csv file", 2); PSPProject psp = Manager.getInstance().loadBackupProject(etc.getProjectPlanSummary().getProject().getProjectName()); if (psp != null && psp.getSummary() != null) { DataIO.saveToFile(etc.getProjectPlanSummary().getProject().getProjectName(), psp, null); } monitor.worked(1); if (psp != null && psp.getSummary() != null) { IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); for (IProject project : projects) { if (project.getName().equals(etc.getProjectPlanSummary().getProject().getProjectName())) { IFile file = CheckOperation.getProjectFile(project); String hash = FileHash.hash(file); try { file.setPersistentProperty(Constants.PROPERTY_HASH, hash); } catch (CoreException e) { e.printStackTrace(); } } } } monitor.worked(1); } finally { monitor.done(); } } }; new ProgressMonitorDialog(activeShell).run(true, true, op); } catch (InvocationTargetException | InterruptedException e) { e.printStackTrace(); } } @Override public void dispose() {} }
mit
dylanmaryk/InsanityRadio-Android
app/src/main/java/insanityradio/insanityradio/PlayPauseReceiver.java
663
package insanityradio.insanityradio; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class PlayPauseReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { try { FragmentNowPlaying.getInstance().playPauseButtonTapped(false); } catch (NullPointerException e) { Intent startActivityIntent = new Intent(context.getApplicationContext(), MainActivity.class); startActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(startActivityIntent); } } }
mit
BU-PCM-Testbed/ThermalProfiler
app/src/main/java/jnt/scimark2/kernel.java
7529
package jnt.scimark2; public class kernel { // each measurement returns approx Mflops public static double measureFFT(int N, double mintime, Random R) { // initialize FFT data as complex (N real/img pairs) double x[] = RandomVector(2*N, R); double oldx[] = NewVectorCopy(x); long cycles = 1; Stopwatch Q = new Stopwatch(); while(true) { Q.start(); for (int i=0; i<cycles; i++) { FFT.transform(x); // forward transform FFT.inverse(x); // backward transform } Q.stop(); if (Q.read() >= mintime) break; cycles *= 2; } // approx Mflops final double EPS = 1.0e-10; if ( FFT.test(x) / N > EPS ) return 0.0; return FFT.num_flops(N)*cycles/ Q.read() * 1.0e-6; } // public static double measureSOR(int N, double min_time, Random R) // { // double G[][] = RandomMatrix(N, N, R); // // //Stopwatch Q = new Stopwatch(); // int cycles=1; // //while(true) // while(cycles <= 32768) // { // //Q.start(); // SOR.execute(1.25, G, cycles); // //Q.stop(); // //if (Q.read() >= min_time) break; // // cycles *= 2; // } // // approx Mflops // //return SOR.num_flops(N, N, cycles) / Q.read() * 1.0e-6; // return SOR.num_flops(N, N, cycles); // } public static double measureSOR(int N, double min_time, Random R) { double G[][] = RandomMatrix(N, N, R); int rep = 10; // 11s @ 594MHz //rep = 75; // 42.5s @ 1026MHz //rep = 150; // 68s @ 1026MHz, this just fully melts PCM, at end of benchmark //rep = 250; // 113s @ 1026MHz //rep = 300; // 126s @ 1026MHz, using this setting in my house, PCM melts fully rep = 75; // 75 short duration // 300 medium duration // 400 long duration int cycles = 2048; for (int i = 0; i < rep; i++) { SOR.execute(1.25, G, cycles); } return SOR.num_flops(N, N, cycles); } public static double measureMonteCarlo(double min_time, Random R) { Stopwatch Q = new Stopwatch(); int cycles=1; while(true) { Q.start(); MonteCarlo.integrate(cycles); Q.stop(); if (Q.read() >= min_time) break; cycles *= 2; } // approx Mflops return MonteCarlo.num_flops(cycles) / Q.read() * 1.0e-6; } public static double measureSparseMatmult(int N, int nz, double min_time, Random R) { // initialize vector multipliers and storage for result // y = A*y; double x[] = RandomVector(N, R); double y[] = new double[N]; // initialize square sparse matrix // // for this test, we create a sparse matrix wit M/nz nonzeros // per row, with spaced-out evenly between the begining of the // row to the main diagonal. Thus, the resulting pattern looks // like // +-----------------+ // +* + // +*** + // +* * * + // +** * * + // +** * * + // +* * * * + // +* * * * + // +* * * * + // +-----------------+ // // (as best reproducible with integer artihmetic) // Note that the first nr rows will have elements past // the diagonal. int nr = nz/N; // average number of nonzeros per row int anz = nr *N; // _actual_ number of nonzeros double val[] = RandomVector(anz, R); int col[] = new int[anz]; int row[] = new int[N+1]; row[0] = 0; for (int r=0; r<N; r++) { // initialize elements for row r int rowr = row[r]; row[r+1] = rowr + nr; int step = r/ nr; if (step < 1) step = 1; // take at least unit steps for (int i=0; i<nr; i++) col[rowr+i] = i*step; } //Stopwatch Q = new Stopwatch(); int cycles = 2048; //while(true) //while(cycles <= 65536) // about 20 seconds //while(cycles <= 1048576) // about 200 seconds int rep = 30; // 14 sec @ 594 for (int i = 0; i < rep; i++) { //Q.start(); SparseCompRow.matmult(y, val, row, col, x, cycles); //Q.stop(); //if (Q.read() >= min_time) break; //cycles *= 2; } // approx Mflops //return SparseCompRow.num_flops(N, nz, cycles) / Q.read() * 1.0e-6; return SparseCompRow.num_flops(N, nz, cycles); } public static double measureLU(int N, double min_time, Random R) { // compute approx Mlfops, or O if LU yields large errors double A[][] = RandomMatrix(N, N, R); double lu[][] = new double[N][N]; int pivot[] = new int[N]; //Stopwatch Q = new Stopwatch(); //while(true) //while (cycles <= 8192) //while (cycles <= 2048) // approx 20 sec //while (cycles <= 6144) // approx 30 sec @ 1242MHz //while (cycles <= 12288) // approx 60 sec @ 1242MHz //while (cycles <= 14336) // approx 70 sec @ 1242MHz //while (cycles <= 16384) // approx 80 sec @ 1242MHz int cycles = 2048; // 14 sec @ 594Hz for (int j = 0; j < cycles; j++) { //Q.start(); //for (int i=0; i<cycles; i++) //{ CopyMatrix(lu, A); LU.factor(lu, pivot); //} //Q.stop(); //if (Q.read() >= min_time) break; //cycles *= 2; } // verify that LU is correct double b[] = RandomVector(N, R); double x[] = NewVectorCopy(b); LU.solve(lu, pivot, x); final double EPS = 1.0e-12; if ( normabs(b, matvec(A,x)) / N > EPS ) return 0.0; // else return approx Mflops // //return LU.num_flops(N) * cycles / Q.read() * 1.0e-6; return LU.num_flops(N) * cycles; } private static double[] NewVectorCopy(double x[]) { int N = x.length; double y[] = new double[N]; for (int i=0; i<N; i++) y[i] = x[i]; return y; } private static void CopyVector(double B[], double A[]) { int N = A.length; for (int i=0; i<N; i++) B[i] = A[i]; } private static double normabs(double x[], double y[]) { int N = x.length; double sum = 0.0; for (int i=0; i<N; i++) sum += Math.abs(x[i]-y[i]); return sum; } public static void CopyMatrix(double B[][], double A[][]) { int M = A.length; int N = A[0].length; int remainder = N & 3; // N mod 4; for (int i=0; i<M; i++) { double Bi[] = B[i]; double Ai[] = A[i]; for (int j=0; j<remainder; j++) Bi[j] = Ai[j]; for (int j=remainder; j<N; j+=4) { Bi[j] = Ai[j]; Bi[j+1] = Ai[j+1]; Bi[j+2] = Ai[j+2]; Bi[j+3] = Ai[j+3]; } } } public static double[][] RandomMatrix(int M, int N, Random R) { double A[][] = new double[M][N]; for (int i=0; i<N; i++) for (int j=0; j<N; j++) A[i][j] = R.nextDouble(); return A; } public static double[] RandomVector(int N, Random R) { double A[] = new double[N]; for (int i=0; i<N; i++) A[i] = R.nextDouble(); return A; } private static double[] matvec(double A[][], double x[]) { int N = x.length; double y[] = new double[N]; matvec(A, x, y); return y; } private static void matvec(double A[][], double x[], double y[]) { int M = A.length; int N = A[0].length; for (int i=0; i<M; i++) { double sum = 0.0; double Ai[] = A[i]; for (int j=0; j<N; j++) sum += Ai[j] * x[j]; y[i] = sum; } } }
mit
madgik/exareme
Exareme-Docker/src/exareme/exareme-worker/src/main/java/madgik/exareme/worker/art/container/job/TableTransferJob.java
667
/** * Copyright MaDgIK Group 2010 - 2015. */ package madgik.exareme.worker.art.container.job; import madgik.exareme.worker.art.container.ContainerJob; import madgik.exareme.worker.art.container.ContainerJobType; import madgik.exareme.worker.art.executionEngine.session.PlanSessionReportID; /** * @author heraldkllapi */ public class TableTransferJob implements ContainerJob { public final PlanSessionReportID sessionReportID; public TableTransferJob(PlanSessionReportID sessionReportID) { this.sessionReportID = sessionReportID; } @Override public ContainerJobType getType() { return ContainerJobType.dataTransfer; } }
mit
MeilCli/Twitter4Holo
library/src/main/java/com/twitter/meil_mitu/twitter4holo/api/help/Tos.java
1064
package com.twitter.meil_mitu.twitter4holo.api.help; import com.twitter.meil_mitu.twitter4holo.AbsGet; import com.twitter.meil_mitu.twitter4holo.AbsOauth; import com.twitter.meil_mitu.twitter4holo.ITwitterJsonConverter; import com.twitter.meil_mitu.twitter4holo.OauthType; import com.twitter.meil_mitu.twitter4holo.ResponseData; import com.twitter.meil_mitu.twitter4holo.data.TosResult; import com.twitter.meil_mitu.twitter4holo.exception.Twitter4HoloException; public class Tos extends AbsGet<ITwitterJsonConverter>{ public Tos(AbsOauth oauth, ITwitterJsonConverter json){ super(oauth, json); } @Override public String url(){ return "https://api.twitter.com/1.1/help/tos.json"; } @Override public int allowOauthType(){ return OauthType.Oauth1 | OauthType.Oauth2; } @Override public boolean isAuthorization(){ return true; } @Override public ResponseData<TosResult> call() throws Twitter4HoloException{ return Json.toTosResultResponseData(Oauth.get(this)); } }
mit
doubleirish/mybatis-spring-boot
src/main/java/com/example/dao/PublisherMapper.java
683
package com.example.dao; import com.example.model.Publisher; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import java.util.List; @Mapper public interface PublisherMapper { @Select("SELECT *, PHONE as phoneNumber from PUBLISHERS") //SQL List<Publisher> findAll(); // === DB === // CREATE TABLE IF NOT EXISTS PUBLISHERS ( // ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY // ,NAME VARCHAR(255) NOT NULL CONSTRAINT PUBLISHERS_NAME_UC UNIQUE // ,PHONE VARCHAR(30)); // === Model === // public class Publisher { // private Integer id ; // private String name; // private String phoneNumber; }
mit
XilongPei/Openparts
Openparts-framework/src/main/java/com/cnpc/framework/utils/FreeMarkerUtil.java
3038
package com.cnpc.framework.utils; import com.cnpc.framework.base.pojo.GenerateSetting; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; import freemarker.template.TemplateException; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import java.io.*; public class FreeMarkerUtil { /** * 获取模板路径 * * @param templateName * 模板名称(含后缀名) * @return * @throws IOException */ public static String getTemplatePath(String templateName) throws IOException { Resource res = FreeMarkerUtil.getResource(templateName); return res.getFile().getPath(); } /** * 获取模板资源 * * @param templateName * 模板名称(含后缀名) * @return Resource */ public static Resource getResource(String templateName) { ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource res = resolver.getResource("/template/" + templateName); return res; } /** * 获取模板 * * @param templateName * 模板名称(含后缀名) * @return Template * @throws IOException */ public static Template getTemplate(String templateName) throws IOException { Configuration cfg = new Configuration(); Template temp = null; File tmpRootFile = getResource(templateName).getFile().getParentFile(); if (tmpRootFile == null) { throw new RuntimeException("无法取得模板根路径!"); } try { cfg.setDefaultEncoding("utf-8"); cfg.setOutputEncoding("utf-8"); cfg.setDirectoryForTemplateLoading(tmpRootFile); /* cfg.setDirectoryForTemplateLoading(getResourceURL()); */ cfg.setObjectWrapper(new DefaultObjectWrapper()); temp = cfg.getTemplate(templateName); } catch (IOException e) { e.printStackTrace(); } return temp; } /** * 根据freemark模板生成文件 * * @param templateName * 模板名称(含后缀名) * @param filePath * 生成文件路径 * @param setting * 参数 */ public static void generateFile(String templateName, String filePath, GenerateSetting setting) throws TemplateException, IOException { Writer writer = null; Template template = getTemplate(templateName); // Windows/Linux // String dir = filePath.substring(0, filePath.lastIndexOf("\\")); String dir = filePath.substring(0, filePath.lastIndexOf("/")); File fdir = new File(dir); if (!fdir.exists()) { if (!fdir.mkdirs()) { System.out.println("创建目录" + fdir.getAbsolutePath() + "失败"); return; } } File file = new File(filePath); if(file.exists()) file.delete(); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8")); template.setEncoding("utf-8"); template.process(setting, writer); writer.flush(); writer.close(); } }
mit
tornaia/hr2
hr2-java-parent/hr2-backend-impl/src/test/java/test/unit/hu/interconnect/hr/module/personaldata/vacations/SzabadsagokatOsszefuggoFelhasznaltSzabadnapReszletekkeKonvertaloTest.java
21192
package test.unit.hu.interconnect.hr.module.personaldata.vacations; import static com.google.common.collect.Lists.newArrayList; import static hu.interconnect.hr.backend.api.enumeration.KivetelnapTipus.MUNKANAP; import static hu.interconnect.hr.backend.api.enumeration.KivetelnapTipus.PIHENONAP; import static java.util.Arrays.asList; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.List; import org.junit.Test; import hu.interconnect.hr.backend.api.dto.SzabadsagFelhasznalasResponseDTO; import hu.interconnect.hr.domain.Kivetelnap; import hu.interconnect.hr.domain.Szabadsag; import hu.interconnect.hr.module.exceptiondays.KivetelnapokHelper; import hu.interconnect.hr.module.personaldata.vacations.SzabadsagokatOsszefuggoFelhasznaltSzabadnapReszletekkeKonvertalo; import test.builder.KivetelnapBuilder; import test.builder.SzabadsagBuilder; import test.builder.SzemelyitorzsBuilder; import test.matcher.SzabadsagFelhasznalasResponseDTOMatcher; import test.unit.AbstractBackendUnitTest; public class SzabadsagokatOsszefuggoFelhasznaltSzabadnapReszletekkeKonvertaloTest extends AbstractBackendUnitTest { private SzabadsagokatOsszefuggoFelhasznaltSzabadnapReszletekkeKonvertalo konvertalo = new SzabadsagokatOsszefuggoFelhasznaltSzabadnapReszletekkeKonvertalo(new KivetelnapokHelper(new ArrayList<Kivetelnap>())); @Test public void nullIllegalArgumentExceptiontDob() { try { konvertalo.konvertal(null); fail(); } catch (IllegalArgumentException e) { assertEquals(e.getLocalizedMessage(), "A bemeno parameter null!"); } } @Test public void uresListaUresetAdVissza() { List<SzabadsagFelhasznalasResponseDTO> kapottReszletek = konvertalo.konvertal(new ArrayList<Szabadsag>()); assertThat(kapottReszletek, hasSize(0)); } @Test public void egyElemuListaEgyelemetAdVissza() { List<SzabadsagFelhasznalasResponseDTO> kapottReszletek = konvertalo.konvertal(newArrayList( new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.03").letrehoz())); SzabadsagFelhasznalasResponseDTOMatcher elvartReszletek = new SzabadsagFelhasznalasResponseDTOMatcher() .tsz(1) .kezdet("2012.12.03") .veg("2012.12.03") .munkanapokSzama(1); assertThat(kapottReszletek, contains(elvartReszletek)); } @Test public void ketEgymasMellettiElemOsszevonodikHaAKetNapKetEgymastKovetkoHetkoznapok() { List<SzabadsagFelhasznalasResponseDTO> kapottReszletek = konvertalo.konvertal(newArrayList( new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.03").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.04").letrehoz())); SzabadsagFelhasznalasResponseDTOMatcher elvartReszletek = new SzabadsagFelhasznalasResponseDTOMatcher() .tsz(1) .kezdet("2012.12.03") .veg("2012.12.04") .munkanapokSzama(2); assertThat(kapottReszletek, contains(elvartReszletek)); } @Test public void ketEgymasMellettiElemOsszevonodikHaAKetNapKozottHetvegeVan() { List<SzabadsagFelhasznalasResponseDTO> kapottReszletek = konvertalo.konvertal(newArrayList( new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.07").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.10").letrehoz())); SzabadsagFelhasznalasResponseDTOMatcher elvartReszletek = new SzabadsagFelhasznalasResponseDTOMatcher() .tsz(1) .kezdet("2012.12.07") .veg("2012.12.10") .munkanapokSzama(2); assertThat(kapottReszletek, contains(elvartReszletek)); } @Test public void csutortokEsPentekOsszevonodikDeAHetvegeNemAdodikHozza() { List<SzabadsagFelhasznalasResponseDTO> kapottReszletek = konvertalo.konvertal(newArrayList( new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.06").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.07").letrehoz())); SzabadsagFelhasznalasResponseDTOMatcher elvartReszletek = new SzabadsagFelhasznalasResponseDTOMatcher() .tsz(1) .kezdet("2012.12.06") .veg("2012.12.07") .munkanapokSzama(2); assertThat(kapottReszletek, contains(elvartReszletek)); } @Test public void hetfotolPentekigOsszevonodikDeAHetvegeNemAdodikHozza() { List<SzabadsagFelhasznalasResponseDTO> kapottReszletek = konvertalo.konvertal(newArrayList( new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.03").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.04").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.05").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.06").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.07").letrehoz())); SzabadsagFelhasznalasResponseDTOMatcher elvartReszletek = new SzabadsagFelhasznalasResponseDTOMatcher() .tsz(1) .kezdet("2012.12.03") .veg("2012.12.07") .munkanapokSzama(5); assertThat(kapottReszletek, contains(elvartReszletek)); } @Test public void pentekEsKovetkezoHetKedd() { List<SzabadsagFelhasznalasResponseDTO> kapottReszletek = konvertalo.konvertal(newArrayList( new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.07").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.11").letrehoz())); SzabadsagFelhasznalasResponseDTOMatcher elvartReszletek1 = new SzabadsagFelhasznalasResponseDTOMatcher() .tsz(1) .kezdet("2012.12.07") .veg("2012.12.07") .munkanapokSzama(1); SzabadsagFelhasznalasResponseDTOMatcher elvartReszletek2 = new SzabadsagFelhasznalasResponseDTOMatcher() .tsz(1) .kezdet("2012.12.11") .veg("2012.12.11") .munkanapokSzama(1); assertThat(kapottReszletek, contains(asList(elvartReszletek1, elvartReszletek2))); } @Test public void pentekEsKovetkezoHetKeddEsAHetvegeNormalisAHetfoPedigPihenonap() { KivetelnapokHelper kivetelnapok = new KivetelnapokHelper(newArrayList(new KivetelnapBuilder() .datum("2012.12.10") .tipus(PIHENONAP) .letrehoz())); konvertalo = new SzabadsagokatOsszefuggoFelhasznaltSzabadnapReszletekkeKonvertalo(kivetelnapok); List<SzabadsagFelhasznalasResponseDTO> kapottReszletek = konvertalo.konvertal(newArrayList( new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.07").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.11").letrehoz())); SzabadsagFelhasznalasResponseDTOMatcher elvartReszletek = new SzabadsagFelhasznalasResponseDTOMatcher() .tsz(1) .kezdet("2012.12.07") .veg("2012.12.11") .munkanapokSzama(2); assertThat(kapottReszletek, contains(elvartReszletek)); } @Test public void bugfix() { KivetelnapokHelper kivetelnapok = new KivetelnapokHelper(newArrayList(new KivetelnapBuilder() .datum("2012.03.16") .tipus(PIHENONAP) .letrehoz())); konvertalo = new SzabadsagokatOsszefuggoFelhasznaltSzabadnapReszletekkeKonvertalo(kivetelnapok); List<SzabadsagFelhasznalasResponseDTO> kapottReszletek = konvertalo.konvertal(newArrayList( new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.01").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.02").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.05").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.06").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.07").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.08").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.15").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.19").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.20").letrehoz())); SzabadsagFelhasznalasResponseDTOMatcher elvartReszletek1 = new SzabadsagFelhasznalasResponseDTOMatcher() .tsz(1) .kezdet("2012.03.01") .veg("2012.03.08") .munkanapokSzama(6); SzabadsagFelhasznalasResponseDTOMatcher elvartReszletek2 = new SzabadsagFelhasznalasResponseDTOMatcher() .tsz(1) .kezdet("2012.03.15") .veg("2012.03.20") .munkanapokSzama(3); assertThat(kapottReszletek, contains(asList(elvartReszletek1, elvartReszletek2))); } @Test public void vasarnapMunkanappaTeveEsErreSzabadsagKiveve() { KivetelnapokHelper kivetelnapok = new KivetelnapokHelper(newArrayList(new KivetelnapBuilder() .datum("2012.12.23") .tipus(MUNKANAP) .letrehoz())); konvertalo = new SzabadsagokatOsszefuggoFelhasznaltSzabadnapReszletekkeKonvertalo(kivetelnapok); List<SzabadsagFelhasznalasResponseDTO> kapottReszletek = konvertalo.konvertal(newArrayList( new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.23").letrehoz())); SzabadsagFelhasznalasResponseDTOMatcher elvartReszletek = new SzabadsagFelhasznalasResponseDTOMatcher() .tsz(1) .kezdet("2012.12.23") .veg("2012.12.23") .munkanapokSzama(1); assertThat(kapottReszletek, contains(asList(elvartReszletek))); } @Test public void bugfix2() { List<SzabadsagFelhasznalasResponseDTO> eredmeny = konvertalo.konvertal(newArrayList( new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2013.01.15").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2013.01.16").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2013.01.17").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2013.01.18").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2013.01.21").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2013.01.22").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2013.01.23").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2013.01.28").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2013.01.29").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2013.01.30").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2013.01.31").letrehoz())); SzabadsagFelhasznalasResponseDTOMatcher elvartReszletek1 = new SzabadsagFelhasznalasResponseDTOMatcher() .tsz(1) .kezdet("2013.01.15") .veg("2013.01.23") .munkanapokSzama(7); SzabadsagFelhasznalasResponseDTOMatcher elvartReszletek2 = new SzabadsagFelhasznalasResponseDTOMatcher() .tsz(1) .kezdet("2013.01.28") .veg("2013.01.31") .munkanapokSzama(4); assertThat(eredmeny, contains(asList(elvartReszletek1, elvartReszletek2))); } @Test public void bugfix3() { KivetelnapokHelper kivetelnapok = new KivetelnapokHelper(newArrayList(new KivetelnapBuilder() .datum("2012.03.16") .tipus(PIHENONAP) .letrehoz(), new KivetelnapBuilder() .datum("2012.03.24") .tipus(MUNKANAP) .letrehoz()) ); konvertalo = new SzabadsagokatOsszefuggoFelhasznaltSzabadnapReszletekkeKonvertalo(kivetelnapok); List<SzabadsagFelhasznalasResponseDTO> eredmeny = konvertalo.konvertal(newArrayList( new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.01").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.02").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.05").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.06").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.07").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.08").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.09").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.12").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.13").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.14").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.15").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.19").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.20").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.21").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.22").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.23").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.24").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.26").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.27").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.28").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.29").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.30").letrehoz())); SzabadsagFelhasznalasResponseDTOMatcher elvartReszletek = new SzabadsagFelhasznalasResponseDTOMatcher() .tsz(1) .kezdet("2012.03.01") .veg("2012.03.30") .munkanapokSzama(22); assertThat(eredmeny, contains(elvartReszletek)); } }
mit
Caaz/danmaku-class-project
Grid.java
1391
public class Grid { public Tile array[][] = new Tile[10][8]; public Grid() { // for(int y = 0; y < getHeight(); y++) { for(int x = 0; x < getWidth(); x++) { array[x][y] = new Tile(); } } } public int getWidth() { return 9; } public int getHeight() { return 7; } public Tile getTile(int x, int y) { Tile mytile = new Tile(); try { //System.out.println("Actual tile returned"); mytile = array[x][y]; } catch(ArrayIndexOutOfBoundsException e) { //System.out.println("Out of bounds tile"); } finally { //System.out.println("Returning false tile"); return mytile; } } public void makeHole() { for(int y = 0; y < getHeight(); y++) { for(int x = 0; x < getWidth(); x++) { if(((y == 1) || (y == 5)) && (x>=3) && (x<=6)) { array[x][y].visible = false; } if(((y == 2) || (y == 4)) && (x>=2) && (x<=6)) { array[x][y].visible = false; } if((y == 3) && (x>=2) && (x<=7)) { array[x][y].visible = false; } } } } public void makeHolierHole() { for(int y = 0; y < getHeight(); y++) { for(int x = 0; x < getWidth(); x++) { if((x >= 1+y%2) && (x <= 5+y%2)) { array[x][y].visible = false; } } } } }
mit
venanciolm/afirma-ui-miniapplet_x_x
afirma_ui_miniapplet/src/main/java/org/apache/oro/text/regex/Perl5Matcher.java
62090
/* * $Id: Perl5Matcher.java,v 1.27 2003/11/07 20:16:25 dfs Exp $ * * ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation", "Jakarta-Oro" * must not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache" * or "Jakarta-Oro", nor may "Apache" or "Jakarta-Oro" appear in their * name, without prior written permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.oro.text.regex; import java.util.Stack; /** * The Perl5Matcher class is used to match regular expressions (conforming to * the Perl5 regular expression syntax) generated by Perl5Compiler. * <p> * Perl5Compiler and Perl5Matcher are designed with the intent that you use a * separate instance of each per thread to avoid the overhead of both * synchronization and concurrent access (e.g., a match that takes a long time * in one thread will block the progress of another thread with a shorter * match). If you want to use a single instance of each in a concurrent program, * you must appropriately protect access to the instances with critical * sections. If you want to share Perl5Pattern instances between concurrently * executing instances of Perl5Matcher, you must compile the patterns with * {@link Perl5Compiler#READ_ONLY_MASK}. * * @since 1.0 * @see PatternMatcher * @see Perl5Compiler */ public final class Perl5Matcher implements PatternMatcher { private static final char __EOS = Character.MAX_VALUE; private static final int __INITIAL_NUM_OFFSETS = 20; private final boolean __multiline = false; private boolean __lastSuccess = false; private boolean __caseInsensitive = false; private char __previousChar, __input[], __originalInput[]; private Perl5Repetition __currentRep; private int __numParentheses, __bol, __eol, __currentOffset, __endOffset; private char[] __program; private int __expSize, __inputOffset, __lastParen; private int[] __beginMatchOffsets, __endMatchOffsets; private final Stack<int[]> __stack = new Stack<int[]>(); private Perl5MatchResult __lastMatchResult = null; private static boolean __compare(final char[] s1, final int s1off, final char[] s2, final int s2off, final int n) { int s2Offs = s2off; int s1Offs = s1off; int cnt; for (cnt = 0; cnt < n; cnt++, s1Offs++, s2Offs++) { if (s1Offs >= s1.length) { return false; } if (s2Offs >= s2.length) { return false; } if (s1[s1Offs] != s2[s2Offs]) { return false; } } return true; } private static int __findFirst(final char[] input, final int curr, final int endOffset, final char[] mustString) { int current = curr; int count, saveCurrent; char ch; if (input.length == 0) { return endOffset; } ch = mustString[0]; // Find the offset of the first character of the must string while (current < endOffset) { if (ch == input[current]) { saveCurrent = current; count = 0; while (current < endOffset && count < mustString.length) { if (mustString[count] != input[current]) { break; } ++count; ++current; } current = saveCurrent; if (count >= mustString.length) { break; } } ++current; } return current; } private void __pushState(final int parenFloor) { int[] state; int stateEntries, paren; stateEntries = 3 * (this.__expSize - parenFloor); if (stateEntries <= 0) { state = new int[3]; } else { state = new int[stateEntries + 3]; } state[0] = this.__expSize; state[1] = this.__lastParen; state[2] = this.__inputOffset; for (paren = this.__expSize; paren > parenFloor; --paren, stateEntries -= 3) { state[stateEntries] = this.__endMatchOffsets[paren]; state[stateEntries + 1] = this.__beginMatchOffsets[paren]; state[stateEntries + 2] = paren; } this.__stack.push(state); } private void __popState() { int[] state; int entry, paren; state = this.__stack.pop(); this.__expSize = state[0]; this.__lastParen = state[1]; this.__inputOffset = state[2]; for (entry = 3; entry < state.length; entry += 3) { paren = state[entry + 2]; this.__beginMatchOffsets[paren] = state[entry + 1]; if (paren <= this.__lastParen) { this.__endMatchOffsets[paren] = state[entry]; } } for (paren = this.__lastParen + 1; paren <= this.__numParentheses; paren++) { if (paren > this.__expSize) { this.__beginMatchOffsets[paren] = OpCode._NULL_OFFSET; } this.__endMatchOffsets[paren] = OpCode._NULL_OFFSET; } } // Initialize globals needed before calling __tryExpression for first time private void __initInterpreterGlobals(final Perl5Pattern expression, final char[] input, final int beginOffset, final int endOff, final int currentOffset) { int endOffset = endOff; // Remove this hack after more efficient case-folding and unicode // character classes are implemented this.__caseInsensitive = expression._isCaseInsensitive; this.__input = input; this.__endOffset = endOffset; this.__currentRep = new Perl5Repetition(); this.__currentRep._numInstances = 0; this.__currentRep._lastRepetition = null; this.__program = expression._program; this.__stack.setSize(0); // currentOffset should always be >= beginOffset and should // always be equal to zero when beginOffset equals 0, but we // make a weak attempt to protect against a violation of this // precondition if (currentOffset == beginOffset || currentOffset <= 0) { this.__previousChar = '\n'; } else { this.__previousChar = input[currentOffset - 1]; if (!this.__multiline && this.__previousChar == '\n') { this.__previousChar = '\0'; } } this.__numParentheses = expression._numParentheses; this.__currentOffset = currentOffset; this.__bol = beginOffset; this.__eol = endOffset; // Ok, here we're using endOffset as a temporary variable. endOffset = this.__numParentheses + 1; if (this.__beginMatchOffsets == null || endOffset > this.__beginMatchOffsets.length) { if (endOffset < __INITIAL_NUM_OFFSETS) { endOffset = __INITIAL_NUM_OFFSETS; } this.__beginMatchOffsets = new int[endOffset]; this.__endMatchOffsets = new int[endOffset]; } } // Set the match result information. Only call this if we successfully // matched. private void __setLastMatchResult() { int offs, maxEndOffs = 0; // endOffset+=dontTry; this.__lastMatchResult = new Perl5MatchResult(this.__numParentheses + 1); // This can happen when using Perl5StreamInput if (this.__endMatchOffsets[0] > this.__originalInput.length) { throw new ArrayIndexOutOfBoundsException(); } this.__lastMatchResult._matchBeginOffset = this.__beginMatchOffsets[0]; while (this.__numParentheses >= 0) { offs = this.__beginMatchOffsets[this.__numParentheses]; if (offs >= 0) { this.__lastMatchResult._beginGroupOffset[this.__numParentheses] = offs - this.__lastMatchResult._matchBeginOffset; } else { this.__lastMatchResult._beginGroupOffset[this.__numParentheses] = OpCode._NULL_OFFSET; } offs = this.__endMatchOffsets[this.__numParentheses]; if (offs >= 0) { this.__lastMatchResult._endGroupOffset[this.__numParentheses] = offs - this.__lastMatchResult._matchBeginOffset; if (offs > maxEndOffs && offs <= this.__originalInput.length) { maxEndOffs = offs; } } else { this.__lastMatchResult._endGroupOffset[this.__numParentheses] = OpCode._NULL_OFFSET; } --this.__numParentheses; } this.__lastMatchResult._match = new String(this.__originalInput, this.__beginMatchOffsets[0], maxEndOffs - this.__beginMatchOffsets[0]); // Free up for garbage collection this.__originalInput = null; } // Expects to receive a valid regular expression program. No checking // is done to ensure validity. // __originalInput must be set before calling this method for // __lastMatchResult to be set correctly. // beginOffset marks the beginning of the string // currentOffset marks where to start the pattern search private boolean __interpret(final Perl5Pattern expression, final char[] input, final int beginOffset, final int endOff, final int currentOffset) { int endOffset = endOff; boolean success; int minLength = 0, dontTry = 0, offset; char ch, mustString[]; __initInterpreterGlobals(expression, input, beginOffset, endOffset, currentOffset); success = false; mustString = expression._mustString; _mainLoop: while (true) { if (mustString != null && ((expression._anchor & Perl5Pattern._OPT_ANCH) == 0 || (this.__multiline || (expression._anchor & Perl5Pattern._OPT_ANCH_MBOL) != 0) && expression._back >= 0)) { this.__currentOffset = __findFirst(this.__input, this.__currentOffset, endOffset, mustString); if (this.__currentOffset >= endOffset) { if ((expression._options & Perl5Compiler.READ_ONLY_MASK) == 0) { expression._mustUtility++; } success = false; break _mainLoop; } else if (expression._back >= 0) { this.__currentOffset -= expression._back; if (this.__currentOffset < currentOffset) { this.__currentOffset = currentOffset; } minLength = expression._back + mustString.length; } else if (!expression._isExpensive && (expression._options & Perl5Compiler.READ_ONLY_MASK) == 0 && --expression._mustUtility < 0) { // Be careful! The preceding logical expression is // constructed // so that mustUtility is only decremented if the expression // is // compiled without READ_ONLY_MASK. mustString = expression._mustString = null; this.__currentOffset = currentOffset; } else { this.__currentOffset = currentOffset; minLength = mustString.length; } } if ((expression._anchor & Perl5Pattern._OPT_ANCH) != 0) { if (this.__currentOffset == beginOffset && __tryExpression(beginOffset)) { success = true; break _mainLoop; } else if (this.__multiline || (expression._anchor & Perl5Pattern._OPT_ANCH_MBOL) != 0 || (expression._anchor & Perl5Pattern._OPT_IMPLICIT) != 0) { if (minLength > 0) { dontTry = minLength - 1; } endOffset -= dontTry; if (this.__currentOffset > currentOffset) { --this.__currentOffset; } while (this.__currentOffset < endOffset) { if (this.__input[this.__currentOffset++] == '\n') { if (this.__currentOffset < endOffset && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } } } } break _mainLoop; } if (expression._startString != null) { mustString = expression._startString; if ((expression._anchor & Perl5Pattern._OPT_SKIP) != 0) { ch = mustString[0]; while (this.__currentOffset < endOffset) { if (ch == this.__input[this.__currentOffset]) { if (__tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } ++this.__currentOffset; while (this.__currentOffset < endOffset && this.__input[this.__currentOffset] == ch) { ++this.__currentOffset; } } ++this.__currentOffset; } } else { while ((this.__currentOffset = __findFirst(this.__input, this.__currentOffset, endOffset, mustString)) < endOffset) { if (__tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } ++this.__currentOffset; } } break _mainLoop; } if ((offset = expression._startClassOffset) != OpCode._NULL_OFFSET) { boolean doEvery, tmp; char op; doEvery = (expression._anchor & Perl5Pattern._OPT_SKIP) == 0; if (minLength > 0) { dontTry = minLength - 1; } endOffset -= dontTry; tmp = true; switch (op = this.__program[offset]) { case OpCode._ANYOF: offset = OpCode._getOperand(offset); while (this.__currentOffset < endOffset) { ch = this.__input[this.__currentOffset]; if (ch < 256 && (this.__program[offset + (ch >> 4)] & 1 << (ch & 0xf)) == 0) { if (tmp && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } tmp = doEvery; } else { tmp = true; } ++this.__currentOffset; } break; case OpCode._ANYOFUN: case OpCode._NANYOFUN: offset = OpCode._getOperand(offset); while (this.__currentOffset < endOffset) { ch = this.__input[this.__currentOffset]; if (__matchUnicodeClass(ch, this.__program, offset, op)) { if (tmp && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } tmp = doEvery; } else { tmp = true; } ++this.__currentOffset; } break; case OpCode._BOUND: if (minLength > 0) { ++dontTry; --endOffset; } if (this.__currentOffset != beginOffset) { ch = this.__input[this.__currentOffset - 1]; tmp = OpCode._isWordCharacter(ch); } else { tmp = OpCode._isWordCharacter(this.__previousChar); } while (this.__currentOffset < endOffset) { ch = this.__input[this.__currentOffset]; if (tmp != OpCode._isWordCharacter(ch)) { tmp = !tmp; if (__tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } } ++this.__currentOffset; } if ((minLength > 0 || tmp) && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } break; case OpCode._NBOUND: if (minLength > 0) { ++dontTry; --endOffset; } if (this.__currentOffset != beginOffset) { ch = this.__input[this.__currentOffset - 1]; tmp = OpCode._isWordCharacter(ch); } else { tmp = OpCode._isWordCharacter(this.__previousChar); } while (this.__currentOffset < endOffset) { ch = this.__input[this.__currentOffset]; if (tmp != OpCode._isWordCharacter(ch)) { tmp = !tmp; } else if (__tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } ++this.__currentOffset; } if ((minLength > 0 || !tmp) && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } break; case OpCode._ALNUM: while (this.__currentOffset < endOffset) { ch = this.__input[this.__currentOffset]; if (OpCode._isWordCharacter(ch)) { if (tmp && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } tmp = doEvery; } else { tmp = true; } ++this.__currentOffset; } break; case OpCode._NALNUM: while (this.__currentOffset < endOffset) { ch = this.__input[this.__currentOffset]; if (!OpCode._isWordCharacter(ch)) { if (tmp && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } tmp = doEvery; } else { tmp = true; } ++this.__currentOffset; } break; case OpCode._SPACE: while (this.__currentOffset < endOffset) { if (Character .isWhitespace(this.__input[this.__currentOffset])) { if (tmp && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } tmp = doEvery; } else { tmp = true; } ++this.__currentOffset; } break; case OpCode._NSPACE: while (this.__currentOffset < endOffset) { if (!Character .isWhitespace(this.__input[this.__currentOffset])) { if (tmp && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } tmp = doEvery; } else { tmp = true; } ++this.__currentOffset; } break; case OpCode._DIGIT: while (this.__currentOffset < endOffset) { if (Character .isDigit(this.__input[this.__currentOffset])) { if (tmp && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } tmp = doEvery; } else { tmp = true; } ++this.__currentOffset; } break; case OpCode._NDIGIT: while (this.__currentOffset < endOffset) { if (!Character .isDigit(this.__input[this.__currentOffset])) { if (tmp && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } tmp = doEvery; } else { tmp = true; } ++this.__currentOffset; } break; default: break; } // end switch } else { if (minLength > 0) { dontTry = minLength - 1; } endOffset -= dontTry; do { if (__tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } } while (this.__currentOffset++ < endOffset); } break _mainLoop; } // end while this.__lastSuccess = success; this.__lastMatchResult = null; return success; } private boolean __matchUnicodeClass(final char code, final char __program1[], final int off, final char opcode) { int offset = off; boolean isANYOF = opcode == OpCode._ANYOFUN; while (__program1[offset] != OpCode._END) { if (__program1[offset] == OpCode._RANGE) { offset++; if (code >= __program1[offset] && code <= __program1[offset + 1]) { return isANYOF; } offset += 2; } else if (__program1[offset] == OpCode._ONECHAR) { offset++; if (__program1[offset++] == code) { return isANYOF; } } else { isANYOF = __program1[offset] == OpCode._OPCODE ? isANYOF : !isANYOF; offset++; switch (__program1[offset++]) { case OpCode._ALNUM: if (OpCode._isWordCharacter(code)) { return isANYOF; } break; case OpCode._NALNUM: if (!OpCode._isWordCharacter(code)) { return isANYOF; } break; case OpCode._SPACE: if (Character.isWhitespace(code)) { return isANYOF; } break; case OpCode._NSPACE: if (!Character.isWhitespace(code)) { return isANYOF; } break; case OpCode._DIGIT: if (Character.isDigit(code)) { return isANYOF; } break; case OpCode._NDIGIT: if (!Character.isDigit(code)) { return isANYOF; } break; case OpCode._ALNUMC: if (Character.isLetterOrDigit(code)) { return isANYOF; } break; case OpCode._ALPHA: if (Character.isLetter(code)) { return isANYOF; } break; case OpCode._BLANK: if (Character.isSpaceChar(code)) { return isANYOF; } break; case OpCode._CNTRL: if (Character.isISOControl(code)) { return isANYOF; } break; case OpCode._LOWER: if (Character.isLowerCase(code)) { return isANYOF; } // Remove this hack after more efficient case-folding and // unicode // character classes are implemented if (this.__caseInsensitive && Character.isUpperCase(code)) { return isANYOF; } break; case OpCode._UPPER: if (Character.isUpperCase(code)) { return isANYOF; } // Remove this hack after more efficient case-folding and // unicode // character classes are implemented if (this.__caseInsensitive && Character.isLowerCase(code)) { return isANYOF; } break; case OpCode._PRINT: if (Character.isSpaceChar(code)) { return isANYOF; } // Fall through to check if the character is alphanumeric, // or a punctuation mark. Printable characters are either // alphanumeric, punctuation marks, or spaces. //$FALL-THROUGH$ case OpCode._GRAPH: if (Character.isLetterOrDigit(code)) { return isANYOF; } // Fall through to check if the character is a punctuation // mark. // Graph characters are either alphanumeric or punctuation. //$FALL-THROUGH$ case OpCode._PUNCT: switch (Character.getType(code)) { case Character.DASH_PUNCTUATION: case Character.START_PUNCTUATION: case Character.END_PUNCTUATION: case Character.CONNECTOR_PUNCTUATION: case Character.OTHER_PUNCTUATION: case Character.MATH_SYMBOL: case Character.CURRENCY_SYMBOL: case Character.MODIFIER_SYMBOL: return isANYOF; default: break; } break; case OpCode._XDIGIT: if (code >= '0' && code <= '9' || code >= 'a' && code <= 'f' || code >= 'A' && code <= 'F') { return isANYOF; } break; case OpCode._ASCII: if (code < 0x80) { return isANYOF; } break; default: return !isANYOF; } } } return !isANYOF; } private boolean __tryExpression(final int offset) { int count; this.__inputOffset = offset; this.__lastParen = 0; this.__expSize = 0; if (this.__numParentheses > 0) { for (count = 0; count <= this.__numParentheses; count++) { this.__beginMatchOffsets[count] = OpCode._NULL_OFFSET; this.__endMatchOffsets[count] = OpCode._NULL_OFFSET; } } if (__match(1)) { this.__beginMatchOffsets[0] = offset; this.__endMatchOffsets[0] = this.__inputOffset; return true; } return false; } private int __repeat(final int offset, final int max) { int scan, eol, operand, ret; char ch; char op; scan = this.__inputOffset; eol = this.__eol; if (max != Character.MAX_VALUE && max < eol - scan) { eol = scan + max; } operand = OpCode._getOperand(offset); switch (op = this.__program[offset]) { case OpCode._ANY: while (scan < eol && this.__input[scan] != '\n') { ++scan; } break; case OpCode._SANY: scan = eol; break; case OpCode._EXACTLY: ++operand; while (scan < eol && this.__program[operand] == this.__input[scan]) { ++scan; } break; case OpCode._ANYOF: if (scan < eol && (ch = this.__input[scan]) < 256) { while (ch < 256 && (this.__program[operand + (ch >> 4)] & 1 << (ch & 0xf)) == 0) { if (++scan < eol) { ch = this.__input[scan]; } else { break; } } } break; case OpCode._ANYOFUN: case OpCode._NANYOFUN: if (scan < eol) { ch = this.__input[scan]; while (__matchUnicodeClass(ch, this.__program, operand, op)) { if (++scan < eol) { ch = this.__input[scan]; } else { break; } } } break; case OpCode._ALNUM: while (scan < eol && OpCode._isWordCharacter(this.__input[scan])) { ++scan; } break; case OpCode._NALNUM: while (scan < eol && !OpCode._isWordCharacter(this.__input[scan])) { ++scan; } break; case OpCode._SPACE: while (scan < eol && Character.isWhitespace(this.__input[scan])) { ++scan; } break; case OpCode._NSPACE: while (scan < eol && !Character.isWhitespace(this.__input[scan])) { ++scan; } break; case OpCode._DIGIT: while (scan < eol && Character.isDigit(this.__input[scan])) { ++scan; } break; case OpCode._NDIGIT: while (scan < eol && !Character.isDigit(this.__input[scan])) { ++scan; } break; default: break; } ret = scan - this.__inputOffset; this.__inputOffset = scan; return ret; } private boolean __match(final int offset) { char nextChar, op; int scan, next, input, maxScan, current, line, arg; boolean inputRemains = true, minMod = false; Perl5Repetition rep; input = this.__inputOffset; inputRemains = input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; scan = offset; maxScan = this.__program.length; while (scan < maxScan /* && scan > 0 */) { next = OpCode._getNext(this.__program, scan); switch (op = this.__program[scan]) { case OpCode._BOL: if (input == this.__bol ? this.__previousChar == '\n' : this.__multiline) { break; } return false; case OpCode._MBOL: if (input == this.__bol ? this.__previousChar == '\n' : (inputRemains || input < this.__eol) && this.__input[input - 1] == '\n') { break; } return false; case OpCode._SBOL: if (input == this.__bol && this.__previousChar == '\n') { break; } return false; case OpCode._GBOL: if (input == this.__bol) { break; } return true; case OpCode._EOL: if ((inputRemains || input < this.__eol) && nextChar != '\n') { return false; } if (!this.__multiline && this.__eol - input > 1) { return false; } break; case OpCode._MEOL: if ((inputRemains || input < this.__eol) && nextChar != '\n') { return false; } break; case OpCode._SEOL: if ((inputRemains || input < this.__eol) && nextChar != '\n') { return false; } if (this.__eol - input > 1) { return false; } break; case OpCode._SANY: if (!inputRemains && input >= this.__eol) { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._ANY: if (!inputRemains && input >= this.__eol || nextChar == '\n') { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._EXACTLY: current = OpCode._getOperand(scan); line = this.__program[current++]; if (this.__program[current] != nextChar) { return false; } if (this.__eol - input < line) { return false; } if (line > 1 && !__compare(this.__program, current, this.__input, input, line)) { return false; } input += line; inputRemains = input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._ANYOF: current = OpCode._getOperand(scan); if (nextChar == __EOS && inputRemains) { nextChar = this.__input[input]; } if (nextChar >= 256 || (this.__program[current + (nextChar >> 4)] & 1 << (nextChar & 0xf)) != 0) { return false; } if (!inputRemains && input >= this.__eol) { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._ANYOFUN: case OpCode._NANYOFUN: current = OpCode._getOperand(scan); if (nextChar == __EOS && inputRemains) { nextChar = this.__input[input]; } if (!__matchUnicodeClass(nextChar, this.__program, current, op)) { return false; } if (!inputRemains && input >= this.__eol) { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._ALNUM: if (!inputRemains) { return false; } if (!OpCode._isWordCharacter(nextChar)) { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._NALNUM: if (!inputRemains && input >= this.__eol) { return false; } if (OpCode._isWordCharacter(nextChar)) { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._NBOUND: case OpCode._BOUND: boolean a, b; if (input == this.__bol) { a = OpCode._isWordCharacter(this.__previousChar); } else { a = OpCode._isWordCharacter(this.__input[input - 1]); } b = OpCode._isWordCharacter(nextChar); if (a == b == (this.__program[scan] == OpCode._BOUND)) { return false; } break; case OpCode._SPACE: if (!inputRemains && input >= this.__eol) { return false; } if (!Character.isWhitespace(nextChar)) { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._NSPACE: if (!inputRemains) { return false; } if (Character.isWhitespace(nextChar)) { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._DIGIT: if (!Character.isDigit(nextChar)) { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._NDIGIT: if (!inputRemains && input >= this.__eol) { return false; } if (Character.isDigit(nextChar)) { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._REF: arg = OpCode._getArg1(this.__program, scan); current = this.__beginMatchOffsets[arg]; if (current == OpCode._NULL_OFFSET) { return false; } if (this.__endMatchOffsets[arg] == OpCode._NULL_OFFSET) { return false; } if (current == this.__endMatchOffsets[arg]) { break; } if (this.__input[current] != nextChar) { return false; } line = this.__endMatchOffsets[arg] - current; if (input + line > this.__eol) { return false; } if (line > 1 && !__compare(this.__input, current, this.__input, input, line)) { return false; } input += line; inputRemains = input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._NOTHING: break; case OpCode._BACK: break; case OpCode._OPEN: arg = OpCode._getArg1(this.__program, scan); this.__beginMatchOffsets[arg] = input; if (arg > this.__expSize) { this.__expSize = arg; } break; case OpCode._CLOSE: arg = OpCode._getArg1(this.__program, scan); this.__endMatchOffsets[arg] = input; if (arg > this.__lastParen) { this.__lastParen = arg; } break; case OpCode._CURLYX: rep = new Perl5Repetition(); rep._lastRepetition = this.__currentRep; this.__currentRep = rep; rep._parenFloor = this.__lastParen; rep._numInstances = -1; rep._min = OpCode._getArg1(this.__program, scan); rep._max = OpCode._getArg2(this.__program, scan); rep._scan = OpCode._getNextOperator(scan) + 2; rep._next = next; rep._minMod = minMod; // Must initialize to -1 because if we initialize to 0 and are // at the beginning of the input the OpCode._WHILEM case will // not work right. rep._lastLocation = -1; this.__inputOffset = input; // use minMod as temporary minMod = __match(OpCode._getPrevOperator(next)); // leave scope call not pertinent? this.__currentRep = rep._lastRepetition; return minMod; case OpCode._WHILEM: rep = this.__currentRep; arg = rep._numInstances + 1; this.__inputOffset = input; if (input == rep._lastLocation) { this.__currentRep = rep._lastRepetition; line = this.__currentRep._numInstances; if (__match(rep._next)) { return true; } this.__currentRep._numInstances = line; this.__currentRep = rep; return false; } if (arg < rep._min) { rep._numInstances = arg; rep._lastLocation = input; if (__match(rep._scan)) { return true; } rep._numInstances = arg - 1; return false; } if (rep._minMod) { this.__currentRep = rep._lastRepetition; line = this.__currentRep._numInstances; if (__match(rep._next)) { return true; } this.__currentRep._numInstances = line; this.__currentRep = rep; if (arg >= rep._max) { return false; } this.__inputOffset = input; rep._numInstances = arg; rep._lastLocation = input; if (__match(rep._scan)) { return true; } rep._numInstances = arg - 1; return false; } if (arg < rep._max) { __pushState(rep._parenFloor); rep._numInstances = arg; rep._lastLocation = input; if (__match(rep._scan)) { return true; } __popState(); this.__inputOffset = input; } this.__currentRep = rep._lastRepetition; line = this.__currentRep._numInstances; if (__match(rep._next)) { return true; } rep._numInstances = line; this.__currentRep = rep; rep._numInstances = arg - 1; return false; case OpCode._BRANCH: if (this.__program[next] != OpCode._BRANCH) { next = OpCode._getNextOperator(scan); } else { int lastParen; lastParen = this.__lastParen; do { this.__inputOffset = input; if (__match(OpCode._getNextOperator(scan))) { return true; } for (arg = this.__lastParen; arg > lastParen; --arg) { // __endMatchOffsets[arg] = 0; this.__endMatchOffsets[arg] = OpCode._NULL_OFFSET; } this.__lastParen = arg; scan = OpCode._getNext(this.__program, scan); } while (scan != OpCode._NULL_OFFSET && this.__program[scan] == OpCode._BRANCH); return false; } break; case OpCode._MINMOD: minMod = true; break; case OpCode._CURLY: case OpCode._STAR: case OpCode._PLUS: if (op == OpCode._CURLY) { line = OpCode._getArg1(this.__program, scan); arg = OpCode._getArg2(this.__program, scan); scan = OpCode._getNextOperator(scan) + 2; } else if (op == OpCode._STAR) { line = 0; arg = Character.MAX_VALUE; scan = OpCode._getNextOperator(scan); } else { line = 1; arg = Character.MAX_VALUE; scan = OpCode._getNextOperator(scan); } if (this.__program[next] == OpCode._EXACTLY) { nextChar = this.__program[OpCode._getOperand(next) + 1]; current = 0; } else { nextChar = __EOS; current = -1000; } this.__inputOffset = input; if (minMod) { minMod = false; if (line > 0 && __repeat(scan, line) < line) { return false; } while (arg >= line || arg == Character.MAX_VALUE && line > 0) { // there may be a bug here with respect to // __inputOffset >= __endOffset, but it seems to be // right for // now. the issue is with __inputOffset being reset // later. // is this test really supposed to happen here? if (current == -1000 || this.__inputOffset >= this.__endOffset || this.__input[this.__inputOffset] == nextChar) { if (__match(next)) { return true; } } this.__inputOffset = input + line; if (__repeat(scan, 1) != 0) { ++line; this.__inputOffset = input + line; } else { return false; } } } else { arg = __repeat(scan, arg); if (line < arg && OpCode._opType[this.__program[next]] == OpCode._EOL && (!this.__multiline && this.__program[next] != OpCode._MEOL || this.__program[next] == OpCode._SEOL)) { line = arg; } while (arg >= line) { // there may be a bug here with respect to // __inputOffset >= __endOffset, but it seems to be // right for // now. the issue is with __inputOffset being reset // later. // is this test really supposed to happen here? if (current == -1000 || this.__inputOffset >= this.__endOffset || this.__input[this.__inputOffset] == nextChar) { if (__match(next)) { return true; } } --arg; this.__inputOffset = input + arg; } } return false; case OpCode._SUCCEED: case OpCode._END: this.__inputOffset = input; // This enforces the rule that two consecutive matches cannot // have // the same end offset. if (this.__inputOffset == this.__lastMatchInputEndOffset) { return false; } return true; case OpCode._IFMATCH: this.__inputOffset = input; scan = OpCode._getNextOperator(scan); if (!__match(scan)) { return false; } break; case OpCode._UNLESSM: this.__inputOffset = input; scan = OpCode._getNextOperator(scan); if (__match(scan)) { return false; } break; default: // todo: Need to throw an exception here. } // end switch // scan = (next > 0 ? next : 0); scan = next; } // end while scan return false; } static char[] _toLower(final char[] in) { char[] input = in.clone(); int current; char[] inp; // todo: // Certainly not the best way to do case insensitive matching. // Must definitely change this in some way, but for now we // do what Perl does and make a copy of the input, converting // it all to lowercase. This is truly better handled in the // compilation phase. inp = new char[input.length]; System.arraycopy(input, 0, inp, 0, input.length); input = inp; // todo: Need to inline toLowerCase() for (current = 0; current < input.length; current++) { if (Character.isUpperCase(input[current])) { input[current] = Character.toLowerCase(input[current]); } } return input; } /** * Determines if a prefix of a string (represented as a char[]) matches a * given pattern, starting from a given offset into the string. If a prefix * of the string matches the pattern, a MatchResult instance representing * the match is made accesible via {@link #getMatch()}. * <p> * This method is useful for certain common token identification tasks that * are made more difficult without this functionality. * <p> * * @param in * The char[] to test for a prefix match. * @param pattern * The Pattern to be matched. * @param offset * The offset at which to start searching for the prefix. * @return True if input matches pattern, false otherwise. */ @Override public boolean matchesPrefix(final char[] in, final Pattern pattern, final int offset) { char[] input = in.clone(); final Perl5Pattern expression = (Perl5Pattern) pattern; this.__originalInput = input; if (expression._isCaseInsensitive) { input = _toLower(input); } __initInterpreterGlobals(expression, input, 0, input.length, offset); this.__lastSuccess = __tryExpression(offset); this.__lastMatchResult = null; return this.__lastSuccess; } /** * Determines if a prefix of a string (represented as a char[]) matches a * given pattern. If a prefix of the string matches the pattern, a * MatchResult instance representing the match is made accesible via * {@link #getMatch()}. * <p> * This method is useful for certain common token identification tasks that * are made more difficult without this functionality. * <p> * * @param input * The char[] to test for a prefix match. * @param pattern * The Pattern to be matched. * @return True if input matches pattern, false otherwise. */ @Override public boolean matchesPrefix(final char[] input, final Pattern pattern) { return matchesPrefix(input, pattern, 0); } /** * Determines if a prefix of a string matches a given pattern. If a prefix * of the string matches the pattern, a MatchResult instance representing * the match is made accesible via {@link #getMatch()}. * <p> * This method is useful for certain common token identification tasks that * are made more difficult without this functionality. * <p> * * @param input * The String to test for a prefix match. * @param pattern * The Pattern to be matched. * @return True if input matches pattern, false otherwise. */ @Override public boolean matchesPrefix(final String input, final Pattern pattern) { return matchesPrefix(input.toCharArray(), pattern, 0); } /** * Determines if a prefix of a PatternMatcherInput instance matches a given * pattern. If there is a match, a MatchResult instance representing the * match is made accesible via {@link #getMatch()}. Unlike the * {@link #contains(PatternMatcherInput, Pattern)} method, the current * offset of the PatternMatcherInput argument is not updated. However, * unlike the {@link #matches matches(PatternMatcherInput, Pattern)} method, * matchesPrefix() will start its search from the current offset rather than * the begin offset of the PatternMatcherInput. * <p> * This method is useful for certain common token identification tasks that * are made more difficult without this functionality. * <p> * * @param input * The PatternMatcherInput to test for a prefix match. * @param pattern * The Pattern to be matched. * @return True if input matches pattern, false otherwise. */ @Override public boolean matchesPrefix(final PatternMatcherInput input, final Pattern pattern) { char[] inp; Perl5Pattern expression; expression = (Perl5Pattern) pattern; this.__originalInput = input._originalBuffer; if (expression._isCaseInsensitive) { if (input._toLowerBuffer == null) { input._toLowerBuffer = _toLower(this.__originalInput); } inp = input._toLowerBuffer; } else { inp = this.__originalInput; } __initInterpreterGlobals(expression, inp, input._beginOffset, input._endOffset, input._currentOffset); this.__lastSuccess = __tryExpression(input._currentOffset); this.__lastMatchResult = null; return this.__lastSuccess; } /** * Determines if a string (represented as a char[]) exactly matches a given * pattern. If there is an exact match, a MatchResult instance representing * the match is made accesible via {@link #getMatch()}. The pattern must be * a Perl5Pattern instance, otherwise a ClassCastException will be thrown. * You are not required to, and indeed should NOT try to (for performance * reasons), catch a ClassCastException because it will never be thrown as * long as you use a Perl5Pattern as the pattern parameter. * <p> * <b>Note:</b> matches() is not the same as sticking a ^ in front of your * expression and a $ at the end of your expression in Perl5 and using the * =~ operator, even though in many cases it will be equivalent. matches() * literally looks for an exact match according to the rules of Perl5 * expression matching. Therefore, if you have a pattern <em>foo|foot</em> * and are matching the input <em>foot</em> it will not produce an exact * match. But <em>foot|foo</em> will produce an exact match for either * <em>foot</em> or <em>foo</em>. Remember, Perl5 regular expressions do not * match the longest possible match. From the perlre manpage: <blockquote> * Alternatives are tried from left to right, so the first alternative found * for which the entire expression matches, is the one that is chosen. This * means that alternatives are not necessarily greedy. For example: when * matching foo|foot against "barefoot", only the "foo" part will match, as * that is the first alternative tried, and it successfully matches the * target string. </blockquote> * <p> * * @param in * The char[] to test for an exact match. * @param pattern * The Perl5Pattern to be matched. * @return True if input matches pattern, false otherwise. * @exception ClassCastException * If a Pattern instance other than a Perl5Pattern is passed * as the pattern parameter. */ @Override public boolean matches(final char[] in, final Pattern pattern) { char[] input = in.clone(); final Perl5Pattern expression = (Perl5Pattern) pattern; this.__originalInput = input; if (expression._isCaseInsensitive) { input = _toLower(input); } __initInterpreterGlobals(expression, input, 0, input.length, 0); this.__lastSuccess = __tryExpression(0) && this.__endMatchOffsets[0] == input.length; this.__lastMatchResult = null; return this.__lastSuccess; } /** * Determines if a string exactly matches a given pattern. If there is an * exact match, a MatchResult instance representing the match is made * accesible via {@link #getMatch()}. The pattern must be a Perl5Pattern * instance, otherwise a ClassCastException will be thrown. You are not * required to, and indeed should NOT try to (for performance reasons), * catch a ClassCastException because it will never be thrown as long as you * use a Perl5Pattern as the pattern parameter. * <p> * <b>Note:</b> matches() is not the same as sticking a ^ in front of your * expression and a $ at the end of your expression in Perl5 and using the * =~ operator, even though in many cases it will be equivalent. matches() * literally looks for an exact match according to the rules of Perl5 * expression matching. Therefore, if you have a pattern <em>foo|foot</em> * and are matching the input <em>foot</em> it will not produce an exact * match. But <em>foot|foo</em> will produce an exact match for either * <em>foot</em> or <em>foo</em>. Remember, Perl5 regular expressions do not * match the longest possible match. From the perlre manpage: <blockquote> * Alternatives are tried from left to right, so the first alternative found * for which the entire expression matches, is the one that is chosen. This * means that alternatives are not necessarily greedy. For example: when * matching foo|foot against "barefoot", only the "foo" part will match, as * that is the first alternative tried, and it successfully matches the * target string. </blockquote> * <p> * * @param input * The String to test for an exact match. * @param pattern * The Perl5Pattern to be matched. * @return True if input matches pattern, false otherwise. * @exception ClassCastException * If a Pattern instance other than a Perl5Pattern is passed * as the pattern parameter. */ @Override public boolean matches(final String input, final Pattern pattern) { return matches(input.toCharArray(), pattern); } /** * Determines if the contents of a PatternMatcherInput instance exactly * matches a given pattern. If there is an exact match, a MatchResult * instance representing the match is made accesible via {@link #getMatch()} * . Unlike the {@link #contains(PatternMatcherInput, Pattern)} method, the * current offset of the PatternMatcherInput argument is not updated. You * should remember that the region between the begin (NOT the current) and * end offsets of the PatternMatcherInput will be tested for an exact match. * <p> * The pattern must be a Perl5Pattern instance, otherwise a * ClassCastException will be thrown. You are not required to, and indeed * should NOT try to (for performance reasons), catch a ClassCastException * because it will never be thrown as long as you use a Perl5Pattern as the * pattern parameter. * <p> * <b>Note:</b> matches() is not the same as sticking a ^ in front of your * expression and a $ at the end of your expression in Perl5 and using the * =~ operator, even though in many cases it will be equivalent. matches() * literally looks for an exact match according to the rules of Perl5 * expression matching. Therefore, if you have a pattern <em>foo|foot</em> * and are matching the input <em>foot</em> it will not produce an exact * match. But <em>foot|foo</em> will produce an exact match for either * <em>foot</em> or <em>foo</em>. Remember, Perl5 regular expressions do not * match the longest possible match. From the perlre manpage: <blockquote> * Alternatives are tried from left to right, so the first alternative found * for which the entire expression matches, is the one that is chosen. This * means that alternatives are not necessarily greedy. For example: when * matching foo|foot against "barefoot", only the "foo" part will match, as * that is the first alternative tried, and it successfully matches the * target string. </blockquote> * <p> * * @param input * The PatternMatcherInput to test for a match. * @param pattern * The Perl5Pattern to be matched. * @return True if input matches pattern, false otherwise. * @exception ClassCastException * If a Pattern instance other than a Perl5Pattern is passed * as the pattern parameter. */ @Override public boolean matches(final PatternMatcherInput input, final Pattern pattern) { char[] inp; Perl5Pattern expression; expression = (Perl5Pattern) pattern; this.__originalInput = input._originalBuffer; if (expression._isCaseInsensitive) { if (input._toLowerBuffer == null) { input._toLowerBuffer = _toLower(this.__originalInput); } inp = input._toLowerBuffer; } else { inp = this.__originalInput; } __initInterpreterGlobals(expression, inp, input._beginOffset, input._endOffset, input._beginOffset); this.__lastMatchResult = null; if (__tryExpression(input._beginOffset)) { if (this.__endMatchOffsets[0] == input._endOffset || input.length() == 0 || input._beginOffset == input._endOffset) { this.__lastSuccess = true; return true; } } this.__lastSuccess = false; return false; } /** * Determines if a string contains a pattern. If the pattern is matched by * some substring of the input, a MatchResult instance representing the <b> * first </b> such match is made acessible via {@link #getMatch()}. If you * want to access subsequent matches you should either use a * PatternMatcherInput object or use the offset information in the * MatchResult to create a substring representing the remaining input. Using * the MatchResult offset information is the recommended method of obtaining * the parts of the string preceeding the match and following the match. * <p> * The pattern must be a Perl5Pattern instance, otherwise a * ClassCastException will be thrown. You are not required to, and indeed * should NOT try to (for performance reasons), catch a ClassCastException * because it will never be thrown as long as you use a Perl5Pattern as the * pattern parameter. * <p> * * @param input * The String to test for a match. * @param pattern * The Perl5Pattern to be matched. * @return True if the input contains a pattern match, false otherwise. * @exception ClassCastException * If a Pattern instance other than a Perl5Pattern is passed * as the pattern parameter. */ @Override public boolean contains(final String input, final Pattern pattern) { return contains(input.toCharArray(), pattern); } /** * Determines if a string (represented as a char[]) contains a pattern. If * the pattern is matched by some substring of the input, a MatchResult * instance representing the <b> first </b> such match is made acessible via * {@link #getMatch()}. If you want to access subsequent matches you should * either use a PatternMatcherInput object or use the offset information in * the MatchResult to create a substring representing the remaining input. * Using the MatchResult offset information is the recommended method of * obtaining the parts of the string preceeding the match and following the * match. * <p> * The pattern must be a Perl5Pattern instance, otherwise a * ClassCastException will be thrown. You are not required to, and indeed * should NOT try to (for performance reasons), catch a ClassCastException * because it will never be thrown as long as you use a Perl5Pattern as the * pattern parameter. * <p> * * @param in * The char[] to test for a match. * @param pattern * The Perl5Pattern to be matched. * @return True if the input contains a pattern match, false otherwise. * @exception ClassCastException * If a Pattern instance other than a Perl5Pattern is passed * as the pattern parameter. */ @Override public boolean contains(final char[] in, final Pattern pattern) { char[] input = in.clone(); final Perl5Pattern expression = (Perl5Pattern) pattern; this.__originalInput = input; if (expression._isCaseInsensitive) { input = _toLower(input); } return __interpret(expression, input, 0, input.length, 0); } private static final int __DEFAULT_LAST_MATCH_END_OFFSET = -100; private int __lastMatchInputEndOffset = __DEFAULT_LAST_MATCH_END_OFFSET; /** * Determines if the contents of a PatternMatcherInput, starting from the * current offset of the input contains a pattern. If a pattern match is * found, a MatchResult instance representing the <b>first</b> such match is * made acessible via {@link #getMatch()}. The current offset of the * PatternMatcherInput is set to the offset corresponding to the end of the * match, so that a subsequent call to this method will continue searching * where the last call left off. You should remember that the region between * the begin and end offsets of the PatternMatcherInput are considered the * input to be searched, and that the current offset of the * PatternMatcherInput reflects where a search will start from. Matches * extending beyond the end offset of the PatternMatcherInput will not be * matched. In other words, a match must occur entirely between the begin * and end offsets of the input. See <code>PatternMatcherInput</code> for * more details. * <p> * As a side effect, if a match is found, the PatternMatcherInput match * offset information is updated. See the * <code>PatternMatcherInput.setMatchOffsets(int, int)</code> method for * more details. * <p> * The pattern must be a Perl5Pattern instance, otherwise a * ClassCastException will be thrown. You are not required to, and indeed * should NOT try to (for performance reasons), catch a ClassCastException * because it will never be thrown as long as you use a Perl5Pattern as the * pattern parameter. * <p> * This method is usually used in a loop as follows: <blockquote> * * <pre> * PatternMatcher matcher; * PatternCompiler compiler; * Pattern pattern; * PatternMatcherInput input; * MatchResult result; * * compiler = new Perl5Compiler(); * matcher = new Perl5Matcher(); * * try { * pattern = compiler.compile(somePatternString); * } catch (MalformedPatternException e) { * System.err.println(&quot;Bad pattern.&quot;); * System.err.println(e.getMessage()); * return; * } * * input = new PatternMatcherInput(someStringInput); * * while (matcher.contains(input, pattern)) { * result = matcher.getMatch(); * // Perform whatever processing on the result you want. * } * * </pre> * * </blockquote> * <p> * * @param input * The PatternMatcherInput to test for a match. * @param pattern * The Pattern to be matched. * @return True if the input contains a pattern match, false otherwise. * @exception ClassCastException * If a Pattern instance other than a Perl5Pattern is passed * as the pattern parameter. */ @Override public boolean contains(final PatternMatcherInput input, final Pattern pattern) { char[] inp; Perl5Pattern expression; boolean matchFound; // if(input.length() > 0) { // We want to allow a null string to match at the end of the input // which is why we don't check endOfInput. Not sure if this is a // safe thing to do or not. if (input._currentOffset > input._endOffset) { return false; } // } /* * else if(input._endOfInput()) return false; */ expression = (Perl5Pattern) pattern; this.__originalInput = input._originalBuffer; // Todo: // Really should only reduce to lowercase that part of the // input that is necessary, instead of the whole thing. // Adjust MatchResult offsets accordingly. Actually, pass an adjustment // value to __interpret. this.__originalInput = input._originalBuffer; if (expression._isCaseInsensitive) { if (input._toLowerBuffer == null) { input._toLowerBuffer = _toLower(this.__originalInput); } inp = input._toLowerBuffer; } else { inp = this.__originalInput; } this.__lastMatchInputEndOffset = input.getMatchEndOffset(); matchFound = __interpret(expression, inp, input._beginOffset, input._endOffset, input._currentOffset); if (matchFound) { input.setCurrentOffset(this.__endMatchOffsets[0]); input.setMatchOffsets(this.__beginMatchOffsets[0], this.__endMatchOffsets[0]); } else { input.setCurrentOffset(input._endOffset + 1); } // Restore so it doesn't interfere with other unrelated matches. this.__lastMatchInputEndOffset = __DEFAULT_LAST_MATCH_END_OFFSET; return matchFound; } /** * Fetches the last match found by a call to a matches() or contains() * method. If you plan on modifying the original search input, you must call * this method BEFORE you modify the original search input, as a lazy * evaluation technique is used to create the MatchResult. This reduces the * cost of pattern matching when you don't care about the actual match and * only care if the pattern occurs in the input. Otherwise, a MatchResult * would be created for every match found, whether or not the MatchResult * was later used by a call to getMatch(). * <p> * * @return A MatchResult instance containing the pattern match found by the * last call to any one of the matches() or contains() methods. If * no match was found by the last call, returns null. */ @Override public MatchResult getMatch() { if (!this.__lastSuccess) { return null; } if (this.__lastMatchResult == null) { __setLastMatchResult(); } return this.__lastMatchResult; } }
mit
aoq/resident-background-service
app/src/androidTest/java/com/aokyu/service/ApplicationTest.java
348
package com.aokyu.service; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
mit
UMM-CSci/Coding-dojos
PatientRecordsKata/IdParserTest.java
807
import static org.junit.Assert.*; import java.util.List; import org.junit.Test; public class IdParserTest { @Test public void testListParser() { String testMedList = "{1;3;9}"; List<Integer> ids = IdParser.parse(testMedList); assertEquals(3, ids.size()); assertEquals(new Integer(1), ids.get(0)); assertEquals(new Integer(3), ids.get(1)); assertEquals(new Integer(9), ids.get(2)); } @Test public void testEmptyListParser() { String testMedList = "{}"; List<Integer> ids = IdParser.parse(testMedList); assertEquals(0, ids.size()); } @Test public void testSingletonListParser() { String testMedList = "{1}"; List<Integer> ids = IdParser.parse(testMedList); assertEquals(1, ids.size()); assertEquals(new Integer(1), ids.get(0)); } }
mit
amritbhat786/DocIT
101repo/contributions/javawsServer/OneOhOneCompanies/src/org/softlang/service/company/Department.java
1240
package org.softlang.service.company; import java.io.Serializable; import java.util.LinkedList; import java.util.List; /** * A department has a name, a manager, employees, and subdepartments. */ public class Department implements Serializable { private static final long serialVersionUID = -2008895922177165250L; private String name; private Employee manager; private List<Department> subdepts = new LinkedList<Department>(); private List<Employee> employees = new LinkedList<Employee>(); public String getName() { return name; } public void setName(String name) { this.name = name; } public Employee getManager() { return manager; } public void setManager(Employee manager) { this.manager = manager; } public List<Department> getSubdepts() { return subdepts; } public List<Employee> getEmployees() { return employees; } public double total() { double total = 0; total += getManager().getSalary(); for (Department s : getSubdepts()) total += s.total(); for (Employee e : getEmployees()) total += e.getSalary(); return total; } public void cut() { getManager().cut(); for (Department s : getSubdepts()) s.cut(); for (Employee e : getEmployees()) e.cut(); } }
mit
francescafrontini/MWExtractor
src/multiword/package-info.java
262
/** * Contains methods for extracting/selecting final multiword candidates. * @author Valeria Quochi @author Francesca Frontini @author Francesco Rubino * Istituto di linguistica Computazionale "A. Zampolli" - CNR Pisa - Italy * */ package multiword;
mit
NathanJAdams/MeshIO
src/com/ripplargames/meshio/meshformats/ply/PlyVertexDataType.java
531
package com.ripplargames.meshio.meshformats.ply; import com.ripplargames.meshio.vertices.VertexType; public class PlyVertexDataType { private final VertexType vertexType; private final PlyDataType plyDataType; public PlyVertexDataType(VertexType vertexType, PlyDataType plyDataType) { this.vertexType = vertexType; this.plyDataType = plyDataType; } public VertexType vertexType() { return vertexType; } public PlyDataType plyDataType() { return plyDataType; } }
mit
nico01f/z-pec
ZimbraServer/src/java/com/zimbra/cs/util/SpamExtract.java
21891
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Server * Copyright (C) 2006, 2007, 2008, 2009, 2010 Zimbra, Inc. * * The contents of this file are subject to the Zimbra Public License * Version 1.3 ("License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.zimbra.com/license. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * ***** END LICENSE BLOCK ***** */ package com.zimbra.cs.util; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import java.util.Properties; import javax.mail.BodyPart; import javax.mail.MessagingException; import javax.mail.Part; import javax.mail.Session; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpState; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.protocol.Protocol; import com.zimbra.common.account.Key.AccountBy; import com.zimbra.common.httpclient.HttpClientUtil; import com.zimbra.common.localconfig.LC; import com.zimbra.common.service.ServiceException; import com.zimbra.common.soap.AccountConstants; import com.zimbra.common.soap.AdminConstants; import com.zimbra.common.soap.Element; import com.zimbra.common.soap.MailConstants; import com.zimbra.common.soap.SoapFaultException; import com.zimbra.common.soap.SoapHttpTransport; import com.zimbra.common.util.BufferStream; import com.zimbra.common.util.ByteUtil; import com.zimbra.common.util.CliUtil; import com.zimbra.common.util.Log; import com.zimbra.common.util.LogFactory; import com.zimbra.common.util.ZimbraCookie; import com.zimbra.common.zmime.ZMimeMessage; import com.zimbra.common.zmime.ZSharedFileInputStream; import com.zimbra.cs.account.Account; import com.zimbra.cs.account.Config; import com.zimbra.cs.account.Provisioning; import com.zimbra.cs.account.Server; import com.zimbra.cs.service.mail.ItemAction; public class SpamExtract { private static Log mLog = LogFactory.getLog(SpamExtract.class); private static Options mOptions = new Options(); static { mOptions.addOption("s", "spam", false, "extract messages from configured spam mailbox"); mOptions.addOption("n", "notspam", false, "extract messages from configured notspam mailbox"); mOptions.addOption("m", "mailbox", true, "extract messages from specified mailbox"); mOptions.addOption("d", "delete", false, "delete extracted messages (default is to keep)"); mOptions.addOption("o", "outdir", true, "directory to store extracted messages"); mOptions.addOption("a", "admin", true, "admin user name for auth (default is zimbra_ldap_userdn)"); mOptions.addOption("p", "password", true, "admin password for auth (default is zimbra_ldap_password)"); mOptions.addOption("u", "url", true, "admin SOAP service url (default is target mailbox's server's admin service port)"); mOptions.addOption("q", "query", true, "search query whose results should be extracted (default is in:inbox)"); mOptions.addOption("r", "raw", false, "extract raw message (default: gets message/rfc822 attachments)"); mOptions.addOption("h", "help", false, "show this usage text"); mOptions.addOption("D", "debug", false, "enable debug level logging"); mOptions.addOption("v", "verbose", false, "be verbose while running"); } private static void usage(String errmsg) { if (errmsg != null) { mLog.error(errmsg); } HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("zmspamextract [options] ", "where [options] are one of:", mOptions, "SpamExtract retrieve messages that may have been marked as spam or not spam in the Zimbra Web Client."); System.exit((errmsg == null) ? 0 : 1); } private static CommandLine parseArgs(String args[]) { CommandLineParser parser = new GnuParser(); CommandLine cl = null; try { cl = parser.parse(mOptions, args); } catch (ParseException pe) { usage(pe.getMessage()); } if (cl.hasOption("h")) { usage(null); } return cl; } private static boolean mVerbose = false; public static void main(String[] args) throws ServiceException, HttpException, SoapFaultException, IOException { CommandLine cl = parseArgs(args); if (cl.hasOption('D')) { CliUtil.toolSetup("DEBUG"); } else { CliUtil.toolSetup("INFO"); } if (cl.hasOption('v')) { mVerbose = true; } boolean optDelete = cl.hasOption('d'); if (!cl.hasOption('o')) { usage("must specify directory to extract messages to"); } String optDirectory = cl.getOptionValue('o'); File outputDirectory = new File(optDirectory); if (!outputDirectory.exists()) { mLog.info("Creating directory: " + optDirectory); outputDirectory.mkdirs(); if (!outputDirectory.exists()) { mLog.error("could not create directory " + optDirectory); System.exit(2); } } String optAdminUser; if (cl.hasOption('a')) { optAdminUser = cl.getOptionValue('a'); } else { optAdminUser = LC.zimbra_ldap_user.value(); } String optAdminPassword; if (cl.hasOption('p')) { optAdminPassword = cl.getOptionValue('p'); } else { optAdminPassword = LC.zimbra_ldap_password.value(); } String optQuery = "in:inbox"; if (cl.hasOption('q')) { optQuery = cl.getOptionValue('q'); } Account account = getAccount(cl); if (account == null) { System.exit(1); } boolean optRaw = cl.hasOption('r'); if (mVerbose) mLog.info("Extracting from account " + account.getName()); Server server = Provisioning.getInstance().getServer(account); String optAdminURL; if (cl.hasOption('u')) { optAdminURL = cl.getOptionValue('u'); } else { optAdminURL = getSoapURL(server, true); } String adminAuthToken = getAdminAuthToken(optAdminURL, optAdminUser, optAdminPassword); String authToken = getDelegateAuthToken(optAdminURL, account, adminAuthToken); extract(authToken, account, server, optQuery, outputDirectory, optDelete, optRaw); } public static final String TYPE_MESSAGE = "message"; private static void extract(String authToken, Account account, Server server, String query, File outdir, boolean delete, boolean raw) throws ServiceException, HttpException, SoapFaultException, IOException { String soapURL = getSoapURL(server, false); URL restURL = getServerURL(server, false); HttpClient hc = new HttpClient(); // CLI only, don't need conn mgr HttpState state = new HttpState(); GetMethod gm = new GetMethod(); gm.setFollowRedirects(true); Cookie authCookie = new Cookie(restURL.getHost(), ZimbraCookie.COOKIE_ZM_AUTH_TOKEN, authToken, "/", -1, false); state.addCookie(authCookie); hc.setState(state); hc.getHostConfiguration().setHost(restURL.getHost(), restURL.getPort(), Protocol.getProtocol(restURL.getProtocol())); gm.getParams().setSoTimeout(60000); if (mVerbose) mLog.info("Mailbox requests to: " + restURL); SoapHttpTransport transport = new SoapHttpTransport(soapURL); transport.setRetryCount(1); transport.setTimeout(0); transport.setAuthToken(authToken); int totalProcessed = 0; boolean haveMore = true; int offset = 0; while (haveMore) { Element searchReq = new Element.XMLElement(MailConstants.SEARCH_REQUEST); searchReq.addElement(MailConstants.A_QUERY).setText(query); searchReq.addAttribute(MailConstants.A_SEARCH_TYPES, TYPE_MESSAGE); searchReq.addAttribute(MailConstants.A_QUERY_OFFSET, offset); try { if (mLog.isDebugEnabled()) mLog.debug(searchReq.prettyPrint()); Element searchResp = transport.invoke(searchReq, false, true, account.getId()); if (mLog.isDebugEnabled()) mLog.debug(searchResp.prettyPrint()); StringBuilder deleteList = new StringBuilder(); for (Iterator<Element> iter = searchResp.elementIterator(MailConstants.E_MSG); iter.hasNext();) { offset++; Element e = iter.next(); String mid = e.getAttribute(MailConstants.A_ID); if (mid == null) { mLog.warn("null message id SOAP response"); continue; } String path = "/service/user/" + account.getName() + "/?id=" + mid; if (extractMessage(hc, gm, path, outdir, raw)) { deleteList.append(mid).append(','); } totalProcessed++; } haveMore = false; String more = searchResp.getAttribute(MailConstants.A_QUERY_MORE); if (more != null && more.length() > 0) { try { int m = Integer.parseInt(more); if (m > 0) { haveMore = true; } } catch (NumberFormatException nfe) { mLog.warn("more flag from server not a number: " + more, nfe); } } if (delete && deleteList.length() > 0) { deleteList.deleteCharAt(deleteList.length()-1); // -1 removes trailing comma Element msgActionReq = new Element.XMLElement(MailConstants.MSG_ACTION_REQUEST); Element action = msgActionReq.addElement(MailConstants.E_ACTION); action.addAttribute(MailConstants.A_ID, deleteList.toString()); action.addAttribute(MailConstants.A_OPERATION, ItemAction.OP_HARD_DELETE); if (mLog.isDebugEnabled()) mLog.debug(msgActionReq.prettyPrint()); Element msgActionResp = transport.invoke(msgActionReq, false, true, account.getId()); if (mLog.isDebugEnabled()) mLog.debug(msgActionResp.prettyPrint()); } } finally { gm.releaseConnection(); } } mLog.info("Total messages processed: " + totalProcessed); } private static Session mJMSession; private static String mOutputPrefix; static { Properties props = new Properties(); props.setProperty("mail.mime.address.strict", "false"); mJMSession = Session.getInstance(props); mOutputPrefix = Long.toHexString(System.currentTimeMillis()); } private static boolean extractMessage(HttpClient hc, GetMethod gm, String path, File outdir, boolean raw) { try { extractMessage0(hc, gm, path, outdir, raw); return true; } catch (MessagingException me) { mLog.warn("exception occurred fetching message", me); } catch (IOException ioe) { mLog.warn("exception occurred fetching message", ioe); } return false; } private static int mExtractIndex; private static final int MAX_BUFFER_SIZE = 10 * 1024 * 1024; private static void extractMessage0(HttpClient hc, GetMethod gm, String path, File outdir, boolean raw) throws IOException, MessagingException { gm.setPath(path); if (mLog.isDebugEnabled()) mLog.debug("Fetching " + path); HttpClientUtil.executeMethod(hc, gm); if (gm.getStatusCode() != HttpStatus.SC_OK) { throw new IOException("HTTP GET failed: " + gm.getPath() + ": " + gm.getStatusCode() + ": " + gm.getStatusText()); } if (raw) { // Write the message as-is. File file = new File(outdir, mOutputPrefix + "-" + mExtractIndex++); OutputStream os = null; try { os = new BufferedOutputStream(new FileOutputStream(file)); ByteUtil.copy(gm.getResponseBodyAsStream(), true, os, false); if (mVerbose) mLog.info("Wrote: " + file); } catch (java.io.IOException e) { String fileName = outdir + "/" + mOutputPrefix + "-" + mExtractIndex; mLog.error("Cannot write to " + fileName, e); } finally { if (os != null) os.close(); } return; } // Write the attached message to the output directory. BufferStream buffer = new BufferStream(gm.getResponseContentLength(), MAX_BUFFER_SIZE); buffer.setSequenced(false); MimeMessage mm = null; InputStream fis = null; try { ByteUtil.copy(gm.getResponseBodyAsStream(), true, buffer, false); if (buffer.isSpooled()) { fis = new ZSharedFileInputStream(buffer.getFile()); mm = new ZMimeMessage(mJMSession, fis); } else { mm = new ZMimeMessage(mJMSession, buffer.getInputStream()); } writeAttachedMessages(mm, outdir, gm.getPath()); } finally { ByteUtil.closeStream(fis); } } private static void writeAttachedMessages(MimeMessage mm, File outdir, String msgUri) throws IOException, MessagingException { // Not raw - ignore the spam report and extract messages that are in attachments... if (!(mm.getContent() instanceof MimeMultipart)) { mLog.warn("Spam/notspam messages must have attachments (skipping " + msgUri + ")"); return; } MimeMultipart mmp = (MimeMultipart)mm.getContent(); int nAttachments = mmp.getCount(); boolean foundAtleastOneAttachedMessage = false; for (int i = 0; i < nAttachments; i++) { BodyPart bp = mmp.getBodyPart(i); if (!bp.isMimeType("message/rfc822")) { // Let's ignore all parts that are not messages. continue; } foundAtleastOneAttachedMessage = true; Part msg = (Part) bp.getContent(); // the actual message File file = new File(outdir, mOutputPrefix + "-" + mExtractIndex++); OutputStream os = null; try { os = new BufferedOutputStream(new FileOutputStream(file)); msg.writeTo(os); } finally { os.close(); } if (mVerbose) mLog.info("Wrote: " + file); } if (!foundAtleastOneAttachedMessage) { String msgid = mm.getHeader("Message-ID", " "); mLog.warn("message uri=" + msgUri + " message-id=" + msgid + " had no attachments"); } } public static URL getServerURL(Server server, boolean admin) throws ServiceException { String host = server.getAttr(Provisioning.A_zimbraServiceHostname); if (host == null) { throw ServiceException.FAILURE("invalid " + Provisioning.A_zimbraServiceHostname + " in server " + server.getName(), null); } String protocol = "http"; String portAttr = Provisioning.A_zimbraMailPort; if (admin) { protocol = "https"; portAttr = Provisioning.A_zimbraAdminPort; } else { String mode = server.getAttr(Provisioning.A_zimbraMailMode); if (mode == null) { throw ServiceException.FAILURE("null " + Provisioning.A_zimbraMailMode + " in server " + server.getName(), null); } if (mode.equalsIgnoreCase("https")) { protocol = "https"; portAttr = Provisioning.A_zimbraMailSSLPort; } if (mode.equalsIgnoreCase("redirect")) { protocol = "https"; portAttr = Provisioning.A_zimbraMailSSLPort; } } int port = server.getIntAttr(portAttr, -1); if (port < 1) { throw ServiceException.FAILURE("invalid " + portAttr + " in server " + server.getName(), null); } try { return new URL(protocol, host, port, ""); } catch (MalformedURLException mue) { throw ServiceException.FAILURE("exception creating url (protocol=" + protocol + " host=" + host + " port=" + port + ")", mue); } } public static String getSoapURL(Server server, boolean admin) throws ServiceException { String url = getServerURL(server, admin).toString(); String file = admin ? AdminConstants.ADMIN_SERVICE_URI : AccountConstants.USER_SERVICE_URI; return url + file; } public static String getAdminAuthToken(String adminURL, String adminUser, String adminPassword) throws ServiceException { SoapHttpTransport transport = new SoapHttpTransport(adminURL); transport.setRetryCount(1); transport.setTimeout(0); Element authReq = new Element.XMLElement(AdminConstants.AUTH_REQUEST); authReq.addAttribute(AdminConstants.E_NAME, adminUser, Element.Disposition.CONTENT); authReq.addAttribute(AdminConstants.E_PASSWORD, adminPassword, Element.Disposition.CONTENT); try { if (mVerbose) mLog.info("Auth request to: " + adminURL); if (mLog.isDebugEnabled()) mLog.debug(authReq.prettyPrint()); Element authResp = transport.invokeWithoutSession(authReq); if (mLog.isDebugEnabled()) mLog.debug(authResp.prettyPrint()); String authToken = authResp.getAttribute(AdminConstants.E_AUTH_TOKEN); return authToken; } catch (Exception e) { throw ServiceException.FAILURE("admin auth failed url=" + adminURL, e); } } public static String getDelegateAuthToken(String adminURL, Account account, String adminAuthToken) throws ServiceException { SoapHttpTransport transport = new SoapHttpTransport(adminURL); transport.setRetryCount(1); transport.setTimeout(0); transport.setAuthToken(adminAuthToken); Element daReq = new Element.XMLElement(AdminConstants.DELEGATE_AUTH_REQUEST); Element acctElem = daReq.addElement(AdminConstants.E_ACCOUNT); acctElem.addAttribute(AdminConstants.A_BY, AdminConstants.BY_ID); acctElem.setText(account.getId()); try { if (mVerbose) mLog.info("Delegate auth request to: " + adminURL); if (mLog.isDebugEnabled()) mLog.debug(daReq.prettyPrint()); Element daResp = transport.invokeWithoutSession(daReq); if (mLog.isDebugEnabled()) mLog.debug(daResp.prettyPrint()); String authToken = daResp.getAttribute(AdminConstants.E_AUTH_TOKEN); return authToken; } catch (Exception e) { throw ServiceException.FAILURE("Delegate auth failed url=" + adminURL, e); } } private static Account getAccount(CommandLine cl) throws ServiceException { Provisioning prov = Provisioning.getInstance(); Config conf; try { conf = prov.getConfig(); } catch (ServiceException e) { throw ServiceException.FAILURE("Unable to connect to LDAP directory", e); } String name = null; if (cl.hasOption('s')) { if (cl.hasOption('n') || cl.hasOption('m')) { mLog.error("only one of s, n or m options can be specified"); return null; } name = conf.getAttr(Provisioning.A_zimbraSpamIsSpamAccount); if (name == null || name.length() == 0) { mLog.error("no account configured for spam"); return null; } } else if (cl.hasOption('n')) { if (cl.hasOption('m')) { mLog.error("only one of s, n, or m options can be specified"); return null; } name = conf.getAttr(Provisioning.A_zimbraSpamIsNotSpamAccount); if (name == null || name.length() == 0) { mLog.error("no account configured for ham"); return null; } } else if (cl.hasOption('m')) { name = cl.getOptionValue('m'); if (name.length() == 0) { mLog.error("illegal argument to m option"); return null; } } else { mLog.error("one of s, n or m options must be specified"); return null; } Account account = prov.get(AccountBy.name, name); if (account == null) { mLog.error("can not find account " + name); return null; } return account; } }
mit
WesCook/WateringCans
src/main/java/ca/wescook/wateringcans/events/EventFOV.java
1001
package ca.wescook.wateringcans.events; import ca.wescook.wateringcans.potions.ModPotions; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.player.EntityPlayer; import net.minecraftforge.client.event.FOVUpdateEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class EventFOV { @SubscribeEvent public void fovUpdates(FOVUpdateEvent event) { // Get player object EntityPlayer player = event.getEntity(); if (player.getActivePotionEffect(ModPotions.inhibitFOV) != null) { // Get player data double playerSpeed = player.getEntityAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).getAttributeValue(); float capableSpeed = player.capabilities.getWalkSpeed(); float fov = event.getFov(); // Disable FOV change event.setNewfov((float) (fov / ((playerSpeed / capableSpeed + 1.0) / 2.0))); } } }
mit
zerobandwidth-net/android
libZeroAndroid/src/androidTest/java/net/zer0bandwidth/android/lib/content/querybuilder/DeletionBuilderTest.java
1665
package net.zer0bandwidth.android.lib.content.querybuilder; import android.content.ContentResolver; import android.support.test.runner.AndroidJUnit4; import android.test.ProviderTestCase2; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static junit.framework.Assert.assertNull; /** * Exercises {@link DeletionBuilder}. * @since zer0bandwidth-net/android 0.1.7 (#39) */ @RunWith( AndroidJUnit4.class ) public class DeletionBuilderTest extends ProviderTestCase2<MockContentProvider> { protected QueryBuilderTest.MockContext m_mockery = new QueryBuilderTest.MockContext() ; @SuppressWarnings( "unused" ) // sAuthority is intentionally ignored public DeletionBuilderTest() { super( MockContentProvider.class, QueryBuilderTest.MockContext.AUTHORITY ) ; } @Override @Before public void setUp() throws Exception { super.setUp() ; } /** Exercises {@link DeletionBuilder#deleteAll} */ @Test public void testDeleteAll() { DeletionBuilder qb = new DeletionBuilder( m_mockery.ctx, m_mockery.uri ) ; qb.m_sExplicitWhereFormat = "qarnflarglebarg" ; qb.m_asExplicitWhereParams = new String[] { "foo", "bar", "baz" } ; qb.deleteAll() ; assertNull( qb.m_sExplicitWhereFormat ) ; assertNull( qb.m_asExplicitWhereParams ) ; } /** Exercises {@link DeletionBuilder#executeQuery}. */ @Test public void testExecuteQuery() throws Exception // Any uncaught exception is a failure. { ContentResolver rslv = this.getMockContentResolver() ; int nDeleted = QueryBuilder.deleteFrom( rslv, m_mockery.uri ).execute(); assertEquals( MockContentProvider.EXPECTED_DELETE_COUNT, nDeleted ) ; } }
mit
dayler/AsteriskInterface
src/me/dayler/ai/ami/conn/SocketConnectionFacadeImpl.java
4154
/** * */ package me.dayler.ai.ami.conn; import javax.net.SocketFactory; import javax.net.ssl.SSLSocketFactory; import java.io.*; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.util.NoSuchElementException; import java.util.Scanner; import java.util.regex.Pattern; /** * Default implementation of the SocketConnectionFacade interface using java.io. * * @author srt, asalazar * @version $Id: SocketConnectionFacadeImpl.java 1377 2009-10-17 03:24:49Z srt $ */ public class SocketConnectionFacadeImpl implements SocketConnectionFacade { static final Pattern CRNL_PATTERN = Pattern.compile("\r\n"); static final Pattern NL_PATTERN = Pattern.compile("\n"); private Socket socket; private Scanner scanner; private BufferedWriter writer; /** * Creates a new instance for use with the Manager API that uses CRNL ("\r\n") as line delimiter. * * @param host the foreign host to connect to. * @param port the foreign port to connect to. * @param ssl <code>true</code> to use SSL, <code>false</code> otherwise. * @param timeout 0 incidcates default * @param readTimeout see {@link Socket#setSoTimeout(int)} * @throws IOException if the connection cannot be established. */ public SocketConnectionFacadeImpl(String host, int port, boolean ssl, int timeout, int readTimeout) throws IOException { Socket socket; if (ssl) { socket = SSLSocketFactory.getDefault().createSocket(); } else { socket = SocketFactory.getDefault().createSocket(); } socket.setSoTimeout(readTimeout); socket.connect(new InetSocketAddress(host, port), timeout); initialize(socket, CRNL_PATTERN); } /** * Creates a new instance for use with FastAGI that uses NL ("\n") as line delimiter. * * @param socket the underlying socket. * @throws IOException if the connection cannot be initialized. */ SocketConnectionFacadeImpl(Socket socket) throws IOException { initialize(socket, NL_PATTERN); } private void initialize(Socket socket, Pattern pattern) throws IOException { this.socket = socket; InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); this.scanner = new Scanner(reader); this.scanner.useDelimiter(pattern); this.writer = new BufferedWriter(new OutputStreamWriter(outputStream)); } public String readLine() throws IOException { String line; try { line = scanner.next(); } catch (IllegalStateException e) { if (scanner.ioException() != null) { throw scanner.ioException(); } else { // throw new IOException("No more lines available", e); // JDK6 throw new IOException("No more lines available: " + e.getMessage()); } } catch (NoSuchElementException e) { if (scanner.ioException() != null) { throw scanner.ioException(); } else { // throw new IOException("No more lines available", e); // JDK6 throw new IOException("No more lines available: " + e.getMessage()); } } return line; } public void write(String s) throws IOException { writer.write(s); } public void flush() throws IOException { writer.flush(); } public void close() throws IOException { socket.close(); scanner.close(); } public boolean isConnected() { return socket.isConnected(); } public InetAddress getLocalAddress() { return socket.getLocalAddress(); } public int getLocalPort() { return socket.getLocalPort(); } public InetAddress getRemoteAddress() { return socket.getInetAddress(); } public int getRemotePort() { return socket.getPort(); } }
mit
yongli82/dsl
src/main/java/info/yongli/statistic/table/ColumnTransformer.java
123
package info.yongli.statistic.table; /** * Created by yangyongli on 25/04/2017. */ public class ColumnTransformer { }
mit
digitalheir/java-wetten-nl-library
src/main/java/nl/wetten/bwbng/toestand/Intitule.java
7834
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.10.21 at 02:36:24 PM CEST // package nl.wetten.bwbng.toestand; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlElementRefs; import javax.xml.bind.annotation.XmlMixed; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;choice maxOccurs="unbounded" minOccurs="0"> * &lt;group ref="{}tekst.minimaal"/> * &lt;element ref="{}nootref"/> * &lt;element ref="{}noot"/> * &lt;/choice> * &lt;element ref="{}meta-data" minOccurs="0"/> * &lt;/sequence> * &lt;attGroup ref="{}attlist.intitule"/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "content" }) @XmlRootElement(name = "intitule") public class Intitule { @XmlElementRefs({ @XmlElementRef(name = "nadruk", type = Nadruk.class, required = false), @XmlElementRef(name = "omissie", type = Omissie.class, required = false), @XmlElementRef(name = "sup", type = JAXBElement.class, required = false), @XmlElementRef(name = "noot", type = Noot.class, required = false), @XmlElementRef(name = "unl", type = JAXBElement.class, required = false), @XmlElementRef(name = "meta-data", type = MetaData.class, required = false), @XmlElementRef(name = "nootref", type = Nootref.class, required = false), @XmlElementRef(name = "ovl", type = JAXBElement.class, required = false), @XmlElementRef(name = "inf", type = JAXBElement.class, required = false) }) @XmlMixed protected List<Object> content; @XmlAttribute(name = "id") @XmlSchemaType(name = "anySimpleType") protected String id; @XmlAttribute(name = "status") protected String status; @XmlAttribute(name = "terugwerking") @XmlSchemaType(name = "anySimpleType") protected String terugwerking; @XmlAttribute(name = "label-id") @XmlSchemaType(name = "anySimpleType") protected String labelId; @XmlAttribute(name = "stam-id") @XmlSchemaType(name = "anySimpleType") protected String stamId; @XmlAttribute(name = "versie-id") @XmlSchemaType(name = "anySimpleType") protected String versieId; @XmlAttribute(name = "publicatie") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String publicatie; /** * Gets the value of the content property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the content property. * * <p> * For example, to add a new item, do as follows: * <pre> * getContent().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Nadruk } * {@link Omissie } * {@link JAXBElement }{@code <}{@link String }{@code >} * {@link Noot } * {@link JAXBElement }{@code <}{@link String }{@code >} * {@link MetaData } * {@link Nootref } * {@link JAXBElement }{@code <}{@link String }{@code >} * {@link JAXBElement }{@code <}{@link String }{@code >} * {@link String } * * */ public List<Object> getContent() { if (content == null) { content = new ArrayList<Object>(); } return this.content; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the status property. * * @return * possible object is * {@link String } * */ public String getStatus() { return status; } /** * Sets the value of the status property. * * @param value * allowed object is * {@link String } * */ public void setStatus(String value) { this.status = value; } /** * Gets the value of the terugwerking property. * * @return * possible object is * {@link String } * */ public String getTerugwerking() { return terugwerking; } /** * Sets the value of the terugwerking property. * * @param value * allowed object is * {@link String } * */ public void setTerugwerking(String value) { this.terugwerking = value; } /** * Gets the value of the labelId property. * * @return * possible object is * {@link String } * */ public String getLabelId() { return labelId; } /** * Sets the value of the labelId property. * * @param value * allowed object is * {@link String } * */ public void setLabelId(String value) { this.labelId = value; } /** * Gets the value of the stamId property. * * @return * possible object is * {@link String } * */ public String getStamId() { return stamId; } /** * Sets the value of the stamId property. * * @param value * allowed object is * {@link String } * */ public void setStamId(String value) { this.stamId = value; } /** * Gets the value of the versieId property. * * @return * possible object is * {@link String } * */ public String getVersieId() { return versieId; } /** * Sets the value of the versieId property. * * @param value * allowed object is * {@link String } * */ public void setVersieId(String value) { this.versieId = value; } /** * Gets the value of the publicatie property. * * @return * possible object is * {@link String } * */ public String getPublicatie() { return publicatie; } /** * Sets the value of the publicatie property. * * @param value * allowed object is * {@link String } * */ public void setPublicatie(String value) { this.publicatie = value; } }
mit
Azure/azure-sdk-for-java
sdk/resourcemanagerhybrid/azure-resourcemanager-network/src/test/java/com/azure/resourcemanager/network/DdosProtectionPlanTests.java
1570
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.resourcemanager.network; import com.azure.core.http.rest.PagedIterable; import com.azure.resourcemanager.network.models.DdosProtectionPlan; import com.azure.resourcemanager.test.utils.TestUtilities; import com.azure.core.management.Region; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class DdosProtectionPlanTests extends NetworkManagementTest { @Test public void canCRUDDdosProtectionPlan() throws Exception { String ppName = generateRandomResourceName("ddosplan", 15); DdosProtectionPlan pPlan = networkManager .ddosProtectionPlans() .define(ppName) .withRegion(locationOrDefault(Region.US_SOUTH_CENTRAL)) .withNewResourceGroup(rgName) .withTag("tag1", "value1") .create(); Assertions.assertEquals("value1", pPlan.tags().get("tag1")); PagedIterable<DdosProtectionPlan> ppList = networkManager.ddosProtectionPlans().list(); Assertions.assertTrue(TestUtilities.getSize(ppList) > 0); ppList = networkManager.ddosProtectionPlans().listByResourceGroup(rgName); Assertions.assertTrue(TestUtilities.getSize(ppList) > 0); networkManager.ddosProtectionPlans().deleteById(pPlan.id()); ppList = networkManager.ddosProtectionPlans().listByResourceGroup(rgName); Assertions.assertTrue(TestUtilities.isEmpty(ppList)); } }
mit
zalando/problem-spring-web
problem-spring-web/src/main/java/org/zalando/problem/spring/web/advice/package-info.java
135
@ParametersAreNonnullByDefault package org.zalando.problem.spring.web.advice; import javax.annotation.ParametersAreNonnullByDefault;
mit
uprm-gaming/virtual-factory
src/com/virtualfactory/screen/layer/components/FlowChartScreenController.java
4455
package com.virtualfactory.screen.layer.components; import de.lessvoid.nifty.Nifty; import de.lessvoid.nifty.NiftyEventSubscriber; import de.lessvoid.nifty.controls.ButtonClickedEvent; import de.lessvoid.nifty.controls.Controller; import de.lessvoid.nifty.controls.window.WindowControl; import de.lessvoid.nifty.elements.Element; import de.lessvoid.nifty.elements.render.ImageRenderer; import de.lessvoid.nifty.input.NiftyInputEvent; import de.lessvoid.nifty.render.NiftyImage; import de.lessvoid.nifty.screen.Screen; import de.lessvoid.nifty.tools.SizeValue; import de.lessvoid.xml.xpp3.Attributes; import com.virtualfactory.engine.GameEngine; import com.virtualfactory.utils.CommonBuilders; import com.virtualfactory.utils.Pair; import java.util.Properties; /** * * @author David */ public class FlowChartScreenController implements Controller { private Nifty nifty; private Screen screen; private WindowControl winControls; private boolean isVisible; private GameEngine gameEngine; final CommonBuilders common = new CommonBuilders(); private NiftyImage flowChartImage; @Override public void bind( final Nifty nifty, final Screen screen, final Element element, final Properties parameter, final Attributes controlDefinitionAttributes) { this.nifty = nifty; this.screen = screen; this.winControls = screen.findNiftyControl("winFlowChartControl", WindowControl.class); Attributes x = new Attributes(); x.set("hideOnClose", "true"); this.winControls.bind(nifty, screen, winControls.getElement(), null, x); isVisible = false; } public boolean isIsVisible() { return isVisible; } public void setIsVisible(boolean isVisible) { this.isVisible = isVisible; } @Override public void init(Properties parameter, Attributes controlDefinitionAttributes) { } @Override public void onStartScreen() { } @Override public void onFocus(boolean getFocus) { } @Override public boolean inputEvent(final NiftyInputEvent inputEvent) { return false; } public void loadWindowControl(GameEngine game,int index, Pair<Integer,Integer> position){ this.gameEngine = game; if (index == -1){ winControls.getElement().setVisible(false); winControls.getContent().hide(); isVisible = false; }else{ winControls.getElement().setVisible(true); winControls.getContent().show(); isVisible = true; if (position != null){ if (winControls.getWidth() + position.getFirst() > gameEngine.jmonkeyApp.getGuiViewPort().getCamera().getWidth()) position.setFirst(gameEngine.jmonkeyApp.getGuiViewPort().getCamera().getWidth() - winControls.getWidth()); if (winControls.getHeight() + position.getSecond() > gameEngine.jmonkeyApp.getGuiViewPort().getCamera().getHeight()) position.setSecond(gameEngine.jmonkeyApp.getGuiViewPort().getCamera().getHeight() - winControls.getHeight()); winControls.getElement().setConstraintX(new SizeValue(position.getFirst() + "px")); winControls.getElement().setConstraintY(new SizeValue(position.getSecond() + "px")); winControls.getElement().getParent().layoutElements(); } winControls.getElement().setConstraintX(null); winControls.getElement().setConstraintY(null); } loadValues(index); } private void loadValues(int index){ if (index == -1){ flowChartImage = nifty.createImage("Models/Flows/none.png", false); screen.findElementByName("imageFlowOfActivities").getRenderer(ImageRenderer.class).setImage(flowChartImage); }else{ flowChartImage = nifty.createImage("Models/Flows/" + gameEngine.getGameData().getCurrentGame().getFlowImage(), false); screen.findElementByName("imageFlowOfActivities").getRenderer(ImageRenderer.class).setImage(flowChartImage); } } @NiftyEventSubscriber(id="closeFlowChart") public void onCloseFlowChartButtonClicked(final String id, final ButtonClickedEvent event) { gameEngine.updateLastActivitySystemTime(); loadWindowControl(gameEngine, -1, null); } }
mit